ztmux 3.7.20

A Rust port of tmux — the full terminal multiplexer, server and client
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
// 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.
use crate::options_::options_get_number_;
use crate::*;

#[repr(i32)]
#[derive(Copy, Clone, Default, Eq, PartialEq)]
pub enum screen_write_citem_type {
    #[default]
    Text,
    Clear,
}

impl_tailq_entry!(screen_write_citem, entry, tailq_entry<screen_write_citem>);
#[repr(C)]
pub struct screen_write_citem {
    x: u32,
    wrapped: bool,

    type_: screen_write_citem_type,
    used: u32,
    bg: u32,

    gc: grid_cell,

    entry: tailq_entry<screen_write_citem>,
}

#[repr(C)]
pub struct screen_write_cline {
    data: *mut u8,
    items: tailq_head<screen_write_citem>,
}

pub static mut SCREEN_WRITE_CITEM_FREELIST: tailq_head<screen_write_citem> =
    TAILQ_HEAD_INITIALIZER!(SCREEN_WRITE_CITEM_FREELIST);

/// C `vendor/tmux/screen-write.c:63`: `static struct screen_write_citem *screen_write_get_citem(void)`
unsafe fn screen_write_get_citem() -> NonNull<screen_write_citem> {
    unsafe {
        if let Some(ci) = NonNull::new(tailq_first(&raw mut SCREEN_WRITE_CITEM_FREELIST)) {
            tailq_remove(&raw mut SCREEN_WRITE_CITEM_FREELIST, ci.as_ptr());
            memset0(ci.as_ptr());
            return ci;
        }
        NonNull::new(xcalloc1::<screen_write_citem>()).unwrap()
    }
}

/// C `vendor/tmux/screen-write.c:77`: `static void screen_write_free_citem(struct screen_write_citem *ci)`
unsafe fn screen_write_free_citem(ci: *mut screen_write_citem) {
    unsafe {
        tailq_insert_tail(&raw mut SCREEN_WRITE_CITEM_FREELIST, ci);
    }
}

/// C `vendor/tmux/screen-write.c:83`: `static void screen_write_offset_timer(__unused int fd, __unused short events, void *data)`
unsafe extern "C-unwind" fn screen_write_offset_timer(_fd: i32, _events: i16, w: NonNull<window>) {
    unsafe {
        tty_update_window_offset(w.as_ptr());
    }
}

/// Set cursor position.
/// C `vendor/tmux/screen-write.c:92`: `static void screen_write_set_cursor(struct screen_write_ctx *ctx, int cx, int cy)`
unsafe fn screen_write_set_cursor(ctx: *mut screen_write_ctx, mut cx: i32, mut cy: i32) {
    unsafe {
        let wp = (*ctx).wp;
        let s = (*ctx).s;
        let tv: timeval = timeval {
            tv_usec: 10000,
            tv_sec: 0,
        };

        if cx != -1 && cx as u32 == (*s).cx && cy != -1 && cy as u32 == (*s).cy {
            return;
        }

        if cx != -1 {
            if cx as u32 > screen_size_x(s) {
                cx = screen_size_x(s) as i32 - 1;
            } // allow last column
            (*s).cx = cx as u32;
        }
        if cy != -1 {
            if cy as u32 > screen_size_y(s) - 1 {
                cy = screen_size_y(s) as i32 - 1;
            }
            (*s).cy = cy as u32;
        }

        if wp.is_null() {
            return;
        }
        let w = (*wp).window;

        if event_initialized(&raw mut (*w).offset_timer) == 0 {
            evtimer_set(
                &raw mut (*w).offset_timer,
                screen_write_offset_timer,
                NonNull::new_unchecked(w),
            );
        }
        if evtimer_pending(&raw mut (*w).offset_timer, null_mut()) == 0 {
            evtimer_add(&raw mut (*w).offset_timer, &raw const tv);
        }
    }
}

/// C `vendor/tmux/screen-write.c`: `static void screen_write_sync_callback(int fd, short events, void *data)`
unsafe extern "C-unwind" fn screen_write_sync_callback(
    _fd: i32,
    _events: i16,
    wp: NonNull<window_pane>,
) {
    unsafe {
        screen_write_stop_sync(wp.as_ptr());
    }
}

/// Enter synchronized-output mode (DEC 2026): set the mode flag and (re)arm the
/// 1-second safety timer that clears it if the application never sends the reset.
/// ztmux writes cells immediately instead of buffering dirty lines during sync,
/// so C's `screen_write_flush_dirty` on stop has nothing to flush — the
/// deferred-render batching is a perf optimisation not ported here, but the
/// mode state apps set and query (`#{synchronized_output_flag}`, DECRQM) is
/// faithful.
/// C `vendor/tmux/screen-write.c`: `void screen_write_start_sync(struct window_pane *wp)`
pub unsafe fn screen_write_start_sync(wp: *mut window_pane) {
    unsafe {
        let tv = timeval { tv_sec: 1, tv_usec: 0 };
        if wp.is_null() {
            return;
        }
        (*wp).base.mode |= mode_flag::MODE_SYNC;
        if event_initialized(&raw mut (*wp).sync_timer) == 0 {
            evtimer_set(
                &raw mut (*wp).sync_timer,
                screen_write_sync_callback,
                NonNull::new_unchecked(wp),
            );
        }
        evtimer_add(&raw mut (*wp).sync_timer, &raw const tv);
        log_debug!("screen_write_start_sync: %{} started sync mode", (*wp).id);
    }
}

/// Leave synchronized-output mode.
/// C `vendor/tmux/screen-write.c`: `void screen_write_stop_sync(struct window_pane *wp)`
pub unsafe fn screen_write_stop_sync(wp: *mut window_pane) {
    unsafe {
        if wp.is_null() || !(*wp).base.mode.intersects(mode_flag::MODE_SYNC) {
            return;
        }
        if event_initialized(&raw mut (*wp).sync_timer) != 0 {
            evtimer_del(&raw mut (*wp).sync_timer);
        }
        (*wp).base.mode &= !mode_flag::MODE_SYNC;
        log_debug!("screen_write_stop_sync: %{} stopped sync mode", (*wp).id);
    }
}

/// Do a full redraw.
/// C `vendor/tmux/screen-write.c:125`: `static void screen_write_redraw_cb(const struct tty_ctx *ttyctx)`
unsafe fn screen_write_redraw_cb(ttyctx: *const tty_ctx) {
    unsafe {
        let wp: *mut window_pane = (*ttyctx).arg.cast();

        if !wp.is_null() {
            (*wp).flags |= window_pane_flags::PANE_REDRAW;
        }
    }
}

/// Update context for client.
/// C `vendor/tmux/screen-write.c:135`: `static int screen_write_set_client_cb(struct tty_ctx *ttyctx, struct client *c)`
unsafe fn screen_write_set_client_cb(ttyctx: *mut tty_ctx, c: *mut client) -> i32 {
    unsafe {
        let wp: *mut window_pane = (*ttyctx).arg.cast();

        if (*ttyctx).allow_invisible_panes != 0 {
            if session_has((*c).session, (*wp).window) {
                return 1;
            }
            return 0;
        }

        if (*(*(*c).session).curw).window != (*wp).window {
            return 0;
        }
        if (*wp).layout_cell.is_null() {
            return 0;
        }

        if (*wp)
            .flags
            .intersects(window_pane_flags::PANE_REDRAW | window_pane_flags::PANE_DROP)
        {
            return -1;
        }
        if (*c).flags.intersects(client_flag::REDRAWPANES) {
            // Redraw is already deferred to redraw another pane - redraw
            // this one also when that happens.
            // log_debug("%s: adding %%%u to deferred redraw", __func__, (*wp).id);
            (*wp).flags |= window_pane_flags::PANE_REDRAW;
            return -1;
        }

        (*ttyctx).bigger = tty_window_offset(
            &raw mut (*c).tty,
            &raw mut (*ttyctx).wox,
            &raw mut (*ttyctx).woy,
            &raw mut (*ttyctx).wsx,
            &raw mut (*ttyctx).wsy,
        );

        (*ttyctx).rxoff = (*wp).xoff;
        (*ttyctx).xoff = (*wp).xoff;

        (*ttyctx).ryoff = (*wp).yoff;
        (*ttyctx).yoff = (*wp).yoff;

        if status_at_line(c) == 0 {
            (*ttyctx).yoff += status_line_size(c);
        }

        1
    }
}

/// Set up context for TTY command.
/// C `vendor/tmux/screen-write.c:262`: `static void screen_write_initctx(struct screen_write_ctx *ctx, struct tty_ctx *ttyctx, int is_sync, int check_obscured)`
unsafe fn screen_write_initctx(ctx: *mut screen_write_ctx, ttyctx: *mut tty_ctx, sync: i32) {
    unsafe {
        let s = (*ctx).s;

        memset0(ttyctx);

        (*ttyctx).s = s;
        (*ttyctx).sx = screen_size_x(s);
        (*ttyctx).sy = screen_size_y(s);

        (*ttyctx).ocx = (*s).cx;
        (*ttyctx).ocy = (*s).cy;
        (*ttyctx).orlower = (*s).rlower;
        (*ttyctx).orupper = (*s).rupper;

        memcpy__(&raw mut (*ttyctx).defaults, &raw const GRID_DEFAULT_CELL);
        if let Some(init_ctx_cb) = (*ctx).init_ctx_cb {
            init_ctx_cb(ctx, ttyctx);
            if !(*ttyctx).palette.is_null() {
                if (*ttyctx).defaults.fg == 8 {
                    (*ttyctx).defaults.fg = (*(*ttyctx).palette).fg;
                }
                if (*ttyctx).defaults.bg == 8 {
                    (*ttyctx).defaults.bg = (*(*ttyctx).palette).bg;
                }
            }
        } else {
            (*ttyctx).redraw_cb = Some(screen_write_redraw_cb);
            if !(*ctx).wp.is_null() {
                tty_default_colours(&raw mut (*ttyctx).defaults, (*ctx).wp);
                (*ttyctx).palette = &raw mut (*(*ctx).wp).palette;
                (*ttyctx).set_client_cb = Some(screen_write_set_client_cb);
                (*ttyctx).arg = (*ctx).wp.cast();
            }
        }

        if (*ctx).flags & SCREEN_WRITE_SYNC == 0 {
            // For the active pane or for an overlay (no pane), we want to
            // only use synchronized updates if requested (commands that
            // move the cursor); for other panes, always use it, since the
            // cursor will have to move.
            if !(*ctx).wp.is_null() {
                if (*ctx).wp != (*(*(*ctx).wp).window).active {
                    (*ttyctx).num = 1;
                } else {
                    (*ttyctx).num = sync as u32;
                }
            } else {
                (*ttyctx).num = 0x10 | (sync as u32);
            }
            tty_write(tty_cmd_syncstart, ttyctx);
            (*ctx).flags |= SCREEN_WRITE_SYNC;
        }
    }
}

/// Make write list.
/// C `vendor/tmux/screen-write.c:328`: `void screen_write_make_list(struct screen *s)`
pub unsafe fn screen_write_make_list(s: *mut screen) {
    unsafe {
        (*s).write_list = xcalloc_(screen_size_y(s) as usize).as_ptr();
        for y in 0..screen_size_y(s) {
            tailq_init(&raw mut (*(*s).write_list.add(y as usize)).items);
        }
    }
}

/// Free write list.
/// C `vendor/tmux/screen-write.c:339`: `void screen_write_free_list(struct screen *s)`
pub unsafe fn screen_write_free_list(s: *mut screen) {
    unsafe {
        for y in 0..screen_size_y(s) {
            free_((*(*s).write_list.add(y as usize)).data);
        }
        free_((*s).write_list);
    }
}

/// Set up for writing.
/// C `vendor/tmux/screen-write.c:350`: `static void screen_write_init(struct screen_write_ctx *ctx, struct screen *s)`
unsafe fn screen_write_init(ctx: *mut screen_write_ctx, s: *mut screen) {
    unsafe {
        memset0(ctx);

        (*ctx).s = s;

        if (*(*ctx).s).write_list.is_null() {
            screen_write_make_list((*ctx).s);
        }
        (*ctx).item = screen_write_get_citem().as_ptr();

        (*ctx).scrolled = 0;
        (*ctx).bg = 8;
    }
}

/// Initialize writing with a pane.
/// C `vendor/tmux/screen-write.c:366`: `void screen_write_start_pane(struct screen_write_ctx *ctx, struct window_pane *wp, struct screen *s)`
pub unsafe fn screen_write_start_pane(
    ctx: *mut screen_write_ctx,
    wp: *mut window_pane,
    mut s: *mut screen,
) {
    unsafe {
        if s.is_null() {
            s = (*wp).screen;
        }
        screen_write_init(ctx, s);
        (*ctx).wp = wp;

        if log_get_level() != 0 {
            // log_debug("%s: size %ux%u, pane %%%u (at %u,%u)", __func__, screen_size_x((*ctx).s), screen_size_y((*ctx).s), (*wp).id, (*wp).xoff, (*wp).yoff);
        }
    }
}

