summaryrefslogtreecommitdiff
path: root/usr.bin/tmux/tty.c
blob: 124cb357d620bc13dafac084a744ecba07e106de (plain)
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
/* $OpenBSD: tty.c,v 1.437 2024/08/04 09:35:30 nicm Exp $ */

/*
 * Copyright (c) 2007 Nicholas Marriott <nicholas.marriott@gmail.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/types.h>
#include <sys/ioctl.h>

#include <netinet/in.h>

#include <curses.h>
#include <errno.h>
#include <fcntl.h>
#include <resolv.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>

#include "tmux.h"

static int	tty_log_fd = -1;

static void	tty_set_italics(struct tty *);
static int	tty_try_colour(struct tty *, int, const char *);
static void	tty_force_cursor_colour(struct tty *, int);
static void	tty_cursor_pane(struct tty *, const struct tty_ctx *, u_int,
		    u_int);
static void	tty_cursor_pane_unless_wrap(struct tty *,
		    const struct tty_ctx *, u_int, u_int);
static void	tty_invalidate(struct tty *);
static void	tty_colours(struct tty *, const struct grid_cell *);
static void	tty_check_fg(struct tty *, struct colour_palette *,
    		    struct grid_cell *);
static void	tty_check_bg(struct tty *, struct colour_palette *,
    		    struct grid_cell *);
static void	tty_check_us(struct tty *, struct colour_palette *,
    		    struct grid_cell *);
static void	tty_colours_fg(struct tty *, const struct grid_cell *);
static void	tty_colours_bg(struct tty *, const struct grid_cell *);
static void	tty_colours_us(struct tty *, const struct grid_cell *);

static void	tty_region_pane(struct tty *, const struct tty_ctx *, u_int,
		    u_int);
static void	tty_region(struct tty *, u_int, u_int);
static void	tty_margin_pane(struct tty *, const struct tty_ctx *);
static void	tty_margin(struct tty *, u_int, u_int);
static int	tty_large_region(struct tty *, const struct tty_ctx *);
static int	tty_fake_bce(const struct tty *, const struct grid_cell *,
		    u_int);
static void	tty_redraw_region(struct tty *, const struct tty_ctx *);
static void	tty_emulate_repeat(struct tty *, enum tty_code_code,
		    enum tty_code_code, u_int);
static void	tty_repeat_space(struct tty *, u_int);
static void	tty_draw_pane(struct tty *, const struct tty_ctx *, u_int);
static void	tty_default_attributes(struct tty *, const struct grid_cell *,
		    struct colour_palette *, u_int, struct hyperlinks *);
static int	tty_check_overlay(struct tty *, u_int, u_int);
static void	tty_check_overlay_range(struct tty *, u_int, u_int, u_int,
		    struct overlay_ranges *);

#define tty_use_margin(tty) \
	(tty->term->flags & TERM_DECSLRM)
#define tty_full_width(tty, ctx) \
	((ctx)->xoff == 0 && (ctx)->sx >= (tty)->sx)

#define TTY_BLOCK_INTERVAL (100000 /* 100 milliseconds */)
#define TTY_BLOCK_START(tty) (1 + ((tty)->sx * (tty)->sy) * 8)
#define TTY_BLOCK_STOP(tty) (1 + ((tty)->sx * (tty)->sy) / 8)

#define TTY_QUERY_TIMEOUT 5
#define TTY_REQUEST_LIMIT 30

void
tty_create_log(void)
{
	char	name[64];

	xsnprintf(name, sizeof name, "tmux-out-%ld.log", (long)getpid());

	tty_log_fd = open(name, O_WRONLY|O_CREAT|O_TRUNC, 0644);
	if (tty_log_fd != -1 && fcntl(tty_log_fd, F_SETFD, FD_CLOEXEC) == -1)
		fatal("fcntl failed");
}

int
tty_init(struct tty *tty, struct client *c)
{
	if (!isatty(c->fd))
		return (-1);

	memset(tty, 0, sizeof *tty);
	tty->client = c;

	tty->cstyle = SCREEN_CURSOR_DEFAULT;
	tty->ccolour = -1;
	tty->fg = tty->bg = -1;

	if (tcgetattr(c->fd, &tty->tio) != 0)
		return (-1);
	return (0);
}

void
tty_resize(struct tty *tty)
{
	struct client	*c = tty->client;
	struct winsize	 ws;
	u_int		 sx, sy, xpixel, ypixel;

	if (ioctl(c->fd, TIOCGWINSZ, &ws) != -1) {
		sx = ws.ws_col;
		if (sx == 0) {
			sx = 80;
			xpixel = 0;
		} else
			xpixel = ws.ws_xpixel / sx;
		sy = ws.ws_row;
		if (sy == 0) {
			sy = 24;
			ypixel = 0;
		} else
			ypixel = ws.ws_ypixel / sy;
	} else {
		sx = 80;
		sy = 24;
		xpixel = 0;
		ypixel = 0;
	}
	log_debug("%s: %s now %ux%u (%ux%u)", __func__, c->name, sx, sy,
	    xpixel, ypixel);
	tty_set_size(tty, sx, sy, xpixel, ypixel);
	tty_invalidate(tty);
}

void
tty_set_size(struct tty *tty, u_int sx, u_int sy, u_int xpixel, u_int ypixel)
{
	tty->sx = sx;
	tty->sy = sy;
	tty->xpixel = xpixel;
	tty->ypixel = ypixel;
}

static void
tty_read_callback(__unused int fd, __unused short events, void *data)
{
	struct tty	*tty = data;
	struct client	*c = tty->client;
	const char	*name = c->name;
	size_t		 size = EVBUFFER_LENGTH(tty->in);
	int		 nread;

	nread = evbuffer_read(tty->in, c->fd, -1);
	if (nread == 0 || nread == -1) {
		if (nread == 0)
			log_debug("%s: read closed", name);
		else
			log_debug("%s: read error: %s", name, strerror(errno));
		event_del(&tty->event_in);
		server_client_lost(tty->client);
		return;
	}
	log_debug("%s: read %d bytes (already %zu)", name, nread, size);

	while (tty_keys_next(tty))
		;
}

static void
tty_timer_callback(__unused int fd, __unused short events, void *data)
{
	struct tty	*tty = data;
	struct client	*c = tty->client;
	struct timeval	 tv = { .tv_usec = TTY_BLOCK_INTERVAL };

	log_debug("%s: %zu discarded", c->name, tty->discarded);

	c->flags |= CLIENT_ALLREDRAWFLAGS;
	c->discarded += tty->discarded;

	if (tty->discarded < TTY_BLOCK_STOP(tty)) {
		tty->flags &= ~TTY_BLOCK;
		tty_invalidate(tty);
		return;
	}
	tty->discarded = 0;
	evtimer_add(&tty->timer, &tv);
}

static int
tty_block_maybe(struct tty *tty)
{
	struct client	*c = tty->client;
	size_t		 size = EVBUFFER_LENGTH(tty->out);
	struct timeval	 tv = { .tv_usec = TTY_BLOCK_INTERVAL };

	if (size == 0)
		tty->flags &= ~TTY_NOBLOCK;
	else if (tty->flags & TTY_NOBLOCK)
		return (0);

	if (size < TTY_BLOCK_START(tty))
		return (0);

	if (tty->flags & TTY_BLOCK)
		return (1);
	tty->flags |= TTY_BLOCK;

	log_debug("%s: can't keep up, %zu discarded", c->name, size);

	evbuffer_drain(tty->out, size);
	c->discarded += size;

	tty->discarded = 0;
	evtimer_add(&tty->timer, &tv);
	return (1);
}

static void
tty_write_callback(__unused int fd, __unused short events, void *data)
{
	struct tty	*tty = data;
	struct client	*c = tty->client;
	size_t		 size = EVBUFFER_LENGTH(tty->out);
	int		 nwrite;

	nwrite = evbuffer_write(tty->out, c->fd);
	if (nwrite == -1)
		return;
	log_debug("%s: wrote %d bytes (of %zu)", c->name, nwrite, size);

	if (c->redraw > 0) {
		if ((size_t)nwrite >= c->redraw)
			c->redraw = 0;
		else
			c->redraw -= nwrite;
		log_debug("%s: waiting for redraw, %zu bytes left", c->name,
		    c->redraw);
	} else if (tty_block_maybe(tty))
		return;

	if (EVBUFFER_LENGTH(tty->out) != 0)
		event_add(&tty->event_out, NULL);
}

int
tty_open(struct tty *tty, char **cause)
{
	struct client	*c = tty->client;

	tty->term = tty_term_create(tty, c->term_name, c->term_caps,
	    c->term_ncaps, &c->term_features, cause);
	if (tty->term == NULL) {
		tty_close(tty);
		return (-1);
	}
	tty->flags |= TTY_OPENED;

	tty->flags &= ~(TTY_NOCURSOR|TTY_FREEZE|TTY_BLOCK|TTY_TIMER);

	event_set(&tty->event_in, c->fd, EV_PERSIST|EV_READ,
	    tty_read_callback, tty);
	tty->in = evbuffer_new();
	if (tty->in == NULL)
		fatal("out of memory");

	event_set(&tty->event_out, c->fd, EV_WRITE, tty_write_callback, tty);
	tty->out = evbuffer_new();
	if (tty->out == NULL)
		fatal("out of memory");

	evtimer_set(&tty->timer, tty_timer_callback, tty);

	tty_start_tty(tty);
	tty_keys_build(tty);

	return (0);
}

static void
tty_start_timer_callback(__unused int fd, __unused short events, void *data)
{
	struct tty	*tty = data;
	struct client	*c = tty->client;

	log_debug("%s: start timer fired", c->name);
	if ((tty->flags & (TTY_HAVEDA|TTY_HAVEDA2|TTY_HAVEXDA)) == 0)
		tty_update_features(tty);
	tty->flags |= TTY_ALL_REQUEST_FLAGS;
}

void
tty_start_tty(struct tty *tty)
{
	struct client	*c = tty->client;
	struct termios	 tio;
	struct timeval	 tv = { .tv_sec = TTY_QUERY_TIMEOUT };

	setblocking(c->fd, 0);
	event_add(&tty->event_in, NULL);

	memcpy(&tio, &tty->tio, sizeof tio);
	tio.c_iflag &= ~(IXON|IXOFF|ICRNL|INLCR|IGNCR|IMAXBEL|ISTRIP);
	tio.c_iflag |= IGNBRK;
	tio.c_oflag &= ~(OPOST|ONLCR|OCRNL|ONLRET);
	tio.c_lflag &= ~(IEXTEN|ICANON|ECHO|ECHOE|ECHONL|ECHOCTL|ECHOPRT|
	    ECHOKE|ISIG);
	tio.c_cc[VMIN] = 1;
	tio.c_cc[VTIME] = 0;
	if (tcsetattr(c->fd, TCSANOW, &tio) == 0)
		tcflush(c->fd, TCOFLUSH);

	tty_putcode(tty, TTYC_SMCUP);

	tty_putcode(tty, TTYC_SMKX);
	tty_putcode(tty, TTYC_CLEAR);

	if (tty_acs_needed(tty)) {
		log_debug("%s: using capabilities for ACS", c->name);
		tty_putcode(tty, TTYC_ENACS);
	} else
		log_debug("%s: using UTF-8 for ACS", c->name);

	tty_putcode(tty, TTYC_CNORM);
	if (tty_term_has(tty->term, TTYC_KMOUS)) {
		tty_puts(tty, "\033[?1000l\033[?1002l\033[?1003l");
		tty_puts(tty, "\033[?1006l\033[?1005l");
	}
	if (tty_term_has(tty->term, TTYC_ENBP))
		tty_putcode(tty, TTYC_ENBP);

	evtimer_set(&tty->start_timer, tty_start_timer_callback, tty);
	evtimer_add(&tty->start_timer, &tv);

	tty->flags |= TTY_STARTED;
	tty_invalidate(tty);

	if (tty->ccolour != -1)
		tty_force_cursor_colour(tty, -1);

	tty->mouse_drag_flag = 0;
	tty->mouse_drag_update = NULL;
	tty->mouse_drag_release = NULL;
}

void
tty_send_requests(struct tty *tty)
{
	if (~tty->flags & TTY_STARTED)
		return;

	if (tty->term->flags & TERM_VT100LIKE) {
		if (~tty->term->flags & TTY_HAVEDA)
			tty_puts(tty, "\033[c");
		if (~tty->flags & TTY_HAVEDA2)
			tty_puts(tty, "\033[>c");
		if (~tty->flags & TTY_HAVEXDA)
			tty_puts(tty, "\033[>q");
		tty_puts(tty, "\033]10;?\033\\");
		tty_puts(tty, "\033]11;?\033\\");
	} else
		tty->flags |= TTY_ALL_REQUEST_FLAGS;
	tty->last_requests = time(NULL);
}

