ftui-tty 0.4.0

Native Unix terminal backend for FrankenTUI (replaces Crossterm).
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
#![forbid(unsafe_code)]
//! Native Unix terminal backend for FrankenTUI.
//!
//! This crate implements the `ftui-backend` traits for native Unix/macOS terminals.
//! It replaces Crossterm as the terminal I/O layer (Unix-first; Windows deferred).
//!
//! ## Escape Sequence Reference
//!
//! | Feature           | Enable                    | Disable                   |
//! |-------------------|---------------------------|---------------------------|
//! | Alternate screen  | `CSI ? 1049 h`            | `CSI ? 1049 l`            |
//! | Mouse (SGR)       | `CSI ? 1000;1002;1006 h` (+ split compatibility) | `CSI ? 1000;1002;1006 l` (+ legacy reset hygiene) |
//! | Bracketed paste   | `CSI ? 2004 h`            | `CSI ? 2004 l`            |
//! | Focus events      | `CSI ? 1004 h`            | `CSI ? 1004 l`            |
//! | Kitty keyboard    | `CSI > 15 u`              | `CSI < u`                 |
//! | Cursor show/hide  | `CSI ? 25 h`              | `CSI ? 25 l`              |
//! | Sync output       | `CSI ? 2026 h`            | `CSI ? 2026 l`            |

use core::time::Duration;
use std::collections::VecDeque;
use std::io::{self, BufWriter, Read, Write};
#[cfg(unix)]
use std::os::unix::net::UnixStream;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Mutex, OnceLock};
use std::time::Instant;

use ftui_backend::{Backend, BackendClock, BackendEventSource, BackendFeatures, BackendPresenter};
use ftui_core::event::{Event, MouseEventKind};
use ftui_core::input_parser::InputParser;
use ftui_core::terminal_capabilities::TerminalCapabilities;
use ftui_render::buffer::Buffer;
use ftui_render::diff::BufferDiff;
use ftui_render::presenter::Presenter;

#[cfg(unix)]
use signal_hook::consts::signal::{SIGHUP, SIGINT, SIGQUIT, SIGTERM, SIGWINCH};
#[cfg(unix)]
use signal_hook::iterator::Signals;

// ── Escape Sequences ─────────────────────────────────────────────────────

const ALT_SCREEN_ENTER: &[u8] = b"\x1b[?1049h";
const ALT_SCREEN_LEAVE: &[u8] = b"\x1b[?1049l";

// Mouse mode hygiene:
// 1) Reset legacy/alternate encodings that can linger across sessions.
// 2) Enable canonical SGR mouse (1000 + 1002 + 1006) using both combined and
//    split forms for emulator/mux compatibility.
// 3) Clear 1016 before enabling SGR to avoid terminals that interpret 1016l
//    after 1006h as a fallback to X10 mode.
// 4) Avoid DECSET 1003 (any-event mouse) because high-rate move streams can
//    destabilize some mux pipelines.
// NOTE: Set SGR format (1006) before enabling mouse event modes for better
// compatibility with terminals that key off "last mode set" ordering.
const MOUSE_ENABLE: &[u8] = b"\x1b[?1001l\x1b[?1003l\x1b[?1005l\x1b[?1015l\x1b[?1016l\x1b[?1006;1000;1002h\x1b[?1006h\x1b[?1000h\x1b[?1002h";
const MOUSE_ENABLE_MUX_SAFE: &[u8] =
    b"\x1b[?1001l\x1b[?1003l\x1b[?1005l\x1b[?1015l\x1b[?1016l\x1b[?1006h\x1b[?1000h\x1b[?1002h";
const MOUSE_DISABLE: &[u8] = b"\x1b[?1000;1002;1006l\x1b[?1000l\x1b[?1002l\x1b[?1006l\x1b[?1001l\x1b[?1003l\x1b[?1005l\x1b[?1015l\x1b[?1016l";
const MOUSE_DISABLE_MUX_SAFE: &[u8] =
    b"\x1b[?1016l\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1001l\x1b[?1005l\x1b[?1015l";

const BRACKETED_PASTE_ENABLE: &[u8] = b"\x1b[?2004h";
const BRACKETED_PASTE_DISABLE: &[u8] = b"\x1b[?2004l";

const FOCUS_ENABLE: &[u8] = b"\x1b[?1004h";
const FOCUS_DISABLE: &[u8] = b"\x1b[?1004l";

const KITTY_KEYBOARD_ENABLE: &[u8] = b"\x1b[>15u";
const KITTY_KEYBOARD_DISABLE: &[u8] = b"\x1b[<u";

const CURSOR_SHOW: &[u8] = b"\x1b[?25h";
#[allow(dead_code)]
const CURSOR_HIDE: &[u8] = b"\x1b[?25l";

const SYNC_END: &[u8] = b"\x1b[?2026l";
const RESET_SCROLL_REGION: &[u8] = b"\x1b[r";
const SGR_RESET: &[u8] = b"\x1b[0m";

// ── Debug Input Tracing ──────────────────────────────────────────────────

const INPUT_TRACE_ENV: &str = "FTUI_TTY_INPUT_TRACE";
const SIGNAL_SHUTDOWN_GRACE: Duration = Duration::from_secs(2);
const SIGNAL_SHUTDOWN_POLL: Duration = Duration::from_millis(10);
static LIVE_SIGNAL_INTERCEPT_SESSIONS: AtomicUsize = AtomicUsize::new(0);

#[cfg(unix)]
#[derive(Debug)]
struct SignalInterceptGuard {
    active: bool,
}

#[cfg(unix)]
impl SignalInterceptGuard {
    fn new(enabled: bool) -> Self {
        if enabled {
            LIVE_SIGNAL_INTERCEPT_SESSIONS.fetch_add(1, Ordering::SeqCst);
            install_termination_signal_hook();
        }
        Self { active: enabled }
    }

    fn disarm(&mut self) -> bool {
        let was_active = self.active;
        self.active = false;
        was_active
    }
}

#[cfg(unix)]
impl Drop for SignalInterceptGuard {
    fn drop(&mut self) {
        if self.active {
            LIVE_SIGNAL_INTERCEPT_SESSIONS.fetch_sub(1, Ordering::SeqCst);
        }
    }
}

#[derive(Debug)]
struct InputTrace {
    seq: u64,
    writer: BufWriter<std::fs::File>,
}

impl InputTrace {
    fn from_env() -> Option<Self> {
        let path = std::env::var(INPUT_TRACE_ENV).ok()?;
        let trimmed = path.trim();
        if trimmed.is_empty() {
            return None;
        }
        let file = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(trimmed)
            .ok()?;
        Some(Self {
            seq: 0,
            writer: BufWriter::new(file),
        })
    }

    fn record(&mut self, bytes: &[u8], parsed: &[Event]) {
        self.seq = self.seq.saturating_add(1);
        let _ = write!(self.writer, "seq={} n={} hex=", self.seq, bytes.len());
        let _ = write_hex(&mut self.writer, bytes);
        let _ = writeln!(self.writer);
        for ev in parsed {
            let _ = writeln!(self.writer, "  {:?}", ev);
        }
        let _ = writeln!(self.writer, "---");
        let _ = self.writer.flush();
    }
}

fn write_hex(w: &mut impl Write, bytes: &[u8]) -> io::Result<()> {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    for &b in bytes {
        w.write_all(&[HEX[(b >> 4) as usize], HEX[(b & 0x0f) as usize]])?;
    }
    Ok(())
}

#[inline]
const fn mouse_disable_sequence_for_capabilities(
    capabilities: TerminalCapabilities,
) -> &'static [u8] {
    if capabilities.in_any_mux() {
        MOUSE_DISABLE_MUX_SAFE
    } else {
        MOUSE_DISABLE
    }
}

#[inline]
const fn mouse_enable_sequence_for_capabilities(
    capabilities: TerminalCapabilities,
) -> &'static [u8] {
    if capabilities.in_any_mux() {
        MOUSE_ENABLE_MUX_SAFE
    } else {
        MOUSE_ENABLE
    }
}

#[inline]
const fn sanitize_feature_request(
    requested: BackendFeatures,
    capabilities: TerminalCapabilities,
) -> BackendFeatures {
    // Conservative policy for terminal mode toggles:
    // - Never request unsupported modes.
    // - Keep kitty keyboard off in all mux environments.
    // - Keep focus events off in all mux contexts; passthrough behavior varies.
    let focus_events_supported = capabilities.focus_events && !capabilities.in_any_mux();
    let kitty_keyboard_supported = capabilities.kitty_keyboard && !capabilities.in_any_mux();

    BackendFeatures {
        mouse_capture: requested.mouse_capture && capabilities.mouse_sgr,
        bracketed_paste: requested.bracketed_paste && capabilities.bracketed_paste,
        focus_events: requested.focus_events && focus_events_supported,
        kitty_keyboard: requested.kitty_keyboard && kitty_keyboard_supported,
    }
}

#[inline]
const fn conservative_feature_union(a: BackendFeatures, b: BackendFeatures) -> BackendFeatures {
    BackendFeatures {
        mouse_capture: a.mouse_capture || b.mouse_capture,
        bracketed_paste: a.bracketed_paste || b.bracketed_paste,
        focus_events: a.focus_events || b.focus_events,
        kitty_keyboard: a.kitty_keyboard || b.kitty_keyboard,
    }
}

const CLEAR_SCREEN: &[u8] = b"\x1b[2J";
const CURSOR_HOME: &[u8] = b"\x1b[H";
const READ_BUFFER_BYTES: usize = 8192;
const MAX_DRAIN_BYTES_PER_POLL: usize = READ_BUFFER_BYTES;
const INFERRED_PIXEL_WIDTH_PER_CELL: u16 = 8;
const INFERRED_PIXEL_HEIGHT_PER_CELL: u16 = 16;
/// Grace period before resolving a pending ambiguous escape/UTF-8 sequence.
///
/// This prevents split escape sequences (`ESC` then `[` in a later read) from
/// being prematurely emitted as a literal Escape key event.
const PARSER_TIMEOUT_GRACE: Duration = Duration::from_millis(50);

#[cfg(unix)]
fn raw_mode_snapshot_slot() -> &'static Mutex<Option<nix::sys::termios::Termios>> {
    static SLOT: OnceLock<Mutex<Option<nix::sys::termios::Termios>>> = OnceLock::new();
    SLOT.get_or_init(|| Mutex::new(None))
}

#[cfg(unix)]
fn store_raw_mode_snapshot(termios: &nix::sys::termios::Termios) {
    let slot = raw_mode_snapshot_slot();
    let mut guard = slot.lock().unwrap_or_else(|poison| poison.into_inner());
    *guard = Some(termios.clone());
}

#[cfg(unix)]
fn clear_raw_mode_snapshot() {
    let slot = raw_mode_snapshot_slot();
    let mut guard = slot.lock().unwrap_or_else(|poison| poison.into_inner());
    *guard = None;
}

#[cfg(unix)]
fn restore_raw_mode_snapshot() {
    let slot = raw_mode_snapshot_slot();
    let snapshot = {
        let guard = slot.lock().unwrap_or_else(|poison| poison.into_inner());
        guard.clone()
    };

    let Some(original) = snapshot else {
        return;
    };

    let Ok(tty) = std::fs::File::open("/dev/tty") else {
        return;
    };
    let _ = nix::sys::termios::tcsetattr(&tty, nix::sys::termios::SetArg::TCSAFLUSH, &original);
}

#[inline]
const fn cleanup_features_for_capabilities(capabilities: TerminalCapabilities) -> BackendFeatures {
    BackendFeatures {
        mouse_capture: capabilities.mouse_sgr,
        bracketed_paste: capabilities.bracketed_paste,
        focus_events: capabilities.focus_events && !capabilities.in_any_mux(),
        kitty_keyboard: capabilities.kitty_keyboard && !capabilities.in_any_mux(),
    }
}

#[cfg(unix)]
fn write_terminal_state_resets(writer: &mut impl Write) -> io::Result<()> {
    writer.write_all(RESET_SCROLL_REGION)?;
    writer.write_all(SGR_RESET)?;
    Ok(())
}

#[cfg(unix)]
fn best_effort_termination_cleanup() {
    let mut stdout = io::stdout();
    let caps = TerminalCapabilities::with_overrides();
    let _ = write_terminal_state_resets(&mut stdout);
    // This path cannot prove ownership of an active sync block; avoid emitting
    // standalone DEC ?2026l during panic/signal cleanup.
    let emit_sync_end = false;
    let features = cleanup_features_for_capabilities(caps);
    let mouse_disable = mouse_disable_sequence_for_capabilities(caps);
    let _ = write_cleanup_sequence_policy_with_mouse(
        &features,
        true,
        emit_sync_end,
        mouse_disable,
        &mut stdout,
    );
    let _ = stdout.flush();
    restore_raw_mode_snapshot();
}

#[cfg(unix)]
fn install_abort_panic_hook() {
    if !cfg!(panic = "abort") {
        return;
    }
    static HOOK: OnceLock<()> = OnceLock::new();
    HOOK.get_or_init(|| {
        let previous = std::panic::take_hook();
        std::panic::set_hook(Box::new(move |info| {
            best_effort_termination_cleanup();
            previous(info);
        }));
    });
}

#[cfg(unix)]
fn install_termination_signal_hook() {
    static HOOK: OnceLock<()> = OnceLock::new();
    HOOK.get_or_init(|| {
        let mut signals = match Signals::new([SIGINT, SIGTERM, SIGHUP, SIGQUIT]) {
            Ok(signals) => signals,
            Err(_) => return,
        };
        let _ = std::thread::Builder::new()
            .name("ftui-tty-term-signal".to_string())
            .spawn(move || {
                for signal in signals.forever() {
                    if LIVE_SIGNAL_INTERCEPT_SESSIONS.load(Ordering::SeqCst) == 0 {
                        std::process::exit(128 + signal);
                    }

                    ftui_core::shutdown_signal::record_pending_termination_signal(signal);
                    best_effort_termination_cleanup();
                    let deadline = std::time::Instant::now()
                        .checked_add(SIGNAL_SHUTDOWN_GRACE)
                        .unwrap_or_else(std::time::Instant::now);
                    loop {
                        if ftui_core::shutdown_signal::pending_termination_signal().is_none() {
                            break;
                        }
                        if std::time::Instant::now() >= deadline {
                            std::process::exit(128 + signal);
                        }
                        std::thread::sleep(SIGNAL_SHUTDOWN_POLL);
                    }
                }
            });
    });
}

// ── Raw Mode Guard ───────────────────────────────────────────────────────

/// RAII guard that saves the original termios and restores it on drop.
///
/// This is the foundation for panic-safe terminal cleanup: even if the
/// application panics, the Drop impl runs (unless `panic = "abort"`) and
/// the terminal returns to its original state.
///
/// The guard opens `/dev/tty` to get an owned fd that is valid for the
/// lifetime of the guard, avoiding unsafe `BorrowedFd` construction.
#[cfg(unix)]
pub struct RawModeGuard {
    original_termios: nix::sys::termios::Termios,
    tty: std::fs::File,
}

#[cfg(unix)]
impl RawModeGuard {
    /// Enter raw mode on the controlling terminal, returning a guard that
    /// restores the original termios on drop.
    pub fn enter() -> io::Result<Self> {
        let tty = std::fs::File::open("/dev/tty")?;
        Self::enter_on(tty)
    }

    /// Enter raw mode on a specific terminal file (e.g., a PTY slave for testing).
    pub fn enter_on(tty: std::fs::File) -> io::Result<Self> {
        let original_termios = nix::sys::termios::tcgetattr(&tty).map_err(io::Error::other)?;

        let mut raw = original_termios.clone();
        nix::sys::termios::cfmakeraw(&mut raw);
        nix::sys::termios::tcsetattr(&tty, nix::sys::termios::SetArg::TCSAFLUSH, &raw)
            .map_err(io::Error::other)?;

        store_raw_mode_snapshot(&original_termios);

        Ok(Self {
            original_termios,
            tty,
        })
    }
}