/// Initialize writing with a callback.
/// C `vendor/tmux/screen-write.c:383`: `void screen_write_start_callback(struct screen_write_ctx *ctx, struct screen *s, screen_write_init_ctx_cb cb, void *arg)`
pub unsafe fn screen_write_start_callback(
    ctx: *mut screen_write_ctx,
    s: *mut screen,
    cb: screen_write_init_ctx_cb,
    arg: *mut c_void,
) {
    unsafe {
        screen_write_init(ctx, s);

        (*ctx).init_ctx_cb = cb;
        (*ctx).arg = arg;

        if log_get_level() != 0 {
            // log_debug("%s: size %ux%u, with callback", __func__, screen_size_x((*ctx).s), screen_size_y((*ctx).s));
        }
    }
}

/// Initialize writing.
/// C `vendor/tmux/screen-write.c:399`: `void screen_write_start(struct screen_write_ctx *ctx, struct screen *s)`
pub unsafe fn screen_write_start(ctx: *mut screen_write_ctx, s: *mut screen) {
    unsafe {
        screen_write_init(ctx, s);

        if log_get_level() != 0 {
            // log_debug("%s: size %ux%u, no pane", __func__, screen_size_x((*ctx).s), screen_size_y((*ctx).s));
        }
    }
}

/// Finish writing.
/// C `vendor/tmux/screen-write.c:411`: `void screen_write_stop(struct screen_write_ctx *ctx)`
pub unsafe fn screen_write_stop(ctx: *mut screen_write_ctx) {
    unsafe {
        screen_write_collect_end(ctx);
        screen_write_collect_flush(ctx, 0, "screen_write_stop");

        screen_write_free_citem((*ctx).item);
    }
}

/// Reset screen state.
/// C `vendor/tmux/screen-write.c:421`: `void screen_write_reset(struct screen_write_ctx *ctx)`
pub unsafe fn screen_write_reset(ctx: *mut screen_write_ctx) {
    unsafe {
        let s = (*ctx).s;

        screen_reset_tabs(s);
        screen_write_scrollregion(ctx, 0, screen_size_y(s) - 1);

        (*s).mode = mode_flag::MODE_CURSOR | mode_flag::MODE_WRAP;

        if options_get_number_(GLOBAL_OPTIONS, "extended-keys") == 2 {
            (*s).mode = ((*s).mode & !EXTENDED_KEY_MODES) | mode_flag::MODE_KEYS_EXTENDED;
        }

        screen_write_clearscreen(ctx, 8);
        screen_write_set_cursor(ctx, 0, 0);
    }
}

/// Write character.
/// C `vendor/tmux/screen-write.c:439`: `void screen_write_putc(struct screen_write_ctx *ctx, const struct grid_cell *gcp, u_char ch)`
pub unsafe fn screen_write_putc(ctx: *mut screen_write_ctx, gcp: *const grid_cell, ch: u8) {
    unsafe {
        let mut gc: grid_cell = zeroed();
        memcpy__(&raw mut gc, gcp);

        utf8_set(&raw mut gc.data, ch);
        screen_write_cell(ctx, &raw mut gc);
    }
}

macro_rules! screen_write_strlen {
   ($fmt:literal $(, $args:expr)* $(,)?) => {
        crate::screen_write::screen_write_strlen_(format_args!($fmt $(, $args)*))
    };
}
pub(crate) use screen_write_strlen;
/// Calculate string length.
pub unsafe fn screen_write_strlen_(args: std::fmt::Arguments) -> usize {
    unsafe {
        let mut ud: utf8_data = zeroed();

        let mut size = 0;

        let mut msg = args.to_string();
        msg.push('\0');
        let mut ptr: *mut u8 = msg.as_mut_ptr();

        while *ptr != b'\0' {
            if *ptr > 0x7f && utf8_open(&raw mut ud, *ptr) == utf8_state::UTF8_MORE {
                ptr = ptr.add(1);

                let left = strlen(ptr.cast());
                if left < ud.size as usize - 1 {
                    break;
                }
                let mut more: utf8_state;
                while {
                    more = utf8_append(&raw mut ud, *ptr);
                    more == utf8_state::UTF8_MORE
                } {
                    ptr = ptr.add(1);
                }
                ptr = ptr.add(1);

                if more == utf8_state::UTF8_DONE {
                    size += ud.width;
                }
            } else {
                if *ptr > 0x1f && *ptr < 0x7f {
                    size += 1;
                }
                ptr = ptr.add(1);
            }
        }

        size as usize
    }
}

macro_rules! screen_write_text {
   ($ctx:expr, $cx:expr, $width: expr, $lines: expr, $more: expr, $gcp: expr, $fmt:literal $(, $args:expr)* $(,)?) => {
        crate::screen_write::screen_write_text_($ctx, $cx, $width, $lines, $more, $gcp, format_args!($fmt $(, $args)*))
    };
}
pub(crate) use screen_write_text;

/// Write string wrapped over lines.
pub unsafe fn screen_write_text_(
    ctx: *mut screen_write_ctx,
    cx: u32,
    width: u32,
    lines: u32,
    more: i32,
    gcp: *const grid_cell,
    args: std::fmt::Arguments,
) -> bool {
    unsafe {
        let more = more != 0;
        let s = (*ctx).s;
        let cy = (*s).cy;
        let mut idx = 0;

        let mut gc: grid_cell = zeroed();
        memcpy__(&raw mut gc, gcp);

        let mut tmp = args.to_string();
        tmp.push('\0');
        let tmp = tmp.as_mut_ptr().cast();
        let text = utf8_fromcstr(tmp);

        let mut left = (cx + width) - (*s).cx;
        loop {
            // Find the end of what can fit on the line.
            let mut at = 0;
            let mut end = idx;
            while (*text.add(end)).size != 0 {
                if (*text.add(end)).size == 1 && (*text.add(end)).data[0] == b'\n' {
                    break;
                }
                if at + (*text.add(end)).width as u32 > left {
                    break;
                }
                at += (*text.add(end)).width as u32;
                end += 1;
            }

            // If we're on a space, that's the end. If not, walk back to
            // try and find one.
            let next = if (*text.add(end)).size == 0 {
                end
            } else if ((*text.add(end)).size == 1 && (*text.add(end)).data[0] == b'\n')
                || ((*text.add(end)).size == 1 && (*text.add(end)).data[0] == b' ')
            {
                end + 1
            } else {
                let mut i = end;
                while i > idx {
                    if (*text.add(i)).size == 1 && (*text.add(i)).data[0] == b' ' {
                        break;
                    }
                    i -= 1;
                }
                if i != idx {
                    end = i;
                    i + 1
                } else {
                    end
                }
            };

            // Print the line.
            for i in idx..end {
                utf8_copy(&raw mut gc.data, text.add(i));
                screen_write_cell(ctx, &gc);
            }

            // If at the bottom, stop.
            idx = next;
            if (*s).cy == cy + lines - 1 || (*text.add(idx)).size == 0 {
                break;
            }

            screen_write_cursormove(ctx, cx as i32, (*s).cy as i32 + 1, 0);
            left = width;
        }

        // Fail if on the last line and there is more to come or at the end, or
        // if the text was not entirely consumed.
        if ((*s).cy == cy + lines - 1 && (!more || (*s).cx == cx + width))
            || (*text.add(idx)).size != 0
        {
            free_(text);
            return false;
        }
        free_(text);

        // If no more to come, move to the next line. Otherwise, leave on
        // the same line (except if at the end).
        if !more || (*s).cx == cx + width {
            screen_write_cursormove(ctx, cx as i32, (*s).cy as i32 + 1, 0);
        }
        true
    }
}

/// Write simple string (no maximum length).
macro_rules! screen_write_puts {
   ($ctx:expr, $gcp:expr, $fmt:literal $(, $args:expr)* $(,)?) => {
        crate::screen_write::screen_write_vnputs!($ctx, -1, $gcp, $fmt $(, $args)*);
   }
}
pub(crate) use screen_write_puts;

/// Write string with length limit (-1 for unlimited).
macro_rules! screen_write_nputs {
   ($ctx:expr, $maxlen:expr, $gcp:expr, $fmt:literal $(, $args:expr)* $(,)?) => {
        crate::screen_write::screen_write_vnputs!($ctx, $maxlen, $gcp, $fmt $(, $args)*);
   }
}
pub(crate) use screen_write_nputs;

macro_rules! screen_write_vnputs {
   ($ctx:expr, $maxlen:expr, $gcp:expr, $fmt:literal $(, $args:expr)* $(,)?) => {
        crate::screen_write::screen_write_vnputs_($ctx, $maxlen, $gcp, format_args!($fmt $(, $args)*))
    };
}
pub(crate) use screen_write_vnputs;

pub(crate) unsafe fn screen_write_vnputs_(
    ctx: *mut screen_write_ctx,
    maxlen: isize,
    gcp: *const grid_cell,
    args: std::fmt::Arguments,
) {
    unsafe {
        let mut gc: grid_cell = zeroed();
        let ud: *mut utf8_data = &raw mut gc.data;
        let mut size: usize = 0;

        memcpy__(&raw mut gc, gcp);
        let mut msg = args.to_string();
        msg.push('\0');

        let mut ptr: *mut u8 = msg.as_mut_ptr();
        while *ptr != b'\0' {
            if *ptr > 0x7f && utf8_open(ud, *ptr) == utf8_state::UTF8_MORE {
                ptr = ptr.add(1);

                let left = strlen(ptr.cast());
                if left < (*ud).size as usize - 1 {
                    break;
                }
                let mut more: utf8_state;
                while {
                    more = utf8_append(ud, *ptr);
                    more == utf8_state::UTF8_MORE
                } {
                    ptr = ptr.add(1);
                }
                ptr = ptr.add(1);

                if more != utf8_state::UTF8_DONE {
                    continue;
                }
                if maxlen > 0 && size + (*ud).width as usize > maxlen as usize {
                    while size < maxlen as usize {
                        screen_write_putc(ctx, &raw const gc, b' ');
                        size += 1;
                    }
                    break;
                }
                size += (*ud).width as usize;
                screen_write_cell(ctx, &raw const gc);
            } else {
                if maxlen > 0 && size + 1 > maxlen as usize {
                    break;
                }

                if *ptr == b'\x01' {
                    gc.attr ^= grid_attr::GRID_ATTR_CHARSET;
                } else if *ptr == b'\n' {
                    screen_write_linefeed(ctx, false, 8);
                    screen_write_carriagereturn(ctx);
                } else if *ptr > 0x1f && *ptr < 0x7f {
                    size += 1;
                    screen_write_putc(ctx, &gc, *ptr);
                }
                ptr = ptr.add(1);
            }
        }
    }
}

/// Copy from another screen but without the selection stuff. Assumes the target
/// region is already big enough.
/// C `vendor/tmux/screen-write.c:666`: `void screen_write_fast_copy(struct screen_write_ctx *ctx, struct screen *src, u_int px, u_int py, u_int nx, u_int ny)`
pub unsafe fn screen_write_fast_copy(
    ctx: *mut screen_write_ctx,
    src: *mut screen,
    px: u32,
    py: u32,
    nx: u32,
    ny: u32,
) {
    unsafe {
        let s = (*ctx).s;
        let gd = (*src).grid;
        let mut gc: grid_cell = zeroed();

        if nx == 0 || ny == 0 {
            return;
        }

        let mut cy = (*s).cy;
        for yy in py..(py + ny) {
            if yy >= (*gd).hsize + (*gd).sy {
                break;
            }
            let mut cx = (*s).cx;
            for xx in px..(px + nx) {
                if xx >= (*grid_get_line(gd, yy)).cellsize {
                    break;
                }
                grid_get_cell(gd, xx, yy, &raw mut gc);
                if xx + gc.data.width as u32 > px + nx {
                    break;
                }
                grid_view_set_cell((*(*ctx).s).grid, cx, cy, &gc);
                cx += 1;
            }
            cy += 1;
        }
    }
}