void
tty_repeat_requests(struct tty *tty)
{
	time_t	t = time(NULL);

	if (~tty->flags & TTY_STARTED)
		return;

	if (t - tty->last_requests <= TTY_REQUEST_LIMIT)
		return;
	tty->last_requests = t;

	if (tty->term->flags & TERM_VT100LIKE) {
		tty_puts(tty, "\033]10;?\033\\");
		tty_puts(tty, "\033]11;?\033\\");
	}
}

void
tty_stop_tty(struct tty *tty)
{
	struct client	*c = tty->client;
	struct winsize	 ws;

	if (!(tty->flags & TTY_STARTED))
		return;
	tty->flags &= ~TTY_STARTED;

	evtimer_del(&tty->start_timer);

	event_del(&tty->timer);
	tty->flags &= ~TTY_BLOCK;

	event_del(&tty->event_in);
	event_del(&tty->event_out);

	/*
	 * Be flexible about error handling and try not kill the server just
	 * because the fd is invalid. Things like ssh -t can easily leave us
	 * with a dead tty.
	 */
	if (ioctl(c->fd, TIOCGWINSZ, &ws) == -1)
		return;
	if (tcsetattr(c->fd, TCSANOW, &tty->tio) == -1)
		return;

	tty_raw(tty, tty_term_string_ii(tty->term, TTYC_CSR, 0, ws.ws_row - 1));
	if (tty_acs_needed(tty))
		tty_raw(tty, tty_term_string(tty->term, TTYC_RMACS));
	tty_raw(tty, tty_term_string(tty->term, TTYC_SGR0));
	tty_raw(tty, tty_term_string(tty->term, TTYC_RMKX));
	tty_raw(tty, tty_term_string(tty->term, TTYC_CLEAR));
	if (tty->cstyle != SCREEN_CURSOR_DEFAULT) {
		if (tty_term_has(tty->term, TTYC_SE))
			tty_raw(tty, tty_term_string(tty->term, TTYC_SE));
		else if (tty_term_has(tty->term, TTYC_SS))
			tty_raw(tty, tty_term_string_i(tty->term, TTYC_SS, 0));
	}
	if (tty->ccolour != -1)
		tty_raw(tty, tty_term_string(tty->term, TTYC_CR));

	tty_raw(tty, tty_term_string(tty->term, TTYC_CNORM));
	if (tty_term_has(tty->term, TTYC_KMOUS)) {
		tty_raw(tty, "\033[?1000l\033[?1002l\033[?1003l");
		tty_raw(tty, "\033[?1006l\033[?1005l");
	}
	if (tty_term_has(tty->term, TTYC_DSBP))
		tty_raw(tty, tty_term_string(tty->term, TTYC_DSBP));

	if (tty->term->flags & TERM_VT100LIKE)
		tty_raw(tty, "\033[?7727l");
	tty_raw(tty, tty_term_string(tty->term, TTYC_DSFCS));
	tty_raw(tty, tty_term_string(tty->term, TTYC_DSEKS));

	if (tty_use_margin(tty))
		tty_raw(tty, tty_term_string(tty->term, TTYC_DSMG));
	tty_raw(tty, tty_term_string(tty->term, TTYC_RMCUP));

	setblocking(c->fd, 1);
}

void
tty_close(struct tty *tty)
{
	if (event_initialized(&tty->key_timer))
		evtimer_del(&tty->key_timer);
	tty_stop_tty(tty);

	if (tty->flags & TTY_OPENED) {
		evbuffer_free(tty->in);
		event_del(&tty->event_in);
		evbuffer_free(tty->out);
		event_del(&tty->event_out);

		tty_term_free(tty->term);
		tty_keys_free(tty);

		tty->flags &= ~TTY_OPENED;
	}
}

void
tty_free(struct tty *tty)
{
	tty_close(tty);
}

void
tty_update_features(struct tty *tty)
{
	struct client	*c = tty->client;

	if (tty_apply_features(tty->term, c->term_features))
		tty_term_apply_overrides(tty->term);

	if (tty_use_margin(tty))
		tty_putcode(tty, TTYC_ENMG);
	if (options_get_number(global_options, "extended-keys"))
		tty_puts(tty, tty_term_string(tty->term, TTYC_ENEKS));
	if (options_get_number(global_options, "focus-events"))
		tty_puts(tty, tty_term_string(tty->term, TTYC_ENFCS));
	if (tty->term->flags & TERM_VT100LIKE)
		tty_puts(tty, "\033[?7727h");

	/*
	 * Features might have changed since the first draw during attach. For
	 * example, this happens when DA responses are received.
	 */
	server_redraw_client(c);

	tty_invalidate(tty);
}

void
tty_raw(struct tty *tty, const char *s)
{
	struct client	*c = tty->client;
	ssize_t		 n, slen;
	u_int		 i;

	slen = strlen(s);
	for (i = 0; i < 5; i++) {
		n = write(c->fd, s, slen);
		if (n >= 0) {
			s += n;
			slen -= n;
			if (slen == 0)
				break;
		} else if (n == -1 && errno != EAGAIN)
			break;
		usleep(100);
	}
}

void
tty_putcode(struct tty *tty, enum tty_code_code code)
{
	tty_puts(tty, tty_term_string(tty->term, code));
}

void
tty_putcode_i(struct tty *tty, enum tty_code_code code, int a)
{
	if (a < 0)
		return;
	tty_puts(tty, tty_term_string_i(tty->term, code, a));
}

void
tty_putcode_ii(struct tty *tty, enum tty_code_code code, int a, int b)
{
	if (a < 0 || b < 0)
		return;
	tty_puts(tty, tty_term_string_ii(tty->term, code, a, b));
}

void
tty_putcode_iii(struct tty *tty, enum tty_code_code code, int a, int b, int c)
{
	if (a < 0 || b < 0 || c < 0)
		return;
	tty_puts(tty, tty_term_string_iii(tty->term, code, a, b, c));
}

void
tty_putcode_s(struct tty *tty, enum tty_code_code code, const char *a)
{
	if (a != NULL)
		tty_puts(tty, tty_term_string_s(tty->term, code, a));
}

void
tty_putcode_ss(struct tty *tty, enum tty_code_code code, const char *a,
    const char *b)
{
	if (a != NULL && b != NULL)
		tty_puts(tty, tty_term_string_ss(tty->term, code, a, b));
}

static void
tty_add(struct tty *tty, const char *buf, size_t len)
{
	struct client	*c = tty->client;

	if (tty->flags & TTY_BLOCK) {
		tty->discarded += len;
		return;
	}

	evbuffer_add(tty->out, buf, len);
	log_debug("%s: %.*s", c->name, (int)len, buf);
	c->written += len;

	if (tty_log_fd != -1)
		write(tty_log_fd, buf, len);
	if (tty->flags & TTY_STARTED)
		event_add(&tty->event_out, NULL);
}

void
tty_puts(struct tty *tty, const char *s)
{
	if (*s != '\0')
		tty_add(tty, s, strlen(s));
}

void
tty_putc(struct tty *tty, u_char ch)
{
	const char	*acs;

	if ((tty->term->flags & TERM_NOAM) &&
	    ch >= 0x20 && ch != 0x7f &&
	    tty->cy == tty->sy - 1 &&
	    tty->cx + 1 >= tty->sx)
		return;

	if (tty->cell.attr & GRID_ATTR_CHARSET) {
		acs = tty_acs_get(tty, ch);
		if (acs != NULL)
			tty_add(tty, acs, strlen(acs));
		else
			tty_add(tty, &ch, 1);
	} else
		tty_add(tty, &ch, 1);

	if (ch >= 0x20 && ch != 0x7f) {
		if (tty->cx >= tty->sx) {
			tty->cx = 1;
			if (tty->cy != tty->rlower)
				tty->cy++;

			/*
			 * On !am terminals, force the cursor position to where
			 * we think it should be after a line wrap - this means
			 * it works on sensible terminals as well.
			 */
			if (tty->term->flags & TERM_NOAM)
				tty_putcode_ii(tty, TTYC_CUP, tty->cy, tty->cx);
		} else
			tty->cx++;
	}
}

void
tty_putn(struct tty *tty, const void *buf, size_t len, u_int width)
{
	if ((tty->term->flags & TERM_NOAM) &&
	    tty->cy == tty->sy - 1 &&
	    tty->cx + len >= tty->sx)
		len = tty->sx - tty->cx - 1;

	tty_add(tty, buf, len);
	if (tty->cx + width > tty->sx) {
		tty->cx = (tty->cx + width) - tty->sx;
		if (tty->cx <= tty->sx)
			tty->cy++;
		else
			tty->cx = tty->cy = UINT_MAX;
	} else
		tty->cx += width;
}

static void
tty_set_italics(struct tty *tty)
{
	const char	*s;

	if (tty_term_has(tty->term, TTYC_SITM)) {
		s = options_get_string(global_options, "default-terminal");
		if (strcmp(s, "screen") != 0 && strncmp(s, "screen-", 7) != 0) {
			tty_putcode(tty, TTYC_SITM);
			return;
		}
	}
	tty_putcode(tty, TTYC_SMSO);
}

void
tty_set_title(struct tty *tty, const char *title)
{
	if (!tty_term_has(tty->term, TTYC_TSL) ||
	    !tty_term_has(tty->term, TTYC_FSL))
		return;

	tty_putcode(tty, TTYC_TSL);
	tty_puts(tty, title);
	tty_putcode(tty, TTYC_FSL);
}

void
tty_set_path(struct tty *tty, const char *title)
{
	if (!tty_term_has(tty->term, TTYC_SWD) ||
	    !tty_term_has(tty->term, TTYC_FSL))
		return;

	tty_putcode(tty, TTYC_SWD);
	tty_puts(tty, title);
	tty_putcode(tty, TTYC_FSL);
}

static void
tty_force_cursor_colour(struct tty *tty, int c)
{
	u_char	r, g, b;
	char	s[13];

	if (c != -1)
		c = colour_force_rgb(c);
	if (c == tty->ccolour)
		return;
	if (c == -1)
		tty_putcode(tty, TTYC_CR);
	else {
		colour_split_rgb(c, &r, &g, &b);
		xsnprintf(s, sizeof s, "rgb:%02hhx/%02hhx/%02hhx", r, g, b);
		tty_putcode_s(tty, TTYC_CS, s);
	}
	tty->ccolour = c;
}

static int
tty_update_cursor(struct tty *tty, int mode, struct screen *s)
{
	enum screen_cursor_style	cstyle;
	int				ccolour, changed, cmode = mode;

	/* Set cursor colour if changed. */
	if (s != NULL) {
		ccolour = s->ccolour;
		if (s->ccolour == -1)
			ccolour = s->default_ccolour;
		tty_force_cursor_colour(tty, ccolour);
	}

	/* If cursor is off, set as invisible. */
	if (~cmode & MODE_CURSOR) {
		if (tty->mode & MODE_CURSOR)
			tty_putcode(tty, TTYC_CIVIS);
		return (cmode);
	}

	/* Check if blinking or very visible flag changed or style changed. */
	if (s == NULL)
		cstyle = tty->cstyle;
	else {
		cstyle = s->cstyle;
		if (cstyle == SCREEN_CURSOR_DEFAULT) {
			if (~cmode & MODE_CURSOR_BLINKING_SET) {
				if (s->default_mode & MODE_CURSOR_BLINKING)
					cmode |= MODE_CURSOR_BLINKING;
				else
					cmode &= ~MODE_CURSOR_BLINKING;
			}
			cstyle = s->default_cstyle;
		}
	}

	/* If nothing changed, do nothing. */
	changed = cmode ^ tty->mode;
	if ((changed & CURSOR_MODES) == 0 && cstyle == tty->cstyle)
		return (cmode);

	/*
	 * Set cursor style. If an explicit style has been set with DECSCUSR,
	 * set it if supported, otherwise send cvvis for blinking styles.
	 *
	 * If no style, has been set (SCREEN_CURSOR_DEFAULT), then send cvvis
	 * if either the blinking or very visible flags are set.
	 */
	tty_putcode(tty, TTYC_CNORM);
	switch (cstyle) {
	case SCREEN_CURSOR_DEFAULT:
		if (tty->cstyle != SCREEN_CURSOR_DEFAULT) {
			if (tty_term_has(tty->term, TTYC_SE))
				tty_putcode(tty, TTYC_SE);
			else
				tty_putcode_i(tty, TTYC_SS, 0);
		}
		if (cmode & (MODE_CURSOR_BLINKING|MODE_CURSOR_VERY_VISIBLE))
			tty_putcode(tty, TTYC_CVVIS);
		break;
	case SCREEN_CURSOR_BLOCK:
		if (tty_term_has(tty->term, TTYC_SS)) {
			if (cmode & MODE_CURSOR_BLINKING)
				tty_putcode_i(tty, TTYC_SS, 1);
			else
				tty_putcode_i(tty, TTYC_SS, 2);
		} else if (cmode & MODE_CURSOR_BLINKING)
			tty_putcode(tty, TTYC_CVVIS);
		break;
	case SCREEN_CURSOR_UNDERLINE:
		if (tty_term_has(tty->term, TTYC_SS)) {
			if (cmode & MODE_CURSOR_BLINKING)
				tty_putcode_i(tty, TTYC_SS, 3);
			else
				tty_putcode_i(tty, TTYC_SS, 4);
		} else if (cmode & MODE_CURSOR_BLINKING)
			tty_putcode(tty, TTYC_CVVIS);
		break;
	case SCREEN_CURSOR_BAR:
		if (tty_term_has(tty->term, TTYC_SS)) {
			if (cmode & MODE_CURSOR_BLINKING)
				tty_putcode_i(tty, TTYC_SS, 5);
			else
				tty_putcode_i(tty, TTYC_SS, 6);
		} else if (cmode & MODE_CURSOR_BLINKING)
			tty_putcode(tty, TTYC_CVVIS);
		break;
	}
	tty->cstyle = cstyle;
	return (cmode);
 }