#[cfg(unix)]
impl Drop for RawModeGuard {
    fn drop(&mut self) {
        // Best-effort restore — ignore errors during cleanup.
        let _ = nix::sys::termios::tcsetattr(
            &self.tty,
            nix::sys::termios::SetArg::TCSAFLUSH,
            &self.original_termios,
        );
        clear_raw_mode_snapshot();
    }
}

// ── Session Options ──────────────────────────────────────────────────────

/// Configuration for opening a terminal session.
#[derive(Debug, Clone)]
pub struct TtySessionOptions {
    /// Enter the alternate screen buffer on open.
    pub alternate_screen: bool,
    /// Initial feature toggles to enable.
    pub features: BackendFeatures,
    /// Install a signal handler to restore terminal state on SIGINT/SIGTERM/SIGHUP.
    pub intercept_signals: bool,
}

impl Default for TtySessionOptions {
    fn default() -> Self {
        Self {
            alternate_screen: false,
            features: BackendFeatures::default(),
            intercept_signals: true,
        }
    }
}

// ── Clock ────────────────────────────────────────────────────────────────

/// Monotonic clock backed by `std::time::Instant`.
pub struct TtyClock {
    epoch: std::time::Instant,
}

impl TtyClock {
    #[must_use]
    pub fn new() -> Self {
        Self {
            epoch: std::time::Instant::now(),
        }
    }
}

impl Default for TtyClock {
    fn default() -> Self {
        Self::new()
    }
}

impl BackendClock for TtyClock {
    fn now_mono(&self) -> Duration {
        self.epoch.elapsed()
    }
}

// ── Event Source ──────────────────────────────────────────────────────────

// Resize notifications are produced via SIGWINCH on Unix.
//
// We use a dedicated signal thread to avoid unsafe `sigaction` calls in-tree
// (unsafe is forbidden) while still delivering low-latency resize events.
#[cfg(unix)]
#[derive(Debug)]
struct ResizeSignalGuard {
    handle: signal_hook::iterator::Handle,
    thread: Option<std::thread::JoinHandle<()>>,
}

#[cfg(unix)]
impl ResizeSignalGuard {
    fn new(mut wake_writer: UnixStream) -> io::Result<Self> {
        wake_writer.set_nonblocking(true)?;
        let mut signals = Signals::new([SIGWINCH]).map_err(io::Error::other)?;
        let handle = signals.handle();
        let thread = std::thread::spawn(move || {
            let pulse = [1u8; 1];
            for _ in signals.forever() {
                match wake_writer.write(&pulse) {
                    // The read side coalesces by draining all pending bytes before
                    // querying winsize, so any successful wake byte is enough.
                    Ok(_) => {}
                    Err(err)
                        if matches!(
                            err.kind(),
                            io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted
                        ) => {}
                    Err(_) => break,
                }
            }
        });

        Ok(Self {
            handle,
            thread: Some(thread),
        })
    }
}

#[cfg(unix)]
impl Drop for ResizeSignalGuard {
    fn drop(&mut self) {
        self.handle.close();
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
    }
}

/// Native Unix event source (raw terminal bytes → `Event`).
///
/// Manages terminal feature toggles by emitting the appropriate escape
/// sequences. Reads raw bytes from the tty fd, feeds them through
/// `InputParser`, and serves parsed events via `poll_event`/`read_event`.
pub struct TtyEventSource {
    features: BackendFeatures,
    capabilities: TerminalCapabilities,
    width: u16,
    height: u16,
    /// Terminal pixel width reported by `TIOCGWINSZ` (0 if unavailable).
    pixel_width: u16,
    /// Terminal pixel height reported by `TIOCGWINSZ` (0 if unavailable).
    pixel_height: u16,
    /// Sticky detector for SGR-pixel mouse leakage (1016-style coordinates).
    ///
    /// Once we observe pixel-like coordinates, normalize subsequent mouse
    /// reports in this capture session so low-column clicks also map correctly.
    mouse_coords_pixels: bool,
    /// Inferred pixel width when `TIOCGWINSZ.ws_xpixel` is unavailable.
    ///
    /// Some terminals emit pixel-space SGR coordinates but report zero
    /// pixel geometry via winsize. Track observed maxima so we can project
    /// coordinates back into cells instead of clamping everything to edges.
    inferred_pixel_width: u16,
    /// Inferred pixel height when `TIOCGWINSZ.ws_ypixel` is unavailable.
    inferred_pixel_height: u16,
    /// When true, escape sequences are actually written to stdout.
    /// False in test/headless mode.
    live: bool,
    /// Read end of the resize wake stream.
    ///
    /// The SIGWINCH listener thread writes a byte here so the event loop can
    /// block in `poll(2)` until a resize actually happens.
    #[cfg(unix)]
    resize_reader: Option<UnixStream>,
    /// Owns the SIGWINCH handler thread (kept alive by this field).
    #[cfg(unix)]
    _resize_guard: Option<ResizeSignalGuard>,
    /// Parser state machine: decodes terminal byte sequences into Events.
    parser: InputParser,
    /// Buffered events from the most recent parse.
    event_queue: VecDeque<Event>,
    /// Tty file handle for reading input (None in headless mode).
    tty_reader: Option<std::fs::File>,
    /// True when tty_reader is configured as nonblocking and may be drained in a loop.
    reader_nonblocking: bool,
    /// Monotonic timestamp of the most recent byte read from the tty.
    last_input_byte_at: Option<Instant>,
    /// Optional raw input trace sink (env-gated).
    input_trace: Option<InputTrace>,
}

impl TtyEventSource {
    /// Create an event source in headless mode (no escape sequence output, no I/O).
    #[must_use]
    pub fn new(width: u16, height: u16) -> Self {
        Self {
            features: BackendFeatures::default(),
            capabilities: TerminalCapabilities::basic(),
            width,
            height,
            pixel_width: 0,
            pixel_height: 0,
            mouse_coords_pixels: false,
            inferred_pixel_width: 0,
            inferred_pixel_height: 0,
            live: false,
            #[cfg(unix)]
            resize_reader: None,
            #[cfg(unix)]
            _resize_guard: None,
            parser: InputParser::new(),
            event_queue: VecDeque::new(),
            tty_reader: None,
            reader_nonblocking: false,
            last_input_byte_at: None,
            input_trace: None,
        }
    }

    /// Create an event source in live mode (reads from /dev/tty, writes
    /// escape sequences to stdout).
    fn live(width: u16, height: u16, capabilities: TerminalCapabilities) -> io::Result<Self> {
        let tty_reader = std::fs::File::open("/dev/tty")?;
        let reader_nonblocking = Self::try_enable_nonblocking(&tty_reader);
        let mut w = width;
        let mut h = height;
        let mut pw = 0;
        let mut ph = 0;
        #[cfg(unix)]
        if let Ok(ws) = rustix::termios::tcgetwinsize(&tty_reader) {
            if ws.ws_col > 0 && ws.ws_row > 0 {
                w = ws.ws_col;
                h = ws.ws_row;
            }
            pw = ws.ws_xpixel;
            ph = ws.ws_ypixel;
        }

        #[cfg(unix)]
        let (resize_guard, resize_reader) = match UnixStream::pair() {
            Ok((resize_reader, resize_writer)) => {
                if resize_reader.set_nonblocking(true).is_ok() {
                    match ResizeSignalGuard::new(resize_writer) {
                        Ok(guard) => (Some(guard), Some(resize_reader)),
                        Err(_) => (None, None),
                    }
                } else {
                    (None, None)
                }
            }
            Err(_) => (None, None),
        };

        Ok(Self {
            features: BackendFeatures::default(),
            capabilities,
            width: w,
            height: h,
            pixel_width: pw,
            pixel_height: ph,
            mouse_coords_pixels: false,
            inferred_pixel_width: 0,
            inferred_pixel_height: 0,
            live: true,
            #[cfg(unix)]
            resize_reader,
            #[cfg(unix)]
            _resize_guard: resize_guard,
            parser: InputParser::new(),
            event_queue: VecDeque::new(),
            tty_reader: Some(tty_reader),
            reader_nonblocking,
            last_input_byte_at: None,
            input_trace: InputTrace::from_env(),
        })
    }

    /// Create an event source that reads from an arbitrary file descriptor.
    ///
    /// Escape sequences are NOT written to stdout (headless feature toggle
    /// behavior). This is primarily useful for testing with pipes.
    #[cfg(test)]
    fn from_reader(width: u16, height: u16, reader: std::fs::File) -> Self {
        let reader_nonblocking = Self::try_enable_nonblocking(&reader);
        Self {
            features: BackendFeatures::default(),
            capabilities: TerminalCapabilities::basic(),
            width,
            height,
            pixel_width: 0,
            pixel_height: 0,
            mouse_coords_pixels: false,
            inferred_pixel_width: 0,
            inferred_pixel_height: 0,
            live: false,
            #[cfg(unix)]
            resize_reader: None,
            #[cfg(unix)]
            _resize_guard: None,
            parser: InputParser::new(),
            event_queue: VecDeque::new(),
            tty_reader: Some(reader),
            reader_nonblocking,
            last_input_byte_at: None,
            input_trace: None,
        }
    }

    #[cfg(unix)]
    fn try_enable_nonblocking(reader: &std::fs::File) -> bool {
        use rustix::fs::{OFlags, fcntl_getfl, fcntl_setfl};

        let Ok(flags) = fcntl_getfl(reader) else {
            return false;
        };
        if flags.contains(OFlags::NONBLOCK) {
            return true;
        }
        fcntl_setfl(reader, flags | OFlags::NONBLOCK).is_ok()
    }

    #[cfg(not(unix))]
    fn try_enable_nonblocking(_reader: &std::fs::File) -> bool {
        false
    }

    /// Current feature state.
    #[must_use]
    pub fn features(&self) -> BackendFeatures {
        self.features
    }

    #[inline]
    fn sanitize_features(&self, requested: BackendFeatures) -> BackendFeatures {
        if !self.live {
            return requested;
        }
        sanitize_feature_request(requested, self.capabilities)
    }

    /// Apply feature state to internal parser/runtime flags without emitting
    /// terminal escape sequences.
    ///
    /// Keep both legacy mouse fallbacks enabled whenever mouse capture is on.
    ///
    /// Some terminals/mux stacks (notably Ghostty edge cases) can fall back to
    /// raw X10 `CSI M cb cx cy` packets despite SGR mode negotiation. We keep
    /// numeric legacy and X10 parsing active while capture is enabled so these
    /// sessions remain interactive.
    fn apply_feature_state(&mut self, features: BackendFeatures) {
        self.features = features;
        if !features.mouse_capture {
            self.mouse_coords_pixels = false;
            self.inferred_pixel_width = 0;
            self.inferred_pixel_height = 0;
        }
        self.parser.set_expect_x10_mouse(features.mouse_capture);
        // Always allow numeric legacy mouse fallback when capture is enabled.
        // Some terminals/muxes may ignore SGR mode requests in edge cases.
        self.parser.set_allow_legacy_mouse(features.mouse_capture);
    }

    fn push_resize(&mut self, new_width: u16, new_height: u16) {
        if new_width == 0 || new_height == 0 {
            return;
        }
        if (new_width, new_height) == (self.width, self.height) {
            return;
        }
        self.width = new_width;
        self.height = new_height;
        // Reset sticky pixel detection on resize.
        // If we previously entered pixel mode due to a resize race (clicks appearing "outside"
        // the old small bounds), we must give the terminal a chance to prove it's using
        // cells again against the new bounds.
        self.mouse_coords_pixels = false;
        self.inferred_pixel_width = 0;
        self.inferred_pixel_height = 0;
        self.event_queue.push_back(Event::Resize {
            width: new_width,
            height: new_height,
        });
    }

    /// Normalize mouse coordinates when terminals report SGR-pixel coordinates
    /// despite requesting cell mode.
    ///
    /// Some emulators can leak pixel-space coordinates (`1016h`) in mixed
    /// environments. If we detect obviously pixel-scale values and have tty
    /// pixel dimensions, project them back into the cell grid.
    fn normalize_event(&mut self, event: Event) -> Event {
        let Event::Mouse(mut mouse) = event else {
            return event;
        };

        let outside_grid = mouse.x >= self.width || mouse.y >= self.height;
        // Heuristic: Pixel coordinates are typically much larger than cell coordinates.
        // We use `width * 2` to scale with window size, but also enforce a static minimum (600)
        // to prevent false positives on wide terminals during resize races (e.g. clicking at
        // col 170 when internal width is still 80).
        let strongly_outside = (mouse.x >= self.width.saturating_mul(2)
            || mouse.y >= self.height.saturating_mul(2))
            && (mouse.x > 600 || mouse.y > 400);

        if !self.mouse_coords_pixels && strongly_outside {
            self.mouse_coords_pixels = true;
        }
        let likely_pixel_space = self.mouse_coords_pixels || strongly_outside;
        if !self.features.mouse_capture || !self.capabilities.mouse_sgr {
            return Event::Mouse(mouse);
        }
        if !likely_pixel_space {
            // Minor out-of-grid events happen at viewport edges in some terminals.
            // Clamp to valid cell coordinates but avoid arming sticky pixel mode.
            if outside_grid {
                mouse.x = mouse.x.min(self.width.saturating_sub(1));
                mouse.y = mouse.y.min(self.height.saturating_sub(1));
            }
            return Event::Mouse(mouse);
        }

        if self.width == 0 || self.height == 0 {
            return Event::Mouse(mouse);
        }
        if self.pixel_width > 0 && self.pixel_height > 0 {
            mouse.x = Self::scale_mouse_coord(mouse.x, self.width, self.pixel_width);
            mouse.y = Self::scale_mouse_coord(mouse.y, self.height, self.pixel_height);
        } else {
            // Fallback when winsize pixel dimensions are unavailable:
            // seed with conservative per-cell estimates so the first event does
            // not collapse toward viewport edges, then expand from observations.
            if self.inferred_pixel_width == 0 {
                self.inferred_pixel_width = self
                    .width
                    .saturating_mul(INFERRED_PIXEL_WIDTH_PER_CELL)
                    .max(self.width);
            }
            if self.inferred_pixel_height == 0 {
                self.inferred_pixel_height = self
                    .height
                    .saturating_mul(INFERRED_PIXEL_HEIGHT_PER_CELL)
                    .max(self.height);
            }
            self.inferred_pixel_width = self
                .inferred_pixel_width
                .max(mouse.x.saturating_add(1))
                .max(self.width);
            self.inferred_pixel_height = self
                .inferred_pixel_height
                .max(mouse.y.saturating_add(1))
                .max(self.height);

            mouse.x =
                Self::scale_mouse_coord(mouse.x, self.width, self.inferred_pixel_width.max(1));
            mouse.y =
                Self::scale_mouse_coord(mouse.y, self.height, self.inferred_pixel_height.max(1));
        }
        Event::Mouse(mouse)
    }

    #[inline]
    fn scale_mouse_coord(coord: u16, cells: u16, pixels: u16) -> u16 {
        if cells <= 1 {
            return 0;
        }
        if pixels <= 1 {
            return coord.min(cells.saturating_sub(1));
        }

        let num = u32::from(coord).saturating_mul(u32::from(cells.saturating_sub(1)));
        let den = u32::from(pixels.saturating_sub(1));
        let scaled = num / den.max(1);
        let scaled_u16 = u16::try_from(scaled).unwrap_or(u16::MAX);
        scaled_u16.min(cells.saturating_sub(1))
    }

    #[cfg(unix)]
    fn query_tty_winsize(&self) -> Option<rustix::termios::Winsize> {
        if !self.live {
            return None;
        }
        let tty = self.tty_reader.as_ref()?;
        rustix::termios::tcgetwinsize(tty).ok()
    }

    #[cfg(unix)]
    fn query_tty_size(&self) -> Option<(u16, u16)> {
        let ws = self.query_tty_winsize()?;
        if ws.ws_col == 0 || ws.ws_row == 0 {
            return None;
        }
        Some((ws.ws_col, ws.ws_row))
    }