/// Select character set for drawing border lines.
/// C `vendor/tmux/screen-write.c:722`: `static void screen_write_box_border_set(enum box_lines lines, int cell_type, struct grid_cell *gc)`
unsafe fn screen_write_box_border_set(lines: box_lines, cell_type: cell_type, gc: *mut grid_cell) {
    unsafe {
        match lines {
            box_lines::BOX_LINES_NONE => (),
            box_lines::BOX_LINES_DOUBLE => {
                (*gc).attr &= !grid_attr::GRID_ATTR_CHARSET;
                utf8_copy(&raw mut (*gc).data, tty_acs_double_borders(cell_type));
            }
            box_lines::BOX_LINES_HEAVY => {
                (*gc).attr &= !grid_attr::GRID_ATTR_CHARSET;
                utf8_copy(&raw mut (*gc).data, tty_acs_heavy_borders(cell_type));
            }
            box_lines::BOX_LINES_ROUNDED => {
                (*gc).attr &= !grid_attr::GRID_ATTR_CHARSET;
                utf8_copy(&raw mut (*gc).data, tty_acs_rounded_borders(cell_type));
            }
            box_lines::BOX_LINES_SIMPLE => {
                (*gc).attr &= !grid_attr::GRID_ATTR_CHARSET;
                utf8_set(&raw mut (*gc).data, SIMPLE_BORDERS[cell_type as usize]);
            }
            box_lines::BOX_LINES_PADDED => {
                (*gc).attr &= !grid_attr::GRID_ATTR_CHARSET;
                utf8_set(&raw mut (*gc).data, PADDED_BORDERS[cell_type as usize]);
            }
            box_lines::BOX_LINES_SINGLE | box_lines::BOX_LINES_DEFAULT => {
                (*gc).attr |= grid_attr::GRID_ATTR_CHARSET;
                utf8_set(&raw mut (*gc).data, CELL_BORDERS[cell_type as usize]);
            }
        }
    }
}

/// Draw a horizontal line on screen.
/// C `vendor/tmux/screen-write.c:758`: `void screen_write_hline(struct screen_write_ctx *ctx, u_int nx, int left, int right, enum box_lines lines, const struct grid_cell *border_gc)`
pub unsafe fn screen_write_hline(
    ctx: *mut screen_write_ctx,
    nx: u32,
    left: i32,
    right: i32,
    lines: box_lines,
    border_gc: *const grid_cell,
) {
    unsafe {
        let s: *mut screen = (*ctx).s;
        let mut gc: grid_cell = zeroed();
        // u_int cx, cy, i;

        let cx = (*s).cx;
        let cy = (*s).cy;

        if !border_gc.is_null() {
            memcpy__(&raw mut gc, border_gc);
        } else {
            memcpy__(&raw mut gc, &raw const GRID_DEFAULT_CELL);
        }
        gc.attr |= grid_attr::GRID_ATTR_CHARSET;

        if left != 0 {
            screen_write_box_border_set(lines, cell_type::CELL_LEFTJOIN, &raw mut gc);
        } else {
            screen_write_box_border_set(lines, cell_type::CELL_LEFTRIGHT, &raw mut gc);
        }
        screen_write_cell(ctx, &gc);

        screen_write_box_border_set(lines, cell_type::CELL_LEFTRIGHT, &raw mut gc);
        for _ in 1..(nx - 1) {
            screen_write_cell(ctx, &raw mut gc);
        }

        if right != 0 {
            screen_write_box_border_set(lines, cell_type::CELL_RIGHTJOIN, &raw mut gc);
        } else {
            screen_write_box_border_set(lines, cell_type::CELL_LEFTRIGHT, &raw mut gc);
        }
        screen_write_cell(ctx, &raw const gc);

        screen_write_set_cursor(ctx, cx as i32, cy as i32);
    }
}

/// Draw a vertical line on screen.
/// C `vendor/tmux/screen-write.c:795`: `void screen_write_vline(struct screen_write_ctx *ctx, u_int ny, int top, int bottom, const struct grid_cell *gcp)`
pub unsafe fn screen_write_vline(ctx: *mut screen_write_ctx, ny: u32, top: i32, bottom: i32) {
    unsafe {
        let s = (*ctx).s;
        let mut gc: grid_cell = zeroed();

        let cx = (*s).cx;
        let cy = (*s).cy;

        memcpy__(&raw mut gc, &raw const GRID_DEFAULT_CELL);
        gc.attr |= grid_attr::GRID_ATTR_CHARSET;

        screen_write_putc(ctx, &raw const gc, if top != 0 { b'w' } else { b'x' });

        for i in 1..(ny - 1) {
            screen_write_set_cursor(ctx, cx as i32, (cy + i) as i32);
            screen_write_putc(ctx, &raw const gc, b'x');
        }
        screen_write_set_cursor(ctx, cx as i32, (cy + ny - 1) as i32);
        screen_write_putc(ctx, &raw const gc, if bottom != 0 { b'v' } else { b'x' });

        screen_write_set_cursor(ctx, cx as i32, cy as i32);
    }
}

/// Draw a menu on screen.
/// C `vendor/tmux/screen-write.c:824`: `void screen_write_menu(struct screen_write_ctx *ctx, struct menu *menu, int choice, enum box_lines lines, const struct grid_cell *menu_gc, const struct grid_cell *border_gc, const struct grid_cell *choice_gc)`
pub unsafe fn screen_write_menu(
    ctx: *mut screen_write_ctx,
    menu: *mut menu,
    choice: i32,
    lines: box_lines,
    menu_gc: *const grid_cell,
    border_gc: *const grid_cell,
    choice_gc: *const grid_cell,
) {
    unsafe {
        let s = (*ctx).s;
        let mut default_gc: grid_cell = zeroed();
        let mut gc = &raw const default_gc;

        // u_int cx, cy, i, j;
        let width = (*menu).width;

        let cx = (*s).cx;
        let cy = (*s).cy;

        memcpy__(&raw mut default_gc, menu_gc);

        screen_write_box(
            ctx,
            (*menu).width + 4,
            (*menu).items.len() as u32 + 2,
            lines,
            border_gc,
            Some(&(*menu).title),
        );

        for (i, item) in (*menu).items.iter_mut().enumerate() {
            let name: &str = &item.name;
            // TODO double check this name.is_empty() was previously name.is_null()
            if name.is_empty() {
                screen_write_cursormove(ctx, cx as i32, (cy + 1 + i as u32) as i32, 0);
                screen_write_hline(ctx, width + 4, 1, 1, lines, border_gc);
                continue;
            }

            if choice >= 0 && i as u32 == choice as u32 && !name.starts_with('-') {
                gc = choice_gc;
            }

            screen_write_cursormove(ctx, cx as i32 + 1, (cy + 1 + i as u32) as i32, 0);
            for _ in 0..(width + 2) {
                screen_write_putc(ctx, gc, b' ');
            }

            screen_write_cursormove(ctx, cx as i32 + 2, (cy + 1 + i as u32) as i32, 0);
            if let Some(stripped) = name.strip_prefix('-') {
                default_gc.attr |= grid_attr::GRID_ATTR_DIM;
                format_draw(ctx, gc, width, stripped, null_mut(), 0);
                default_gc.attr &= !grid_attr::GRID_ATTR_DIM;
                continue;
            }

            format_draw(ctx, gc, width, name, null_mut(), 0);
            gc = &raw mut default_gc;
        }

        screen_write_set_cursor(ctx, cx as i32, cy as i32);
    }
}

/// Draw a box on screen.
/// C `vendor/tmux/screen-write.c:875`: `void screen_write_box(struct screen_write_ctx *ctx, u_int nx, u_int ny, enum box_lines lines, const struct grid_cell *gcp, const char *title)`
pub unsafe fn screen_write_box(
    ctx: *mut screen_write_ctx,
    nx: u32,
    ny: u32,
    lines: box_lines,
    gcp: *const grid_cell,
    title: Option<&str>,
) {
    unsafe {
        let s = (*ctx).s;
        let mut gc: grid_cell = zeroed();

        let cx = (*s).cx;
        let cy = (*s).cy;

        if !gcp.is_null() {
            memcpy__(&raw mut gc, gcp);
        } else {
            memcpy__(&raw mut gc, &raw const GRID_DEFAULT_CELL);
        }

        gc.attr |= grid_attr::GRID_ATTR_CHARSET;
        gc.flags |= grid_flag::NOPALETTE;

        // Draw top border
        screen_write_box_border_set(lines, cell_type::CELL_TOPLEFT, &raw mut gc);
        screen_write_cell(ctx, &raw const gc);
        screen_write_box_border_set(lines, cell_type::CELL_LEFTRIGHT, &raw mut gc);
        for _ in 1..(nx - 1) {
            screen_write_cell(ctx, &raw const gc);
        }
        screen_write_box_border_set(lines, cell_type::CELL_TOPRIGHT, &raw mut gc);
        screen_write_cell(ctx, &raw const gc);

        // Draw bottom border
        screen_write_set_cursor(ctx, cx as i32, (cy + ny - 1) as i32);
        screen_write_box_border_set(lines, cell_type::CELL_BOTTOMLEFT, &raw mut gc);
        screen_write_cell(ctx, &gc);
        screen_write_box_border_set(lines, cell_type::CELL_LEFTRIGHT, &raw mut gc);
        for _ in 1..(nx - 1) {
            screen_write_cell(ctx, &raw const gc);
        }
        screen_write_box_border_set(lines, cell_type::CELL_BOTTOMRIGHT, &raw mut gc);
        screen_write_cell(ctx, &raw const gc);

        // Draw sides
        screen_write_box_border_set(lines, cell_type::CELL_TOPBOTTOM, &raw mut gc);
        for i in 1..(ny - 1) {
            // left side
            screen_write_set_cursor(ctx, cx as i32, (cy + i) as i32);
            screen_write_cell(ctx, &raw const gc);
            // right side
            screen_write_set_cursor(ctx, (cx + nx - 1) as i32, (cy + i) as i32);
            screen_write_cell(ctx, &raw const gc);
        }

        if let Some(title) = title {
            gc.attr &= !grid_attr::GRID_ATTR_CHARSET;
            screen_write_cursormove(ctx, (cx + 2) as i32, cy as i32, 0);
            format_draw(ctx, &raw const gc, nx - 4, title, null_mut(), 0);
        }

        screen_write_set_cursor(ctx, cx as i32, cy as i32);
    }
}

/// Write a preview version of a window. Assumes target area is big enough and already cleared.
/// C `vendor/tmux/screen-write.c:937`: `void screen_write_preview(struct screen_write_ctx *ctx, struct screen *src, u_int nx, u_int ny)`
pub unsafe fn screen_write_preview(ctx: *mut screen_write_ctx, src: *mut screen, nx: u32, ny: u32) {
    unsafe {
        let s = (*ctx).s;
        let mut gc: grid_cell = zeroed();

        let cx = (*s).cx;
        let cy = (*s).cy;

        // If the cursor is on, pick the area around the cursor, otherwise use
        // the top left.
        let mut px: u32;
        let mut py: u32;
        if (*src).mode.intersects(mode_flag::MODE_CURSOR) {
            px = (*src).cx;
            if px < nx / 3 {
                px = 0;
            } else {
                px -= nx / 3;
            }
            if px + nx > screen_size_x(src) {
                if nx > screen_size_x(src) {
                    px = 0;
                } else {
                    px = screen_size_x(src) - nx;
                }
            }
            py = (*src).cy;
            if py < ny / 3 {
                py = 0;
            } else {
                py -= ny / 3;
            }
            if py + ny > screen_size_y(src) {
                if ny > screen_size_y(src) {
                    py = 0;
                } else {
                    py = screen_size_y(src) - ny;
                }
            }
        } else {
            px = 0;
            py = 0;
        }

        screen_write_fast_copy(ctx, src, px, (*(*src).grid).hsize + py, nx, ny);

        if (*src).mode.intersects(mode_flag::MODE_CURSOR) {
            grid_view_get_cell((*src).grid, (*src).cx, (*src).cy, &raw mut gc);
            gc.attr |= grid_attr::GRID_ATTR_REVERSE;
            screen_write_set_cursor(
                ctx,
                cx as i32 + ((*src).cx - px) as i32,
                cy as i32 + ((*src).cy - py) as i32,
            );
            screen_write_cell(ctx, &raw const gc);
        }
    }
}

/// Set a mode.
/// C `vendor/tmux/screen-write.c:992`: `void screen_write_mode_set(struct screen_write_ctx *ctx, int mode)`
pub unsafe fn screen_write_mode_set(ctx: *mut screen_write_ctx, mode: mode_flag) {
    unsafe {
        let s = (*ctx).s;

        (*s).mode |= mode;

        if log_get_level() != 0 {
            // log_debug("%s: %s", __func__, screen_mode_to_string(mode));
        }
    }
}

/// Clear a mode.
/// C `vendor/tmux/screen-write.c:1004`: `void screen_write_mode_clear(struct screen_write_ctx *ctx, int mode)`
pub unsafe fn screen_write_mode_clear(ctx: *mut screen_write_ctx, mode: mode_flag) {
    unsafe {
        let s = (*ctx).s;

        (*s).mode &= !mode;

        if log_get_level() != 0 {
            // log_debug("%s: %s", __func__, screen_mode_to_string(mode));
        }
    }
}