void
tty_update_mode(struct tty *tty, int mode, struct screen *s)
{
	struct tty_term	*term = tty->term;
	struct client	*c = tty->client;
	int		 changed;

	if (tty->flags & TTY_NOCURSOR)
		mode &= ~MODE_CURSOR;

	if (tty_update_cursor(tty, mode, s) & MODE_CURSOR_BLINKING)
		mode |= MODE_CURSOR_BLINKING;
	else
		mode &= ~MODE_CURSOR_BLINKING;

	changed = mode ^ tty->mode;
	if (log_get_level() != 0 && changed != 0) {
		log_debug("%s: current mode %s", c->name,
		    screen_mode_to_string(tty->mode));
		log_debug("%s: setting mode %s", c->name,
		    screen_mode_to_string(mode));
	}

	if ((changed & ALL_MOUSE_MODES) && tty_term_has(term, TTYC_KMOUS)) {
		/*
		 * If the mouse modes have changed, clear then all and apply
		 * again. There are differences in how terminals track the
		 * various bits.
		 */
		tty_puts(tty, "\033[?1006l\033[?1000l\033[?1002l\033[?1003l");
		if (mode & ALL_MOUSE_MODES)
			tty_puts(tty, "\033[?1006h");
		if (mode & MODE_MOUSE_ALL)
			tty_puts(tty, "\033[?1000h\033[?1002h\033[?1003h");
		else if (mode & MODE_MOUSE_BUTTON)
			tty_puts(tty, "\033[?1000h\033[?1002h");
		else if (mode & MODE_MOUSE_STANDARD)
			tty_puts(tty, "\033[?1000h");
	}
	tty->mode = mode;
}

static void
tty_emulate_repeat(struct tty *tty, enum tty_code_code code,
    enum tty_code_code code1, u_int n)
{
	if (tty_term_has(tty->term, code))
		tty_putcode_i(tty, code, n);
	else {
		while (n-- > 0)
			tty_putcode(tty, code1);
	}
}

static void
tty_repeat_space(struct tty *tty, u_int n)
{
	static char s[500];

	if (*s != ' ')
		memset(s, ' ', sizeof s);

	while (n > sizeof s) {
		tty_putn(tty, s, sizeof s, sizeof s);
		n -= sizeof s;
	}
	if (n != 0)
		tty_putn(tty, s, n, n);
}

/* Is this window bigger than the terminal? */
int
tty_window_bigger(struct tty *tty)
{
	struct client	*c = tty->client;
	struct window	*w = c->session->curw->window;

	return (tty->sx < w->sx || tty->sy - status_line_size(c) < w->sy);
}

/* What offset should this window be drawn at? */
int
tty_window_offset(struct tty *tty, u_int *ox, u_int *oy, u_int *sx, u_int *sy)
{
	*ox = tty->oox;
	*oy = tty->ooy;
	*sx = tty->osx;
	*sy = tty->osy;

	return (tty->oflag);
}

/* What offset should this window be drawn at? */
static int
tty_window_offset1(struct tty *tty, u_int *ox, u_int *oy, u_int *sx, u_int *sy)
{
	struct client		*c = tty->client;
	struct window		*w = c->session->curw->window;
	struct window_pane	*wp = server_client_get_pane(c);
	u_int			 cx, cy, lines;

	lines = status_line_size(c);

	if (tty->sx >= w->sx && tty->sy - lines >= w->sy) {
		*ox = 0;
		*oy = 0;
		*sx = w->sx;
		*sy = w->sy;

		c->pan_window = NULL;
		return (0);
	}

	*sx = tty->sx;
	*sy = tty->sy - lines;

	if (c->pan_window == w) {
		if (*sx >= w->sx)
			c->pan_ox = 0;
		else if (c->pan_ox + *sx > w->sx)
			c->pan_ox = w->sx - *sx;
		*ox = c->pan_ox;
		if (*sy >= w->sy)
			c->pan_oy = 0;
		else if (c->pan_oy + *sy > w->sy)
			c->pan_oy = w->sy - *sy;
		*oy = c->pan_oy;
		return (1);
	}

	if (~wp->screen->mode & MODE_CURSOR) {
		*ox = 0;
		*oy = 0;
	} else {
		cx = wp->xoff + wp->screen->cx;
		cy = wp->yoff + wp->screen->cy;

		if (cx < *sx)
			*ox = 0;
		else if (cx > w->sx - *sx)
			*ox = w->sx - *sx;
		else
			*ox = cx - *sx / 2;

		if (cy < *sy)
			*oy = 0;
		else if (cy > w->sy - *sy)
			*oy = w->sy - *sy;
		else
			*oy = cy - *sy / 2;
	}

	c->pan_window = NULL;
	return (1);
}

/* Update stored offsets for a window and redraw if necessary. */
void
tty_update_window_offset(struct window *w)
{
	struct client	*c;

	TAILQ_FOREACH(c, &clients, entry) {
		if (c->session != NULL &&
		    c->session->curw != NULL &&
		    c->session->curw->window == w)
			tty_update_client_offset(c);
	}
}

/* Update stored offsets for a client and redraw if necessary. */
void
tty_update_client_offset(struct client *c)
{
	u_int	ox, oy, sx, sy;

	if (~c->flags & CLIENT_TERMINAL)
		return;

	c->tty.oflag = tty_window_offset1(&c->tty, &ox, &oy, &sx, &sy);
	if (ox == c->tty.oox &&
	    oy == c->tty.ooy &&
	    sx == c->tty.osx &&
	    sy == c->tty.osy)
		return;

	log_debug ("%s: %s offset has changed (%u,%u %ux%u -> %u,%u %ux%u)",
	    __func__, c->name, c->tty.oox, c->tty.ooy, c->tty.osx, c->tty.osy,
	    ox, oy, sx, sy);

	c->tty.oox = ox;
	c->tty.ooy = oy;
	c->tty.osx = sx;
	c->tty.osy = sy;

	c->flags |= (CLIENT_REDRAWWINDOW|CLIENT_REDRAWSTATUS);
}

/*
 * Is the region large enough to be worth redrawing once later rather than
 * probably several times now? Currently yes if it is more than 50% of the
 * pane.
 */
static int
tty_large_region(__unused struct tty *tty, const struct tty_ctx *ctx)
{
	return (ctx->orlower - ctx->orupper >= ctx->sy / 2);
}

/*
 * Return if BCE is needed but the terminal doesn't have it - it'll need to be
 * emulated.
 */
static int
tty_fake_bce(const struct tty *tty, const struct grid_cell *gc, u_int bg)
{
	if (tty_term_flag(tty->term, TTYC_BCE))
		return (0);
	if (!COLOUR_DEFAULT(bg) || !COLOUR_DEFAULT(gc->bg))
		return (1);
	return (0);
}

/*
 * Redraw scroll region using data from screen (already updated). Used when
 * CSR not supported, or window is a pane that doesn't take up the full
 * width of the terminal.
 */
static void
tty_redraw_region(struct tty *tty, const struct tty_ctx *ctx)
{
	struct client		*c = tty->client;
	u_int			 i;

	/*
	 * If region is large, schedule a redraw. In most cases this is likely
	 * to be followed by some more scrolling.
	 */
	if (tty_large_region(tty, ctx)) {
		log_debug("%s: %s large redraw", __func__, c->name);
		ctx->redraw_cb(ctx);
		return;
	}

	for (i = ctx->orupper; i <= ctx->orlower; i++)
		tty_draw_pane(tty, ctx, i);
}

/* Is this position visible in the pane? */
static int
tty_is_visible(__unused struct tty *tty, const struct tty_ctx *ctx, u_int px,
    u_int py, u_int nx, u_int ny)
{
	u_int	xoff = ctx->rxoff + px, yoff = ctx->ryoff + py;

	if (!ctx->bigger)
		return (1);

	if (xoff + nx <= ctx->wox || xoff >= ctx->wox + ctx->wsx ||
	    yoff + ny <= ctx->woy || yoff >= ctx->woy + ctx->wsy)
		return (0);
	return (1);
}

/* Clamp line position to visible part of pane. */
static int
tty_clamp_line(struct tty *tty, const struct tty_ctx *ctx, u_int px, u_int py,
    u_int nx, u_int *i, u_int *x, u_int *rx, u_int *ry)
{
	u_int	xoff = ctx->rxoff + px;

	if (!tty_is_visible(tty, ctx, px, py, nx, 1))
		return (0);
	*ry = ctx->yoff + py - ctx->woy;

	if (xoff >= ctx->wox && xoff + nx <= ctx->wox + ctx->wsx) {
		/* All visible. */
		*i = 0;
		*x = ctx->xoff + px - ctx->wox;
		*rx = nx;
	} else if (xoff < ctx->wox && xoff + nx > ctx->wox + ctx->wsx) {
		/* Both left and right not visible. */
		*i = ctx->wox;
		*x = 0;
		*rx = ctx->wsx;
	} else if (xoff < ctx->wox) {
		/* Left not visible. */
		*i = ctx->wox - (ctx->xoff + px);
		*x = 0;
		*rx = nx - *i;
	} else {
		/* Right not visible. */
		*i = 0;
		*x = (ctx->xoff + px) - ctx->wox;
		*rx = ctx->wsx - *x;
	}
	if (*rx > nx)
		fatalx("%s: x too big, %u > %u", __func__, *rx, nx);

	return (1);
}

/* Clear a line. */
static void
tty_clear_line(struct tty *tty, const struct grid_cell *defaults, u_int py,
    u_int px, u_int nx, u_int bg)
{
	struct client		*c = tty->client;
	struct overlay_ranges	 r;
	u_int			 i;

	log_debug("%s: %s, %u at %u,%u", __func__, c->name, nx, px, py);

	/* Nothing to clear. */
	if (nx == 0)
		return;

	/* If genuine BCE is available, can try escape sequences. */
	if (c->overlay_check == NULL && !tty_fake_bce(tty, defaults, bg)) {
		/* Off the end of the line, use EL if available. */
		if (px + nx >= tty->sx && tty_term_has(tty->term, TTYC_EL)) {
			tty_cursor(tty, px, py);
			tty_putcode(tty, TTYC_EL);
			return;
		}

		/* At the start of the line. Use EL1. */
		if (px == 0 && tty_term_has(tty->term, TTYC_EL1)) {
			tty_cursor(tty, px + nx - 1, py);
			tty_putcode(tty, TTYC_EL1);
			return;
		}

		/* Section of line. Use ECH if possible. */
		if (tty_term_has(tty->term, TTYC_ECH)) {
			tty_cursor(tty, px, py);
			tty_putcode_i(tty, TTYC_ECH, nx);
			return;
		}
	}

	/*
	 * Couldn't use an escape sequence, use spaces. Clear only the visible
	 * bit if there is an overlay.
	 */
	tty_check_overlay_range(tty, px, py, nx, &r);
	for (i = 0; i < OVERLAY_MAX_RANGES; i++) {
		if (r.nx[i] == 0)
			continue;
		tty_cursor(tty, r.px[i], py);
		tty_repeat_space(tty, r.nx[i]);
	}
}