    #[cfg(unix)]
    fn drain_resize_wake_bytes(&mut self) -> bool {
        let Some(reader) = self.resize_reader.as_mut() else {
            return false;
        };
        let mut any = false;
        let mut retire_reader = false;
        let mut buf = [0u8; 64];
        loop {
            match reader.read(&mut buf) {
                Ok(0) => {
                    retire_reader = true;
                    break;
                }
                Ok(_) => any = true,
                Err(err) if err.kind() == io::ErrorKind::WouldBlock => break,
                Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
                Err(_) => {
                    retire_reader = true;
                    break;
                }
            }
        }
        if retire_reader {
            self.resize_reader = None;
        }
        any
    }

    #[cfg(unix)]
    fn drain_resize_notifications(&mut self) {
        if !self.live {
            return;
        }
        // Drain all pending SIGWINCH notifications, coalescing into a single
        // resize query (the authoritative size comes from ioctl, not the signal).
        let got_resize = self.drain_resize_wake_bytes();
        if got_resize && let Some(ws) = self.query_tty_winsize() {
            self.pixel_width = ws.ws_xpixel;
            self.pixel_height = ws.ws_ypixel;
            if ws.ws_col > 0 && ws.ws_row > 0 {
                self.push_resize(ws.ws_col, ws.ws_row);
            }
        }
    }

    /// Read available bytes from the tty reader and feed them to the parser.
    fn drain_available_bytes(&mut self) -> io::Result<()> {
        if self.tty_reader.is_none() {
            return Ok(());
        }
        let mut buf = [0u8; READ_BUFFER_BYTES];
        let mut drained_bytes = 0usize;
        let mut parsed_events = Vec::new();
        loop {
            let read_result = {
                let Some(tty) = self.tty_reader.as_mut() else {
                    return Ok(());
                };
                tty.read(&mut buf)
            };
            match read_result {
                Ok(0) => {
                    // Treat EOF as terminal source exhaustion. Keeping the fd alive
                    // after a hangup causes future timed polls to wake immediately
                    // on POLLHUP and spin until the outer deadline.
                    self.tty_reader = None;
                    self.reader_nonblocking = false;
                    return Ok(());
                }
                Ok(n) => {
                    self.last_input_byte_at = Some(Instant::now());
                    parsed_events.clear();
                    self.parser
                        .parse_with(&buf[..n], |event| parsed_events.push(event));
                    if let Some(ref mut trace) = self.input_trace {
                        trace.record(&buf[..n], &parsed_events);
                    }
                    for event in parsed_events.drain(..) {
                        let normalized = self.normalize_event(event);
                        self.push_event_coalescing(normalized);
                    }
                    drained_bytes = drained_bytes.saturating_add(n);
                    if !self.reader_nonblocking {
                        return Ok(());
                    }
                    if drained_bytes >= MAX_DRAIN_BYTES_PER_POLL {
                        return Ok(());
                    }
                }
                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => return Ok(()),
                Err(ref e) if e.kind() == io::ErrorKind::Interrupted => continue,
                Err(e) => return Err(e),
            }
        }
    }

    /// Push an event into the queue, coalescing the hottest high-volume event types.
    ///
    /// Some terminals can emit a very high rate of `Moved` events
    /// (trackpad jitter, hover streams). Coalescing consecutive move events keeps
    /// the queue bounded and prevents input storms from starving the render loop.
    fn push_event_coalescing(&mut self, event: Event) {
        if let Event::Mouse(m) = event
            && matches!(m.kind, MouseEventKind::Moved)
            && matches!(
                self.event_queue.back(),
                Some(Event::Mouse(prev)) if matches!(prev.kind, MouseEventKind::Moved)
            )
        {
            let _ = self.event_queue.pop_back();
        }
        self.event_queue.push_back(event);
    }

    #[inline]
    fn parser_timeout_event_if_due(&mut self) -> Option<Event> {
        if !self.parser.has_pending_timeout_state() {
            return None;
        }
        if let Some(last) = self.last_input_byte_at
            && last.elapsed() < PARSER_TIMEOUT_GRACE
        {
            return None;
        }
        let event = self.parser.timeout();
        if event.is_some() {
            self.last_input_byte_at = None;
        }
        event
    }

    #[inline]
    fn parser_timeout_wait_budget(&self) -> Option<Duration> {
        if !self.parser.has_pending_timeout_state() {
            return None;
        }
        Some(
            self.last_input_byte_at
                .map(|last| PARSER_TIMEOUT_GRACE.saturating_sub(last.elapsed()))
                .unwrap_or(Duration::ZERO),
        )
    }

    /// Give immediately ready bytes one last chance to complete an ambiguous
    /// parser state before synthesizing a timeout event.
    fn drain_ready_bytes_before_parser_timeout(&mut self) -> io::Result<bool> {
        if self.tty_reader.is_none() {
            return Ok(false);
        }
        if self.reader_nonblocking {
            self.drain_available_bytes()?;
        } else {
            let _ = self.poll_tty(Duration::ZERO)?;
        }
        Ok(!self.event_queue.is_empty())
    }

    /// Poll the tty fd for available data using `poll(2)`.
    ///
    /// On macOS, `poll(2)` on `/dev/tty` always returns `POLLNVAL` even though
    /// the fd is valid for `open()`, `fcntl()`, and nonblocking `read()`.  When
    /// this happens we fall back to a nonblocking `drain_available_bytes()` call
    /// (if the reader is in nonblocking mode) so that input still works.  A
    /// short backoff sleep prevents a tight spin loop.
    #[cfg(unix)]
    fn poll_tty(&mut self, timeout: Duration) -> io::Result<bool> {
        use std::os::fd::AsFd;

        /// Backoff sleep when poll(2) reports POLLNVAL (macOS /dev/tty).
        const TTY_UNAVAILABLE_BACKOFF: Duration = Duration::from_millis(8);

        let (tty_ready, tty_unavailable, resize_ready) = {
            let Some(ref tty) = self.tty_reader else {
                return Ok(false);
            };
            let mut poll_fds = Vec::with_capacity(2);
            poll_fds.push(nix::poll::PollFd::new(
                tty.as_fd(),
                nix::poll::PollFlags::POLLIN,
            ));
            let resize_index = if let Some(ref resize_reader) = self.resize_reader {
                poll_fds.push(nix::poll::PollFd::new(
                    resize_reader.as_fd(),
                    nix::poll::PollFlags::POLLIN,
                ));
                Some(1usize)
            } else {
                None
            };
            // Use i32 for timeout to allow values > 65s (up to ~24 days).
            // poll(2) takes milliseconds as a signed int.
            let timeout_ms: i32 = timeout.as_millis().try_into().unwrap_or(i32::MAX);
            let _ = match nix::poll::poll(
                &mut poll_fds,
                nix::poll::PollTimeout::try_from(timeout_ms).unwrap_or(nix::poll::PollTimeout::MAX),
            ) {
                Ok(n) => n,
                Err(nix::errno::Errno::EINTR) => return Ok(false),
                Err(e) => return Err(io::Error::other(e)),
            };
            let tty_revents = poll_fds.first().and_then(nix::poll::PollFd::revents);
            let tty_ready = tty_revents.is_some_and(|revents| {
                revents.intersects(
                    nix::poll::PollFlags::POLLIN
                        | nix::poll::PollFlags::POLLERR
                        | nix::poll::PollFlags::POLLHUP,
                )
            });
            let tty_unavailable = tty_revents
                .is_some_and(|revents| revents.intersects(nix::poll::PollFlags::POLLNVAL));
            let resize_ready = resize_index
                .and_then(|idx| poll_fds.get(idx))
                .and_then(nix::poll::PollFd::revents)
                .is_some_and(|revents| {
                    revents.intersects(
                        nix::poll::PollFlags::POLLIN
                            | nix::poll::PollFlags::POLLERR
                            | nix::poll::PollFlags::POLLHUP,
                    )
                });
            (tty_ready, tty_unavailable, resize_ready)
        };
        if tty_ready {
            self.drain_available_bytes()?;
        } else if tty_unavailable {
            // macOS: /dev/tty doesn't support poll(2) and always returns
            // POLLNVAL, but the fd is valid for nonblocking reads.
            if self.reader_nonblocking {
                self.drain_available_bytes()?;
            }
            // Always process resize even on the POLLNVAL path — the resize
            // fd is a UnixStream, not /dev/tty, so poll(2) works fine on it.
            if resize_ready {
                self.drain_resize_notifications();
            }
            if !self.event_queue.is_empty() {
                return Ok(true);
            }
            if timeout != Duration::ZERO {
                std::thread::sleep(timeout.min(TTY_UNAVAILABLE_BACKOFF));
            }
            return Ok(!self.event_queue.is_empty());
        }
        if resize_ready {
            self.drain_resize_notifications();
        }
        Ok(!self.event_queue.is_empty())
    }

    /// Stub for non-Unix platforms.
    #[cfg(not(unix))]
    fn poll_tty(&mut self, _timeout: Duration) -> io::Result<bool> {
        Ok(false)
    }

    /// Write the escape sequences needed to transition from current to new features.
    fn write_feature_delta(
        current: &BackendFeatures,
        new: &BackendFeatures,
        capabilities: TerminalCapabilities,
        writer: &mut impl Write,
    ) -> io::Result<()> {
        let mouse_enable_seq = mouse_enable_sequence_for_capabilities(capabilities);
        let mouse_disable_seq = mouse_disable_sequence_for_capabilities(capabilities);
        Self::write_feature_delta_with_mouse(
            current,
            new,
            mouse_enable_seq,
            mouse_disable_seq,
            writer,
        )
    }

    fn write_feature_delta_with_mouse(
        current: &BackendFeatures,
        new: &BackendFeatures,
        mouse_enable_seq: &[u8],
        mouse_disable_seq: &[u8],
        writer: &mut impl Write,
    ) -> io::Result<()> {
        if new.mouse_capture != current.mouse_capture {
            writer.write_all(if new.mouse_capture {
                mouse_enable_seq
            } else {
                mouse_disable_seq
            })?;
        }
        if new.bracketed_paste != current.bracketed_paste {
            writer.write_all(if new.bracketed_paste {
                BRACKETED_PASTE_ENABLE
            } else {
                BRACKETED_PASTE_DISABLE
            })?;
        }
        if new.focus_events != current.focus_events {
            writer.write_all(if new.focus_events {
                FOCUS_ENABLE
            } else {
                FOCUS_DISABLE
            })?;
        }
        if new.kitty_keyboard != current.kitty_keyboard {
            writer.write_all(if new.kitty_keyboard {
                KITTY_KEYBOARD_ENABLE
            } else {
                KITTY_KEYBOARD_DISABLE
            })?;
        }
        Ok(())
    }

    /// Disable all active features, writing escape sequences to `writer`.
    fn disable_all(&mut self, writer: &mut impl Write) -> io::Result<()> {
        let off = BackendFeatures::default();
        Self::write_feature_delta(&self.features, &off, self.capabilities, writer)?;
        self.apply_feature_state(off);
        Ok(())
    }
}

impl BackendEventSource for TtyEventSource {
    type Error = io::Error;

    fn size(&self) -> Result<(u16, u16), Self::Error> {
        #[cfg(unix)]
        if let Some((w, h)) = self.query_tty_size() {
            return Ok((w, h));
        }
        Ok((self.width, self.height))
    }

    fn set_features(&mut self, features: BackendFeatures) -> Result<(), Self::Error> {
        let effective_features = self.sanitize_features(features);
        if self.live {
            let mut stdout = io::stdout();
            if let Err(err) = Self::write_feature_delta(
                &self.features,
                &effective_features,
                self.capabilities,
                &mut stdout,
            )
            .and_then(|_| stdout.flush())
            {
                // A failed write can still partially apply terminal modes.
                // Track a conservative superset so drop-time cleanup disables
                // anything that might have been enabled before the error.
                self.apply_feature_state(conservative_feature_union(
                    self.features,
                    effective_features,
                ));
                return Err(err);
            }
        }
        self.apply_feature_state(effective_features);
        Ok(())
    }

    fn poll_event(&mut self, timeout: Duration) -> Result<bool, Self::Error> {
        #[cfg(unix)]
        self.drain_resize_notifications();

        // If we already have buffered events, return immediately.
        if !self.event_queue.is_empty() {
            return Ok(true);
        }

        if timeout == Duration::ZERO {
            let ready = self.poll_tty(Duration::ZERO)?;
            if !ready && self.drain_ready_bytes_before_parser_timeout()? {
                return Ok(true);
            }
            if !ready && let Some(event) = self.parser_timeout_event_if_due() {
                self.event_queue.push_back(event);
                return Ok(true);
            }
            return Ok(!self.event_queue.is_empty());
        }

        let deadline = std::time::Instant::now()
            .checked_add(timeout)
            .unwrap_or_else(std::time::Instant::now);

        loop {
            if !self.event_queue.is_empty() {
                return Ok(true);
            }

            if self.tty_reader.is_none() && !self.parser.has_pending_timeout_state() {
                return Ok(false);
            }

            if self.parser.has_pending_timeout_state() {
                if self.drain_ready_bytes_before_parser_timeout()? {
                    return Ok(true);
                }
                if let Some(event) = self.parser_timeout_event_if_due() {
                    self.event_queue.push_back(event);
                    return Ok(true);
                }
            }

            let now = std::time::Instant::now();
            if now >= deadline {
                return Ok(false);
            }

            let mut poll_for = deadline.saturating_duration_since(now);
            if let Some(parser_wait_budget) = self.parser_timeout_wait_budget() {
                poll_for = poll_for.min(parser_wait_budget);
            }

            let _ = self.poll_tty(poll_for)?;
            #[cfg(unix)]
            self.drain_resize_notifications();
        }
    }

    fn read_event(&mut self) -> Result<Option<Event>, Self::Error> {
        if let Some(event) = self.event_queue.pop_front() {
            return Ok(Some(event));
        }

        #[cfg(unix)]
        {
            self.drain_resize_notifications();
            if let Some(event) = self.event_queue.pop_front() {
                return Ok(Some(event));
            }
        }

        // Opportunistically drain any newly-arrived bytes when the reader is nonblocking.
        //
        // This reduces poll(2) syscalls in bursty workloads by allowing the consumer's
        // `while let Some(e) = read_event()` drain loop to pick up additional input
        // without requiring another `poll_event()` round-trip.
        if self.drain_ready_bytes_before_parser_timeout()?
            && let Some(event) = self.event_queue.pop_front()
        {
            return Ok(Some(event));
        }

        Ok(self.parser_timeout_event_if_due())
    }
}

// ── Presenter ────────────────────────────────────────────────────────────

/// Native ANSI presenter (Buffer → escape sequences → stdout).
///
/// Wraps `ftui_render::presenter::Presenter<W>` for real ANSI output.
/// In headless mode (`inner = None`), all operations are no-ops.
pub struct TtyPresenter<W: Write + Send = io::Stdout> {
    capabilities: TerminalCapabilities,
    inner: Option<Presenter<W>>,
}

impl TtyPresenter {
    /// Create a headless presenter (no output). Used for tests and headless backends.
    #[must_use]
    pub fn new(capabilities: TerminalCapabilities) -> Self {
        Self {
            capabilities,
            inner: None,
        }
    }

    /// Create a live presenter that writes ANSI escape sequences to stdout.
    #[must_use]
    pub fn live(capabilities: TerminalCapabilities) -> Self {
        Self {
            capabilities,
            inner: Some(Presenter::new(io::stdout(), capabilities)),
        }
    }
}

impl<W: Write + Send> TtyPresenter<W> {
    /// Create a presenter that writes to an arbitrary `Write` sink.
    pub fn with_writer(writer: W, capabilities: TerminalCapabilities) -> Self {
        Self {
            capabilities,
            inner: Some(Presenter::new(writer, capabilities)),
        }
    }
}