/// Cursor up by ny.
/// C `vendor/tmux/screen-write.c:1064`: `void screen_write_cursorup(struct screen_write_ctx *ctx, u_int ny)`
pub unsafe fn screen_write_cursorup(ctx: *mut screen_write_ctx, mut ny: u32) {
    unsafe {
        let s = (*ctx).s;
        let mut cx: u32 = (*s).cx;
        let mut cy: u32 = (*s).cy;

        if ny == 0 {
            ny = 1;
        }

        if cy < (*s).rupper {
            // Above region.
            if ny > cy {
                ny = cy;
            }
        } else {
            // Below region.
            if ny > cy - (*s).rupper {
                ny = cy - (*s).rupper;
            }
        }
        if cx == screen_size_x(s) {
            cx -= 1;
        }

        cy -= ny;

        screen_write_set_cursor(ctx, cx as i32, cy as i32);
    }
}

/// Cursor down by ny.
/// C `vendor/tmux/screen-write.c:1091`: `void screen_write_cursordown(struct screen_write_ctx *ctx, u_int ny)`
pub unsafe fn screen_write_cursordown(ctx: *mut screen_write_ctx, mut ny: u32) {
    unsafe {
        let s: *mut screen = (*ctx).s;
        let mut cx: u32 = (*s).cx;
        let mut cy: u32 = (*s).cy;

        if ny == 0 {
            ny = 1;
        }

        if cy > (*s).rlower {
            // Below region.
            if ny > screen_size_y(s) - 1 - cy {
                ny = screen_size_y(s) - 1 - cy;
            }
        } else {
            // Above region.
            if ny > (*s).rlower - cy {
                ny = (*s).rlower - cy;
            }
        }
        if cx == screen_size_x(s) {
            cx -= 1;
        } else if ny == 0 {
            return;
        }

        cy += ny;

        screen_write_set_cursor(ctx, cx as i32, cy as i32);
    }
}

/// Cursor right by nx.
/// C `vendor/tmux/screen-write.c:1120`: `void screen_write_cursorright(struct screen_write_ctx *ctx, u_int nx)`
pub unsafe fn screen_write_cursorright(ctx: *mut screen_write_ctx, mut nx: u32) {
    unsafe {
        let s = (*ctx).s;
        let mut cx: u32 = (*s).cx;
        let cy: u32 = (*s).cy;

        if nx == 0 {
            nx = 1;
        }

        if nx > screen_size_x(s) - 1 - cx {
            nx = screen_size_x(s) - 1 - cx;
        }
        if nx == 0 {
            return;
        }

        cx += nx;

        screen_write_set_cursor(ctx, cx as i32, cy as i32);
    }
}

/// Cursor left by nx.
/// C `vendor/tmux/screen-write.c:1140`: `void screen_write_cursorleft(struct screen_write_ctx *ctx, u_int nx)`
pub unsafe fn screen_write_cursorleft(ctx: *mut screen_write_ctx, mut nx: u32) {
    unsafe {
        let s = (*ctx).s;
        let mut cx: u32 = (*s).cx;
        let cy: u32 = (*s).cy;

        if nx == 0 {
            nx = 1;
        }

        if nx > cx {
            nx = cx;
        }
        if nx == 0 {
            return;
        }

        cx -= nx;

        screen_write_set_cursor(ctx, cx as i32, cy as i32);
    }
}

/// Backspace; cursor left unless at start of wrapped line when can move up.
/// C `vendor/tmux/screen-write.c:1160`: `void screen_write_backspace(struct screen_write_ctx *ctx)`
pub unsafe fn screen_write_backspace(ctx: *mut screen_write_ctx) {
    unsafe {
        let s = (*ctx).s;
        let mut cx = (*s).cx;
        let mut cy = (*s).cy;

        if cx == 0 {
            if cy == 0 {
                return;
            }
            let gl = grid_get_line((*s).grid, (*(*s).grid).hsize + cy - 1);
            if (*gl).flags.intersects(grid_line_flag::WRAPPED) {
                cy -= 1;
                cx = screen_size_x(s) - 1;
            }
        } else {
            cx -= 1;
        }

        screen_write_set_cursor(ctx, cx as i32, cy as i32);
    }
}

/// VT100 alignment test.
/// C `vendor/tmux/screen-write.c:1301`: `void screen_write_alignmenttest(struct screen_write_ctx *ctx)`
pub unsafe fn screen_write_alignmenttest(ctx: *mut screen_write_ctx) {
    unsafe {
        let s = (*ctx).s;
        let mut ttyctx: tty_ctx = zeroed();
        let mut gc: grid_cell = zeroed();

        memcpy__(&raw mut gc, &raw const GRID_DEFAULT_CELL);
        utf8_set(&raw mut gc.data, b'E');

        #[cfg(feature = "sixel")]
        {
            if crate::image_::image_free_all(s) && !(*ctx).wp.is_null() {
                (*(*ctx).wp).flags |= window_pane_flags::PANE_REDRAW;
            }
        }

        for yy in 0..screen_size_y(s) {
            for xx in 0..screen_size_x(s) {
                grid_view_set_cell((*s).grid, xx, yy, &raw const gc);
            }
        }

        screen_write_set_cursor(ctx, 0, 0);

        (*s).rupper = 0;
        (*s).rlower = screen_size_y(s) - 1;

        screen_write_initctx(ctx, &raw mut ttyctx, 1);

        screen_write_collect_clear(ctx, 0, screen_size_y(s) - 1);
        tty_write(tty_cmd_alignmenttest, &raw mut ttyctx);
    }
}

/// Insert nx characters.
/// C `vendor/tmux/screen-write.c:1342`: `void screen_write_insertcharacter(struct screen_write_ctx *ctx, u_int nx, u_int bg)`
pub unsafe fn screen_write_insertcharacter(ctx: *mut screen_write_ctx, mut nx: u32, bg: u32) {
    unsafe {
        let s = (*ctx).s;
        let mut ttyctx: tty_ctx = zeroed();

        if nx == 0 {
            nx = 1;
        }

        if nx > screen_size_x(s) - (*s).cx {
            nx = screen_size_x(s) - (*s).cx;
        }
        if nx == 0 {
            return;
        }

        if (*s).cx > screen_size_x(s) - 1 {
            return;
        }

        #[cfg(feature = "sixel")]
        {
            if crate::image_::image_check_line(s, (*s).cy, 1) && !(*ctx).wp.is_null() {
                (*(*ctx).wp).flags |= window_pane_flags::PANE_REDRAW;
            }
        }

        screen_write_initctx(ctx, &raw mut ttyctx, 0);
        ttyctx.bg = bg;

        grid_view_insert_cells((*s).grid, (*s).cx, (*s).cy, nx, bg);

        screen_write_collect_flush(ctx, 0, "screen_write_insertcharacter");
        ttyctx.num = nx;
        tty_write(tty_cmd_insertcharacter, &raw mut ttyctx);
    }
}

/// Delete nx characters.
/// C `vendor/tmux/screen-write.c:1383`: `void screen_write_deletecharacter(struct screen_write_ctx *ctx, u_int nx, u_int bg)`
pub unsafe fn screen_write_deletecharacter(ctx: *mut screen_write_ctx, mut nx: u32, bg: u32) {
    unsafe {
        let s = (*ctx).s;
        let mut ttyctx: tty_ctx = zeroed();

        if nx == 0 {
            nx = 1;
        }

        if nx > screen_size_x(s) - (*s).cx {
            nx = screen_size_x(s) - (*s).cx;
        }
        if nx == 0 {
            return;
        }

        if (*s).cx > screen_size_x(s) - 1 {
            return;
        }

        #[cfg(feature = "sixel")]
        {
            if crate::image_::image_check_line(s, (*s).cy, 1) && !(*ctx).wp.is_null() {
                (*(*ctx).wp).flags |= window_pane_flags::PANE_REDRAW;
            }
        }

        screen_write_initctx(ctx, &raw mut ttyctx, 0);
        ttyctx.bg = bg;

        grid_view_delete_cells((*s).grid, (*s).cx, (*s).cy, nx, bg);

        screen_write_collect_flush(ctx, 0, "screen_write_deletecharacter");
        ttyctx.num = nx;
        tty_write(tty_cmd_deletecharacter, &raw mut ttyctx);
    }
}

/// Clear nx characters.
/// C `vendor/tmux/screen-write.c:1424`: `void screen_write_clearcharacter(struct screen_write_ctx *ctx, u_int nx, u_int bg)`
pub unsafe fn screen_write_clearcharacter(ctx: *mut screen_write_ctx, mut nx: u32, bg: u32) {
    unsafe {
        let s = (*ctx).s;
        let mut ttyctx: tty_ctx = zeroed();

        if nx == 0 {
            nx = 1;
        }

        if nx > screen_size_x(s) - (*s).cx {
            nx = screen_size_x(s) - (*s).cx;
        }
        if nx == 0 {
            return;
        }

        if (*s).cx > screen_size_x(s) - 1 {
            return;
        }

        #[cfg(feature = "sixel")]
        {
            if crate::image_::image_check_line(s, (*s).cy, 1) && !(*ctx).wp.is_null() {
                (*(*ctx).wp).flags |= window_pane_flags::PANE_REDRAW;
            }
        }

        screen_write_initctx(ctx, &raw mut ttyctx, 0);
        ttyctx.bg = bg;

        grid_view_clear((*s).grid, (*s).cx, (*s).cy, nx, 1, bg);

        screen_write_collect_flush(ctx, 0, "screen_write_clearcharacter");
        ttyctx.num = nx;
        tty_write(tty_cmd_clearcharacter, &raw mut ttyctx);
    }
}

/// Insert ny lines.
/// C `vendor/tmux/screen-write.c:1465`: `void screen_write_insertline(struct screen_write_ctx *ctx, u_int ny, u_int bg)`
pub unsafe fn screen_write_insertline(ctx: *mut screen_write_ctx, mut ny: u32, bg: u32) {
    unsafe {
        let s = (*ctx).s;
        let gd = (*s).grid;
        let mut ttyctx: tty_ctx = zeroed();

        if ny == 0 {
            ny = 1;
        }

        #[cfg(feature = "sixel")]
        {
            let sy = screen_size_y(s);
            if crate::image_::image_check_line(s, (*s).cy, sy - (*s).cy) && !(*ctx).wp.is_null() {
                (*(*ctx).wp).flags |= window_pane_flags::PANE_REDRAW;
            }
        }

        if (*s).cy < (*s).rupper || (*s).cy > (*s).rlower {
            if ny > screen_size_y(s) - (*s).cy {
                ny = screen_size_y(s) - (*s).cy;
            }
            if ny == 0 {
                return;
            }

            screen_write_initctx(ctx, &raw mut ttyctx, 1);
            ttyctx.bg = bg;

            grid_view_insert_lines(gd, (*s).cy, ny, bg);

            screen_write_collect_flush(ctx, 0, "screen_write_insertline");
            ttyctx.num = ny;
            tty_write(tty_cmd_insertline, &raw mut ttyctx);
            return;
        }

        if ny > (*s).rlower + 1 - (*s).cy {
            ny = (*s).rlower + 1 - (*s).cy;
        }
        if ny == 0 {
            return;
        }

        screen_write_initctx(ctx, &raw mut ttyctx, 1);
        ttyctx.bg = bg;

        if (*s).cy < (*s).rupper || (*s).cy > (*s).rlower {
            grid_view_insert_lines(gd, (*s).cy, ny, bg);
        } else {
            grid_view_insert_lines_region(gd, (*s).rlower, (*s).cy, ny, bg);
        }

        screen_write_collect_flush(ctx, 0, "screen_write_insertline");

        ttyctx.num = ny;
        tty_write(tty_cmd_insertline, &raw mut ttyctx);
    }
}