/* Clear a line, adjusting to visible part of pane. */
static void
tty_clear_pane_line(struct tty *tty, const struct tty_ctx *ctx, u_int py,
    u_int px, u_int nx, u_int bg)
{
	struct client	*c = tty->client;
	u_int		 i, x, rx, ry;

	log_debug("%s: %s, %u at %u,%u", __func__, c->name, nx, px, py);

	if (tty_clamp_line(tty, ctx, px, py, nx, &i, &x, &rx, &ry))
		tty_clear_line(tty, &ctx->defaults, ry, x, rx, bg);
}

/* Clamp area position to visible part of pane. */
static int
tty_clamp_area(struct tty *tty, const struct tty_ctx *ctx, u_int px, u_int py,
    u_int nx, u_int ny, u_int *i, u_int *j, u_int *x, u_int *y, u_int *rx,
    u_int *ry)
{
	u_int	xoff = ctx->rxoff + px, yoff = ctx->ryoff + py;

	if (!tty_is_visible(tty, ctx, px, py, nx, ny))
		return (0);

	if (xoff >= ctx->wox && xoff + nx <= ctx->wox + ctx->wsx) {
		/* All visible. */
		*i = 0;
		*x = ctx->xoff + px - ctx->wox;
		*rx = nx;
	} else if (xoff < ctx->wox && xoff + nx > ctx->wox + ctx->wsx) {
		/* Both left and right not visible. */
		*i = ctx->wox;
		*x = 0;
		*rx = ctx->wsx;
	} else if (xoff < ctx->wox) {
		/* Left not visible. */
		*i = ctx->wox - (ctx->xoff + px);
		*x = 0;
		*rx = nx - *i;
	} else {
		/* Right not visible. */
		*i = 0;
		*x = (ctx->xoff + px) - ctx->wox;
		*rx = ctx->wsx - *x;
	}
	if (*rx > nx)
		fatalx("%s: x too big, %u > %u", __func__, *rx, nx);

	if (yoff >= ctx->woy && yoff + ny <= ctx->woy + ctx->wsy) {
		/* All visible. */
		*j = 0;
		*y = ctx->yoff + py - ctx->woy;
		*ry = ny;
	} else if (yoff < ctx->woy && yoff + ny > ctx->woy + ctx->wsy) {
		/* Both top and bottom not visible. */
		*j = ctx->woy;
		*y = 0;
		*ry = ctx->wsy;
	} else if (yoff < ctx->woy) {
		/* Top not visible. */
		*j = ctx->woy - (ctx->yoff + py);
		*y = 0;
		*ry = ny - *j;
	} else {
		/* Bottom not visible. */
		*j = 0;
		*y = (ctx->yoff + py) - ctx->woy;
		*ry = ctx->wsy - *y;
	}
	if (*ry > ny)
		fatalx("%s: y too big, %u > %u", __func__, *ry, ny);

	return (1);
}

/* Clear an area, adjusting to visible part of pane. */
static void
tty_clear_area(struct tty *tty, const struct grid_cell *defaults, u_int py,
    u_int ny, u_int px, u_int nx, u_int bg)
{
	struct client	*c = tty->client;
	u_int		 yy;
	char		 tmp[64];

	log_debug("%s: %s, %u,%u at %u,%u", __func__, c->name, nx, ny, px, py);

	/* Nothing to clear. */
	if (nx == 0 || ny == 0)
		return;

	/* If genuine BCE is available, can try escape sequences. */
	if (c->overlay_check == NULL && !tty_fake_bce(tty, defaults, bg)) {
		/* Use ED if clearing off the bottom of the terminal. */
		if (px == 0 &&
		    px + nx >= tty->sx &&
		    py + ny >= tty->sy &&
		    tty_term_has(tty->term, TTYC_ED)) {
			tty_cursor(tty, 0, py);
			tty_putcode(tty, TTYC_ED);
			return;
		}

		/*
		 * On VT420 compatible terminals we can use DECFRA if the
		 * background colour isn't default (because it doesn't work
		 * after SGR 0).
		 */
		if ((tty->term->flags & TERM_DECFRA) && !COLOUR_DEFAULT(bg)) {
			xsnprintf(tmp, sizeof tmp, "\033[32;%u;%u;%u;%u$x",
			    py + 1, px + 1, py + ny, px + nx);
			tty_puts(tty, tmp);
			return;
		}

		/* Full lines can be scrolled away to clear them. */
		if (px == 0 &&
		    px + nx >= tty->sx &&
		    ny > 2 &&
		    tty_term_has(tty->term, TTYC_CSR) &&
		    tty_term_has(tty->term, TTYC_INDN)) {
			tty_region(tty, py, py + ny - 1);
			tty_margin_off(tty);
			tty_putcode_i(tty, TTYC_INDN, ny);
			return;
		}

		/*
		 * If margins are supported, can just scroll the area off to
		 * clear it.
		 */
		if (nx > 2 &&
		    ny > 2 &&
		    tty_term_has(tty->term, TTYC_CSR) &&
		    tty_use_margin(tty) &&
		    tty_term_has(tty->term, TTYC_INDN)) {
			tty_region(tty, py, py + ny - 1);
			tty_margin(tty, px, px + nx - 1);
			tty_putcode_i(tty, TTYC_INDN, ny);
			return;
		}
	}

	/* Couldn't use an escape sequence, loop over the lines. */
	for (yy = py; yy < py + ny; yy++)
		tty_clear_line(tty, defaults, yy, px, nx, bg);
}

/* Clear an area in a pane. */
static void
tty_clear_pane_area(struct tty *tty, const struct tty_ctx *ctx, u_int py,
    u_int ny, u_int px, u_int nx, u_int bg)
{
	u_int	i, j, x, y, rx, ry;

	if (tty_clamp_area(tty, ctx, px, py, nx, ny, &i, &j, &x, &y, &rx, &ry))
		tty_clear_area(tty, &ctx->defaults, y, ry, x, rx, bg);
}

static void
tty_draw_pane(struct tty *tty, const struct tty_ctx *ctx, u_int py)
{
	struct screen	*s = ctx->s;
	u_int		 nx = ctx->sx, i, x, rx, ry;

	log_debug("%s: %s %u %d", __func__, tty->client->name, py, ctx->bigger);

	if (!ctx->bigger) {
		tty_draw_line(tty, s, 0, py, nx, ctx->xoff, ctx->yoff + py,
		    &ctx->defaults, ctx->palette);
		return;
	}
	if (tty_clamp_line(tty, ctx, 0, py, nx, &i, &x, &rx, &ry)) {
		tty_draw_line(tty, s, i, py, rx, x, ry, &ctx->defaults,
		    ctx->palette);
	}
}

static const struct grid_cell *
tty_check_codeset(struct tty *tty, const struct grid_cell *gc)
{
	static struct grid_cell	new;
	int			c;

	/* Characters less than 0x7f are always fine, no matter what. */
	if (gc->data.size == 1 && *gc->data.data < 0x7f)
		return (gc);

	/* UTF-8 terminal and a UTF-8 character - fine. */
	if (tty->client->flags & CLIENT_UTF8)
		return (gc);
	memcpy(&new, gc, sizeof new);

	/* See if this can be mapped to an ACS character. */
	c = tty_acs_reverse_get(tty, gc->data.data, gc->data.size);
	if (c != -1) {
		utf8_set(&new.data, c);
		new.attr |= GRID_ATTR_CHARSET;
		return (&new);
	}

	/* Replace by the right number of underscores. */
	new.data.size = gc->data.width;
	if (new.data.size > UTF8_SIZE)
		new.data.size = UTF8_SIZE;
	memset(new.data.data, '_', new.data.size);
	return (&new);
}

/*
 * Check if a single character is obstructed by the overlay and return a
 * boolean.
 */
static int
tty_check_overlay(struct tty *tty, u_int px, u_int py)
{
	struct overlay_ranges	r;

	/*
	 * A unit width range will always return nx[2] == 0 from a check, even
	 * with multiple overlays, so it's sufficient to check just the first
	 * two entries.
	 */
	tty_check_overlay_range(tty, px, py, 1, &r);
	if (r.nx[0] + r.nx[1] == 0)
		return (0);
	return (1);
}

/* Return parts of the input range which are visible. */
static void
tty_check_overlay_range(struct tty *tty, u_int px, u_int py, u_int nx,
    struct overlay_ranges *r)
{
	struct client	*c = tty->client;

	if (c->overlay_check == NULL) {
		r->px[0] = px;
		r->nx[0] = nx;
		r->px[1] = 0;
		r->nx[1] = 0;
		r->px[2] = 0;
		r->nx[2] = 0;
		return;
	}

	c->overlay_check(c, c->overlay_data, px, py, nx, r);
}

void
tty_draw_line(struct tty *tty, struct screen *s, u_int px, u_int py, u_int nx,
    u_int atx, u_int aty, const struct grid_cell *defaults,
    struct colour_palette *palette)
{
	struct grid		*gd = s->grid;
	struct grid_cell	 gc, last;
	const struct grid_cell	*gcp;
	struct grid_line	*gl;
	struct client		*c = tty->client;
	struct overlay_ranges	 r;
	u_int			 i, j, ux, sx, width, hidden, eux, nxx;
	u_int			 cellsize;
	int			 flags, cleared = 0, wrapped = 0;
	char			 buf[512];
	size_t			 len;

	log_debug("%s: px=%u py=%u nx=%u atx=%u aty=%u", __func__,
	    px, py, nx, atx, aty);
	log_debug("%s: defaults: fg=%d, bg=%d", __func__, defaults->fg,
	    defaults->bg);

	/*
	 * py is the line in the screen to draw.
	 * px is the start x and nx is the width to draw.
	 * atx,aty is the line on the terminal to draw it.
	 */

	flags = (tty->flags & TTY_NOCURSOR);
	tty->flags |= TTY_NOCURSOR;
	tty_update_mode(tty, tty->mode, s);

	tty_region_off(tty);
	tty_margin_off(tty);

	/*
	 * Clamp the width to cellsize - note this is not cellused, because
	 * there may be empty background cells after it (from BCE).
	 */
	sx = screen_size_x(s);
	if (nx > sx)
		nx = sx;
	cellsize = grid_get_line(gd, gd->hsize + py)->cellsize;
	if (sx > cellsize)
		sx = cellsize;
	if (sx > tty->sx)
		sx = tty->sx;
	if (sx > nx)
		sx = nx;
	ux = 0;

	if (py == 0)
		gl = NULL;
	else
		gl = grid_get_line(gd, gd->hsize + py - 1);
	if (gl == NULL ||
	    (~gl->flags & GRID_LINE_WRAPPED) ||
	    atx != 0 ||
	    tty->cx < tty->sx ||
	    nx < tty->sx) {
		if (nx < tty->sx &&
		    atx == 0 &&
		    px + sx != nx &&
		    tty_term_has(tty->term, TTYC_EL1) &&
		    !tty_fake_bce(tty, defaults, 8) &&
		    c->overlay_check == NULL) {
			tty_default_attributes(tty, defaults, palette, 8,
			    s->hyperlinks);
			tty_cursor(tty, nx - 1, aty);
			tty_putcode(tty, TTYC_EL1);
			cleared = 1;
		}
	} else {
		log_debug("%s: wrapped line %u", __func__, aty);
		wrapped = 1;
	}

	memcpy(&last, &grid_default_cell, sizeof last);
	len = 0;
	width = 0;