impl<W: Write + Send> BackendPresenter for TtyPresenter<W> {
    type Error = io::Error;

    fn capabilities(&self) -> &TerminalCapabilities {
        &self.capabilities
    }

    fn write_log(&mut self, _text: &str) -> Result<(), Self::Error> {
        // The runtime's terminal path routes logs through `TerminalWriter`, which
        // positions output in the inline scrollback region safely. Emitting from
        // here risks interleaving with UI ANSI output on the same terminal stream.
        // Until this backend owns a dedicated safe log channel, keep this a no-op.
        Ok(())
    }

    fn present_ui(
        &mut self,
        buf: &Buffer,
        diff: Option<&BufferDiff>,
        full_repaint_hint: bool,
    ) -> Result<(), Self::Error> {
        let Some(ref mut presenter) = self.inner else {
            return Ok(());
        };
        if full_repaint_hint {
            let full = BufferDiff::full(buf.width(), buf.height());
            presenter.present(buf, &full)?;
        } else if let Some(diff) = diff {
            presenter.present(buf, diff)?;
        } else {
            let full = BufferDiff::full(buf.width(), buf.height());
            presenter.present(buf, &full)?;
        }
        Ok(())
    }
}

// ── Backend ──────────────────────────────────────────────────────────────

/// Native Unix terminal backend.
///
/// Combines `TtyClock`, `TtyEventSource`, and `TtyPresenter` into a single
/// `Backend` implementation that the ftui runtime can drive.
///
/// When created with [`TtyBackend::open`], the backend enters raw mode and
/// manages the terminal lifecycle via RAII. On drop (including panics),
/// all features are disabled, the cursor is shown, the alt screen is exited,
/// and raw mode is restored — in that order.
///
/// When created with [`TtyBackend::new`] (headless), no terminal I/O occurs.
pub struct TtyBackend {
    // Fields are ordered for correct drop sequence:
    // 1. clock (no cleanup needed)
    // 2. events (feature state tracking)
    // 3. presenter (BufWriter flush on drop; benign — present() always flushes)
    // 4. alt_screen_active (tracked for cleanup)
    // 5. raw_mode — MUST be last: termios is restored after escape sequences
    clock: TtyClock,
    events: TtyEventSource,
    presenter: TtyPresenter,
    alt_screen_active: bool,
    #[cfg(unix)]
    signal_interception_active: bool,
    #[cfg(unix)]
    raw_mode: Option<RawModeGuard>,
}

impl TtyBackend {
    /// Create a headless backend (no terminal I/O). Useful for testing.
    #[must_use]
    pub fn new(width: u16, height: u16) -> Self {
        Self {
            clock: TtyClock::new(),
            events: TtyEventSource::new(width, height),
            presenter: TtyPresenter::new(TerminalCapabilities::detect()),
            alt_screen_active: false,
            #[cfg(unix)]
            signal_interception_active: false,
            #[cfg(unix)]
            raw_mode: None,
        }
    }

    /// Create a headless backend with explicit capabilities.
    #[must_use]
    pub fn with_capabilities(width: u16, height: u16, capabilities: TerminalCapabilities) -> Self {
        Self {
            clock: TtyClock::new(),
            events: TtyEventSource::new(width, height),
            presenter: TtyPresenter::new(capabilities),
            alt_screen_active: false,
            #[cfg(unix)]
            signal_interception_active: false,
            #[cfg(unix)]
            raw_mode: None,
        }
    }

    /// Open a live terminal session: enter raw mode, enable requested features.
    ///
    /// The terminal is fully restored on drop (even during panics, unless
    /// `panic = "abort"`).
    #[cfg(unix)]
    pub fn open(width: u16, height: u16, options: TtySessionOptions) -> io::Result<Self> {
        // Enter raw mode first — if this fails, nothing to clean up.
        let raw_mode = RawModeGuard::enter()?;
        install_abort_panic_hook();
        let mut signal_guard = SignalInterceptGuard::new(options.intercept_signals);
        let capabilities = TerminalCapabilities::with_overrides();
        let requested_features = options.features;
        let effective_features = sanitize_feature_request(requested_features, capabilities);

        let mut stdout = io::stdout();
        let mut alt_screen_active = false;

        // Enable initial features.
        let mut events = TtyEventSource::live(width, height, capabilities)?;
        let setup: io::Result<()> = (|| {
            // Enter alt screen if requested.
            if options.alternate_screen {
                stdout.write_all(ALT_SCREEN_ENTER)?;
                stdout.write_all(CLEAR_SCREEN)?;
                stdout.write_all(CURSOR_HOME)?;
                alt_screen_active = true;
            }

            TtyEventSource::write_feature_delta(
                &BackendFeatures::default(),
                &effective_features,
                capabilities,
                &mut stdout,
            )?;

            stdout.flush()?;
            Ok(())
        })();

        if let Err(err) = setup {
            // Best-effort cleanup: we may have partially enabled features or entered alt screen.
            //
            // No synchronized-output block has been opened during setup, so avoid
            // emitting a standalone DEC ?2026l on this path.
            let mouse_disable_seq = mouse_disable_sequence_for_capabilities(capabilities);
            let _ = write_terminal_state_resets(&mut stdout);
            let _ = write_cleanup_sequence_policy_with_mouse(
                &effective_features,
                options.alternate_screen,
                false,
                mouse_disable_seq,
                &mut stdout,
            );
            let _ = stdout.flush();
            return Err(err);
        }

        events.apply_feature_state(effective_features);

        Ok(Self {
            clock: TtyClock::new(),
            events,
            presenter: TtyPresenter::live(capabilities),
            alt_screen_active,
            signal_interception_active: signal_guard.disarm(),
            raw_mode: Some(raw_mode),
        })
    }

    /// Whether this backend has an active terminal session (raw mode).
    #[must_use]
    pub fn is_live(&self) -> bool {
        #[cfg(unix)]
        {
            self.raw_mode.is_some()
        }
        #[cfg(not(unix))]
        {
            false
        }
    }
}

impl Drop for TtyBackend {
    fn drop(&mut self) {
        // Only run cleanup if we have an active session.
        #[cfg(unix)]
        if self.raw_mode.is_some() {
            let mut stdout = io::stdout();
            let _ = write_terminal_state_resets(&mut stdout);

            // Disable features in reverse order of typical enable.
            let _ = self.events.disable_all(&mut stdout);

            // Always show cursor.
            let _ = stdout.write_all(CURSOR_SHOW);

            // Leave alt screen.
            if self.alt_screen_active {
                let _ = stdout.write_all(ALT_SCREEN_LEAVE);
                self.alt_screen_active = false;
            }

            // Flush everything before RawModeGuard restores termios.
            let _ = stdout.flush();

            if self.signal_interception_active {
                LIVE_SIGNAL_INTERCEPT_SESSIONS.fetch_sub(1, Ordering::SeqCst);
                self.signal_interception_active = false;
            }

            // RawModeGuard::drop() runs after this, restoring original termios.
        }
    }
}

/// Allow `TtyBackend` to be used directly as a `BackendEventSource` in
/// `Program<M, TtyBackend, W>`.  Delegates to the inner `TtyEventSource`.
/// This is the primary integration point: the runtime owns a `TtyBackend`
/// as its event source, which also provides RAII terminal cleanup on drop.
impl BackendEventSource for TtyBackend {
    type Error = io::Error;

    fn size(&self) -> Result<(u16, u16), io::Error> {
        self.events.size()
    }

    fn set_features(&mut self, features: BackendFeatures) -> Result<(), io::Error> {
        self.events.set_features(features)
    }

    fn poll_event(&mut self, timeout: Duration) -> Result<bool, io::Error> {
        self.events.poll_event(timeout)
    }

    fn read_event(&mut self) -> Result<Option<Event>, io::Error> {
        self.events.read_event()
    }
}

impl Backend for TtyBackend {
    type Error = io::Error;
    type Clock = TtyClock;
    type Events = TtyEventSource;
    type Presenter = TtyPresenter;

    fn clock(&self) -> &Self::Clock {
        &self.clock
    }

    fn events(&mut self) -> &mut Self::Events {
        &mut self.events
    }

    fn presenter(&mut self) -> &mut Self::Presenter {
        &mut self.presenter
    }
}

// ── Utility: write cleanup sequence to a byte buffer (for testing) ───────

/// Write the full cleanup sequence for the given feature state to `writer`.
///
/// This is useful for verifying cleanup in PTY tests without needing
/// a real terminal session. By default this omits DEC ?2026l because no
/// synchronized-output ownership is implied by this utility API.
pub fn write_cleanup_sequence(
    features: &BackendFeatures,
    alt_screen: bool,
    writer: &mut impl Write,
) -> io::Result<()> {
    write_cleanup_sequence_policy(features, alt_screen, false, writer)
}

/// Write cleanup with an explicit DEC ?2026l prefix.
///
/// Use this only when the caller owns a matching synchronized-output begin.
pub fn write_cleanup_sequence_with_sync_end(
    features: &BackendFeatures,
    alt_screen: bool,
    writer: &mut impl Write,
) -> io::Result<()> {
    write_cleanup_sequence_policy(features, alt_screen, true, writer)
}

fn write_cleanup_sequence_policy(
    features: &BackendFeatures,
    alt_screen: bool,
    emit_sync_end: bool,
    writer: &mut impl Write,
) -> io::Result<()> {
    write_cleanup_sequence_policy_with_mouse(
        features,
        alt_screen,
        emit_sync_end,
        MOUSE_DISABLE,
        writer,
    )
}

fn write_cleanup_sequence_policy_with_mouse(
    features: &BackendFeatures,
    alt_screen: bool,
    emit_sync_end: bool,
    mouse_disable_seq: &[u8],
    writer: &mut impl Write,
) -> io::Result<()> {
    if emit_sync_end {
        writer.write_all(SYNC_END)?;
    }
    // Disable features in reverse order.
    if features.kitty_keyboard {
        writer.write_all(KITTY_KEYBOARD_DISABLE)?;
    }
    if features.focus_events {
        writer.write_all(FOCUS_DISABLE)?;
    }
    if features.bracketed_paste {
        writer.write_all(BRACKETED_PASTE_DISABLE)?;
    }
    if features.mouse_capture {
        writer.write_all(mouse_disable_seq)?;
    }
    writer.write_all(CURSOR_SHOW)?;
    if alt_screen {
        writer.write_all(ALT_SCREEN_LEAVE)?;
    }
    Ok(())
}