/// Delete ny lines.
/// C `vendor/tmux/screen-write.c:1533`: `void screen_write_deleteline(struct screen_write_ctx *ctx, u_int ny, u_int bg)`
pub unsafe fn screen_write_deleteline(ctx: *mut screen_write_ctx, mut ny: u32, bg: u32) {
    unsafe {
        let s = (*ctx).s;
        let gd = (*s).grid;
        let mut ttyctx: tty_ctx = zeroed();
        let sy = screen_size_y(s);

        if ny == 0 {
            ny = 1;
        }

        #[cfg(feature = "sixel")]
        {
            if crate::image_::image_check_line(s, (*s).cy, sy - (*s).cy) && !(*ctx).wp.is_null() {
                (*(*ctx).wp).flags |= window_pane_flags::PANE_REDRAW;
            }
        }

        if (*s).cy < (*s).rupper || (*s).cy > (*s).rlower {
            if ny > sy - (*s).cy {
                ny = sy - (*s).cy;
            }
            if ny == 0 {
                return;
            }

            screen_write_initctx(ctx, &raw mut ttyctx, 1);
            ttyctx.bg = bg;

            grid_view_delete_lines(gd, (*s).cy, ny, bg);

            screen_write_collect_flush(ctx, 0, "screen_write_deleteline");
            ttyctx.num = ny;
            tty_write(tty_cmd_deleteline, &raw mut ttyctx);
            return;
        }

        if ny > (*s).rlower + 1 - (*s).cy {
            ny = (*s).rlower + 1 - (*s).cy;
        }
        if ny == 0 {
            return;
        }

        screen_write_initctx(ctx, &raw mut ttyctx, 1);
        ttyctx.bg = bg;

        if (*s).cy < (*s).rupper || (*s).cy > (*s).rlower {
            grid_view_delete_lines(gd, (*s).cy, ny, bg);
        } else {
            grid_view_delete_lines_region(gd, (*s).rlower, (*s).cy, ny, bg);
        }

        screen_write_collect_flush(ctx, 0, "screen_write_deleteline");
        ttyctx.num = ny;
        tty_write(tty_cmd_deleteline, &raw mut ttyctx);
    }
}

/// Clear line at cursor.
/// C `vendor/tmux/screen-write.c:1603`: `void screen_write_clearline(struct screen_write_ctx *ctx, u_int bg)`
pub unsafe fn screen_write_clearline(ctx: *mut screen_write_ctx, bg: u32) {
    unsafe {
        let s = (*ctx).s;
        let sx = screen_size_x(s);
        let ci = (*ctx).item;

        let gl = grid_get_line((*s).grid, (*(*s).grid).hsize + (*s).cy);
        if (*gl).cellsize == 0 && COLOUR_DEFAULT(bg as i32) {
            return;
        }

        #[cfg(feature = "sixel")]
        {
            if crate::image_::image_check_line(s, (*s).cy, 1) && !(*ctx).wp.is_null() {
                (*(*ctx).wp).flags |= window_pane_flags::PANE_REDRAW;
            }
        }

        grid_view_clear((*s).grid, 0, (*s).cy, sx, 1, bg);

        screen_write_collect_clear(ctx, (*s).cy, 1);
        (*ci).x = 0;
        (*ci).used = sx;
        (*ci).type_ = screen_write_citem_type::Clear;
        (*ci).bg = bg;
        tailq_insert_tail(
            &raw mut (*(*(*ctx).s).write_list.add((*s).cy as usize)).items,
            ci,
        );
        (*ctx).item = screen_write_get_citem().as_ptr();
    }
}

/// Clear to end of line from cursor.
/// C `vendor/tmux/screen-write.c:1636`: `void screen_write_clearendofline(struct screen_write_ctx *ctx, u_int bg)`
pub unsafe fn screen_write_clearendofline(ctx: *mut screen_write_ctx, bg: u32) {
    unsafe {
        let s = (*ctx).s;
        let sx = screen_size_x(s);
        let ci = (*ctx).item;

        if (*s).cx == 0 {
            screen_write_clearline(ctx, bg);
            return;
        }

        let gl = grid_get_line((*s).grid, (*(*s).grid).hsize + (*s).cy);
        if (*s).cx > sx - 1 || ((*s).cx >= (*gl).cellsize && COLOUR_DEFAULT(bg as i32)) {
            return;
        }

        #[cfg(feature = "sixel")]
        {
            if crate::image_::image_check_line(s, (*s).cy, 1) && !(*ctx).wp.is_null() {
                (*(*ctx).wp).flags |= window_pane_flags::PANE_REDRAW;
            }
        }

        grid_view_clear((*s).grid, (*s).cx, (*s).cy, sx - (*s).cx, 1, bg);

        let before = screen_write_collect_trim(ctx, (*s).cy, (*s).cx, sx - (*s).cx, null_mut());
        (*ci).x = (*s).cx;
        (*ci).used = sx - (*s).cx;
        (*ci).type_ = screen_write_citem_type::Clear;
        (*ci).bg = bg;
        if before.is_null() {
            tailq_insert_tail(
                &raw mut (*(*(*ctx).s).write_list.add((*s).cy as usize)).items,
                ci,
            );
        } else {
            tailq_insert_before(before, ci);
        }
        (*ctx).item = screen_write_get_citem().as_ptr();
    }
}

/// Clear to start of line from cursor.
/// C `vendor/tmux/screen-write.c:1668`: `void screen_write_clearstartofline(struct screen_write_ctx *ctx, u_int bg)`
pub unsafe fn screen_write_clearstartofline(ctx: *mut screen_write_ctx, bg: u32) {
    unsafe {
        let s = (*ctx).s;
        let sx = screen_size_x(s);
        let ci = (*ctx).item;

        if (*s).cx >= sx - 1 {
            screen_write_clearline(ctx, bg);
            return;
        }

        #[cfg(feature = "sixel")]
        {
            if crate::image_::image_check_line(s, (*s).cy, 1) && !(*ctx).wp.is_null() {
                (*(*ctx).wp).flags |= window_pane_flags::PANE_REDRAW;
            }
        }

        if (*s).cx > sx - 1 {
            grid_view_clear((*s).grid, 0, (*s).cy, sx, 1, bg);
        } else {
            grid_view_clear((*s).grid, 0, (*s).cy, (*s).cx + 1, 1, bg);
        }

        let before = screen_write_collect_trim(ctx, (*s).cy, 0, (*s).cx + 1, null_mut());
        (*ci).x = 0;
        (*ci).used = (*s).cx + 1;
        (*ci).type_ = screen_write_citem_type::Clear;
        (*ci).bg = bg;
        if before.is_null() {
            tailq_insert_tail(
                &raw mut (*(*(*ctx).s).write_list.add((*s).cy as usize)).items,
                ci,
            );
        } else {
            tailq_insert_before(before, ci);
        }
        (*ctx).item = screen_write_get_citem().as_ptr();
    }
}

/// Move cursor to px,py.
/// C `vendor/tmux/screen-write.c:1698`: `void screen_write_cursormove(struct screen_write_ctx *ctx, int px, int py, int origin)`
pub unsafe fn screen_write_cursormove(
    ctx: *mut screen_write_ctx,
    mut px: i32,
    mut py: i32,
    origin: i32,
) {
    unsafe {
        let s = (*ctx).s;

        if origin != 0 && py != -1 && (*s).mode.intersects(mode_flag::MODE_ORIGIN) {
            if py as u32 > (*s).rlower - (*s).rupper {
                py = (*s).rlower as i32;
            } else {
                py += (*s).rupper as i32;
            }
        }

        if px != -1 && px as u32 > screen_size_x(s) - 1 {
            px = screen_size_x(s) as i32 - 1;
        }
        if py != -1 && py as u32 > screen_size_y(s) - 1 {
            py = screen_size_y(s) as i32 - 1;
        }

        // log_debug("%s: from %u,%u to %u,%u", __func__, (*s).cx, (*s).cy, px, py);
        screen_write_set_cursor(ctx, px, py);
    }
}

/// Reverse index (up with scroll).
/// C `vendor/tmux/screen-write.c:1721`: `void screen_write_reverseindex(struct screen_write_ctx *ctx, u_int bg)`
pub unsafe fn screen_write_reverseindex(ctx: *mut screen_write_ctx, bg: u32) {
    unsafe {
        let s = (*ctx).s;
        let mut ttyctx: tty_ctx = zeroed();

        if (*s).cy == (*s).rupper {
            #[cfg(feature = "sixel")]
            {
                if crate::image_::image_free_all(s) && !(*ctx).wp.is_null() {
                    (*(*ctx).wp).flags |= window_pane_flags::PANE_REDRAW;
                }
            }

            grid_view_scroll_region_down((*s).grid, (*s).rupper, (*s).rlower, bg);
            screen_write_collect_flush(ctx, 0, "screen_write_reverseindex");

            screen_write_initctx(ctx, &raw mut ttyctx, 1);
            ttyctx.bg = bg;

            tty_write(tty_cmd_reverseindex, &raw mut ttyctx);
        } else if (*s).cy > 0 {
            screen_write_set_cursor(ctx, -1, (*s).cy as i32 - 1);
        }
    }
}

/// Set scroll region.
/// C `vendor/tmux/screen-write.c:1757`: `void screen_write_scrollregion(struct screen_write_ctx *ctx, u_int rupper, u_int rlower)`
pub unsafe fn screen_write_scrollregion(
    ctx: *mut screen_write_ctx,
    mut rupper: u32,
    mut rlower: u32,
) {
    unsafe {
        let s = (*ctx).s;

        if rupper > screen_size_y(s) - 1 {
            rupper = screen_size_y(s) - 1;
        }
        if rlower > screen_size_y(s) - 1 {
            rlower = screen_size_y(s) - 1;
        }
        if rupper >= rlower {
            return;
        } // cannot be one line

        screen_write_collect_flush(ctx, 0, "screen_write_scrollregion");

        // Cursor moves to top-left.
        screen_write_set_cursor(ctx, 0, 0);

        (*s).rupper = rupper;
        (*s).rlower = rlower;
    }
}

/// Line feed.
/// C `vendor/tmux/screen-write.c:1780`: `void screen_write_linefeed(struct screen_write_ctx *ctx, int wrapped, u_int bg)`
pub unsafe fn screen_write_linefeed(ctx: *mut screen_write_ctx, wrapped: bool, bg: u32) {
    unsafe {
        let s = (*ctx).s;
        let gd = (*s).grid;

        let rupper = (*s).rupper;
        let rlower = (*s).rlower;

        let gl = grid_get_line(gd, (*gd).hsize + (*s).cy);
        if wrapped {
            (*gl).flags |= grid_line_flag::WRAPPED;
        }

        log_debug!(
            "screen_write_linefeed: at {},{} (region {}-{})",
            (*s).cx,
            (*s).cy,
            rupper,
            rlower
        );

        if bg != (*ctx).bg {
            screen_write_collect_flush(ctx, 1, "screen_write_linefeed");
            (*ctx).bg = bg;
        }

        if (*s).cy == (*s).rlower {
            #[cfg(feature = "sixel")]
            {
                let redraw = if rlower == screen_size_y(s) - 1 {
                    crate::image_::image_scroll_up(s, 1)
                } else {
                    crate::image_::image_check_line(s, rupper, rlower - rupper)
                };
                if redraw && !(*ctx).wp.is_null() {
                    (*(*ctx).wp).flags |= window_pane_flags::PANE_REDRAW;
                }
            }
            grid_view_scroll_region_up(gd, (*s).rupper, (*s).rlower, bg);
            screen_write_collect_scroll(ctx, bg);
            (*ctx).scrolled += 1;
        } else if (*s).cy < screen_size_y(s) - 1 {
            screen_write_set_cursor(ctx, -1, (*s).cy as i32 + 1);
        }
    }
}

/// Scroll up.
/// C `vendor/tmux/screen-write.c:1824`: `void screen_write_scrollup(struct screen_write_ctx *ctx, u_int lines, u_int bg)`
pub unsafe fn screen_write_scrollup(ctx: *mut screen_write_ctx, mut lines: u32, bg: u32) {
    unsafe {
        let s = (*ctx).s;
        let gd = (*s).grid;

        if lines == 0 {
            lines = 1;
        } else if lines > (*s).rlower - (*s).rupper + 1 {
            lines = (*s).rlower - (*s).rupper + 1;
        }

        if bg != (*ctx).bg {
            screen_write_collect_flush(ctx, 1, "screen_write_scrollup");
            (*ctx).bg = bg;
        }

        #[cfg(feature = "sixel")]
        {
            if crate::image_::image_scroll_up(s, lines) && !(*ctx).wp.is_null() {
                (*(*ctx).wp).flags |= window_pane_flags::PANE_REDRAW;
            }
        }

        for _ in 0..lines {
            grid_view_scroll_region_up(gd, (*s).rupper, (*s).rlower, bg);
            screen_write_collect_scroll(ctx, bg);
        }
        (*ctx).scrolled += lines;
    }
}

/// Scroll down.
/// C `vendor/tmux/screen-write.c:1854`: `void screen_write_scrolldown(struct screen_write_ctx *ctx, u_int lines, u_int bg)`
pub unsafe fn screen_write_scrolldown(ctx: *mut screen_write_ctx, mut lines: u32, bg: u32) {
    unsafe {
        let s = (*ctx).s;
        let gd = (*s).grid;
        let mut ttyctx: tty_ctx = zeroed();

        screen_write_initctx(ctx, &raw mut ttyctx, 1);
        ttyctx.bg = bg;

        if lines == 0 {
            lines = 1;
        } else if lines > (*s).rlower - (*s).rupper + 1 {
            lines = (*s).rlower - (*s).rupper + 1;
        }

        #[cfg(feature = "sixel")]
        {
            if crate::image_::image_free_all(s) && !(*ctx).wp.is_null() {
                (*(*ctx).wp).flags |= window_pane_flags::PANE_REDRAW;
            }
        }

        for _ in 0..lines {
            grid_view_scroll_region_down(gd, (*s).rupper, (*s).rlower, bg);
        }

        screen_write_collect_flush(ctx, 0, "screen_write_scrolldown");
        ttyctx.num = lines;
        tty_write(tty_cmd_scrolldown, &raw mut ttyctx);
    }
}