	for (i = 0; i < sx; i++) {
		grid_view_get_cell(gd, px + i, py, &gc);
		gcp = tty_check_codeset(tty, &gc);
		if (len != 0 &&
		    (!tty_check_overlay(tty, atx + ux + width, aty) ||
		    (gcp->attr & GRID_ATTR_CHARSET) ||
		    gcp->flags != last.flags ||
		    gcp->attr != last.attr ||
		    gcp->fg != last.fg ||
		    gcp->bg != last.bg ||
		    gcp->us != last.us ||
		    gcp->link != last.link ||
		    ux + width + gcp->data.width > nx ||
		    (sizeof buf) - len < gcp->data.size)) {
			tty_attributes(tty, &last, defaults, palette,
			    s->hyperlinks);
			if (last.flags & GRID_FLAG_CLEARED) {
				log_debug("%s: %zu cleared", __func__, len);
				tty_clear_line(tty, defaults, aty, atx + ux,
				    width, last.bg);
			} else {
				if (!wrapped || atx != 0 || ux != 0)
					tty_cursor(tty, atx + ux, aty);
				tty_putn(tty, buf, len, width);
			}
			ux += width;

			len = 0;
			width = 0;
			wrapped = 0;
		}

		if (gcp->flags & GRID_FLAG_SELECTED)
			screen_select_cell(s, &last, gcp);
		else
			memcpy(&last, gcp, sizeof last);

		tty_check_overlay_range(tty, atx + ux, aty, gcp->data.width,
		    &r);
		hidden = 0;
		for (j = 0; j < OVERLAY_MAX_RANGES; j++)
			hidden += r.nx[j];
		hidden = gcp->data.width - hidden;
		if (hidden != 0 && hidden == gcp->data.width) {
			if (~gcp->flags & GRID_FLAG_PADDING)
				ux += gcp->data.width;
		} else if (hidden != 0 || ux + gcp->data.width > nx) {
			if (~gcp->flags & GRID_FLAG_PADDING) {
				tty_attributes(tty, &last, defaults, palette,
				    s->hyperlinks);
				for (j = 0; j < OVERLAY_MAX_RANGES; j++) {
					if (r.nx[j] == 0)
						continue;
					/* Effective width drawn so far. */
					eux = r.px[j] - atx;
					if (eux < nx) {
						tty_cursor(tty, r.px[j], aty);
						nxx = nx - eux;
						if (r.nx[j] > nxx)
							r.nx[j] = nxx;
						tty_repeat_space(tty, r.nx[j]);
						ux = eux + r.nx[j];
					}
				}
			}
		} else if (gcp->attr & GRID_ATTR_CHARSET) {
			tty_attributes(tty, &last, defaults, palette,
			    s->hyperlinks);
			tty_cursor(tty, atx + ux, aty);
			for (j = 0; j < gcp->data.size; j++)
				tty_putc(tty, gcp->data.data[j]);
			ux += gcp->data.width;
		} else if (~gcp->flags & GRID_FLAG_PADDING) {
			memcpy(buf + len, gcp->data.data, gcp->data.size);
			len += gcp->data.size;
			width += gcp->data.width;
		}
	}
	if (len != 0 && ((~last.flags & GRID_FLAG_CLEARED) || last.bg != 8)) {
		tty_attributes(tty, &last, defaults, palette, s->hyperlinks);
		if (last.flags & GRID_FLAG_CLEARED) {
			log_debug("%s: %zu cleared (end)", __func__, len);
			tty_clear_line(tty, defaults, aty, atx + ux, width,
			    last.bg);
		} else {
			if (!wrapped || atx != 0 || ux != 0)
				tty_cursor(tty, atx + ux, aty);
			tty_putn(tty, buf, len, width);
		}
		ux += width;
	}

	if (!cleared && ux < nx) {
		log_debug("%s: %u to end of line (%zu cleared)", __func__,
		    nx - ux, len);
		tty_default_attributes(tty, defaults, palette, 8,
		    s->hyperlinks);
		tty_clear_line(tty, defaults, aty, atx + ux, nx - ux, 8);
	}

	tty->flags = (tty->flags & ~TTY_NOCURSOR) | flags;
	tty_update_mode(tty, tty->mode, s);
}

void
tty_sync_start(struct tty *tty)
{
	if (tty->flags & TTY_BLOCK)
		return;
	if (tty->flags & TTY_SYNCING)
		return;
	tty->flags |= TTY_SYNCING;

	if (tty_term_has(tty->term, TTYC_SYNC)) {
		log_debug("%s sync start", tty->client->name);
		tty_putcode_i(tty, TTYC_SYNC, 1);
	}
}

void
tty_sync_end(struct tty *tty)
{
	if (tty->flags & TTY_BLOCK)
		return;
	if (~tty->flags & TTY_SYNCING)
		return;
	tty->flags &= ~TTY_SYNCING;

	if (tty_term_has(tty->term, TTYC_SYNC)) {
 		log_debug("%s sync end", tty->client->name);
		tty_putcode_i(tty, TTYC_SYNC, 2);
	}
}

static int
tty_client_ready(const struct tty_ctx *ctx, struct client *c)
{
	if (c->session == NULL || c->tty.term == NULL)
		return (0);
	if (c->flags & CLIENT_SUSPENDED)
		return (0);

	/*
	 * If invisible panes are allowed (used for passthrough), don't care if
	 * redrawing or frozen.
	 */
	if (ctx->allow_invisible_panes)
		return (1);

	if (c->flags & CLIENT_REDRAWWINDOW)
		return (0);
	if (c->tty.flags & TTY_FREEZE)
		return (0);
	return (1);
}

void
tty_write(void (*cmdfn)(struct tty *, const struct tty_ctx *),
    struct tty_ctx *ctx)
{
	struct client	*c;
	int		 state;

	if (ctx->set_client_cb == NULL)
		return;
	TAILQ_FOREACH(c, &clients, entry) {
		if (tty_client_ready(ctx, c)) {
			state = ctx->set_client_cb(ctx, c);
			if (state == -1)
				break;
			if (state == 0)
				continue;
			cmdfn(&c->tty, ctx);
		}
	}
}

void
tty_cmd_insertcharacter(struct tty *tty, const struct tty_ctx *ctx)
{
	struct client	*c = tty->client;

	if (ctx->bigger ||
	    !tty_full_width(tty, ctx) ||
	    tty_fake_bce(tty, &ctx->defaults, ctx->bg) ||
	    (!tty_term_has(tty->term, TTYC_ICH) &&
	    !tty_term_has(tty->term, TTYC_ICH1)) ||
	    c->overlay_check != NULL) {
		tty_draw_pane(tty, ctx, ctx->ocy);
		return;
	}

	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
	    ctx->s->hyperlinks);

	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);

	tty_emulate_repeat(tty, TTYC_ICH, TTYC_ICH1, ctx->num);
}

void
tty_cmd_deletecharacter(struct tty *tty, const struct tty_ctx *ctx)
{
	struct client	*c = tty->client;

	if (ctx->bigger ||
	    !tty_full_width(tty, ctx) ||
	    tty_fake_bce(tty, &ctx->defaults, ctx->bg) ||
	    (!tty_term_has(tty->term, TTYC_DCH) &&
	    !tty_term_has(tty->term, TTYC_DCH1)) ||
	    c->overlay_check != NULL) {
		tty_draw_pane(tty, ctx, ctx->ocy);
		return;
	}

	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
	    ctx->s->hyperlinks);

	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);

	tty_emulate_repeat(tty, TTYC_DCH, TTYC_DCH1, ctx->num);
}

void
tty_cmd_clearcharacter(struct tty *tty, const struct tty_ctx *ctx)
{
	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
	    ctx->s->hyperlinks);

	tty_clear_pane_line(tty, ctx, ctx->ocy, ctx->ocx, ctx->num, ctx->bg);
}

void
tty_cmd_insertline(struct tty *tty, const struct tty_ctx *ctx)
{
	struct client	*c = tty->client;

	if (ctx->bigger ||
	    !tty_full_width(tty, ctx) ||
	    tty_fake_bce(tty, &ctx->defaults, ctx->bg) ||
	    !tty_term_has(tty->term, TTYC_CSR) ||
	    !tty_term_has(tty->term, TTYC_IL1) ||
	    ctx->sx == 1 ||
	    ctx->sy == 1 ||
	    c->overlay_check != NULL) {
		tty_redraw_region(tty, ctx);
		return;
	}

	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
	    ctx->s->hyperlinks);

	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
	tty_margin_off(tty);
	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);

	tty_emulate_repeat(tty, TTYC_IL, TTYC_IL1, ctx->num);
	tty->cx = tty->cy = UINT_MAX;
}

void
tty_cmd_deleteline(struct tty *tty, const struct tty_ctx *ctx)
{
	struct client	*c = tty->client;

	if (ctx->bigger ||
	    !tty_full_width(tty, ctx) ||
	    tty_fake_bce(tty, &ctx->defaults, ctx->bg) ||
	    !tty_term_has(tty->term, TTYC_CSR) ||
	    !tty_term_has(tty->term, TTYC_DL1) ||
	    ctx->sx == 1 ||
	    ctx->sy == 1 ||
	    c->overlay_check != NULL) {
		tty_redraw_region(tty, ctx);
		return;
	}

	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
	    ctx->s->hyperlinks);

	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
	tty_margin_off(tty);
	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);

	tty_emulate_repeat(tty, TTYC_DL, TTYC_DL1, ctx->num);
	tty->cx = tty->cy = UINT_MAX;
}

void
tty_cmd_clearline(struct tty *tty, const struct tty_ctx *ctx)
{
	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
	    ctx->s->hyperlinks);

	tty_clear_pane_line(tty, ctx, ctx->ocy, 0, ctx->sx, ctx->bg);
}

void
tty_cmd_clearendofline(struct tty *tty, const struct tty_ctx *ctx)
{
	u_int	nx = ctx->sx - ctx->ocx;

	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
	    ctx->s->hyperlinks);

	tty_clear_pane_line(tty, ctx, ctx->ocy, ctx->ocx, nx, ctx->bg);
}

void
tty_cmd_clearstartofline(struct tty *tty, const struct tty_ctx *ctx)
{
	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
	    ctx->s->hyperlinks);

	tty_clear_pane_line(tty, ctx, ctx->ocy, 0, ctx->ocx + 1, ctx->bg);
}

void
tty_cmd_reverseindex(struct tty *tty, const struct tty_ctx *ctx)
{
	struct client	*c = tty->client;

	if (ctx->ocy != ctx->orupper)
		return;

	if (ctx->bigger ||
	    (!tty_full_width(tty, ctx) && !tty_use_margin(tty)) ||
	    tty_fake_bce(tty, &ctx->defaults, 8) ||
	    !tty_term_has(tty->term, TTYC_CSR) ||
	    (!tty_term_has(tty->term, TTYC_RI) &&
	    !tty_term_has(tty->term, TTYC_RIN)) ||
	    ctx->sx == 1 ||
	    ctx->sy == 1 ||
	    c->overlay_check != NULL) {
		tty_redraw_region(tty, ctx);
		return;
	}

	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
	    ctx->s->hyperlinks);

	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
	tty_margin_pane(tty, ctx);
	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->orupper);

	if (tty_term_has(tty->term, TTYC_RI))
		tty_putcode(tty, TTYC_RI);
	else
		tty_putcode_i(tty, TTYC_RIN, 1);
}

void
tty_cmd_linefeed(struct tty *tty, const struct tty_ctx *ctx)
{
	struct client	*c = tty->client;

	if (ctx->ocy != ctx->orlower)
		return;

	if (ctx->bigger ||
	    (!tty_full_width(tty, ctx) && !tty_use_margin(tty)) ||
	    tty_fake_bce(tty, &ctx->defaults, 8) ||
	    !tty_term_has(tty->term, TTYC_CSR) ||
	    ctx->sx == 1 ||
	    ctx->sy == 1 ||
	    c->overlay_check != NULL) {
		tty_redraw_region(tty, ctx);
		return;
	}

	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
	    ctx->s->hyperlinks);

	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
	tty_margin_pane(tty, ctx);

	/*
	 * If we want to wrap a pane while using margins, the cursor needs to
	 * be exactly on the right of the region. If the cursor is entirely off
	 * the edge - move it back to the right. Some terminals are funny about
	 * this and insert extra spaces, so only use the right if margins are
	 * enabled.
	 */
	if (ctx->xoff + ctx->ocx > tty->rright) {
		if (!tty_use_margin(tty))
			tty_cursor(tty, 0, ctx->yoff + ctx->ocy);
		else
			tty_cursor(tty, tty->rright, ctx->yoff + ctx->ocy);
	} else
		tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);

	tty_putc(tty, '\n');
}

void
tty_cmd_scrollup(struct tty *tty, const struct tty_ctx *ctx)
{
	struct client	*c = tty->client;
	u_int		 i;

	if (ctx->bigger ||
	    (!tty_full_width(tty, ctx) && !tty_use_margin(tty)) ||
	    tty_fake_bce(tty, &ctx->defaults, 8) ||
	    !tty_term_has(tty->term, TTYC_CSR) ||
	    ctx->sx == 1 ||
	    ctx->sy == 1 ||
	    c->overlay_check != NULL) {
		tty_redraw_region(tty, ctx);
		return;
	}

	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
	    ctx->s->hyperlinks);

	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
	tty_margin_pane(tty, ctx);

	if (ctx->num == 1 || !tty_term_has(tty->term, TTYC_INDN)) {
		if (!tty_use_margin(tty))
			tty_cursor(tty, 0, tty->rlower);
		else
			tty_cursor(tty, tty->rright, tty->rlower);
		for (i = 0; i < ctx->num; i++)
			tty_putc(tty, '\n');
	} else {
		if (tty->cy == UINT_MAX)
			tty_cursor(tty, 0, 0);
		else
			tty_cursor(tty, 0, tty->cy);
		tty_putcode_i(tty, TTYC_INDN, ctx->num);
	}
}