// ── Tests ────────────────────────────────────────────────────────────────

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

    #[test]
    fn clock_is_monotonic() {
        let clock = TtyClock::new();
        let t1 = clock.now_mono();
        std::hint::black_box(0..1000).for_each(|_| {});
        let t2 = clock.now_mono();
        assert!(t2 >= t1, "clock must be monotonic");
    }

    #[test]
    fn event_source_reports_size() {
        let src = TtyEventSource::new(80, 24);
        let (w, h) = src.size().unwrap();
        assert_eq!(w, 80);
        assert_eq!(h, 24);
    }

    #[test]
    fn event_source_set_features_headless() {
        let mut src = TtyEventSource::new(80, 24);
        let features = BackendFeatures {
            mouse_capture: true,
            bracketed_paste: true,
            focus_events: false,
            kitty_keyboard: false,
        };
        src.set_features(features).unwrap();
        assert_eq!(src.features(), features);
    }

    #[test]
    fn poll_returns_false_headless() {
        let mut src = TtyEventSource::new(80, 24);
        assert!(!src.poll_event(Duration::from_millis(0)).unwrap());
    }

    #[test]
    fn read_returns_none_headless() {
        let mut src = TtyEventSource::new(80, 24);
        assert!(src.read_event().unwrap().is_none());
    }

    #[test]
    fn push_resize_enqueues_event_and_updates_size() {
        let mut src = TtyEventSource::new(80, 24);
        src.push_resize(120, 40);
        assert_eq!(src.size().unwrap(), (120, 40));
        assert_eq!(
            src.read_event().unwrap(),
            Some(Event::Resize {
                width: 120,
                height: 40,
            })
        );
        assert!(src.read_event().unwrap().is_none());
    }

    #[test]
    fn push_resize_deduplicates_same_size() {
        let mut src = TtyEventSource::new(80, 24);
        src.push_resize(80, 24);
        assert!(src.event_queue.is_empty(), "no event when size unchanged");
    }

    #[test]
    fn push_resize_ignores_zero_dimensions() {
        let mut src = TtyEventSource::new(80, 24);
        src.push_resize(0, 24);
        assert!(src.event_queue.is_empty());
        src.push_resize(80, 0);
        assert!(src.event_queue.is_empty());
        src.push_resize(0, 0);
        assert!(src.event_queue.is_empty());
    }

    #[test]
    fn resize_storm_coalesces_and_no_panic() {
        let mut src = TtyEventSource::new(80, 24);
        // Simulate a rapid resize storm: 1000 identical resize signals.
        for _ in 0..1000 {
            src.push_resize(120, 40);
        }
        // First push changes 80x24→120x40, rest are deduped.
        assert_eq!(src.event_queue.len(), 1);
        assert_eq!(
            src.event_queue.pop_front().unwrap(),
            Event::Resize {
                width: 120,
                height: 40,
            }
        );
    }

    #[test]
    fn resize_storm_varied_sizes_no_panic() {
        let mut src = TtyEventSource::new(80, 24);
        // Rapidly varying sizes — all should produce events.
        for i in 1..=500u16 {
            src.push_resize(80 + i, 24 + (i % 50));
        }
        // No panics, events are in order.
        let mut prev_w = 80u16;
        while let Some(Event::Resize { width, .. }) = src.event_queue.pop_front() {
            assert!(
                width > prev_w || width == prev_w + 1 || width != prev_w,
                "events must be in push order"
            );
            prev_w = width;
        }
    }

    // ── Pipe-based input parity tests ─────────────────────────────────

    /// Create a (reader_file, writer_stream) pair using Unix sockets.
    #[cfg(unix)]
    fn pipe_pair() -> (std::fs::File, std::os::unix::net::UnixStream) {
        use std::os::unix::net::UnixStream;
        let (a, b) = UnixStream::pair().unwrap();
        // Convert reader to File via OwnedFd for compatibility with TtyEventSource.
        let reader: std::fs::File = std::os::fd::OwnedFd::from(a).into();
        (reader, b)
    }

    #[cfg(unix)]
    #[test]
    fn pipe_ascii_chars() {
        use ftui_core::event::{KeyCode, KeyEvent, KeyEventKind, Modifiers};
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        writer.write_all(b"abc").unwrap();
        assert!(src.poll_event(Duration::from_millis(100)).unwrap());
        let e1 = src.read_event().unwrap().unwrap();
        assert_eq!(
            e1,
            Event::Key(KeyEvent {
                code: KeyCode::Char('a'),
                modifiers: Modifiers::NONE,
                kind: KeyEventKind::Press,
            })
        );
        let e2 = src.read_event().unwrap().unwrap();
        assert_eq!(
            e2,
            Event::Key(KeyEvent {
                code: KeyCode::Char('b'),
                modifiers: Modifiers::NONE,
                kind: KeyEventKind::Press,
            })
        );
        let e3 = src.read_event().unwrap().unwrap();
        assert_eq!(
            e3,
            Event::Key(KeyEvent {
                code: KeyCode::Char('c'),
                modifiers: Modifiers::NONE,
                kind: KeyEventKind::Press,
            })
        );
        // Queue should now be empty.
        assert!(src.read_event().unwrap().is_none());
    }

    #[cfg(unix)]
    #[test]
    fn pipe_arrow_keys() {
        use ftui_core::event::{KeyCode, KeyEvent};
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        // Up (A), Down (B), Right (C), Left (D)
        writer.write_all(b"\x1b[A\x1b[B\x1b[C\x1b[D").unwrap();
        assert!(src.poll_event(Duration::from_millis(100)).unwrap());
        let codes: Vec<KeyCode> = std::iter::from_fn(|| src.read_event().unwrap())
            .map(|e| match e {
                Event::Key(KeyEvent { code, .. }) => Ok(code),
                other => Err(other),
            })
            .collect::<Result<Vec<_>, _>>()
            .unwrap();
        assert_eq!(
            codes,
            vec![KeyCode::Up, KeyCode::Down, KeyCode::Right, KeyCode::Left]
        );
    }

    #[cfg(unix)]
    #[test]
    fn pipe_ctrl_keys() {
        use ftui_core::event::{KeyCode, KeyEvent, KeyEventKind, Modifiers};
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        // Ctrl+A = 0x01, Ctrl+C = 0x03
        writer.write_all(&[0x01, 0x03]).unwrap();
        assert!(src.poll_event(Duration::from_millis(100)).unwrap());
        let e1 = src.read_event().unwrap().unwrap();
        assert_eq!(
            e1,
            Event::Key(KeyEvent {
                code: KeyCode::Char('a'),
                modifiers: Modifiers::CTRL,
                kind: KeyEventKind::Press,
            })
        );
        let e2 = src.read_event().unwrap().unwrap();
        assert_eq!(
            e2,
            Event::Key(KeyEvent {
                code: KeyCode::Char('c'),
                modifiers: Modifiers::CTRL,
                kind: KeyEventKind::Press,
            })
        );
    }

    #[cfg(unix)]
    #[test]
    fn pipe_function_keys() {
        use ftui_core::event::{KeyCode, KeyEvent, KeyEventKind, Modifiers};
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        // F1 (SS3 P) and F5 (CSI 15~)
        writer.write_all(b"\x1bOP\x1b[15~").unwrap();
        assert!(src.poll_event(Duration::from_millis(100)).unwrap());
        let e1 = src.read_event().unwrap().unwrap();
        assert_eq!(
            e1,
            Event::Key(KeyEvent {
                code: KeyCode::F(1),
                modifiers: Modifiers::NONE,
                kind: KeyEventKind::Press,
            })
        );
        let e2 = src.read_event().unwrap().unwrap();
        assert_eq!(
            e2,
            Event::Key(KeyEvent {
                code: KeyCode::F(5),
                modifiers: Modifiers::NONE,
                kind: KeyEventKind::Press,
            })
        );
    }

    #[cfg(unix)]
    #[test]
    fn pipe_mouse_sgr_click() {
        use ftui_core::event::{Modifiers, MouseButton, MouseEvent, MouseEventKind};
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        // SGR mouse: left click at (10, 20) — 1-indexed in protocol, 0-indexed in Event.
        writer.write_all(b"\x1b[<0;10;20M").unwrap();
        assert!(src.poll_event(Duration::from_millis(100)).unwrap());
        let e = src.read_event().unwrap().unwrap();
        assert_eq!(
            e,
            Event::Mouse(MouseEvent {
                kind: MouseEventKind::Down(MouseButton::Left),
                x: 9,
                y: 19,
                modifiers: Modifiers::NONE,
            })
        );
    }

    #[cfg(unix)]
    #[test]
    fn pipe_mouse_x10_click_when_mouse_capture_enabled() {
        use ftui_core::event::{Modifiers, MouseButton, MouseEvent, MouseEventKind};
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        src.set_features(BackendFeatures {
            mouse_capture: true,
            ..BackendFeatures::default()
        })
        .unwrap();

        // X10 mouse: left click at (10, 20) in 1-indexed protocol coordinates.
        // CSI M Cb Cx Cy, with each byte encoded as value + 32 (or +33 for x/y).
        writer.write_all(&[0x1B, b'[', b'M', 32, 42, 52]).unwrap();
        assert!(src.poll_event(Duration::from_millis(100)).unwrap());
        let e = src.read_event().unwrap().unwrap();
        assert_eq!(
            e,
            Event::Mouse(MouseEvent {
                kind: MouseEventKind::Down(MouseButton::Left),
                x: 9,
                y: 19,
                modifiers: Modifiers::NONE,
            })
        );
    }

    #[cfg(unix)]
    #[test]
    fn pipe_mouse_x10_not_decoded_when_mouse_capture_disabled() {
        use ftui_core::event::{KeyCode, KeyEvent};
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        src.set_features(BackendFeatures::default()).unwrap();

        // Same X10 sequence as above; with mouse capture disabled, this should
        // not be interpreted as a mouse event.
        writer.write_all(&[0x1B, b'[', b'M', 32, 42, 52]).unwrap();
        assert!(src.poll_event(Duration::from_millis(100)).unwrap());
        let e = src.read_event().unwrap().unwrap();
        assert!(matches!(
            e,
            Event::Key(KeyEvent {
                code: KeyCode::Char(' '),
                ..
            })
        ));
    }

    #[cfg(unix)]
    #[test]
    fn pipe_mouse_legacy_1015_click_when_mouse_capture_enabled() {
        use ftui_core::event::{Modifiers, MouseButton, MouseEvent, MouseEventKind};
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        src.set_features(BackendFeatures {
            mouse_capture: true,
            ..BackendFeatures::default()
        })
        .unwrap();

        // Legacy xterm/rxvt 1015 mouse: CSI Cb;Cx;Cy M
        writer.write_all(b"\x1b[0;10;20M").unwrap();
        assert!(src.poll_event(Duration::from_millis(100)).unwrap());
        let e = src.read_event().unwrap().unwrap();
        assert_eq!(
            e,
            Event::Mouse(MouseEvent {
                kind: MouseEventKind::Down(MouseButton::Left),
                x: 9,
                y: 19,
                modifiers: Modifiers::NONE,
            })
        );
    }

    #[cfg(unix)]
    #[test]
    fn pipe_mouse_legacy_1015_not_decoded_when_mouse_capture_disabled() {
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        src.set_features(BackendFeatures::default()).unwrap();

        writer.write_all(b"\x1b[0;10;20M").unwrap();
        assert!(!src.poll_event(Duration::from_millis(25)).unwrap());
        assert!(src.read_event().unwrap().is_none());
    }

    #[cfg(unix)]
    #[test]
    fn pipe_focus_events() {
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        // Focus in (CSI I) and focus out (CSI O)
        writer.write_all(b"\x1b[I\x1b[O").unwrap();
        assert!(src.poll_event(Duration::from_millis(100)).unwrap());
        assert_eq!(src.read_event().unwrap().unwrap(), Event::Focus(true));
        assert_eq!(src.read_event().unwrap().unwrap(), Event::Focus(false));
    }

    #[cfg(unix)]
    #[test]
    fn pipe_bracketed_paste() {
        use ftui_core::event::PasteEvent;
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        writer.write_all(b"\x1b[200~hello world\x1b[201~").unwrap();
        assert!(src.poll_event(Duration::from_millis(100)).unwrap());
        let e = src.read_event().unwrap().unwrap();
        assert_eq!(
            e,
            Event::Paste(PasteEvent {
                text: "hello world".to_string(),
                bracketed: true,
            })
        );
    }

    #[cfg(unix)]
    #[test]
    fn pipe_modified_arrow_key() {
        use ftui_core::event::{KeyCode, KeyEvent, KeyEventKind, Modifiers};
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        // Ctrl+Up: CSI 1;5A
        writer.write_all(b"\x1b[1;5A").unwrap();
        assert!(src.poll_event(Duration::from_millis(100)).unwrap());
        let e = src.read_event().unwrap().unwrap();
        assert_eq!(
            e,
            Event::Key(KeyEvent {
                code: KeyCode::Up,
                modifiers: Modifiers::CTRL,
                kind: KeyEventKind::Press,
            })
        );
    }

    #[cfg(unix)]
    #[test]
    fn pipe_scroll_events() {
        use ftui_core::event::{Modifiers, MouseEvent, MouseEventKind};
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        // SGR scroll up at (5, 5): button=64 (scroll bit + up)
        writer.write_all(b"\x1b[<64;5;5M").unwrap();
        assert!(src.poll_event(Duration::from_millis(100)).unwrap());
        let e = src.read_event().unwrap().unwrap();
        assert_eq!(
            e,
            Event::Mouse(MouseEvent {
                kind: MouseEventKind::ScrollUp,
                x: 4,
                y: 4,
                modifiers: Modifiers::NONE,
            })
        );
    }

    #[cfg(unix)]
    #[test]
    fn poll_returns_buffered_events_immediately() {
        use ftui_core::event::{KeyCode, KeyEvent, KeyEventKind, Modifiers};
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        // Write multiple chars to produce multiple events.
        writer.write_all(b"xy").unwrap();
        assert!(src.poll_event(Duration::from_millis(100)).unwrap());
        // Consume only one event.
        let _ = src.read_event().unwrap().unwrap();
        // Second poll should return true immediately (buffered event).
        assert!(src.poll_event(Duration::from_millis(0)).unwrap());
        let e = src.read_event().unwrap().unwrap();
        assert_eq!(
            e,
            Event::Key(KeyEvent {
                code: KeyCode::Char('y'),
                modifiers: Modifiers::NONE,
                kind: KeyEventKind::Press,
            })
        );
    }

    #[cfg(unix)]
    #[test]
    fn pipe_large_ascii_burst_roundtrips() {
        use ftui_core::event::{KeyCode, KeyEvent};

        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        let payload = vec![b'a'; 4 * 1024 * 1024];
        let expected_len = payload.len();
        let writer_thread = std::thread::spawn(move || writer.write_all(&payload));

        let mut count = 0usize;
        let deadline = std::time::Instant::now() + Duration::from_secs(15);
        while count < expected_len {
            if !src.poll_event(Duration::from_millis(100)).unwrap() {
                assert!(
                    std::time::Instant::now() < deadline,
                    "timed out waiting for burst events: received {count} / {expected_len}"
                );
                continue;
            }
            while let Some(event) = src.read_event().unwrap() {
                match event {
                    Event::Key(KeyEvent {
                        code: KeyCode::Char('a'),
                        ..
                    }) => count += 1,
                    other => panic!("unexpected event in ascii burst test: {other:?}"),
                }
            }
        }
        writer_thread.join().unwrap().unwrap();

        assert_eq!(count, expected_len, "all bytes should decode to key events");
    }

    // ── Edge-case input parser tests ─────────────────────────────────

    #[cfg(unix)]
    #[test]
    fn truncated_csi_followed_by_valid_input() {
        use ftui_core::event::{KeyCode, KeyEvent, KeyEventKind, Modifiers};
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        // Write an incomplete CSI sequence followed by a valid character.
        // The incomplete `\x1b[` should be buffered; when `a` arrives
        // (not a valid CSI final byte when directly after `[`), the parser
        // should eventually recover. We follow with a clear valid sequence.
        writer.write_all(b"\x1b[").unwrap();
        // Give the poll a chance to consume the partial sequence.
        let _ = src.poll_event(Duration::from_millis(50));
        // Now send a valid key to force the parser forward.
        writer.write_all(b"\x1b[Ax").unwrap();
        assert!(src.poll_event(Duration::from_millis(100)).unwrap());
        // Drain all events and verify we get at least the valid ones.
        let mut events = Vec::new();
        while let Some(e) = src.read_event().unwrap() {
            events.push(e);
        }
        // The Up arrow (\x1b[A) and the 'x' key should both be parsed.
        let has_up = events.iter().any(|e| {
            matches!(
                e,
                Event::Key(KeyEvent {
                    code: KeyCode::Up,
                    ..
                })
            )
        });
        let has_x = events.iter().any(|e| {
            matches!(
                e,
                Event::Key(KeyEvent {
                    code: KeyCode::Char('x'),
                    modifiers: Modifiers::NONE,
                    kind: KeyEventKind::Press,
                })
            )
        });
        assert!(
            has_up,
            "should parse Up arrow after partial CSI: {events:?}"
        );
        assert!(has_x, "should parse 'x' after recovery: {events:?}");
    }

    #[cfg(unix)]
    #[test]
    fn unknown_csi_sequence_does_not_block_parser() {
        use ftui_core::event::{KeyCode, KeyEvent, KeyEventKind, Modifiers};
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        // \x1b[999~ is an unknown tilde-code; the parser should silently
        // drop it and still parse the subsequent 'z' key event.
        writer.write_all(b"\x1b[999~z").unwrap();
        assert!(src.poll_event(Duration::from_millis(100)).unwrap());
        let mut events = Vec::new();
        while let Some(e) = src.read_event().unwrap() {
            events.push(e);
        }
        let has_z = events.iter().any(|e| {
            matches!(
                e,
                Event::Key(KeyEvent {
                    code: KeyCode::Char('z'),
                    modifiers: Modifiers::NONE,
                    kind: KeyEventKind::Press,
                })
            )
        });
        assert!(
            has_z,
            "valid key after unknown CSI must be parsed: {events:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn eof_on_pipe_does_not_panic() {
        let (reader, writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        // Close the writer end immediately to simulate EOF.
        drop(writer);
        // poll_event should return false (no data) without panicking.
        let result = src.poll_event(Duration::from_millis(50));
        assert!(result.is_ok(), "poll_event after EOF should not error");
        assert!(
            src.tty_reader.is_none(),
            "EOF should retire the exhausted reader"
        );
        // read_event should also return None cleanly.
        let event = src.read_event().unwrap();
        assert!(event.is_none(), "read_event after EOF should be None");
    }

    #[cfg(unix)]
    #[test]
    fn eof_disables_reader_for_future_polls() {
        let (reader, writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        drop(writer);

        assert!(!src.poll_event(Duration::from_millis(20)).unwrap());
        assert!(src.tty_reader.is_none(), "EOF should clear the reader");

        let start = Instant::now();
        assert!(!src.poll_event(Duration::from_millis(200)).unwrap());
        assert!(
            start.elapsed() < Duration::from_millis(50),
            "polls after EOF should return immediately once the reader is retired"
        );
    }

    #[cfg(unix)]
    #[test]
    fn interleaved_invalid_and_valid_sequences() {
        use ftui_core::event::{KeyCode, KeyEvent};
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        // Mix of: invalid UTF-8 lead byte, valid 'a', unknown CSI, valid 'b',
        // bare ESC followed by valid char, valid 'c'.
        writer.write_all(b"\xC0a\x1b[999~b\x1b c").unwrap();
        assert!(src.poll_event(Duration::from_millis(100)).unwrap());
        let mut key_chars = Vec::new();
        while let Some(e) = src.read_event().unwrap() {
            if let Event::Key(KeyEvent {
                code: KeyCode::Char(ch),
                ..
            }) = e
            {
                key_chars.push(ch);
            }
        }
        // 'a', 'b', and 'c' must all appear (possibly with Alt modifier for 'c'
        // since \x1b followed by space+c could parse as Alt+Space then 'c').
        assert!(
            key_chars.contains(&'a'),
            "should parse 'a' amid invalid input: {key_chars:?}"
        );
        assert!(
            key_chars.contains(&'b'),
            "should parse 'b' amid invalid input: {key_chars:?}"
        );
        assert!(
            key_chars.contains(&'c'),
            "should parse 'c' amid invalid input: {key_chars:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn split_escape_sequence_across_writes() {
        use ftui_core::event::{KeyCode, KeyEvent};
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        // Write the escape sequence for Down arrow (\x1b[B) in two separate writes.
        writer.write_all(b"\x1b").unwrap();
        // First poll: the lone ESC may or may not produce an event depending
        // on whether the parser waits for more bytes.
        let _ = src.poll_event(Duration::from_millis(30));
        // Complete the sequence.
        writer.write_all(b"[B").unwrap();
        assert!(src.poll_event(Duration::from_millis(100)).unwrap());
        let mut events = Vec::new();
        while let Some(e) = src.read_event().unwrap() {
            events.push(e);
        }
        let has_down = events.iter().any(|e| {
            matches!(
                e,
                Event::Key(KeyEvent {
                    code: KeyCode::Down,
                    ..
                })
            )
        });
        assert!(
            has_down,
            "Down arrow split across writes should be parsed: {events:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn poll_with_zero_timeout_returns_false_on_empty_pipe() {
        let (reader, _writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        // Zero-timeout poll with no data should return false immediately.
        let ready = src.poll_event(Duration::ZERO).unwrap();
        assert!(!ready, "empty pipe with zero timeout should not be ready");
    }

    #[cfg(unix)]
    #[test]
    fn zero_timeout_poll_resolves_pending_escape_after_grace() {
        use ftui_core::event::{KeyCode, KeyEvent};
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);

        // Begin an ambiguous escape sequence with a lone ESC byte.
        writer.write_all(b"\x1b").unwrap();

        // Immediate zero-timeout poll should not resolve it yet.
        let ready = src.poll_event(Duration::ZERO).unwrap();
        assert!(!ready, "pending ESC should wait for timeout grace");

        // After grace elapses, a zero-timeout poll should emit Escape.
        std::thread::sleep(PARSER_TIMEOUT_GRACE + Duration::from_millis(10));
        let ready = src.poll_event(Duration::ZERO).unwrap();
        assert!(ready, "zero-timeout poll should resolve overdue ESC");

        let event = src.read_event().unwrap();
        assert!(matches!(
            event,
            Some(Event::Key(KeyEvent {
                code: KeyCode::Escape,
                ..
            }))
        ));
    }

    #[cfg(unix)]
    #[test]
    fn nonzero_poll_waits_for_pending_escape_to_become_ready() {
        use ftui_core::event::{KeyCode, KeyEvent};
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);

        writer.write_all(b"\x1b").unwrap();

        let ready = src.poll_event(Duration::from_millis(200)).unwrap();
        assert!(
            ready,
            "poll should wait for pending ESC to resolve within timeout"
        );
        assert!(matches!(
            src.read_event().unwrap(),
            Some(Event::Key(KeyEvent {
                code: KeyCode::Escape,
                ..
            }))
        ));
    }

    #[cfg(unix)]
    #[test]
    fn resize_aware_poll_resolves_pending_escape_before_outer_timeout() {
        use ftui_core::event::{KeyCode, KeyEvent};
        let (reader, mut writer) = pipe_pair();
        let (resize_reader, _resize_writer) = UnixStream::pair().unwrap();
        resize_reader.set_nonblocking(true).unwrap();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        src.live = true;
        src.resize_reader = Some(resize_reader);

        writer.write_all(b"\x1b").unwrap();

        let start = Instant::now();
        let ready = src.poll_event(Duration::from_millis(250)).unwrap();
        let elapsed = start.elapsed();
        assert!(
            ready,
            "poll should resolve pending ESC while timeout budget remains"
        );
        assert!(
            elapsed < Duration::from_millis(200),
            "pending ESC should resolve near parser grace, not at outer deadline: {elapsed:?}"
        );
        assert!(matches!(
            src.read_event().unwrap(),
            Some(Event::Key(KeyEvent {
                code: KeyCode::Escape,
                ..
            }))
        ));
    }

    #[cfg(unix)]
    #[test]
    fn resize_wake_bytes_are_drained_and_coalesced() {
        let (resize_reader, mut resize_writer) = UnixStream::pair().unwrap();
        resize_reader.set_nonblocking(true).unwrap();
        resize_writer.set_nonblocking(true).unwrap();

        let mut src = TtyEventSource::new(80, 24);
        src.live = true;
        src.resize_reader = Some(resize_reader);

        resize_writer.write_all(&[1, 1, 1]).unwrap();

        assert!(
            src.drain_resize_wake_bytes(),
            "pending wake bytes should be observed"
        );
        assert!(
            !src.drain_resize_wake_bytes(),
            "draining should coalesce all pending wake bytes"
        );
    }

    #[cfg(unix)]
    #[test]
    fn speculative_read_resolves_pending_escape_after_grace() {
        use ftui_core::event::{KeyCode, KeyEvent};
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);

        writer.write_all(b"\x1b").unwrap();

        let ready = src.poll_event(Duration::ZERO).unwrap();
        assert!(!ready, "pending ESC should wait for timeout grace");

        std::thread::sleep(PARSER_TIMEOUT_GRACE + Duration::from_millis(10));

        let event = src.read_event().unwrap();
        assert!(matches!(
            event,
            Some(Event::Key(KeyEvent {
                code: KeyCode::Escape,
                ..
            }))
        ));
    }

    #[cfg(unix)]
    #[test]
    fn speculative_read_prefers_ready_bytes_over_timeout_resolution_on_blocking_reader() {
        use ftui_core::event::{KeyCode, KeyEvent};
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        src.reader_nonblocking = false;

        writer.write_all(b"\x1b").unwrap();

        let ready = src.poll_event(Duration::ZERO).unwrap();
        assert!(!ready, "pending ESC should wait for timeout grace");

        writer.write_all(b"[B").unwrap();
        std::thread::sleep(PARSER_TIMEOUT_GRACE + Duration::from_millis(10));

        let event = src.read_event().unwrap();
        assert!(matches!(
            event,
            Some(Event::Key(KeyEvent {
                code: KeyCode::Down,
                ..
            }))
        ));
    }

    #[cfg(unix)]
    #[test]
    fn malformed_sgr_mouse_does_not_block() {
        use ftui_core::event::{KeyCode, KeyEvent};
        let (reader, mut writer) = pipe_pair();
        let mut src = TtyEventSource::from_reader(80, 24, reader);
        // Malformed SGR mouse: missing coordinates followed by valid 'q'.
        writer.write_all(b"\x1b[<M q").unwrap();
        assert!(src.poll_event(Duration::from_millis(100)).unwrap());
        let mut events = Vec::new();
        while let Some(e) = src.read_event().unwrap() {
            events.push(e);
        }
        // Parser must recover; 'q' should appear somewhere in the events.
        let has_q = events.iter().any(|e| {
            matches!(
                e,
                Event::Key(KeyEvent {
                    code: KeyCode::Char('q'),
                    ..
                })
            )
        });
        assert!(
            has_q,
            "should parse 'q' after malformed SGR mouse: {events:?}"
        );
    }

    // ── Presenter edge-case tests ────────────────────────────────────

    #[test]
    fn buffer_zero_width_clamped_to_one() {
        let buf = Buffer::new(0, 5);
        assert_eq!(buf.width(), 1);
        assert_eq!(buf.height(), 5);
    }

    #[test]
    fn buffer_zero_height_clamped_to_one() {
        let buf = Buffer::new(5, 0);
        assert_eq!(buf.width(), 5);
        assert_eq!(buf.height(), 1);
    }

    #[test]
    fn presenter_1x1_buffer_does_not_panic() {
        let caps = TerminalCapabilities::detect();
        let mut presenter = TtyPresenter::with_writer(Vec::<u8>::new(), caps);
        let buf = Buffer::new(1, 1);
        let diff = BufferDiff::full(1, 1);
        presenter.present_ui(&buf, Some(&diff), false).unwrap();
        // Verify output was emitted for the single cell.
        let bytes = presenter.inner.unwrap().into_inner().unwrap();
        assert!(!bytes.is_empty(), "1x1 buffer should produce output");
    }

    #[test]
    fn presenter_capabilities() {
        let caps = TerminalCapabilities::detect();
        let presenter = TtyPresenter::new(caps);
        let _c = presenter.capabilities();
    }

    // ── TtyPresenter rendering tests ─────────────────────────────────

    #[test]
    fn headless_presenter_present_ui_is_noop() {
        let caps = TerminalCapabilities::detect();
        let mut presenter = TtyPresenter::new(caps);
        let buf = Buffer::new(10, 5);
        let diff = BufferDiff::full(10, 5);
        // All variants should return Ok without panicking.
        presenter.present_ui(&buf, Some(&diff), false).unwrap();
        presenter.present_ui(&buf, None, false).unwrap();
        presenter.present_ui(&buf, Some(&diff), true).unwrap();
    }

    #[test]
    fn live_presenter_emits_ansi() {
        use ftui_render::cell::{Cell, CellAttrs, CellContent, PackedRgba, StyleFlags};

        let caps = TerminalCapabilities::detect();
        let output = Vec::<u8>::new();
        let mut presenter = TtyPresenter::with_writer(output, caps);

        let mut buf = Buffer::new(10, 2);
        // Place a bold red 'X' at (0, 0).
        let cell = Cell {
            content: CellContent::from_char('X'),
            fg: PackedRgba::RED,
            bg: PackedRgba::BLACK,
            attrs: CellAttrs::new(StyleFlags::BOLD, 0),
        };
        buf.set(0, 0, cell);

        let diff = BufferDiff::full(10, 2);
        presenter.present_ui(&buf, Some(&diff), false).unwrap();

        // Extract the written bytes from the inner Presenter's writer.
        // The Presenter wraps writer in BufWriter<CountingWriter<W>>,
        // so we just check the output isn't empty and contains CSI (ESC[).
        let inner = presenter.inner.unwrap();
        let bytes = inner.into_inner().unwrap();
        assert!(!bytes.is_empty(), "live presenter should emit output");
        assert!(
            bytes.windows(2).any(|w| w == b"\x1b["),
            "output should contain CSI escape sequences"
        );
    }

    #[test]
    fn full_repaint_when_diff_is_none() {
        use ftui_render::cell::Cell;

        let caps = TerminalCapabilities::detect();
        let output = Vec::<u8>::new();
        let mut presenter = TtyPresenter::with_writer(output, caps);

        let mut buf = Buffer::new(5, 1);
        for x in 0..5 {
            buf.set(x, 0, Cell::from_char(b"ABCDE"[x as usize] as char));
        }

        // Pass diff=None — should trigger full repaint.
        presenter.present_ui(&buf, None, false).unwrap();

        let bytes = presenter.inner.unwrap().into_inner().unwrap();
        // All 5 characters should appear in the output.
        let output_str = String::from_utf8_lossy(&bytes);
        for ch in ['A', 'B', 'C', 'D', 'E'] {
            assert!(
                output_str.contains(ch),
                "full repaint should emit '{ch}', got: {output_str}"
            );
        }
    }

    #[test]
    fn diff_based_partial_update() {
        use ftui_render::cell::Cell;

        let caps = TerminalCapabilities::detect();
        let output = Vec::<u8>::new();
        let mut presenter = TtyPresenter::with_writer(output, caps);

        let mut old = Buffer::new(5, 1);
        for x in 0..5 {
            old.set(x, 0, Cell::from_char(b"ABCDE"[x as usize] as char));
        }
        let mut new = old.clone();
        new.set(2, 0, Cell::from_char('Z'));
        let diff = BufferDiff::compute(&old, &new);
        presenter.present_ui(&new, Some(&diff), false).unwrap();

        let bytes = presenter.inner.unwrap().into_inner().unwrap();
        let output_str = String::from_utf8_lossy(&bytes);
        // The changed cell should appear; unchanged leading cell should not.
        assert!(
            output_str.contains('Z'),
            "diff-based update should emit changed cell 'Z'"
        );
        assert!(
            !output_str.contains('A'),
            "diff-based update should not emit unchanged cell 'A'"
        );
    }

    #[test]
    fn write_log_headless_does_not_panic() {
        let caps = TerminalCapabilities::detect();
        let mut presenter = TtyPresenter::new(caps);
        presenter.write_log("headless log test").unwrap();
    }

    #[test]
    fn write_log_live_does_not_corrupt_ui_stream() {
        let caps = TerminalCapabilities::detect();
        let mut presenter = TtyPresenter::with_writer(Vec::<u8>::new(), caps);
        presenter.write_log("live log test").unwrap();
        let bytes = presenter.inner.unwrap().into_inner().unwrap();
        assert!(bytes.is_empty(), "write_log must not emit UI bytes");
    }

    #[test]
    fn backend_headless_construction() {
        let backend = TtyBackend::new(120, 40);
        assert!(!backend.is_live());
        let (w, h) = backend.events.size().unwrap();
        assert_eq!(w, 120);
        assert_eq!(h, 40);
    }

    #[test]
    fn backend_trait_impl() {
        let mut backend = TtyBackend::new(80, 24);
        let _t = backend.clock().now_mono();
        let (w, h) = backend.events().size().unwrap();
        assert_eq!((w, h), (80, 24));
        let _c = backend.presenter().capabilities();
    }

    #[test]
    fn feature_delta_writes_enable_sequences() {
        let current = BackendFeatures::default();
        let new = BackendFeatures {
            mouse_capture: true,
            bracketed_paste: true,
            focus_events: true,
            kitty_keyboard: true,
        };
        let mut buf = Vec::new();
        TtyEventSource::write_feature_delta(
            &current,
            &new,
            TerminalCapabilities::modern(),
            &mut buf,
        )
        .unwrap();
        assert!(
            buf.windows(MOUSE_ENABLE.len()).any(|w| w == MOUSE_ENABLE),
            "expected mouse enable sequence"
        );
        assert!(
            !buf.windows(b"\x1b[?1003h".len())
                .any(|w| w == b"\x1b[?1003h"),
            "mouse enable should avoid 1003 any-event mode"
        );
        assert!(
            !buf.ends_with(b"\x1b[?1016l"),
            "mouse enable should not end with 1016l (can force X10 fallback on some terminals)"
        );
        let pos_1016l = buf
            .windows(b"\x1b[?1016l".len())
            .position(|w| w == b"\x1b[?1016l")
            .expect("mouse enable should clear 1016 before enabling SGR");
        let pos_1006h = buf
            .windows(b"\x1b[?1006h".len())
            .position(|w| w == b"\x1b[?1006h")
            .expect("mouse enable should include 1006 SGR mode");
        assert!(
            pos_1016l < pos_1006h,
            "1016l must be emitted before 1006h to preserve SGR mode on Ghostty-like terminals"
        );
        assert!(
            buf.windows(BRACKETED_PASTE_ENABLE.len())
                .any(|w| w == BRACKETED_PASTE_ENABLE),
            "expected bracketed paste enable"
        );
        assert!(
            buf.windows(FOCUS_ENABLE.len()).any(|w| w == FOCUS_ENABLE),
            "expected focus enable"
        );
        assert!(
            buf.windows(KITTY_KEYBOARD_ENABLE.len())
                .any(|w| w == KITTY_KEYBOARD_ENABLE),
            "expected kitty keyboard enable"
        );
    }

    #[test]
    fn mouse_enable_sequence_for_mux_capabilities_is_safe() {
        let mux_caps = TerminalCapabilities::builder()
            .mouse_sgr(true)
            .in_wezterm_mux(true)
            .build();
        assert_eq!(
            mouse_enable_sequence_for_capabilities(mux_caps),
            MOUSE_ENABLE_MUX_SAFE
        );
        assert!(
            MOUSE_ENABLE_MUX_SAFE
                .windows(b"\x1b[?1005l".len())
                .any(|w| w == b"\x1b[?1005l"),
            "mux-safe enable should clear UTF-8 mouse encoding (1005)"
        );
        assert!(
            MOUSE_ENABLE_MUX_SAFE
                .windows(b"\x1b[?1015l".len())
                .any(|w| w == b"\x1b[?1015l"),
            "mux-safe enable should clear urxvt mouse encoding (1015)"
        );
        assert!(
            MOUSE_ENABLE_MUX_SAFE
                .windows(b"\x1b[?1006h".len())
                .any(|w| w == b"\x1b[?1006h"),
            "mux-safe enable should keep SGR mouse mode"
        );
        assert!(
            !MOUSE_ENABLE_MUX_SAFE
                .windows(b"\x1b[?1003h".len())
                .any(|w| w == b"\x1b[?1003h"),
            "mux-safe enable should avoid 1003 any-event mode"
        );
        let pos_1016l = MOUSE_ENABLE_MUX_SAFE
            .windows(b"\x1b[?1016l".len())
            .position(|w| w == b"\x1b[?1016l")
            .expect("mux-safe enable should clear 1016 before enabling SGR");
        let pos_1006h = MOUSE_ENABLE_MUX_SAFE
            .windows(b"\x1b[?1006h".len())
            .position(|w| w == b"\x1b[?1006h")
            .expect("mux-safe enable should include 1006 SGR mode");
        assert!(
            pos_1016l < pos_1006h,
            "mux-safe enable must emit 1016l before 1006h to preserve SGR mode"
        );
    }

    #[test]
    fn mouse_disable_sequence_for_mux_capabilities_clears_1016() {
        let mux_caps = TerminalCapabilities::builder()
            .mouse_sgr(true)
            .in_wezterm_mux(true)
            .build();
        assert_eq!(
            mouse_disable_sequence_for_capabilities(mux_caps),
            MOUSE_DISABLE_MUX_SAFE
        );
        let pos_1016l = MOUSE_DISABLE_MUX_SAFE
            .windows(b"\x1b[?1016l".len())
            .position(|w| w == b"\x1b[?1016l")
            .expect("mux-safe disable should clear 1016");
        let pos_1006l = MOUSE_DISABLE_MUX_SAFE
            .windows(b"\x1b[?1006l".len())
            .position(|w| w == b"\x1b[?1006l")
            .expect("mux-safe disable should include 1006 reset");
        assert!(
            pos_1016l < pos_1006l,
            "mux-safe disable should clear 1016 before disabling 1006"
        );
    }

    #[test]
    fn feature_delta_uses_mux_safe_mouse_sequence() {
        let current = BackendFeatures::default();
        let new = BackendFeatures {
            mouse_capture: true,
            bracketed_paste: false,
            focus_events: false,
            kitty_keyboard: false,
        };
        let mux_caps = TerminalCapabilities::builder()
            .mouse_sgr(true)
            .in_wezterm_mux(true)
            .build();
        let mut buf = Vec::new();
        TtyEventSource::write_feature_delta(&current, &new, mux_caps, &mut buf).unwrap();
        assert!(
            buf.windows(MOUSE_ENABLE_MUX_SAFE.len())
                .any(|w| w == MOUSE_ENABLE_MUX_SAFE),
            "feature delta should use mux-safe mouse enable sequence in mux contexts"
        );
        assert!(
            buf.windows(b"\x1b[?1005l".len())
                .any(|w| w == b"\x1b[?1005l"),
            "feature delta should clear UTF-8 mouse encoding (1005) in mux contexts"
        );
    }

    #[test]
    fn feature_delta_writes_disable_sequences() {
        let current = BackendFeatures {
            mouse_capture: true,
            bracketed_paste: true,
            focus_events: true,
            kitty_keyboard: true,
        };
        let new = BackendFeatures::default();
        let mut buf = Vec::new();
        TtyEventSource::write_feature_delta(
            &current,
            &new,
            TerminalCapabilities::modern(),
            &mut buf,
        )
        .unwrap();
        assert!(buf.windows(MOUSE_DISABLE.len()).any(|w| w == MOUSE_DISABLE));
        assert!(
            buf.windows(BRACKETED_PASTE_DISABLE.len())
                .any(|w| w == BRACKETED_PASTE_DISABLE)
        );
        assert!(buf.windows(FOCUS_DISABLE.len()).any(|w| w == FOCUS_DISABLE));
        assert!(
            buf.windows(KITTY_KEYBOARD_DISABLE.len())
                .any(|w| w == KITTY_KEYBOARD_DISABLE)
        );
    }

    #[test]
    fn feature_delta_noop_when_unchanged() {
        let features = BackendFeatures {
            mouse_capture: true,
            bracketed_paste: false,
            focus_events: true,
            kitty_keyboard: false,
        };
        let mut buf = Vec::new();
        TtyEventSource::write_feature_delta(
            &features,
            &features,
            TerminalCapabilities::modern(),
            &mut buf,
        )
        .unwrap();
        assert!(buf.is_empty(), "no output expected when features unchanged");
    }

    #[test]
    fn cleanup_sequence_contains_all_disable() {
        let features = BackendFeatures {
            mouse_capture: true,
            bracketed_paste: true,
            focus_events: true,
            kitty_keyboard: true,
        };
        let mut buf = Vec::new();
        write_cleanup_sequence(&features, true, &mut buf).unwrap();

        // Verify expected cleanup disables are present.
        assert!(
            !buf.windows(SYNC_END.len()).any(|w| w == SYNC_END),
            "default cleanup utility must not emit standalone sync_end"
        );
        assert!(buf.windows(MOUSE_DISABLE.len()).any(|w| w == MOUSE_DISABLE));
        assert!(
            buf.windows(BRACKETED_PASTE_DISABLE.len())
                .any(|w| w == BRACKETED_PASTE_DISABLE)
        );
        assert!(buf.windows(FOCUS_DISABLE.len()).any(|w| w == FOCUS_DISABLE));
        assert!(
            buf.windows(KITTY_KEYBOARD_DISABLE.len())
                .any(|w| w == KITTY_KEYBOARD_DISABLE)
        );
        assert!(buf.windows(CURSOR_SHOW.len()).any(|w| w == CURSOR_SHOW));
        assert!(
            buf.windows(ALT_SCREEN_LEAVE.len())
                .any(|w| w == ALT_SCREEN_LEAVE)
        );
    }

    #[test]
    fn cleanup_sequence_with_sync_end_opt_in() {
        let features = BackendFeatures {
            mouse_capture: true,
            bracketed_paste: false,
            focus_events: false,
            kitty_keyboard: false,
        };
        let mut buf = Vec::new();
        write_cleanup_sequence_with_sync_end(&features, true, &mut buf).unwrap();

        assert!(
            buf.windows(SYNC_END.len()).any(|w| w == SYNC_END),
            "opt-in cleanup helper should include sync_end"
        );
        let sync_pos = buf
            .windows(SYNC_END.len())
            .position(|w| w == SYNC_END)
            .expect("sync_end present");
        let cursor_pos = buf
            .windows(CURSOR_SHOW.len())
            .position(|w| w == CURSOR_SHOW)
            .expect("cursor_show present");
        assert!(
            sync_pos < cursor_pos,
            "sync_end should precede cursor_show in opt-in cleanup"
        );
    }

    #[test]
    fn cleanup_sequence_policy_can_skip_sync_end() {
        let features = BackendFeatures {
            mouse_capture: true,
            bracketed_paste: false,
            focus_events: false,
            kitty_keyboard: false,
        };
        let mut buf = Vec::new();
        write_cleanup_sequence_policy(&features, false, false, &mut buf).unwrap();

        assert!(
            !buf.windows(SYNC_END.len()).any(|w| w == SYNC_END),
            "sync_end must be omitted when policy disables synchronized output"
        );
        assert!(
            buf.windows(MOUSE_DISABLE.len()).any(|w| w == MOUSE_DISABLE),
            "other cleanup bytes must still be emitted"
        );
        assert!(buf.windows(CURSOR_SHOW.len()).any(|w| w == CURSOR_SHOW));
    }

    #[test]
    fn conservative_feature_union_is_over_disabling_superset() {
        let a = BackendFeatures {
            mouse_capture: false,
            bracketed_paste: true,
            focus_events: false,
            kitty_keyboard: true,
        };
        let b = BackendFeatures {
            mouse_capture: true,
            bracketed_paste: false,
            focus_events: true,
            kitty_keyboard: false,
        };

        let merged = conservative_feature_union(a, b);
        assert!(merged.mouse_capture);
        assert!(merged.bracketed_paste);
        assert!(merged.focus_events);
        assert!(merged.kitty_keyboard);
    }

    #[test]
    fn sanitize_feature_request_disables_unsupported_capabilities() {
        let requested = BackendFeatures {
            mouse_capture: true,
            bracketed_paste: true,
            focus_events: true,
            kitty_keyboard: true,
        };
        let sanitized = sanitize_feature_request(requested, TerminalCapabilities::basic());
        assert_eq!(sanitized, BackendFeatures::default());
    }

    #[test]
    fn sanitize_feature_request_is_conservative_in_wezterm_mux() {
        let requested = BackendFeatures {
            mouse_capture: true,
            bracketed_paste: true,
            focus_events: true,
            kitty_keyboard: true,
        };
        let caps = TerminalCapabilities::builder()
            .mouse_sgr(true)
            .bracketed_paste(true)
            .focus_events(true)
            .kitty_keyboard(true)
            .in_wezterm_mux(true)
            .build();
        let sanitized = sanitize_feature_request(requested, caps);

        assert!(
            sanitized.mouse_capture,
            "mouse capture should remain available"
        );
        assert!(
            sanitized.bracketed_paste,
            "bracketed paste should remain available"
        );
        assert!(
            !sanitized.focus_events,
            "focus events should be disabled in wezterm mux"
        );
        assert!(
            !sanitized.kitty_keyboard,
            "kitty keyboard should be disabled in mux sessions"
        );
    }

    #[test]
    fn sanitize_feature_request_disables_focus_in_tmux() {
        let requested = BackendFeatures {
            mouse_capture: true,
            bracketed_paste: true,
            focus_events: true,
            kitty_keyboard: true,
        };
        let caps = TerminalCapabilities::builder()
            .mouse_sgr(true)
            .bracketed_paste(true)
            .focus_events(true)
            .kitty_keyboard(true)
            .in_tmux(true)
            .build();
        let sanitized = sanitize_feature_request(requested, caps);

        assert!(sanitized.mouse_capture);
        assert!(sanitized.bracketed_paste);
        assert!(!sanitized.focus_events);
        assert!(!sanitized.kitty_keyboard);
    }

    #[cfg(unix)]
    #[test]
    fn signal_intercept_guard_disabled_reports_inactive() {
        let mut guard = SignalInterceptGuard::new(false);
        assert!(
            !guard.disarm(),
            "disabled guard should report inactive ownership"
        );
    }

    #[cfg(unix)]
    #[test]
    fn signal_intercept_guard_disarm_transfers_ownership() {
        let mut guard = SignalInterceptGuard::new(true);
        assert!(
            guard.disarm(),
            "enabled guard should report transferred ownership on disarm"
        );
        // Exact counter values are process-global and therefore unstable under
        // parallel test execution. We only restore our borrowed slot here.
        LIVE_SIGNAL_INTERCEPT_SESSIONS.fetch_sub(1, Ordering::SeqCst);
    }

    #[test]
    fn apply_feature_state_enables_legacy_fallbacks_when_mouse_capture_on() {
        let mut src = TtyEventSource::new(80, 24);
        src.capabilities = TerminalCapabilities::builder().mouse_sgr(true).build();
        src.apply_feature_state(BackendFeatures {
            mouse_capture: true,
            ..BackendFeatures::default()
        });

        // With SGR support, keep numeric and raw X10 fallbacks enabled for
        // mux/terminal edge-cases that ignore SGR mode requests.
        let modern_events = src.parser.parse(b"\x1b[0;10;20M");
        assert!(
            modern_events.iter().any(|e| matches!(e, Event::Mouse(_))),
            "legacy numeric fallback should remain available with mouse capture on"
        );
        let modern_x10 = src.parser.parse(&[0x1B, b'[', b'M', 32, 42, 52]);
        assert!(
            modern_x10.iter().any(|e| matches!(e, Event::Mouse(_))),
            "raw X10 fallback should stay available with mouse capture on"
        );

        src.capabilities = TerminalCapabilities::basic();
        src.apply_feature_state(BackendFeatures {
            mouse_capture: true,
            ..BackendFeatures::default()
        });

        // Without SGR support, fallback remains enabled.
        let legacy_events = src.parser.parse(b"\x1b[0;10;20M");
        assert!(
            legacy_events.iter().any(|e| matches!(e, Event::Mouse(_))),
            "legacy mouse fallback should be enabled when SGR is unavailable"
        );
        let legacy_x10 = src.parser.parse(&[0x1B, b'[', b'M', 32, 42, 52]);
        assert!(
            legacy_x10.iter().any(|e| matches!(e, Event::Mouse(_))),
            "raw X10 decoding should be enabled when SGR is unavailable"
        );

        src.apply_feature_state(BackendFeatures::default());
        let disabled_x10 = src.parser.parse(&[0x1B, b'[', b'M', 32, 42, 52]);
        assert!(
            disabled_x10.iter().all(|e| !matches!(e, Event::Mouse(_))),
            "raw X10 fallback must be disabled when mouse capture is off"
        );
    }

    #[test]
    fn normalize_event_maps_pixel_space_mouse_to_cell_grid() {
        use ftui_core::event::{Modifiers, MouseButton, MouseEvent, MouseEventKind};

        let mut src = TtyEventSource::new(100, 40);
        src.capabilities = TerminalCapabilities::builder().mouse_sgr(true).build();
        src.features = BackendFeatures {
            mouse_capture: true,
            ..BackendFeatures::default()
        };
        src.pixel_width = 1000;
        src.pixel_height = 800;

        let event = Event::Mouse(MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            x: 500,
            y: 400,
            modifiers: Modifiers::NONE,
        });
        let normalized = src.normalize_event(event);

        let mouse = match normalized {
            Event::Mouse(mouse) => mouse,
            other => {
                panic!("expected mouse event, got {other:?}");
            }
        };
        assert!(mouse.x < src.width, "x should be mapped into cell bounds");
        assert!(mouse.y < src.height, "y should be mapped into cell bounds");
        assert!(
            mouse.x > 0 && mouse.y > 0,
            "pixel-space event should not collapse to origin"
        );
    }

    #[test]
    fn normalize_event_keeps_cell_space_mouse_unchanged() {
        use ftui_core::event::{Modifiers, MouseButton, MouseEvent, MouseEventKind};

        let mut src = TtyEventSource::new(100, 40);
        src.capabilities = TerminalCapabilities::builder().mouse_sgr(true).build();
        src.features = BackendFeatures {
            mouse_capture: true,
            ..BackendFeatures::default()
        };
        src.pixel_width = 1000;
        src.pixel_height = 800;

        let event = Event::Mouse(MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            x: 50,
            y: 10,
            modifiers: Modifiers::NONE,
        });
        let normalized = src.normalize_event(event.clone());
        assert_eq!(
            normalized, event,
            "cell-space coordinates must be preserved"
        );
    }

    #[test]
    fn normalize_event_sticky_pixel_mode_maps_subsequent_low_coordinates() {
        use ftui_core::event::{Modifiers, MouseButton, MouseEvent, MouseEventKind};

        let mut src = TtyEventSource::new(100, 40);
        src.capabilities = TerminalCapabilities::builder().mouse_sgr(true).build();
        src.features = BackendFeatures {
            mouse_capture: true,
            ..BackendFeatures::default()
        };
        src.pixel_width = 1000;
        src.pixel_height = 800;

        let first = Event::Mouse(MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            x: 700,
            y: 500,
            modifiers: Modifiers::NONE,
        });
        let _ = src.normalize_event(first);
        assert!(
            src.mouse_coords_pixels,
            "large out-of-grid mouse event should arm sticky pixel normalization"
        );

        let second = Event::Mouse(MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            x: 100,
            y: 20,
            modifiers: Modifiers::NONE,
        });
        let normalized = src.normalize_event(second);
        let mouse = match normalized {
            Event::Mouse(mouse) => mouse,
            other => {
                panic!("expected mouse event, got {other:?}");
            }
        };
        assert!(mouse.x < src.width, "sticky mode should normalize x");
        assert!(mouse.y < src.height, "sticky mode should normalize y");
    }

    #[test]
    fn apply_feature_state_disabling_mouse_resets_pixel_detector() {
        let mut src = TtyEventSource::new(80, 24);
        src.mouse_coords_pixels = true;
        src.inferred_pixel_width = 1234;
        src.inferred_pixel_height = 777;
        src.apply_feature_state(BackendFeatures::default());
        assert!(
            !src.mouse_coords_pixels,
            "disabling mouse capture should clear sticky pixel-mode detector"
        );
        assert_eq!(src.inferred_pixel_width, 0);
        assert_eq!(src.inferred_pixel_height, 0);
    }

    #[test]
    fn normalize_event_infers_pixel_grid_when_winsize_pixels_missing() {
        use ftui_core::event::{Modifiers, MouseButton, MouseEvent, MouseEventKind};

        let mut src = TtyEventSource::new(100, 40);
        src.capabilities = TerminalCapabilities::builder().mouse_sgr(true).build();
        src.features = BackendFeatures {
            mouse_capture: true,
            ..BackendFeatures::default()
        };
        // Simulate terminals that leak pixel coordinates but report 0x0 pixel winsize.
        src.pixel_width = 0;
        src.pixel_height = 0;

        let first = Event::Mouse(MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            x: 700,
            y: 500,
            modifiers: Modifiers::NONE,
        });
        let normalized_first = src.normalize_event(first);
        let first_mouse = match normalized_first {
            Event::Mouse(mouse) => mouse,
            other => {
                panic!("expected mouse event, got {other:?}");
            }
        };
        assert!(first_mouse.x > 0 && first_mouse.x < src.width.saturating_sub(1));
        assert!(first_mouse.y > 0 && first_mouse.y < src.height.saturating_sub(1));

        let second = Event::Mouse(MouseEvent {
            kind: MouseEventKind::Moved,
            x: 250,
            y: 200,
            modifiers: Modifiers::NONE,
        });
        let normalized = src.normalize_event(second);
        let mouse = match normalized {
            Event::Mouse(mouse) => mouse,
            other => {
                panic!("expected mouse event, got {other:?}");
            }
        };

        assert!(mouse.x < src.width);
        assert!(mouse.y < src.height);
        assert!(mouse.x > 0 && mouse.x < src.width.saturating_sub(1));
        assert!(mouse.y > 0 && mouse.y < src.height.saturating_sub(1));
    }

    #[test]
    fn normalize_event_near_edge_outside_grid_clamps_without_sticky_pixel_mode() {
        use ftui_core::event::{Modifiers, MouseButton, MouseEvent, MouseEventKind};

        let mut src = TtyEventSource::new(100, 40);
        src.capabilities = TerminalCapabilities::builder().mouse_sgr(true).build();
        src.features = BackendFeatures {
            mouse_capture: true,
            ..BackendFeatures::default()
        };
        src.pixel_width = 1000;
        src.pixel_height = 800;

        let near_edge = Event::Mouse(MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            x: 100,
            y: 40,
            modifiers: Modifiers::NONE,
        });
        let normalized = src.normalize_event(near_edge);
        let mouse = match normalized {
            Event::Mouse(mouse) => mouse,
            other => {
                panic!("expected mouse event, got {other:?}");
            }
        };
        assert_eq!(mouse.x, 99);
        assert_eq!(mouse.y, 39);
        assert!(
            !src.mouse_coords_pixels,
            "edge clamp must not arm sticky pixel normalization"
        );

        let follow_up = Event::Mouse(MouseEvent {
            kind: MouseEventKind::Moved,
            x: 50,
            y: 20,
            modifiers: Modifiers::NONE,
        });
        let normalized_follow_up = src.normalize_event(follow_up);
        assert_eq!(
            normalized_follow_up,
            Event::Mouse(MouseEvent {
                kind: MouseEventKind::Moved,
                x: 50,
                y: 20,
                modifiers: Modifiers::NONE,
            }),
            "normal cell-space events should remain unchanged after edge clamp"
        );
    }

    #[test]
    fn cleanup_sequence_ordering() {
        let features = BackendFeatures {
            mouse_capture: true,
            bracketed_paste: true,
            focus_events: true,
            kitty_keyboard: true,
        };
        let mut buf = Vec::new();
        write_cleanup_sequence(&features, true, &mut buf).unwrap();

        // Verify ordering: cursor_show before alt_screen_leave.
        let cursor_pos = buf
            .windows(CURSOR_SHOW.len())
            .position(|w| w == CURSOR_SHOW)
            .expect("cursor_show present");
        let alt_pos = buf
            .windows(ALT_SCREEN_LEAVE.len())
            .position(|w| w == ALT_SCREEN_LEAVE)
            .expect("alt_screen_leave present");

        assert!(
            cursor_pos < alt_pos,
            "cursor_show must come before alt_screen_leave"
        );
    }

    #[test]
    fn disable_all_resets_feature_state() {
        let mut src = TtyEventSource::new(80, 24);
        src.features = BackendFeatures {
            mouse_capture: true,
            bracketed_paste: true,
            focus_events: true,
            kitty_keyboard: true,
        };
        let mut buf = Vec::new();
        src.disable_all(&mut buf).unwrap();
        assert_eq!(src.features(), BackendFeatures::default());
        // Verify disable sequences were written.
        assert!(!buf.is_empty());
    }

    // ── PTY-based raw mode tests ─────────────────────────────────────

    #[cfg(unix)]
    mod pty_tests {
        use super::*;
        use nix::pty::openpty;
        use nix::sys::termios::{self, LocalFlags};
        use std::io::Read;

        fn pty_pair() -> (std::fs::File, std::fs::File) {
            let result = openpty(None, None).expect("openpty failed");
            (
                std::fs::File::from(result.master),
                std::fs::File::from(result.slave),
            )
        }

        #[test]
        fn raw_mode_entered_and_restored_on_drop() {
            let (_master, slave) = pty_pair();
            let slave_dup = slave.try_clone().unwrap();

            // Before: canonical mode with ECHO.
            let before = termios::tcgetattr(&slave_dup).unwrap();
            assert!(
                before.local_flags.contains(LocalFlags::ECHO),
                "default termios should have ECHO"
            );
            assert!(
                before.local_flags.contains(LocalFlags::ICANON),
                "default termios should have ICANON"
            );

            {
                let _guard = RawModeGuard::enter_on(slave).unwrap();

                // During: raw mode — no echo, no canonical.
                let during = termios::tcgetattr(&slave_dup).unwrap();
                assert!(
                    !during.local_flags.contains(LocalFlags::ECHO),
                    "raw mode should clear ECHO"
                );
                assert!(
                    !during.local_flags.contains(LocalFlags::ICANON),
                    "raw mode should clear ICANON"
                );
            }

            // After drop: original termios restored.
            let after = termios::tcgetattr(&slave_dup).unwrap();
            assert!(
                after.local_flags.contains(LocalFlags::ECHO),
                "should restore ECHO after drop"
            );
            assert!(
                after.local_flags.contains(LocalFlags::ICANON),
                "should restore ICANON after drop"
            );
        }

        #[test]
        fn panic_restores_termios() {
            let (_master, slave) = pty_pair();
            let slave_dup = slave.try_clone().unwrap();

            // Spawn a thread that panics with the guard held.
            let handle = std::thread::spawn(move || {
                let _guard = RawModeGuard::enter_on(slave).unwrap();
                std::panic::panic_any("intentional panic for testing raw mode cleanup");
            });

            assert!(handle.join().is_err(), "thread should have panicked");

            // Verify termios restored despite the panic.
            let after = termios::tcgetattr(&slave_dup).unwrap();
            assert!(
                after.local_flags.contains(LocalFlags::ECHO),
                "ECHO should be restored after panic"
            );
            assert!(
                after.local_flags.contains(LocalFlags::ICANON),
                "ICANON should be restored after panic"
            );
        }

        #[test]
        fn backend_drop_writes_cleanup_sequences() {
            let (mut master, slave) = pty_pair();
            let slave_dup = slave.try_clone().unwrap();

            {
                let _guard = RawModeGuard::enter_on(slave).unwrap();

                // Write feature-enable sequences to the PTY.
                let mut stdout_buf = Vec::new();
                let all_on = BackendFeatures {
                    mouse_capture: true,
                    bracketed_paste: true,
                    focus_events: true,
                    kitty_keyboard: true,
                };
                TtyEventSource::write_feature_delta(
                    &BackendFeatures::default(),
                    &all_on,
                    TerminalCapabilities::modern(),
                    &mut stdout_buf,
                )
                .unwrap();
                // Also write cleanup as if TtyBackend::drop ran.
                write_cleanup_sequence(&all_on, true, &mut stdout_buf).unwrap();

                // Write it all to the slave so master can read it.
                use std::io::Write;
                let mut slave_writer = slave_dup.try_clone().unwrap();
                slave_writer.write_all(&stdout_buf).unwrap();
                slave_writer.flush().unwrap();
            }

            // Read from master to verify cleanup sequences were written.
            let mut buf = vec![0u8; 2048];
            let n = master.read(&mut buf).unwrap();
            let output = &buf[..n];

            assert!(
                output.windows(CURSOR_SHOW.len()).any(|w| w == CURSOR_SHOW),
                "cleanup must show cursor"
            );
            assert!(
                output
                    .windows(MOUSE_DISABLE.len())
                    .any(|w| w == MOUSE_DISABLE),
                "cleanup must disable mouse"
            );
            assert!(
                output
                    .windows(ALT_SCREEN_LEAVE.len())
                    .any(|w| w == ALT_SCREEN_LEAVE),
                "cleanup must leave alt-screen"
            );
        }

        /// Helper: write bytes to the PTY slave and read them back from master.
        fn write_to_slave_and_read_master(
            master: &mut std::fs::File,
            slave: &std::fs::File,
            data: &[u8],
        ) -> Vec<u8> {
            use std::io::Write;
            let mut writer = slave.try_clone().unwrap();
            writer.write_all(data).unwrap();
            writer.flush().unwrap();
            let mut buf = vec![0u8; 4096];
            let n = master.read(&mut buf).unwrap();
            buf.truncate(n);
            buf
        }

        #[test]
        fn cursor_hide_on_enter_show_on_drop() {
            let (mut master, slave) = pty_pair();
            let slave_dup = slave.try_clone().unwrap();

            // Simulate entering a session: raw mode + hide cursor.
            {
                let _guard = RawModeGuard::enter_on(slave).unwrap();
                let output = write_to_slave_and_read_master(&mut master, &slave_dup, CURSOR_HIDE);
                assert!(
                    output.windows(CURSOR_HIDE.len()).any(|w| w == CURSOR_HIDE),
                    "cursor-hide should be written on session enter"
                );

                // Simulate drop cleanup: show cursor.
                let output = write_to_slave_and_read_master(&mut master, &slave_dup, CURSOR_SHOW);
                assert!(
                    output.windows(CURSOR_SHOW.len()).any(|w| w == CURSOR_SHOW),
                    "cursor-show should be written on session exit"
                );
            }
        }

        #[test]
        fn alt_screen_enter_and_leave_via_pty() {
            let (mut master, slave) = pty_pair();
            let slave_dup = slave.try_clone().unwrap();

            {
                let _guard = RawModeGuard::enter_on(slave).unwrap();

                // Enter alt-screen.
                let output =
                    write_to_slave_and_read_master(&mut master, &slave_dup, ALT_SCREEN_ENTER);
                assert!(
                    output
                        .windows(ALT_SCREEN_ENTER.len())
                        .any(|w| w == ALT_SCREEN_ENTER),
                    "alt-screen enter should pass through PTY"
                );

                // Leave alt-screen.
                let output =
                    write_to_slave_and_read_master(&mut master, &slave_dup, ALT_SCREEN_LEAVE);
                assert!(
                    output
                        .windows(ALT_SCREEN_LEAVE.len())
                        .any(|w| w == ALT_SCREEN_LEAVE),
                    "alt-screen leave should pass through PTY"
                );
            }
        }

        #[test]
        fn per_feature_disable_on_drop() {
            let (mut master, slave) = pty_pair();
            let slave_dup = slave.try_clone().unwrap();

            {
                let _guard = RawModeGuard::enter_on(slave).unwrap();

                // Enable all features, then write cleanup (simulating TtyBackend::drop).
                let all_on = BackendFeatures {
                    mouse_capture: true,
                    bracketed_paste: true,
                    focus_events: true,
                    kitty_keyboard: true,
                };
                let mut cleanup = Vec::new();
                write_cleanup_sequence(&all_on, false, &mut cleanup).unwrap();

                let output = write_to_slave_and_read_master(&mut master, &slave_dup, &cleanup);

                // Verify each feature's disable sequence individually.
                assert!(
                    output
                        .windows(MOUSE_DISABLE.len())
                        .any(|w| w == MOUSE_DISABLE),
                    "mouse must be disabled on drop"
                );
                assert!(
                    output
                        .windows(BRACKETED_PASTE_DISABLE.len())
                        .any(|w| w == BRACKETED_PASTE_DISABLE),
                    "bracketed paste must be disabled on drop"
                );
                assert!(
                    output
                        .windows(FOCUS_DISABLE.len())
                        .any(|w| w == FOCUS_DISABLE),
                    "focus events must be disabled on drop"
                );
                assert!(
                    output
                        .windows(KITTY_KEYBOARD_DISABLE.len())
                        .any(|w| w == KITTY_KEYBOARD_DISABLE),
                    "kitty keyboard must be disabled on drop"
                );
                assert!(
                    output.windows(CURSOR_SHOW.len()).any(|w| w == CURSOR_SHOW),
                    "cursor must be shown on drop"
                );
            }
        }

        #[test]
        fn panic_with_features_restores_termios() {
            let (_master, slave) = pty_pair();
            let slave_dup = slave.try_clone().unwrap();

            let handle = std::thread::spawn(move || {
                let _guard = RawModeGuard::enter_on(slave).unwrap();
                // Simulate having features enabled — the guard tracks termios, and
                // TtyBackend::drop would disable features. Here we just verify
                // the termios restoration happens even when features were "active".
                std::panic::panic_any("panic with features enabled");
            });

            assert!(handle.join().is_err());

            let after = termios::tcgetattr(&slave_dup).unwrap();
            assert!(
                after.local_flags.contains(LocalFlags::ECHO),
                "ECHO restored after panic with features"
            );
            assert!(
                after.local_flags.contains(LocalFlags::ICANON),
                "ICANON restored after panic with features"
            );
        }

        #[test]
        fn repeated_raw_mode_cycles_no_leak() {
            let (_master, slave) = pty_pair();
            let slave_dup = slave.try_clone().unwrap();

            // Enter and exit raw mode multiple times.
            for _ in 0..5 {
                let s = slave_dup.try_clone().unwrap();
                let guard = RawModeGuard::enter_on(s).unwrap();

                // Verify raw mode active.
                let during = termios::tcgetattr(&slave_dup).unwrap();
                assert!(!during.local_flags.contains(LocalFlags::ECHO));

                drop(guard);

                // Verify restored.
                let after = termios::tcgetattr(&slave_dup).unwrap();
                assert!(
                    after.local_flags.contains(LocalFlags::ECHO),
                    "ECHO must be restored each cycle"
                );
            }
        }

        #[test]
        fn cleanup_ordering_via_pty() {
            let (mut master, slave) = pty_pair();
            let slave_dup = slave.try_clone().unwrap();

            {
                let _guard = RawModeGuard::enter_on(slave).unwrap();

                // Write a full cleanup sequence and verify ordering.
                let features = BackendFeatures {
                    mouse_capture: true,
                    bracketed_paste: true,
                    focus_events: true,
                    kitty_keyboard: true,
                };
                let mut seq = Vec::new();
                write_cleanup_sequence_with_sync_end(&features, true, &mut seq).unwrap();

                let output = write_to_slave_and_read_master(&mut master, &slave_dup, &seq);

                // Verify ordering: sync_end before cursor_show before alt_screen_leave.
                let sync_pos = output
                    .windows(SYNC_END.len())
                    .position(|w| w == SYNC_END)
                    .expect("sync_end present");
                let cursor_pos = output
                    .windows(CURSOR_SHOW.len())
                    .position(|w| w == CURSOR_SHOW)
                    .expect("cursor_show present");
                let alt_pos = output
                    .windows(ALT_SCREEN_LEAVE.len())
                    .position(|w| w == ALT_SCREEN_LEAVE)
                    .expect("alt_screen_leave present");

                assert!(
                    sync_pos < cursor_pos,
                    "sync_end ({sync_pos}) must precede cursor_show ({cursor_pos})"
                );
                assert!(
                    cursor_pos < alt_pos,
                    "cursor_show ({cursor_pos}) must precede alt_screen_leave ({alt_pos})"
                );
            }
        }
    }
}