/// Carriage return (cursor to start of line).
/// C `vendor/tmux/screen-write.c:1893`: `void screen_write_carriagereturn(struct screen_write_ctx *ctx)`
pub unsafe fn screen_write_carriagereturn(ctx: *mut screen_write_ctx) {
    unsafe {
        screen_write_set_cursor(ctx, 0, -1);
    }
}

/// Clear to end of screen from cursor.
/// C `vendor/tmux/screen-write.c:1900`: `void screen_write_clearendofscreen(struct screen_write_ctx *ctx, u_int bg)`
pub unsafe fn screen_write_clearendofscreen(ctx: *mut screen_write_ctx, bg: u32) {
    unsafe {
        let s = (*ctx).s;
        let gd = (*s).grid;
        let mut ttyctx: tty_ctx = zeroed();
        let sx = screen_size_x(s);
        let sy = screen_size_y(s);

        #[cfg(feature = "sixel")]
        {
            if crate::image_::image_check_line(s, (*s).cy, sy - (*s).cy) && !(*ctx).wp.is_null() {
                (*(*ctx).wp).flags |= window_pane_flags::PANE_REDRAW;
            }
        }

        screen_write_initctx(ctx, &raw mut ttyctx, 1);
        ttyctx.bg = bg;

        // Scroll into history if it is enabled and clearing entire screen.
        if (*s).cx == 0
            && (*s).cy == 0
            && ((*gd).flags & GRID_HISTORY != 0)
            && !(*ctx).wp.is_null()
            && options_get_number_((*(*ctx).wp).options, "scroll-on-clear") != 0
        {
            grid_view_clear_history(gd, bg);
        } else {
            if (*s).cx < sx {
                grid_view_clear(gd, (*s).cx, (*s).cy, sx - (*s).cx, 1, bg);
            }
            grid_view_clear(gd, 0, (*s).cy + 1, sx, sy - ((*s).cy + 1), bg);
        }

        screen_write_collect_clear(ctx, (*s).cy + 1, sy - ((*s).cy + 1));
        screen_write_collect_flush(ctx, 0, "screen_write_clearendofscreen");
        tty_write(tty_cmd_clearendofscreen, &raw mut ttyctx);
    }
}

/// Clear to start of screen.
/// C `vendor/tmux/screen-write.c:1982`: `void screen_write_clearstartofscreen(struct screen_write_ctx *ctx, u_int bg)`
pub unsafe fn screen_write_clearstartofscreen(ctx: *mut screen_write_ctx, bg: u32) {
    unsafe {
        let s = (*ctx).s;
        let mut ttyctx: tty_ctx = zeroed();
        let sx = screen_size_x(s);

        #[cfg(feature = "sixel")]
        {
            if crate::image_::image_check_line(s, 0, (*s).cy - 1) && !(*ctx).wp.is_null() {
                (*(*ctx).wp).flags |= window_pane_flags::PANE_REDRAW;
            }
        }

        screen_write_initctx(ctx, &raw mut ttyctx, 1);
        ttyctx.bg = bg;

        if (*s).cy > 0 {
            grid_view_clear((*s).grid, 0, 0, sx, (*s).cy, bg);
        }
        if (*s).cx > sx - 1 {
            grid_view_clear((*s).grid, 0, (*s).cy, sx, 1, bg);
        } else {
            grid_view_clear((*s).grid, 0, (*s).cy, (*s).cx + 1, 1, bg);
        }

        screen_write_collect_clear(ctx, 0, (*s).cy);
        screen_write_collect_flush(ctx, 0, "screen_write_clearstartofscreen");
        tty_write(tty_cmd_clearstartofscreen, &raw mut ttyctx);
    }
}

/// Clear entire screen.
/// C `vendor/tmux/screen-write.c:2055`: `void screen_write_clearscreen(struct screen_write_ctx *ctx, u_int bg)`
pub unsafe fn screen_write_clearscreen(ctx: *mut screen_write_ctx, bg: u32) {
    unsafe {
        let s = (*ctx).s;
        let mut ttyctx: tty_ctx = zeroed();
        let sx = screen_size_x(s);
        let sy = screen_size_y(s);

        #[cfg(feature = "sixel")]
        {
            if crate::image_::image_free_all(s) && !(*ctx).wp.is_null() {
                (*(*ctx).wp).flags |= window_pane_flags::PANE_REDRAW;
            }
        }

        screen_write_initctx(ctx, &raw mut ttyctx, 1);
        ttyctx.bg = bg;

        // Scroll into history if it is enabled.
        if ((*(*s).grid).flags & GRID_HISTORY != 0)
            && !(*ctx).wp.is_null()
            && options_get_number_((*(*ctx).wp).options, "scroll-on-clear") != 0
        {
            grid_view_clear_history((*s).grid, bg);
        } else {
            grid_view_clear((*s).grid, 0, 0, sx, sy, bg);
        }

        screen_write_collect_clear(ctx, 0, sy);
        tty_write(tty_cmd_clearscreen, &raw mut ttyctx);
    }
}

/// Clear entire history.
/// C `vendor/tmux/screen-write.c:2117`: `void screen_write_clearhistory(struct screen_write_ctx *ctx)`
pub unsafe fn screen_write_clearhistory(ctx: *mut screen_write_ctx) {
    unsafe {
        grid_clear_history((*(*ctx).s).grid);
    }
}

/// Force a full redraw.
/// C `vendor/tmux/screen-write.c:2124`: `void screen_write_fullredraw(struct screen_write_ctx *ctx)`
pub unsafe fn screen_write_fullredraw(ctx: *mut screen_write_ctx) {
    unsafe {
        let mut ttyctx: tty_ctx = zeroed();

        screen_write_collect_flush(ctx, 0, "screen_write_fullredraw");

        screen_write_initctx(ctx, &raw mut ttyctx, 1);
        if let Some(redraw_cb) = ttyctx.redraw_cb {
            redraw_cb(&raw const ttyctx);
        }
    }
}

/// Trim collected items.
/// C `vendor/tmux/screen-write.c:2137`: `static struct screen_write_citem *screen_write_collect_trim(struct screen_write_ctx *ctx, u_int y, u_int x, u_int used, int *wrapped)`
pub unsafe fn screen_write_collect_trim(
    ctx: *mut screen_write_ctx,
    y: u32,
    x: u32,
    used: u32,
    wrapped: *mut bool,
) -> *mut screen_write_citem {
    unsafe {
        let cl = (*(*ctx).s).write_list.add(y as usize);
        let mut before = null_mut();
        let sx = x;
        let ex = x + used - 1;

        if tailq_empty(&raw const (*cl).items) {
            return null_mut();
        }
        for ci in tailq_foreach(&raw mut (*cl).items).map(NonNull::as_ptr) {
            let csx = (*ci).x;
            let cex = (*ci).x + (*ci).used - 1;

            // Item is entirely before.
            if cex < sx {
                continue;
            } // log_debug("%s: %p %u-%u before %u-%u", __func__, ci, csx, cex, sx, ex);

            // Item is entirely after.
            if csx > ex {
                // log_debug("%s: %p %u-%u after %u-%u", __func__, ci, csx, cex, sx, ex);
                before = ci;
                break;
            }

            // Item is entirely inside.
            if csx >= sx && cex <= ex {
                // log_debug("%s: %p %u-%u inside %u-%u", __func__, ci, csx, cex, sx, ex);
                tailq_remove(&raw mut (*cl).items, ci);
                screen_write_free_citem(ci);
                if csx == 0 && (*ci).wrapped && !wrapped.is_null() {
                    *wrapped = true;
                }
                continue;
            }

            // Item under the start.
            if csx < sx && cex >= sx && cex <= ex {
                // log_debug("%s: %p %u-%u start %u-%u", __func__, ci, csx, cex, sx, ex);
                (*ci).used = sx - csx;
                // log_debug("%s: %p now %u-%u", __func__, ci, (*ci).x, (*ci).x + (*ci).used + 1);
                continue;
            }

            // Item covers the end.
            if cex > ex && csx >= sx && csx <= ex {
                // log_debug("%s: %p %u-%u end %u-%u", __func__, ci, csx, cex, sx, ex);
                (*ci).x = ex + 1;
                (*ci).used = cex - ex;
                // log_debug("%s: %p now %u-%u", __func__, ci, (*ci).x, (*ci).x + (*ci).used + 1);
                before = ci;
                break;
            }

            // Item must cover both sides.
            // log_debug("%s: %p %u-%u under %u-%u", __func__, ci, csx, cex, sx, ex);
            let ci2 = screen_write_get_citem().as_ptr();
            (*ci2).type_ = (*ci).type_;
            (*ci2).bg = (*ci).bg;
            memcpy__(&raw mut (*ci2).gc, &raw mut (*ci).gc);
            tailq_insert_after(&raw mut (*cl).items, ci, ci2);

            (*ci).used = sx - csx;
            (*ci2).x = ex + 1;
            (*ci2).used = cex - ex;

            // log_debug("%s: %p now %u-%u (%p) and %u-%u (%p)", __func__, ci, (*ci).x, (*ci).x + (*ci).used - 1, ci, (*ci2).x, (*ci2).x + (*ci2).used - 1, ci2);
            before = ci2;
            break;
        }
        before
    }
}

/// Clear collected lines.
/// C `vendor/tmux/screen-write.c:2223`: `static void screen_write_collect_clear(struct screen_write_ctx *ctx, u_int y, u_int n)`
pub unsafe fn screen_write_collect_clear(ctx: *mut screen_write_ctx, y: u32, n: u32) {
    unsafe {
        for i in y..(y + n) {
            let cl = (*(*ctx).s).write_list.add(i as usize);
            tailq_concat(&raw mut SCREEN_WRITE_CITEM_FREELIST, &raw mut (*cl).items);
        }
    }
}

/// Scroll collected lines up.
/// C `vendor/tmux/screen-write.c:2236`: `static void screen_write_collect_scroll(struct screen_write_ctx *ctx, u_int bg)`
pub unsafe fn screen_write_collect_scroll(ctx: *mut screen_write_ctx, bg: u32) {
    unsafe {
        let s = (*ctx).s;
        // log_debug("%s: at %u,%u (region %u-%u)", __func__, (*s).cx, (*s).cy, (*s).rupper, (*s).rlower);

        screen_write_collect_clear(ctx, (*s).rupper, 1);
        let saved = (*(*(*ctx).s).write_list.add((*s).rupper as usize)).data;
        for y in (*s).rupper..(*s).rlower {
            let cl = (*(*ctx).s).write_list.add(y as usize + 1);
            tailq_concat(
                &raw mut (*(*(*ctx).s).write_list.add(y as usize)).items,
                &raw mut (*cl).items,
            );
            (*(*(*ctx).s).write_list.add(y as usize)).data = (*cl).data;
        }
        (*(*(*ctx).s).write_list.add((*s).rlower as usize)).data = saved;

        let ci = screen_write_get_citem().as_ptr();
        (*ci).x = 0;
        (*ci).used = screen_size_x(s);
        (*ci).type_ = screen_write_citem_type::Clear;
        (*ci).bg = bg;
        tailq_insert_tail(
            &raw mut (*(*(*ctx).s).write_list.add((*s).rlower as usize)).items,
            ci,
        );
    }
}