void
tty_cmd_scrolldown(struct tty *tty, const struct tty_ctx *ctx)
{
	u_int		 i;
	struct client	*c = tty->client;

	if (ctx->bigger ||
	    (!tty_full_width(tty, ctx) && !tty_use_margin(tty)) ||
	    tty_fake_bce(tty, &ctx->defaults, 8) ||
	    !tty_term_has(tty->term, TTYC_CSR) ||
	    (!tty_term_has(tty->term, TTYC_RI) &&
	    !tty_term_has(tty->term, TTYC_RIN)) ||
	    ctx->sx == 1 ||
	    ctx->sy == 1 ||
	    c->overlay_check != NULL) {
		tty_redraw_region(tty, ctx);
		return;
	}

	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
	    ctx->s->hyperlinks);

	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
	tty_margin_pane(tty, ctx);
	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->orupper);

	if (tty_term_has(tty->term, TTYC_RIN))
		tty_putcode_i(tty, TTYC_RIN, ctx->num);
	else {
		for (i = 0; i < ctx->num; i++)
			tty_putcode(tty, TTYC_RI);
	}
}

void
tty_cmd_clearendofscreen(struct tty *tty, const struct tty_ctx *ctx)
{
	u_int	px, py, nx, ny;

	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
	    ctx->s->hyperlinks);

	tty_region_pane(tty, ctx, 0, ctx->sy - 1);
	tty_margin_off(tty);

	px = 0;
	nx = ctx->sx;
	py = ctx->ocy + 1;
	ny = ctx->sy - ctx->ocy - 1;

	tty_clear_pane_area(tty, ctx, py, ny, px, nx, ctx->bg);

	px = ctx->ocx;
	nx = ctx->sx - ctx->ocx;
	py = ctx->ocy;

	tty_clear_pane_line(tty, ctx, py, px, nx, ctx->bg);
}

void
tty_cmd_clearstartofscreen(struct tty *tty, const struct tty_ctx *ctx)
{
	u_int	px, py, nx, ny;

	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
	    ctx->s->hyperlinks);

	tty_region_pane(tty, ctx, 0, ctx->sy - 1);
	tty_margin_off(tty);

	px = 0;
	nx = ctx->sx;
	py = 0;
	ny = ctx->ocy;

	tty_clear_pane_area(tty, ctx, py, ny, px, nx, ctx->bg);

	px = 0;
	nx = ctx->ocx + 1;
	py = ctx->ocy;

	tty_clear_pane_line(tty, ctx, py, px, nx, ctx->bg);
}

void
tty_cmd_clearscreen(struct tty *tty, const struct tty_ctx *ctx)
{
	u_int	px, py, nx, ny;

	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
	    ctx->s->hyperlinks);

	tty_region_pane(tty, ctx, 0, ctx->sy - 1);
	tty_margin_off(tty);

	px = 0;
	nx = ctx->sx;
	py = 0;
	ny = ctx->sy;

	tty_clear_pane_area(tty, ctx, py, ny, px, nx, ctx->bg);
}

void
tty_cmd_alignmenttest(struct tty *tty, const struct tty_ctx *ctx)
{
	u_int	i, j;

	if (ctx->bigger) {
		ctx->redraw_cb(ctx);
		return;
	}

	tty_attributes(tty, &grid_default_cell, &ctx->defaults, ctx->palette,
	    ctx->s->hyperlinks);

	tty_region_pane(tty, ctx, 0, ctx->sy - 1);
	tty_margin_off(tty);

	for (j = 0; j < ctx->sy; j++) {
		tty_cursor_pane(tty, ctx, 0, j);
		for (i = 0; i < ctx->sx; i++)
			tty_putc(tty, 'E');
	}
}

void
tty_cmd_cell(struct tty *tty, const struct tty_ctx *ctx)
{
	const struct grid_cell	*gcp = ctx->cell;
	struct screen		*s = ctx->s;
	struct overlay_ranges	 r;
	u_int			 px, py, i, vis = 0;

	px = ctx->xoff + ctx->ocx - ctx->wox;
	py = ctx->yoff + ctx->ocy - ctx->woy;
	if (!tty_is_visible(tty, ctx, ctx->ocx, ctx->ocy, 1, 1) ||
	    (gcp->data.width == 1 && !tty_check_overlay(tty, px, py)))
		return;

	/* Handle partially obstructed wide characters. */
	if (gcp->data.width > 1) {
		tty_check_overlay_range(tty, px, py, gcp->data.width, &r);
		for (i = 0; i < OVERLAY_MAX_RANGES; i++)
			vis += r.nx[i];
		if (vis < gcp->data.width) {
			tty_draw_line(tty, s, s->cx, s->cy, gcp->data.width,
			    px, py, &ctx->defaults, ctx->palette);
			return;
		}
	}

	if (ctx->xoff + ctx->ocx - ctx->wox > tty->sx - 1 &&
	    ctx->ocy == ctx->orlower &&
	    tty_full_width(tty, ctx))
		tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);

	tty_margin_off(tty);
	tty_cursor_pane_unless_wrap(tty, ctx, ctx->ocx, ctx->ocy);

	tty_cell(tty, ctx->cell, &ctx->defaults, ctx->palette,
	    ctx->s->hyperlinks);

	if (ctx->num == 1)
		tty_invalidate(tty);
}

void
tty_cmd_cells(struct tty *tty, const struct tty_ctx *ctx)
{
	struct overlay_ranges	 r;
	u_int			 i, px, py, cx;
	char			*cp = ctx->ptr;

	if (!tty_is_visible(tty, ctx, ctx->ocx, ctx->ocy, ctx->num, 1))
		return;

	if (ctx->bigger &&
	    (ctx->xoff + ctx->ocx < ctx->wox ||
	    ctx->xoff + ctx->ocx + ctx->num > ctx->wox + ctx->wsx)) {
		if (!ctx->wrapped ||
		    !tty_full_width(tty, ctx) ||
		    (tty->term->flags & TERM_NOAM) ||
		    ctx->xoff + ctx->ocx != 0 ||
		    ctx->yoff + ctx->ocy != tty->cy + 1 ||
		    tty->cx < tty->sx ||
		    tty->cy == tty->rlower)
			tty_draw_pane(tty, ctx, ctx->ocy);
		else
			ctx->redraw_cb(ctx);
		return;
	}

	tty_margin_off(tty);
	tty_cursor_pane_unless_wrap(tty, ctx, ctx->ocx, ctx->ocy);
	tty_attributes(tty, ctx->cell, &ctx->defaults, ctx->palette, ctx->s->hyperlinks);

	/* Get tty position from pane position for overlay check. */
	px = ctx->xoff + ctx->ocx - ctx->wox;
	py = ctx->yoff + ctx->ocy - ctx->woy;

	tty_check_overlay_range(tty, px, py, ctx->num, &r);
	for (i = 0; i < OVERLAY_MAX_RANGES; i++) {
		if (r.nx[i] == 0)
			continue;
		/* Convert back to pane position for printing. */
		cx = r.px[i] - ctx->xoff + ctx->wox;
		tty_cursor_pane_unless_wrap(tty, ctx, cx, ctx->ocy);
		tty_putn(tty, cp + r.px[i] - px, r.nx[i], r.nx[i]);
	}
}

void
tty_cmd_setselection(struct tty *tty, const struct tty_ctx *ctx)
{
	tty_set_selection(tty, ctx->ptr2, ctx->ptr, ctx->num);
}

void
tty_set_selection(struct tty *tty, const char *flags, const char *buf,
    size_t len)
{
	char	*encoded;
	size_t	 size;

	if (~tty->flags & TTY_STARTED)
		return;
	if (!tty_term_has(tty->term, TTYC_MS))
		return;

	size = 4 * ((len + 2) / 3) + 1; /* storage for base64 */
	encoded = xmalloc(size);

	b64_ntop(buf, len, encoded, size);
	tty->flags |= TTY_NOBLOCK;
	tty_putcode_ss(tty, TTYC_MS, flags, encoded);

	free(encoded);
}

void
tty_cmd_rawstring(struct tty *tty, const struct tty_ctx *ctx)
{
	tty->flags |= TTY_NOBLOCK;
	tty_add(tty, ctx->ptr, ctx->num);
	tty_invalidate(tty);
}

void
tty_cmd_syncstart(struct tty *tty, const struct tty_ctx *ctx)
{
	if (ctx->num == 0x11) {
		/*
		 * This is an overlay and a command that moves the cursor so
		 * start synchronized updates.
		 */
		tty_sync_start(tty);
	} else if (~ctx->num & 0x10) {
		/*
		 * This is a pane. If there is an overlay, always start;
		 * otherwise, only if requested.
		 */
		if (ctx->num || tty->client->overlay_draw != NULL)
			tty_sync_start(tty);
	}
}

void
tty_cell(struct tty *tty, const struct grid_cell *gc,
    const struct grid_cell *defaults, struct colour_palette *palette,
    struct hyperlinks *hl)
{
	const struct grid_cell	*gcp;

	/* Skip last character if terminal is stupid. */
	if ((tty->term->flags & TERM_NOAM) &&
	    tty->cy == tty->sy - 1 &&
	    tty->cx == tty->sx - 1)
		return;

	/* If this is a padding character, do nothing. */
	if (gc->flags & GRID_FLAG_PADDING)
		return;

	/* Check the output codeset and apply attributes. */
	gcp = tty_check_codeset(tty, gc);
	tty_attributes(tty, gcp, defaults, palette, hl);

	/* If it is a single character, write with putc to handle ACS. */
	if (gcp->data.size == 1) {
		tty_attributes(tty, gcp, defaults, palette, hl);
		if (*gcp->data.data < 0x20 || *gcp->data.data == 0x7f)
			return;
		tty_putc(tty, *gcp->data.data);
		return;
	}

	/* Write the data. */
	tty_putn(tty, gcp->data.data, gcp->data.size, gcp->data.width);
}

void
tty_reset(struct tty *tty)
{
	struct grid_cell	*gc = &tty->cell;

	if (!grid_cells_equal(gc, &grid_default_cell)) {
		if (gc->link != 0)
			tty_putcode_ss(tty, TTYC_HLS, "", "");
		if ((gc->attr & GRID_ATTR_CHARSET) && tty_acs_needed(tty))
			tty_putcode(tty, TTYC_RMACS);
		tty_putcode(tty, TTYC_SGR0);
		memcpy(gc, &grid_default_cell, sizeof *gc);
	}
	memcpy(&tty->last_cell, &grid_default_cell, sizeof tty->last_cell);
}

static void
tty_invalidate(struct tty *tty)
{
	memcpy(&tty->cell, &grid_default_cell, sizeof tty->cell);
	memcpy(&tty->last_cell, &grid_default_cell, sizeof tty->last_cell);

	tty->cx = tty->cy = UINT_MAX;
	tty->rupper = tty->rleft = UINT_MAX;
	tty->rlower = tty->rright = UINT_MAX;

	if (tty->flags & TTY_STARTED) {
		if (tty_use_margin(tty))
			tty_putcode(tty, TTYC_ENMG);
		tty_putcode(tty, TTYC_SGR0);

		tty->mode = ALL_MODES;
		tty_update_mode(tty, MODE_CURSOR, NULL);

		tty_cursor(tty, 0, 0);
		tty_region_off(tty);
		tty_margin_off(tty);
	} else
		tty->mode = MODE_CURSOR;
}

/* Turn off margin. */
void
tty_region_off(struct tty *tty)
{
	tty_region(tty, 0, tty->sy - 1);
}

/* Set region inside pane. */
static void
tty_region_pane(struct tty *tty, const struct tty_ctx *ctx, u_int rupper,
    u_int rlower)
{
	tty_region(tty, ctx->yoff + rupper - ctx->woy,
	    ctx->yoff + rlower - ctx->woy);
}

/* Set region at absolute position. */
static void
tty_region(struct tty *tty, u_int rupper, u_int rlower)
{
	if (tty->rlower == rlower && tty->rupper == rupper)
		return;
	if (!tty_term_has(tty->term, TTYC_CSR))
		return;

	tty->rupper = rupper;
	tty->rlower = rlower;

	/*
	 * Some terminals (such as PuTTY) do not correctly reset the cursor to
	 * 0,0 if it is beyond the last column (they do not reset their wrap
	 * flag so further output causes a line feed). As a workaround, do an
	 * explicit move to 0 first.
	 */
	if (tty->cx >= tty->sx) {
		if (tty->cy == UINT_MAX)
			tty_cursor(tty, 0, 0);
		else
			tty_cursor(tty, 0, tty->cy);
	}

	tty_putcode_ii(tty, TTYC_CSR, tty->rupper, tty->rlower);
	tty->cx = tty->cy = UINT_MAX;
}

/* Turn off margin. */
void
tty_margin_off(struct tty *tty)
{
	tty_margin(tty, 0, tty->sx - 1);
}