/// Flush collected lines.
/// C `vendor/tmux/screen-write.c:2392`: `static void screen_write_collect_flush(struct screen_write_ctx *ctx, int scroll_only, const char *from)`
pub unsafe fn screen_write_collect_flush(ctx: *mut screen_write_ctx, scroll_only: u32, from: &str) {
    unsafe {
        let s = (*ctx).s;
        let mut items = 0;
        let mut ttyctx: tty_ctx = zeroed();

        if (*ctx).scrolled != 0 {
            // log_debug("%s: scrolled %u (region %u-%u)", __func__, (*ctx).scrolled, (*s).rupper, (*s).rlower);
            if (*ctx).scrolled > (*s).rlower - (*s).rupper + 1 {
                (*ctx).scrolled = (*s).rlower - (*s).rupper + 1;
            }

            screen_write_initctx(ctx, &raw mut ttyctx, 1);
            ttyctx.num = (*ctx).scrolled;
            ttyctx.bg = (*ctx).bg;
            tty_write(tty_cmd_scrollup, &raw mut ttyctx);
        }
        (*ctx).scrolled = 0;
        (*ctx).bg = 8;

        if scroll_only != 0 {
            return;
        }

        let cx = (*s).cx;
        let cy = (*s).cy;
        for y in 0..screen_size_y(s) {
            let cl = (*(*ctx).s).write_list.add(y as usize);
            let mut last = u32::MAX;
            for ci in tailq_foreach(&raw mut (*cl).items).map(NonNull::as_ptr) {
                if last != u32::MAX && (*ci).x <= last {
                    panic!("collect list not in order: {} <= {}", (*ci).x, last);
                } // fatalx("collect list not in order: %u <= %u", (*ci).x, last);
                screen_write_set_cursor(ctx, (*ci).x as i32, y as i32);
                if (*ci).type_ == screen_write_citem_type::Clear {
                    screen_write_initctx(ctx, &raw mut ttyctx, 1);
                    ttyctx.bg = (*ci).bg;
                    ttyctx.num = (*ci).used;
                    tty_write(tty_cmd_clearcharacter, &raw mut ttyctx);
                } else {
                    screen_write_initctx(ctx, &raw mut ttyctx, 0);
                    ttyctx.cell = &(*ci).gc;
                    ttyctx.wrapped = (*ci).wrapped;
                    ttyctx.ptr = (*cl).data.add((*ci).x as usize).cast();
                    ttyctx.num = (*ci).used;
                    tty_write(tty_cmd_cells, &raw mut ttyctx);
                }
                items += 1;

                tailq_remove(&raw mut (*cl).items, ci);
                screen_write_free_citem(ci);
                last = (*ci).x;
            }
        }
        (*s).cx = cx;
        (*s).cy = cy;

        log_debug!("screen_write_collect_flush: flushed {items} items ({from})",);
    }
}

/// Finish and store collected cells.
/// C `vendor/tmux/screen-write.c:2478`: `void screen_write_collect_end(struct screen_write_ctx *ctx)`
pub unsafe fn screen_write_collect_end(ctx: *mut screen_write_ctx) {
    unsafe {
        let s = (*ctx).s;
        let ci = (*ctx).item;
        let cl = (*s).write_list.add((*s).cy as usize);
        let mut gc: grid_cell = zeroed();
        let mut wrapped = (*ci).wrapped;

        if (*ci).used == 0 {
            return;
        }

        let before = screen_write_collect_trim(ctx, (*s).cy, (*s).cx, (*ci).used, &raw mut wrapped);
        (*ci).x = (*s).cx;
        (*ci).wrapped = wrapped;
        if before.is_null() {
            tailq_insert_tail(&raw mut (*cl).items, ci);
        } else {
            tailq_insert_before(before, ci);
        }
        (*ctx).item = screen_write_get_citem().as_ptr();

        // log_debug("%s: %u %.*s (at %u,%u)", __func__, (*ci).used, (int)(*ci).used, (*cl).data + (*ci).x, (*s).cx, (*s).cy);

        if (*s).cx != 0 {
            let mut xx = (*s).cx;
            while xx > 0 {
                grid_view_get_cell((*s).grid, xx, (*s).cy, &raw mut gc);
                if !gc.flags.intersects(grid_flag::PADDING) {
                    break;
                }
                grid_view_set_cell((*s).grid, xx, (*s).cy, &GRID_DEFAULT_CELL);
                xx -= 1;
            }
            if gc.data.width > 1 {
                grid_view_set_cell((*s).grid, xx, (*s).cy, &GRID_DEFAULT_CELL);
            }
        }

        #[cfg(feature = "sixel")]
        {
            if crate::image_::image_check_area(s, (*s).cx, (*s).cy, (*ci).used, 1)
                && !(*ctx).wp.is_null()
            {
                (*(*ctx).wp).flags |= window_pane_flags::PANE_REDRAW;
            }
        }

        grid_view_set_cells(
            (*s).grid,
            (*s).cx,
            (*s).cy,
            &(*ci).gc,
            (*cl).data.add((*ci).x as usize),
            (*ci).used as usize,
        );
        screen_write_set_cursor(ctx, ((*s).cx + (*ci).used) as i32, -1);

        for xx in (*s).cx..screen_size_x(s) {
            grid_view_get_cell((*s).grid, xx, (*s).cy, &raw mut gc);
            if !gc.flags.intersects(grid_flag::PADDING) {
                break;
            }
            grid_view_set_cell((*s).grid, xx, (*s).cy, &GRID_DEFAULT_CELL);
        }
    }
}

/// Write cell data, collecting if necessary.
/// C `vendor/tmux/screen-write.c:2560`: `void screen_write_collect_add(struct screen_write_ctx *ctx, const struct grid_cell *gc)`
pub unsafe fn screen_write_collect_add(ctx: *mut screen_write_ctx, gc: *const grid_cell) {
    unsafe {
        let s = (*ctx).s;
        let sx = screen_size_x(s);

        // Don't need to check that the attributes and whatnot are still the
        // same - input_parse will end the collection when anything that isn't
        // a plain character is encountered.

        if ((*gc).data.width != 1 || (*gc).data.size != 1 || (*gc).data.data[0] >= 0x7f)
            || (*gc).flags.contains(grid_flag::TAB)
            || (*gc).attr.intersects(grid_attr::GRID_ATTR_CHARSET)
            || !(*s).mode.intersects(mode_flag::MODE_WRAP)
            || (*s).mode.intersects(mode_flag::MODE_INSERT)
            || !(*s).sel.is_null()
        {
            screen_write_collect_end(ctx);
            screen_write_collect_flush(ctx, 0, "screen_write_collect_add");
            screen_write_cell(ctx, gc);
            return;
        }

        if (*s).cx > sx - 1 || (*(*ctx).item).used > sx - 1 - (*s).cx {
            screen_write_collect_end(ctx);
        }
        let ci = (*ctx).item; // may have changed

        if (*s).cx > sx - 1 {
            // log_debug!("%s: wrapped at %u,%u", __func__, (*s).cx, (*s).cy);
            (*ci).wrapped = true;
            screen_write_linefeed(ctx, true, 8);
            screen_write_set_cursor(ctx, 0, -1);
        }

        if (*ci).used == 0 {
            memcpy__(&raw mut (*ci).gc, gc);
        }
        if (*(*(*ctx).s).write_list.add((*s).cy as usize))
            .data
            .is_null()
        {
            (*(*(*ctx).s).write_list.add((*s).cy as usize)).data =
                xmalloc(screen_size_x((*ctx).s) as usize).as_ptr().cast();
        }
        *(*(*(*ctx).s).write_list.add((*s).cy as usize))
            .data
            .add(((*s).cx + (*ci).used) as usize) = (*gc).data.data[0];
        (*ci).used += 1;
    }
}

/// Write cell data.
/// C `vendor/tmux/screen-write.c:2614`: `void screen_write_cell(struct screen_write_ctx *ctx, const struct grid_cell *gc)`
pub unsafe fn screen_write_cell(ctx: *mut screen_write_ctx, gc: *const grid_cell) {
    unsafe {
        let s = (*ctx).s;
        let gd = (*s).grid;
        let ud = &raw const (*gc).data;

        let gce: *mut grid_cell_entry;

        let mut tmp_gc: grid_cell = zeroed();
        let mut now_gc: grid_cell = zeroed();
        let mut ttyctx: tty_ctx = zeroed();

        let sx = screen_size_x(s);
        let sy = screen_size_y(s);

        let width = (*ud).width as u32;
        // xx, not_wrap;
        let mut skip = true;

        // Ignore padding cells.
        if (*gc).flags.intersects(grid_flag::PADDING) {
            return;
        }

        // Get the previous cell to check for combining.
        if screen_write_combine(ctx, gc) != 0 {
            return;
        }

        // Flush any existing scrolling.
        screen_write_collect_flush(ctx, 1, "screen_write_cell");

        // If this character doesn't fit, ignore it.
        if !(*s).mode.intersects(mode_flag::MODE_WRAP)
            && width > 1
            && (width > sx || ((*s).cx != sx && (*s).cx > sx - width))
        {
            return;
        }

        // If in insert mode, make space for the cells.
        if (*s).mode.intersects(mode_flag::MODE_INSERT) {
            grid_view_insert_cells((*s).grid, (*s).cx, (*s).cy, width, 8);
            skip = false;
        }

        // Check this will fit on the current line and wrap if not.
        if (*s).mode.intersects(mode_flag::MODE_WRAP) && (*s).cx > sx - width {
            // log_debug("%s: wrapped at %u,%u", __func__, (*s).cx, (*s).cy);
            screen_write_linefeed(ctx, true, 8);
            screen_write_set_cursor(ctx, 0, -1);
            screen_write_collect_flush(ctx, 1, "screen_write_cell");
        }

        // Sanity check cursor position.
        if (*s).cx > sx - width || (*s).cy > sy - 1 {
            return;
        }
        screen_write_initctx(ctx, &raw mut ttyctx, 0);

        // Handle overwriting of UTF-8 characters.
        let gl: *mut grid_line = grid_get_line((*s).grid, (*(*s).grid).hsize + (*s).cy);
        if (*gl).flags.intersects(grid_line_flag::EXTENDED) {
            grid_view_get_cell(gd, (*s).cx, (*s).cy, &raw mut now_gc);
            if screen_write_overwrite(ctx, &raw mut now_gc, width) != 0 {
                skip = false;
            }
        }

        // If the new character is UTF-8 wide, fill in padding cells. Have
        // already ensured there is enough room.
        for xx in ((*s).cx + 1)..((*s).cx + width) {
            // log_debug("%s: new padding at %u,%u", __func__, xx, (*s).cy);
            grid_view_set_padding(gd, xx, (*s).cy);
            skip = false;
        }

        // If no change, do not draw.
        if skip {
            if (*s).cx >= (*gl).cellsize {
                skip = grid_cells_equal(gc, &GRID_DEFAULT_CELL);
            } else {
                gce = (*gl).celldata.add((*s).cx as usize);
                if (*gce).flags.intersects(grid_flag::EXTENDED)
                    || (*gc).flags != (*gce).flags
                    || (*gc).attr.bits() != (*gce).union_.data.attr as u16
                    || (*gc).fg != (*gce).union_.data.fg as i32
                    || (*gc).bg != (*gce).union_.data.bg as i32
                    || (*gc).data.width != 1
                    || (*gc).data.size != 1
                    || (*gce).union_.data.data != (*gc).data.data[0]
                {
                    skip = false;
                }
            }
        }

        // Update the selected flag and set the cell.
        let selected = screen_check_selection(s, (*s).cx, (*s).cy) != 0;
        if selected && !(*gc).flags.intersects(grid_flag::SELECTED) {
            memcpy__(&raw mut tmp_gc, gc);
            tmp_gc.flags |= grid_flag::SELECTED;
            grid_view_set_cell(gd, (*s).cx, (*s).cy, &raw const tmp_gc);
        } else if !selected && ((*gc).flags.intersects(grid_flag::SELECTED)) {
            memcpy__(&raw mut tmp_gc, gc);
            tmp_gc.flags &= !grid_flag::SELECTED;
            grid_view_set_cell(gd, (*s).cx, (*s).cy, &tmp_gc);
        } else if !skip {
            grid_view_set_cell(gd, (*s).cx, (*s).cy, gc);
        }
        if selected {
            skip = false;
        }

        // Move the cursor. If not wrapping, stick at the last character and
        // replace it.
        let not_wrap = !((*s).mode.intersects(mode_flag::MODE_WRAP)) as i32;
        if (*s).cx <= (sx as i32 - not_wrap - width as i32) as u32 {
            screen_write_set_cursor(ctx, ((*s).cx + width) as i32, -1);
        } else {
            screen_write_set_cursor(ctx, sx as i32 - not_wrap, -1);
        }

        // Create space for character in insert mode.
        if (*s).mode.intersects(mode_flag::MODE_INSERT) {
            screen_write_collect_flush(ctx, 0, "screen_write_cell");
            ttyctx.num = width;
            tty_write(tty_cmd_insertcharacter, &raw mut ttyctx);
        }

        // Write to the screen.
        if !skip {
            if selected {
                screen_select_cell(s, &raw mut tmp_gc, gc);
                ttyctx.cell = &tmp_gc;
            } else {
                ttyctx.cell = gc;
            }
            tty_write(tty_cmd_cell, &raw mut ttyctx);
        }
    }
}

/// Combine a UTF-8 zero-width character onto the previous if necessary.
/// C `vendor/tmux/screen-write.c:2798`: `static int screen_write_combine(struct screen_write_ctx *ctx, const struct grid_cell *gc)`
pub unsafe fn screen_write_combine(ctx: *mut screen_write_ctx, gc: *const grid_cell) -> i32 {
    unsafe {
        let s = (*ctx).s;
        let gd = (*s).grid;
        let ud: *const utf8_data = &raw const (*gc).data;
        let mut cx = (*s).cx;
        let cy = (*s).cy;

        let mut last: grid_cell = zeroed();
        let mut ttyctx: tty_ctx = zeroed();

        let mut force_wide = 0;
        let mut zero_width = 0;

        // Is this character which makes no sense without being combined? If
        // this is true then flag it here and discard the character (return 1)
        // if we cannot combine it.
        if utf8_is_zwj(ud) {
            zero_width = 1;
        } else if utf8_is_vs(ud) {
            zero_width = 1;
            force_wide = 1;
        } else if (*ud).width == 0 {
            zero_width = 1;
        }

        // Cannot combine empty character or at left.
        if (*ud).size < 2 || cx == 0 {
            return zero_width;
        }
        // log_debug("%s: character %.*s at %u,%u (width %u)", __func__, (int)(*ud).size, (*ud).data, cx, cy, (*ud).width);

        // Find the cell to combine with.
        let mut n = 1;
        grid_view_get_cell(gd, cx - n, cy, &raw mut last);
        if cx != 1 && last.flags.intersects(grid_flag::PADDING) {
            n = 2;
            grid_view_get_cell(gd, cx - n, cy, &raw mut last);
        }
        if n != last.data.width as u32 || last.flags.intersects(grid_flag::PADDING) {
            return zero_width;
        }

        // Check if we need to combine characters. This could be zero width
        // (set above), a modifier character (with an existing Unicode
        // character) or a previous ZWJ.
        if zero_width == 0 {
            if utf8_is_modifier(ud) {
                if last.data.size < 2 {
                    return 0;
                }
                force_wide = 1;
            } else if !utf8_has_zwj(&raw mut last.data) {
                return 0;
            }
        }

        // Check if this combined character would be too long.
        if last.data.size + (*ud).size > UTF8_SIZE as u8 {
            return 0;
        }

        // Combining; flush any pending output.
        screen_write_collect_flush(ctx, 0, "screen_write_combine");

        // log_debug("%s: %.*s -> %.*s at %u,%u (offset %u, width %u)", __func__, (int)(*ud).size, (*ud).data, (int)last.data.size, last.data.data, cx - n, cy, n, last.data.width);

        // Append the data.
        libc::memcpy(
            (&raw mut last.data.data[last.data.size as usize]).cast(),
            (&raw const (*ud).data).cast(),
            (*ud).size as usize,
        );
        last.data.size += (*ud).size;

        // Force the width to 2 for modifiers and variation selector.
        if last.data.width == 1 && force_wide != 0 {
            last.data.width = 2;
            n = 2;
            cx += 1;
        } else {
            force_wide = 0;
        }

        // Set the new cell.
        grid_view_set_cell(gd, cx - n, cy, &last);
        if force_wide != 0 {
            grid_view_set_padding(gd, cx - 1, cy);
        }

        // Redraw the combined cell. If forcing the cell to width 2, reset the
        // cached cursor position in the tty, since we don't really know
        // whether the terminal thought the character was width 1 or width 2
        // and what it is going to do now.
        screen_write_set_cursor(ctx, cx as i32 - n as i32, cy as i32);
        screen_write_initctx(ctx, &raw mut ttyctx, 0);
        ttyctx.cell = &raw const last;
        ttyctx.num = force_wide; // reset cached cursor position
        tty_write(tty_cmd_cell, &raw mut ttyctx);
        screen_write_set_cursor(ctx, cx as i32, cy as i32);

        1
    }
}

// UTF-8 wide characters are a bit of an annoyance. They take up more than one
// cell on the screen, so following cells must not be drawn by marking them as
// padding.
//
// So far, so good. The problem is, when overwriting a padding cell, or a UTF-8
// character, it is necessary to also overwrite any other cells which covered
// by the same character.

/// C `vendor/tmux/screen-write.c:2943`: `static int screen_write_overwrite(struct screen_write_ctx *ctx, struct grid_cell *gc, u_int width)`
pub unsafe fn screen_write_overwrite(
    ctx: *mut screen_write_ctx,
    gc: *mut grid_cell,
    width: u32,
) -> i32 {
    unsafe {
        let s = (*ctx).s;
        let gd = (*s).grid;

        let mut tmp_gc: grid_cell = zeroed();
        let mut done = 0;

        if (*gc).flags.intersects(grid_flag::PADDING) {
            // A padding cell, so clear any following and leading padding
            // cells back to the character. Don't overwrite the current
            // cell as that happens later anyway.
            let mut xx = (*s).cx + 1;
            while {
                xx -= 1;
                xx > 0
            } {
                grid_view_get_cell(gd, xx, (*s).cy, &raw mut tmp_gc);
                if !tmp_gc.flags.intersects(grid_flag::PADDING) {
                    break;
                }
                // log_debug("%s: padding at %u,%u", __func__, xx, (*s).cy);
                grid_view_set_cell(gd, xx, (*s).cy, &raw const GRID_DEFAULT_CELL);
            }

            // Overwrite the character at the start of this padding.
            // log_debug("%s: character at %u,%u", __func__, xx, (*s).cy);
            grid_view_set_cell(gd, xx, (*s).cy, &raw const GRID_DEFAULT_CELL);
            done = 1;
        }

        // Overwrite any padding cells that belong to any UTF-8 characters
        // we'll be overwriting with the current character.
        if width != 1 || (*gc).data.width != 1 || (*gc).flags.intersects(grid_flag::PADDING) {
            let mut xx = (*s).cx + width - 1;
            while {
                xx += 1;
                xx < screen_size_x(s)
            } {
                grid_view_get_cell(gd, xx, (*s).cy, &raw mut tmp_gc);
                if !tmp_gc.flags.intersects(grid_flag::PADDING) {
                    break;
                }
                // log_debug("%s: overwrite at %u,%u", __func__, xx, (*s).cy);
                if (*gc).flags.contains(grid_flag::TAB) {
                    memcpy__(&raw mut tmp_gc, gc);
                    tmp_gc.data.data = [0; UTF8_SIZE];
                    tmp_gc.data.data[0] = b' ';
                    tmp_gc.data.width = 1;
                    tmp_gc.data.size = 1;
                    tmp_gc.data.have = 1;
                    grid_view_set_cell(gd, xx, (*s).cy, &raw const tmp_gc);
                } else {
                    grid_view_set_cell(gd, xx, (*s).cy, &raw const GRID_DEFAULT_CELL);
                }
                done = 1;
            }
        }

        done
    }
}

/// Set external clipboard.
/// C `vendor/tmux/screen-write.c:3007`: `void screen_write_setselection(struct screen_write_ctx *ctx, const char *clip, u_char *str, u_int len)`
pub unsafe fn screen_write_setselection(
    ctx: *mut screen_write_ctx,
    flags: *const u8,
    str: *mut u8,
    len: u32,
) {
    unsafe {
        let mut ttyctx: tty_ctx = zeroed();

        screen_write_initctx(ctx, &raw mut ttyctx, 0);
        ttyctx.ptr = str.cast();
        ttyctx.ptr2 = flags as *mut c_void; // TODO casting away const
        ttyctx.num = len;

        tty_write(tty_cmd_setselection, &raw mut ttyctx);
    }
}

/// Write unmodified string.
/// C `vendor/tmux/screen-write.c:3022`: `void screen_write_rawstring(struct screen_write_ctx *ctx, u_char *str, u_int len, int allow_invisible_panes)`
pub unsafe fn screen_write_rawstring(
    ctx: *mut screen_write_ctx,
    str: *mut u8,
    len: u32,
    allow_invisible_panes: i32,
) {
    unsafe {
        let mut ttyctx: tty_ctx = zeroed();

        screen_write_initctx(ctx, &raw mut ttyctx, 0);
        ttyctx.ptr = str.cast();
        ttyctx.num = len;
        ttyctx.allow_invisible_panes = allow_invisible_panes;

        tty_write(tty_cmd_rawstring, &raw mut ttyctx);
    }
}

/// Write a SIXEL image.
#[cfg(feature = "sixel")]
/// C `vendor/tmux/screen-write.c:3039`: `void screen_write_sixelimage(struct screen_write_ctx *ctx, struct sixel_image *si, u_int bg)`
pub(crate) unsafe fn screen_write_sixelimage(
    ctx: *mut screen_write_ctx,
    mut si: *mut sixel_image,
    bg: u32,
) {
    use crate::image_::{image_scroll_up, image_store};
    use crate::image_sixel::{sixel_free, sixel_scale, sixel_size_in_cells};

    unsafe {
        let s = (*ctx).s;
        let gd = (*s).grid;
        let mut ttyctx: tty_ctx = zeroed();

        let sx: u32;
        let mut sy: u32;
        let cx: u32 = (*s).cx;
        let cy: u32 = (*s).cy;
        let new: *mut sixel_image;

        let (mut x, mut y) = sixel_size_in_cells(&*si);
        if x > screen_size_x(s) || y > screen_size_y(s) {
            if x > screen_size_x(s) - cx {
                sx = screen_size_x(s) - cx;
            } else {
                sx = x;
            }
            if y > screen_size_y(s) - 1 {
                sy = screen_size_y(s) - 1;
            } else {
                sy = y;
            }
            new = sixel_scale(si, 0, 0, 0, y - sy, sx, sy, 1);
            sixel_free(si);
            si = new;

            // Bail out if the image cannot be scaled.
            if si.is_null() {
                return;
            }
            #[expect(unused_assignments)]
            {
                (x, y) = sixel_size_in_cells(&*si);
            }
        }

        sy = screen_size_y(s) - cy;
        if sy < y {
            let lines = y - sy + 1;
            if image_scroll_up(s, lines) && !(*ctx).wp.is_null() {
                (*(*ctx).wp).flags |= window_pane_flags::PANE_REDRAW;
            }
            for _ in 0..lines {
                grid_view_scroll_region_up(gd, 0, screen_size_y(s) - 1, bg);
                screen_write_collect_scroll(ctx, bg);
            }
            (*ctx).scrolled += lines;
            if lines > cy {
                screen_write_cursormove(ctx, -1, 0, 0);
            } else {
                screen_write_cursormove(ctx, -1, cy as i32 - lines as i32, 0);
            }
        }
        screen_write_collect_flush(ctx, 0, "screen_write_sixelimage");

        log_debug!("before screen_write_initctx");
        screen_write_initctx(ctx, &raw mut ttyctx, 0);
        log_debug!("before image_store");
        ttyctx.ptr = image_store(s, si).cast();

        log_debug!("before tty_write");
        tty_write(crate::tty_::tty_cmd_sixelimage, &raw mut ttyctx);

        log_debug!("before screen_write_cursormove");
        screen_write_cursormove(ctx, 0, (cy + y) as i32, 0);
    }
}

/// Turn alternate screen on.
/// C `vendor/tmux/screen-write.c:3098`: `void screen_write_alternateon(struct screen_write_ctx *ctx, struct grid_cell *gc, int cursor)`
pub unsafe fn screen_write_alternateon(
    ctx: *mut screen_write_ctx,
    gc: *mut grid_cell,
    cursor: i32,
) {
    unsafe {
        let mut ttyctx: tty_ctx = zeroed();
        let wp = (*ctx).wp;

        if !wp.is_null() && options_get_number_((*wp).options, "alternate-screen") == 0 {
            return;
        }

        screen_write_collect_flush(ctx, 0, "screen_write_alternateon");
        screen_alternate_on((*ctx).s, gc, cursor);

        screen_write_initctx(ctx, &raw mut ttyctx, 1);
        if let Some(redraw_cb) = ttyctx.redraw_cb {
            redraw_cb(&raw const ttyctx);
        }
    }
}

/// Turn alternate screen off.
/// C `vendor/tmux/screen-write.c:3124`: `void screen_write_alternateoff(struct screen_write_ctx *ctx, struct grid_cell *gc, int cursor)`
pub unsafe fn screen_write_alternateoff(
    ctx: *mut screen_write_ctx,
    gc: *mut grid_cell,
    cursor: i32,
) {
    unsafe {
        let mut ttyctx: tty_ctx = zeroed();
        let wp = (*ctx).wp;
        if !wp.is_null() && options_get_number_((*wp).options, "alternate-screen") == 0 {
            return;
        }

        screen_write_collect_flush(ctx, 0, "screen_write_alternateoff");
        screen_alternate_off((*ctx).s, gc, cursor);

        screen_write_initctx(ctx, &raw mut ttyctx, 1);
        if let Some(redraw_cb) = ttyctx.redraw_cb {
            redraw_cb(&raw mut ttyctx);
        }
    }
}