/* Set margin inside pane. */
static void
tty_margin_pane(struct tty *tty, const struct tty_ctx *ctx)
{
	tty_margin(tty, ctx->xoff - ctx->wox,
	    ctx->xoff + ctx->sx - 1 - ctx->wox);
}

/* Set margin at absolute position. */
static void
tty_margin(struct tty *tty, u_int rleft, u_int rright)
{
	if (!tty_use_margin(tty))
		return;
	if (tty->rleft == rleft && tty->rright == rright)
		return;

	tty_putcode_ii(tty, TTYC_CSR, tty->rupper, tty->rlower);

	tty->rleft = rleft;
	tty->rright = rright;

	if (rleft == 0 && rright == tty->sx - 1)
		tty_putcode(tty, TTYC_CLMG);
	else
		tty_putcode_ii(tty, TTYC_CMG, rleft, rright);
	tty->cx = tty->cy = UINT_MAX;
}

/*
 * Move the cursor, unless it would wrap itself when the next character is
 * printed.
 */
static void
tty_cursor_pane_unless_wrap(struct tty *tty, const struct tty_ctx *ctx,
    u_int cx, u_int cy)
{
	if (!ctx->wrapped ||
	    !tty_full_width(tty, ctx) ||
	    (tty->term->flags & TERM_NOAM) ||
	    ctx->xoff + cx != 0 ||
	    ctx->yoff + cy != tty->cy + 1 ||
	    tty->cx < tty->sx ||
	    tty->cy == tty->rlower)
		tty_cursor_pane(tty, ctx, cx, cy);
	else
		log_debug("%s: will wrap at %u,%u", __func__, tty->cx, tty->cy);
}

/* Move cursor inside pane. */
static void
tty_cursor_pane(struct tty *tty, const struct tty_ctx *ctx, u_int cx, u_int cy)
{
	tty_cursor(tty, ctx->xoff + cx - ctx->wox, ctx->yoff + cy - ctx->woy);
}

/* Move cursor to absolute position. */
void
tty_cursor(struct tty *tty, u_int cx, u_int cy)
{
	struct tty_term	*term = tty->term;
	u_int		 thisx, thisy;
	int		 change;

	if (tty->flags & TTY_BLOCK)
		return;

	thisx = tty->cx;
	thisy = tty->cy;

	/*
	 * If in the automargin space, and want to be there, do not move.
	 * Otherwise, force the cursor to be in range (and complain).
	 */
	if (cx == thisx && cy == thisy && cx == tty->sx)
		return;
	if (cx > tty->sx - 1) {
		log_debug("%s: x too big %u > %u", __func__, cx, tty->sx - 1);
		cx = tty->sx - 1;
	}

	/* No change. */
	if (cx == thisx && cy == thisy)
		return;

	/* Currently at the very end of the line - use absolute movement. */
	if (thisx > tty->sx - 1)
		goto absolute;

	/* Move to home position (0, 0). */
	if (cx == 0 && cy == 0 && tty_term_has(term, TTYC_HOME)) {
		tty_putcode(tty, TTYC_HOME);
		goto out;
	}

	/* Zero on the next line. */
	if (cx == 0 && cy == thisy + 1 && thisy != tty->rlower &&
	    (!tty_use_margin(tty) || tty->rleft == 0)) {
		tty_putc(tty, '\r');
		tty_putc(tty, '\n');
		goto out;
	}

	/* Moving column or row. */
	if (cy == thisy) {
		/*
		 * Moving column only, row staying the same.
		 */

		/* To left edge. */
		if (cx == 0 && (!tty_use_margin(tty) || tty->rleft == 0)) {
			tty_putc(tty, '\r');
			goto out;
		}

		/* One to the left. */
		if (cx == thisx - 1 && tty_term_has(term, TTYC_CUB1)) {
			tty_putcode(tty, TTYC_CUB1);
			goto out;
		}

		/* One to the right. */
		if (cx == thisx + 1 && tty_term_has(term, TTYC_CUF1)) {
			tty_putcode(tty, TTYC_CUF1);
			goto out;
		}

		/* Calculate difference. */
		change = thisx - cx;	/* +ve left, -ve right */

		/*
		 * Use HPA if change is larger than absolute, otherwise move
		 * the cursor with CUB/CUF.
		 */
		if ((u_int) abs(change) > cx && tty_term_has(term, TTYC_HPA)) {
			tty_putcode_i(tty, TTYC_HPA, cx);
			goto out;
		} else if (change > 0 &&
		    tty_term_has(term, TTYC_CUB) &&
		    !tty_use_margin(tty)) {
			if (change == 2 && tty_term_has(term, TTYC_CUB1)) {
				tty_putcode(tty, TTYC_CUB1);
				tty_putcode(tty, TTYC_CUB1);
				goto out;
			}
			tty_putcode_i(tty, TTYC_CUB, change);
			goto out;
		} else if (change < 0 &&
		    tty_term_has(term, TTYC_CUF) &&
		    !tty_use_margin(tty)) {
			tty_putcode_i(tty, TTYC_CUF, -change);
			goto out;
		}
	} else if (cx == thisx) {
		/*
		 * Moving row only, column staying the same.
		 */

		/* One above. */
		if (thisy != tty->rupper &&
		    cy == thisy - 1 && tty_term_has(term, TTYC_CUU1)) {
			tty_putcode(tty, TTYC_CUU1);
			goto out;
		}

		/* One below. */
		if (thisy != tty->rlower &&
		    cy == thisy + 1 && tty_term_has(term, TTYC_CUD1)) {
			tty_putcode(tty, TTYC_CUD1);
			goto out;
		}

		/* Calculate difference. */
		change = thisy - cy;	/* +ve up, -ve down */

		/*
		 * Try to use VPA if change is larger than absolute or if this
		 * change would cross the scroll region, otherwise use CUU/CUD.
		 */
		if ((u_int) abs(change) > cy ||
		    (change < 0 && cy - change > tty->rlower) ||
		    (change > 0 && cy - change < tty->rupper)) {
			    if (tty_term_has(term, TTYC_VPA)) {
				    tty_putcode_i(tty, TTYC_VPA, cy);
				    goto out;
			    }
		} else if (change > 0 && tty_term_has(term, TTYC_CUU)) {
			tty_putcode_i(tty, TTYC_CUU, change);
			goto out;
		} else if (change < 0 && tty_term_has(term, TTYC_CUD)) {
			tty_putcode_i(tty, TTYC_CUD, -change);
			goto out;
		}
	}

absolute:
	/* Absolute movement. */
	tty_putcode_ii(tty, TTYC_CUP, cy, cx);

out:
	tty->cx = cx;
	tty->cy = cy;
}

static void
tty_hyperlink(struct tty *tty, const struct grid_cell *gc,
    struct hyperlinks *hl)
{
	const char	*uri, *id;

	if (gc->link == tty->cell.link)
		return;
	tty->cell.link = gc->link;

	if (hl == NULL)
		return;

	if (gc->link == 0 || !hyperlinks_get(hl, gc->link, &uri, NULL, &id))
		tty_putcode_ss(tty, TTYC_HLS, "", "");
	else
		tty_putcode_ss(tty, TTYC_HLS, id, uri);
}

void
tty_attributes(struct tty *tty, const struct grid_cell *gc,
    const struct grid_cell *defaults, struct colour_palette *palette,
    struct hyperlinks *hl)
{
	struct grid_cell	*tc = &tty->cell, gc2;
	int			 changed;

	/* Copy cell and update default colours. */
	memcpy(&gc2, gc, sizeof gc2);
	if (~gc->flags & GRID_FLAG_NOPALETTE) {
		if (gc2.fg == 8)
			gc2.fg = defaults->fg;
		if (gc2.bg == 8)
			gc2.bg = defaults->bg;
	}

	/* Ignore cell if it is the same as the last one. */
	if (gc2.attr == tty->last_cell.attr &&
	    gc2.fg == tty->last_cell.fg &&
	    gc2.bg == tty->last_cell.bg &&
	    gc2.us == tty->last_cell.us &&
		gc2.link == tty->last_cell.link)
		return;

	/*
	 * If no setab, try to use the reverse attribute as a best-effort for a
	 * non-default background. This is a bit of a hack but it doesn't do
	 * any serious harm and makes a couple of applications happier.
	 */
	if (!tty_term_has(tty->term, TTYC_SETAB)) {
		if (gc2.attr & GRID_ATTR_REVERSE) {
			if (gc2.fg != 7 && !COLOUR_DEFAULT(gc2.fg))
				gc2.attr &= ~GRID_ATTR_REVERSE;
		} else {
			if (gc2.bg != 0 && !COLOUR_DEFAULT(gc2.bg))
				gc2.attr |= GRID_ATTR_REVERSE;
		}
	}

	/* Fix up the colours if necessary. */
	tty_check_fg(tty, palette, &gc2);
	tty_check_bg(tty, palette, &gc2);
	tty_check_us(tty, palette, &gc2);

	/*
	 * If any bits are being cleared or the underline colour is now default,
	 * reset everything.
	 */
	if ((tc->attr & ~gc2.attr) || (tc->us != gc2.us && gc2.us == 0))
		tty_reset(tty);

	/*
	 * Set the colours. This may call tty_reset() (so it comes next) and
	 * may add to (NOT remove) the desired attributes.
	 */
	tty_colours(tty, &gc2);

	/* Filter out attribute bits already set. */
	changed = gc2.attr & ~tc->attr;
	tc->attr = gc2.attr;

	/* Set the attributes. */
	if (changed & GRID_ATTR_BRIGHT)
		tty_putcode(tty, TTYC_BOLD);
	if (changed & GRID_ATTR_DIM)
		tty_putcode(tty, TTYC_DIM);
	if (changed & GRID_ATTR_ITALICS)
		tty_set_italics(tty);
	if (changed & GRID_ATTR_ALL_UNDERSCORE) {
		if ((changed & GRID_ATTR_UNDERSCORE) ||
		    !tty_term_has(tty->term, TTYC_SMULX))
			tty_putcode(tty, TTYC_SMUL);
		else if (changed & GRID_ATTR_UNDERSCORE_2)
			tty_putcode_i(tty, TTYC_SMULX, 2);
		else if (changed & GRID_ATTR_UNDERSCORE_3)
			tty_putcode_i(tty, TTYC_SMULX, 3);
		else if (changed & GRID_ATTR_UNDERSCORE_4)
			tty_putcode_i(tty, TTYC_SMULX, 4);
		else if (changed & GRID_ATTR_UNDERSCORE_5)
			tty_putcode_i(tty, TTYC_SMULX, 5);
	}
	if (changed & GRID_ATTR_BLINK)
		tty_putcode(tty, TTYC_BLINK);
	if (changed & GRID_ATTR_REVERSE) {
		if (tty_term_has(tty->term, TTYC_REV))
			tty_putcode(tty, TTYC_REV);
		else if (tty_term_has(tty->term, TTYC_SMSO))
			tty_putcode(tty, TTYC_SMSO);
	}
	if (changed & GRID_ATTR_HIDDEN)
		tty_putcode(tty, TTYC_INVIS);
	if (changed & GRID_ATTR_STRIKETHROUGH)
		tty_putcode(tty, TTYC_SMXX);
	if (changed & GRID_ATTR_OVERLINE)
		tty_putcode(tty, TTYC_SMOL);
	if ((changed & GRID_ATTR_CHARSET) && tty_acs_needed(tty))
		tty_putcode(tty, TTYC_SMACS);

	/* Set hyperlink if any. */
	tty_hyperlink(tty, gc, hl);

	memcpy(&tty->last_cell, &gc2, sizeof tty->last_cell);
}

static void
tty_colours(struct tty *tty, const struct grid_cell *gc)
{
	struct grid_cell	*tc = &tty->cell;
	int			 have_ax;

	/* No changes? Nothing is necessary. */
	if (gc->fg == tc->fg && gc->bg == tc->bg && gc->us == tc->us)
		return;

	/*
	 * Is either the default colour? This is handled specially because the
	 * best solution might be to reset both colours to default, in which
	 * case if only one is default need to fall onward to set the other
	 * colour.
	 */
	if (COLOUR_DEFAULT(gc->fg) || COLOUR_DEFAULT(gc->bg)) {
		/*
		 * If don't have AX, send sgr0. This resets both colours to default.
		 * Otherwise, try to set the default colour only as needed.
		 */
		if (!tty_term_flag(tty->term, TTYC_AX))
			tty_reset(tty);
		else {
			if (COLOUR_DEFAULT(gc->fg) && !COLOUR_DEFAULT(tc->fg)) {
				tty_puts(tty, "\033[39m");
				tc->fg = gc->fg;
			}
			if (COLOUR_DEFAULT(gc->bg) && !COLOUR_DEFAULT(tc->bg)) {
				tty_puts(tty, "\033[49m");
				tc->bg = gc->bg;
			}
		}
	}

	/* Set the foreground colour. */
	if (!COLOUR_DEFAULT(gc->fg) && gc->fg != tc->fg)
		tty_colours_fg(tty, gc);

	/*
	 * Set the background colour. This must come after the foreground as
	 * tty_colours_fg() can call tty_reset().
	 */
	if (!COLOUR_DEFAULT(gc->bg) && gc->bg != tc->bg)
		tty_colours_bg(tty, gc);

	/* Set the underscore colour. */
	if (gc->us != tc->us)
		tty_colours_us(tty, gc);
}

static void
tty_check_fg(struct tty *tty, struct colour_palette *palette,
    struct grid_cell *gc)
{
	u_char	r, g, b;
	u_int	colours;
	int	c;

	/*
	 * Perform substitution if this pane has a palette. If the bright
	 * attribute is set and Nobr is not present, use the bright entry in
	 * the palette by changing to the aixterm colour
	 */
	if (~gc->flags & GRID_FLAG_NOPALETTE) {
		c = gc->fg;
		if (c < 8 &&
		    gc->attr & GRID_ATTR_BRIGHT &&
		    !tty_term_has(tty->term, TTYC_NOBR))
			c += 90;
		if ((c = colour_palette_get(palette, c)) != -1)
			gc->fg = c;
	}

	/* Is this a 24-bit colour? */
	if (gc->fg & COLOUR_FLAG_RGB) {
		/* Not a 24-bit terminal? Translate to 256-colour palette. */
		if (tty->term->flags & TERM_RGBCOLOURS)
			return;
		colour_split_rgb(gc->fg, &r, &g, &b);
		gc->fg = colour_find_rgb(r, g, b);
	}

	/* How many colours does this terminal have? */
	if (tty->term->flags & TERM_256COLOURS)
		colours = 256;
	else
		colours = tty_term_number(tty->term, TTYC_COLORS);

	/* Is this a 256-colour colour? */
	if (gc->fg & COLOUR_FLAG_256) {
		/* And not a 256 colour mode? */
		if (colours < 256) {
			gc->fg = colour_256to16(gc->fg);
			if (gc->fg & 8) {
				gc->fg &= 7;
				if (colours >= 16)
					gc->fg += 90;
			}
		}
		return;
	}

	/* Is this an aixterm colour? */
	if (gc->fg >= 90 && gc->fg <= 97 && colours < 16) {
		gc->fg -= 90;
		gc->attr |= GRID_ATTR_BRIGHT;
	}
}

static void
tty_check_bg(struct tty *tty, struct colour_palette *palette,
    struct grid_cell *gc)
{
	u_char	r, g, b;
	u_int	colours;
	int	c;

	/* Perform substitution if this pane has a palette. */
	if (~gc->flags & GRID_FLAG_NOPALETTE) {
		if ((c = colour_palette_get(palette, gc->bg)) != -1)
			gc->bg = c;
	}

	/* Is this a 24-bit colour? */
	if (gc->bg & COLOUR_FLAG_RGB) {
		/* Not a 24-bit terminal? Translate to 256-colour palette. */
		if (tty->term->flags & TERM_RGBCOLOURS)
			return;
		colour_split_rgb(gc->bg, &r, &g, &b);
		gc->bg = colour_find_rgb(r, g, b);
	}

	/* How many colours does this terminal have? */
	if (tty->term->flags & TERM_256COLOURS)
		colours = 256;
	else
		colours = tty_term_number(tty->term, TTYC_COLORS);

	/* Is this a 256-colour colour? */
	if (gc->bg & COLOUR_FLAG_256) {
		/*
		 * And not a 256 colour mode? Translate to 16-colour
		 * palette. Bold background doesn't exist portably, so just
		 * discard the bold bit if set.
		 */
		if (colours < 256) {
			gc->bg = colour_256to16(gc->bg);
			if (gc->bg & 8) {
				gc->bg &= 7;
				if (colours >= 16)
					gc->bg += 90;
			}
		}
		return;
	}

	/* Is this an aixterm colour? */
	if (gc->bg >= 90 && gc->bg <= 97 && colours < 16)
		gc->bg -= 90;
}

static void
tty_check_us(__unused struct tty *tty, struct colour_palette *palette,
    struct grid_cell *gc)
{
	int	c;

	/* Perform substitution if this pane has a palette. */
	if (~gc->flags & GRID_FLAG_NOPALETTE) {
		if ((c = colour_palette_get(palette, gc->us)) != -1)
			gc->us = c;
	}

	/* Convert underscore colour if only RGB can be supported. */
	if (!tty_term_has(tty->term, TTYC_SETULC1)) {
		    if ((c = colour_force_rgb (gc->us)) == -1)
			    gc->us = 8;
		    else
			    gc->us = c;
	}
}

static void
tty_colours_fg(struct tty *tty, const struct grid_cell *gc)
{
	struct grid_cell	*tc = &tty->cell;
	char			 s[32];

	/*
	 * If the current colour is an aixterm bright colour and the new is not,
	 * reset because some terminals do not clear bright correctly.
	 */
	if (tty->cell.fg >= 90 &&
	    tty->cell.bg <= 97 &&
	    (gc->fg < 90 || gc->fg > 97))
		tty_reset(tty);

	/* Is this a 24-bit or 256-colour colour? */
	if (gc->fg & COLOUR_FLAG_RGB || gc->fg & COLOUR_FLAG_256) {
		if (tty_try_colour(tty, gc->fg, "38") == 0)
			goto save;
		/* Should not get here, already converted in tty_check_fg. */
		return;
	}

	/* Is this an aixterm bright colour? */
	if (gc->fg >= 90 && gc->fg <= 97) {
		if (tty->term->flags & TERM_256COLOURS) {
			xsnprintf(s, sizeof s, "\033[%dm", gc->fg);
			tty_puts(tty, s);
		} else
			tty_putcode_i(tty, TTYC_SETAF, gc->fg - 90 + 8);
		goto save;
	}

	/* Otherwise set the foreground colour. */
	tty_putcode_i(tty, TTYC_SETAF, gc->fg);

save:
	/* Save the new values in the terminal current cell. */
	tc->fg = gc->fg;
}

static void
tty_colours_bg(struct tty *tty, const struct grid_cell *gc)
{
	struct grid_cell	*tc = &tty->cell;
	char			 s[32];

	/* Is this a 24-bit or 256-colour colour? */
	if (gc->bg & COLOUR_FLAG_RGB || gc->bg & COLOUR_FLAG_256) {
		if (tty_try_colour(tty, gc->bg, "48") == 0)
			goto save;
		/* Should not get here, already converted in tty_check_bg. */
		return;
	}

	/* Is this an aixterm bright colour? */
	if (gc->bg >= 90 && gc->bg <= 97) {
		if (tty->term->flags & TERM_256COLOURS) {
			xsnprintf(s, sizeof s, "\033[%dm", gc->bg + 10);
			tty_puts(tty, s);
		} else
			tty_putcode_i(tty, TTYC_SETAB, gc->bg - 90 + 8);
		goto save;
	}

	/* Otherwise set the background colour. */
	tty_putcode_i(tty, TTYC_SETAB, gc->bg);

save:
	/* Save the new values in the terminal current cell. */
	tc->bg = gc->bg;
}

static void
tty_colours_us(struct tty *tty, const struct grid_cell *gc)
{
	struct grid_cell	*tc = &tty->cell;
	u_int			 c;
	u_char			 r, g, b;

	/* Clear underline colour. */
	if (COLOUR_DEFAULT(gc->us)) {
		tty_putcode(tty, TTYC_OL);
		goto save;
	}

	/*
	 * If this is not an RGB colour, use Setulc1 if it exists, otherwise
	 * convert.
	 */
	if (~gc->us & COLOUR_FLAG_RGB) {
		c = gc->us;
		if ((~c & COLOUR_FLAG_256) && (c >= 90 && c <= 97))
			c -= 82;
		tty_putcode_i(tty, TTYC_SETULC1, c & ~COLOUR_FLAG_256);
		return;
	}

	/*
	 * Setulc and setal follows the ncurses(3) one argument "direct colour"
	 * capability format. Calculate the colour value.
	 */
	colour_split_rgb(gc->us, &r, &g, &b);
	c = (65536 * r) + (256 * g) + b;

	/*
	 * Write the colour. Only use setal if the RGB flag is set because the
	 * non-RGB version may be wrong.
	 */
	if (tty_term_has(tty->term, TTYC_SETULC))
		tty_putcode_i(tty, TTYC_SETULC, c);
	else if (tty_term_has(tty->term, TTYC_SETAL) &&
	    tty_term_has(tty->term, TTYC_RGB))
		tty_putcode_i(tty, TTYC_SETAL, c);

save:
	/* Save the new values in the terminal current cell. */
	tc->us = gc->us;
}

static int
tty_try_colour(struct tty *tty, int colour, const char *type)
{
	u_char	r, g, b;

	if (colour & COLOUR_FLAG_256) {
		if (*type == '3' && tty_term_has(tty->term, TTYC_SETAF))
			tty_putcode_i(tty, TTYC_SETAF, colour & 0xff);
		else if (tty_term_has(tty->term, TTYC_SETAB))
			tty_putcode_i(tty, TTYC_SETAB, colour & 0xff);
		return (0);
	}

	if (colour & COLOUR_FLAG_RGB) {
		colour_split_rgb(colour & 0xffffff, &r, &g, &b);
		if (*type == '3' && tty_term_has(tty->term, TTYC_SETRGBF))
			tty_putcode_iii(tty, TTYC_SETRGBF, r, g, b);
		else if (tty_term_has(tty->term, TTYC_SETRGBB))
			tty_putcode_iii(tty, TTYC_SETRGBB, r, g, b);
		return (0);
	}

	return (-1);
}

static void
tty_window_default_style(struct grid_cell *gc, struct window_pane *wp)
{
	memcpy(gc, &grid_default_cell, sizeof *gc);
	gc->fg = wp->palette.fg;
	gc->bg = wp->palette.bg;
}

void
tty_default_colours(struct grid_cell *gc, struct window_pane *wp)
{
	struct options		*oo = wp->options;
	struct format_tree	*ft;

	memcpy(gc, &grid_default_cell, sizeof *gc);

	if (wp->flags & PANE_STYLECHANGED) {
		log_debug("%%%u: style changed", wp->id);
		wp->flags &= ~PANE_STYLECHANGED;

		ft = format_create(NULL, NULL, FORMAT_PANE|wp->id,
		    FORMAT_NOJOBS);
		format_defaults(ft, NULL, NULL, NULL, wp);
		tty_window_default_style(&wp->cached_active_gc, wp);
		style_add(&wp->cached_active_gc, oo, "window-active-style", ft);
		tty_window_default_style(&wp->cached_gc, wp);
		style_add(&wp->cached_gc, oo, "window-style", ft);
		format_free(ft);
	}

	if (gc->fg == 8) {
		if (wp == wp->window->active && wp->cached_active_gc.fg != 8)
			gc->fg = wp->cached_active_gc.fg;
		else
			gc->fg = wp->cached_gc.fg;
	}

	if (gc->bg == 8) {
		if (wp == wp->window->active && wp->cached_active_gc.bg != 8)
			gc->bg = wp->cached_active_gc.bg;
		else
			gc->bg = wp->cached_gc.bg;
	}
}

static void
tty_default_attributes(struct tty *tty, const struct grid_cell *defaults,
    struct colour_palette *palette, u_int bg, struct hyperlinks *hl)
{
	struct grid_cell	gc;

	memcpy(&gc, &grid_default_cell, sizeof gc);
	gc.bg = bg;
	tty_attributes(tty, &gc, defaults, palette, hl);
}

static void
tty_clipboard_query_callback(__unused int fd, __unused short events, void *data)
{
	struct tty	*tty = data;
	struct client	*c = tty->client;

	c->flags &= ~CLIENT_CLIPBOARDBUFFER;
	free(c->clipboard_panes);
	c->clipboard_panes = NULL;
	c->clipboard_npanes = 0;

	tty->flags &= ~TTY_OSC52QUERY;
}

void
tty_clipboard_query(struct tty *tty)
{
	struct timeval	 tv = { .tv_sec = TTY_QUERY_TIMEOUT };

	if ((~tty->flags & TTY_STARTED) || (tty->flags & TTY_OSC52QUERY))
		return;
	tty_putcode_ss(tty, TTYC_MS, "", "?");

	tty->flags |= TTY_OSC52QUERY;
	evtimer_set(&tty->clipboard_timer, tty_clipboard_query_callback, tty);
	evtimer_add(&tty->clipboard_timer, &tv);
}