summaryrefslogtreecommitdiff
path: root/app/xterm/screen.c
blob: e05d1ee497844e74eabe1b3df7633266586ff77b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
/* $XTermId: screen.c,v 1.418 2010/04/28 23:49:28 tom Exp $ */

/*
 * Copyright 1999-2009,2010 by Thomas E. Dickey
 *
 *                         All Rights Reserved
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name(s) of the above copyright
 * holders shall not be used in advertising or otherwise to promote the
 * sale, use or other dealings in this Software without prior written
 * authorization.
 *
 *
 * Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
 *
 *                         All Rights Reserved
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for any purpose and without fee is hereby granted,
 * provided that the above copyright notice appear in all copies and that
 * both that copyright notice and this permission notice appear in
 * supporting documentation, and that the name of Digital Equipment
 * Corporation not be used in advertising or publicity pertaining to
 * distribution of the software without specific, written prior permission.
 *
 *
 * DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
 * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
 * DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
 * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF 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.
 */

/* screen.c */

#include <stdio.h>
#include <xterm.h>
#include <error.h>
#include <data.h>
#include <xcharmouse.h>
#include <xterm_io.h>

#if OPT_WIDE_CHARS
#include <fontutils.h>
#include <menu.h>
#endif

#include <assert.h>
#include <signal.h>

#define inSaveBuf(screen, buf, inx) \
	((buf) == (screen)->saveBuf_index && \
	 ((inx) < (screen)->savelines || (screen)->savelines == 0))

#define getMinRow(screen) ((xw->flags & ORIGIN) ? (screen)->top_marg : 0)
#define getMaxRow(screen) ((xw->flags & ORIGIN) ? (screen)->bot_marg : (screen)->max_row)
#define getMinCol(screen) 0
#define getMaxCol(screen) ((screen)->max_col)

#define MoveLineData(base, dst, src, len) \
	memmove(scrnHeadAddr(screen, base, (unsigned) (dst)), \
		scrnHeadAddr(screen, base, (unsigned) (src)), \
		(size_t) scrnHeadSize(screen, (unsigned) (len)))

#define SaveLineData(base, src, len) \
	(void) ScrnPointers(screen, len); \
	memcpy (screen->save_ptr, \
		scrnHeadAddr(screen, base, src), \
		(size_t) scrnHeadSize(screen, (unsigned) (len)))

#define RestoreLineData(base, dst, len) \
	memcpy (scrnHeadAddr(screen, base, dst), \
		screen->save_ptr, \
		(size_t) scrnHeadSize(screen, (unsigned) (len)))

#if OPT_SAVE_LINES
#define VisBuf(screen) screen->editBuf_index[screen->whichBuf]
#else
#define VisBuf(screen) scrnHeadAddr(screen, screen->saveBuf_index, (unsigned) savelines)
#endif

/*
 * ScrnPtr's can point to different types of data.
 */
#define SizeofScrnPtr(name) \
	(unsigned) sizeof(*((LineData *)0)->name)

/*
 * The pointers in LineData point into a block of text allocated as a single
 * chunk for the given number of rows.  Ensure that these pointers are aligned
 * at least to int-boundaries.
 */
#define AlignMask()      (sizeof(int) - 1)
#define IsAligned(value) (((unsigned long) (value) & AlignMask()) == 0)

#define AlignValue(value) \
		if (!IsAligned(value)) \
		    value = (value | (unsigned) AlignMask()) + 1

#define SetupScrnPtr(dst,src,type) \
		dst = (type *) src; \
		assert(IsAligned(dst)); \
		src += skipNcol##type

#define ScrnBufAddr(ptrs, offset)  (ScrnBuf)    ((char *) (ptrs) + (offset))
#define LineDataAddr(ptrs, offset) (LineData *) ((char *) (ptrs) + (offset))

#if OPT_TRACE > 1
static void
traceScrnBuf(const char *tag, TScreen * screen, ScrnBuf sb, unsigned len)
{
    unsigned j;

    TRACE(("traceScrnBuf %s\n", tag));
    for (j = 0; j < len; ++j) {
	LineData *src = (LineData *) scrnHeadAddr(screen, sb, j);
	TRACE(("%p %s%3d:%s\n",
	       src, ((int) j >= screen->savelines) ? "*" : " ",
	       j, visibleIChars(src->charData, src->lineSize)));
    }
    TRACE(("...traceScrnBuf %s\n", tag));
}

#define TRACE_SCRNBUF(tag, screen, sb, len) traceScrnBuf(tag, screen, sb, len)
#else
#define TRACE_SCRNBUF(tag, screen, sb, len)	/*nothing */
#endif

static unsigned
scrnHeadSize(TScreen * screen, unsigned count)
{
    unsigned result = SizeOfLineData;

    (void) screen;

#if OPT_WIDE_CHARS
    if (screen->wide_chars) {
	result += (unsigned) screen->lineExtra;
    }
#endif
    result *= count;

    return result;
}

ScrnBuf
scrnHeadAddr(TScreen * screen, ScrnBuf base, unsigned offset)
{
    unsigned size = scrnHeadSize(screen, offset);
    ScrnBuf result = ScrnBufAddr(base, size);

    assert((int) offset >= 0);

    return result;
}

/*
 * Given a block of data, build index to it in the 'base' parameter.
 */
void
setupLineData(TScreen * screen, ScrnBuf base, Char * data, unsigned nrow, unsigned ncol)
{
    unsigned i;
    unsigned offset = 0;
    unsigned jump = scrnHeadSize(screen, 1);
    LineData *ptr;
#if OPT_WIDE_CHARS
    unsigned j;
#endif
    /* these names are based on types */
    unsigned skipNcolChar = (ncol * SizeofScrnPtr(attribs));
    unsigned skipNcolCharData = (ncol * SizeofScrnPtr(charData));
#if OPT_ISO_COLORS
    unsigned skipNcolCellColor = (ncol * SizeofScrnPtr(color));
#endif

    AlignValue(skipNcolChar);
#if OPT_ISO_COLORS
    AlignValue(skipNcolCellColor);
#endif
    AlignValue(skipNcolCharData);

    for (i = 0; i < nrow; i++, offset += jump) {
	ptr = LineDataAddr(base, offset);

	ptr->lineSize = (Dimension) ncol;
	ptr->bufHead = 0;
#if OPT_DEC_CHRSET
	SetLineDblCS(ptr, 0);
#endif
	SetupScrnPtr(ptr->attribs, data, Char);
#if OPT_ISO_COLORS
	SetupScrnPtr(ptr->color, data, CellColor);
#endif
	SetupScrnPtr(ptr->charData, data, CharData);
#if OPT_WIDE_CHARS
	if (screen->wide_chars) {
	    unsigned extra = (unsigned) screen->max_combining;

	    ptr->combSize = (Char) extra;
	    for (j = 0; j < extra; ++j) {
		SetupScrnPtr(ptr->combData[j], data, CharData);
	    }
	}
#endif
    }
}

#define ExtractScrnData(name) \
		memcpy(dstPtrs->name, \
		       ((LineData *) srcPtrs)->name,\
		       dstCols * sizeof(dstPtrs->name[0])); \
		nextPtr += (srcCols * sizeof(dstPtrs->name[0]))

/*
 * As part of reallocating the screen buffer when resizing, extract from
 * the old copy of the screen buffer the data which will be used in the
 * new copy of the screen buffer.
 */
static void
extractScrnData(TScreen * screen,
		ScrnBuf dstPtrs,
		ScrnBuf srcPtrs,
		unsigned nrows,
		unsigned move_down)
{
    unsigned j;

    TRACE(("extractScrnData(nrows %d)\n", nrows));

    TRACE_SCRNBUF("extract from", screen, srcPtrs, nrows);
    for (j = 0; j < nrows; j++) {
	LineData *dst = (LineData *) scrnHeadAddr(screen,
						  dstPtrs, j + move_down);
	LineData *src = (LineData *) scrnHeadAddr(screen,
						  srcPtrs, j);
	copyLineData(dst, src);
    }
}

static ScrnPtr *
allocScrnHead(TScreen * screen, unsigned nrow)
{
    ScrnPtr *result;
    unsigned size = scrnHeadSize(screen, 1);

    result = (ScrnPtr *) calloc((size_t) nrow, (size_t) size);
    if (result == 0)
	SysError(ERROR_SCALLOC);

    TRACE(("allocScrnHead %d -> %d -> %p..%p\n", nrow, nrow * size,
	   (void *) result,
	   (char *) result + (nrow * size) - 1));
    return result;
}

/*
 * Return the size of a line's data.
 */
static unsigned
sizeofScrnRow(TScreen * screen, unsigned ncol)
{
    unsigned result;
    unsigned sizeAttribs;
#if OPT_ISO_COLORS
    unsigned sizeColors;
#endif

    (void) screen;

    result = (ncol * (unsigned) sizeof(CharData));
    AlignValue(result);

#if OPT_WIDE_CHARS
    if (screen->wide_chars) {
	result *= (unsigned) (1 + screen->max_combining);
    }
#endif

    sizeAttribs = (ncol * SizeofScrnPtr(attribs));
    AlignValue(sizeAttribs);
    result += sizeAttribs;

#if OPT_ISO_COLORS
    sizeColors = (ncol * SizeofScrnPtr(color));
    AlignValue(sizeColors);
    result += sizeColors;
#endif

    return result;
}

Char *
allocScrnData(TScreen * screen, unsigned nrow, unsigned ncol)
{
    Char *result;
    size_t length = (nrow * sizeofScrnRow(screen, ncol));

    if ((result = (Char *) calloc(length, sizeof(Char))) == 0)
	SysError(ERROR_SCALLOC2);

    TRACE(("allocScrnData %ux%u -> %lu -> %p..%p\n",
	   nrow, ncol, (unsigned long) length, result, result + length - 1));
    return result;
}

/*
 * Allocates memory for a 2-dimensional array of chars and returns a pointer
 * thereto.  Each line is formed from a set of char arrays, with an index
 * (i.e., the ScrnBuf type).  The first pointer in the index is reserved for
 * per-line flags, and does not point to data.
 *
 * After the per-line flags, we have a series of pointers to char arrays:  The
 * first one is the actual character array, the second one is the attributes,
 * the third is the foreground and background colors, and the fourth denotes
 * the character set.
 *
 * We store it all as pointers, because of alignment considerations.
 */
ScrnBuf
allocScrnBuf(XtermWidget xw, unsigned nrow, unsigned ncol, Char ** addr)
{
    TScreen *screen = TScreenOf(xw);
    ScrnBuf base = 0;

    if (nrow != 0) {
	base = allocScrnHead(screen, nrow);
	*addr = allocScrnData(screen, nrow, ncol);

	setupLineData(screen, base, *addr, nrow, ncol);
    }

    TRACE(("allocScrnBuf %dx%d ->%p\n", nrow, ncol, (void *) base));
    return (base);
}

#if OPT_SAVE_LINES
/*
 * Copy line-data from the visible (edit) buffer to the save-lines buffer.
 */
static void
saveEditBufLines(TScreen * screen, ScrnBuf sb, unsigned n)
{
    unsigned j;

    TRACE(("...copying %d lines from editBuf to saveBuf\n", n));
#if OPT_FIFO_LINES
    (void) sb;
#endif
    for (j = 0; j < n; ++j) {
#if OPT_FIFO_LINES
	LineData *dst = addScrollback(screen);
#else
	unsigned k = (screen->savelines + j - n);
	LineData *dst = (LineData *) scrnHeadAddr(screen, sb, k);
#endif
	LineData *src = getLineData(screen, (int) j);
	copyLineData(dst, src);
    }
}

/*
 * Copy line-data from the save-lines buffer to the visible (edit) buffer.
 */
static void
unsaveEditBufLines(TScreen * screen, ScrnBuf sb, unsigned n)
{
    unsigned j;

    TRACE(("...copying %d lines from saveBuf to editBuf\n", n));
    for (j = 0; j < n; ++j) {
	int extra = (int) (n - j);
	LineData *dst = (LineData *) scrnHeadAddr(screen, sb, j);
#if OPT_FIFO_LINES
	LineData *src;

	if ((screen->saved_fifo - extra) <= 0) {
	    TRACE(("...FIXME: must clear text!\n"));
	    continue;
	}
	src = getScrollback(screen, -extra);
#else
	unsigned k = (screen->savelines - extra);
	LineData *src = (LineData *) scrnHeadAddr(screen,
						  screen->saveBuf_index, k);
#endif
	copyLineData(dst, src);
    }
}
#endif

/*
 *  This is called when the screen is resized.
 *  Returns the number of lines the text was moved down (neg for up).
 *  (Return value only necessary with SouthWestGravity.)
 */
static int
Reallocate(XtermWidget xw,
	   ScrnBuf * sbuf,
	   Char ** sbufaddr,
	   unsigned nrow,
	   unsigned ncol,
	   unsigned oldrow,
	   unsigned oldcol)
{
    TScreen *screen = TScreenOf(xw);
    ScrnBuf oldBufHead;
    ScrnBuf newBufHead;
    Char *newBufData;
    unsigned minrows;
    unsigned mincols;
    Char *oldBufData;
    int move_down = 0, move_up = 0;

    if (sbuf == NULL || *sbuf == NULL) {
	return 0;
    }

    oldBufData = *sbufaddr;

    TRACE(("Reallocate %dx%d -> %dx%d\n", oldrow, oldcol, nrow, ncol));

    /*
     * realloc sbuf, the pointers to all the lines.
     * If the screen shrinks, remove lines off the top of the buffer
     * if resizeGravity resource says to do so.
     */
    TRACE(("Check move_up, nrow %d vs oldrow %d (resizeGravity %s)\n",
	   nrow, oldrow,
	   BtoS(GravityIsSouthWest(xw))));
    if (GravityIsSouthWest(xw)) {
	if (nrow < oldrow) {
	    /* Remove lines off the top of the buffer if necessary. */
	    move_up = (int) (oldrow - nrow)
		- (TScreenOf(xw)->max_row - TScreenOf(xw)->cur_row);
	    if (move_up < 0)
		move_up = 0;
	    /* Overlapping move here! */
	    TRACE(("move_up %d\n", move_up));
	    if (move_up) {
		ScrnBuf dst = *sbuf;
		unsigned len = (unsigned) ((int) oldrow - move_up);

		TRACE_SCRNBUF("before move_up", screen, dst, oldrow);
		SaveLineData(dst, 0, (size_t) move_up);
		MoveLineData(dst, 0, (size_t) move_up, len);
		RestoreLineData(dst, len, (size_t) move_up);
		TRACE_SCRNBUF("after move_up", screen, dst, oldrow);
	    }
	}
    }
    oldBufHead = *sbuf;
    *sbuf = allocScrnHead(screen, (unsigned) nrow);
    newBufHead = *sbuf;

    /*
     * Create the new buffer space and copy old buffer contents there, line by
     * line.
     */
    newBufData = allocScrnData(screen, nrow, ncol);
    *sbufaddr = newBufData;

    minrows = (oldrow < nrow) ? oldrow : nrow;
    mincols = (oldcol < ncol) ? oldcol : ncol;
    if (GravityIsSouthWest(xw)) {
	if (nrow > oldrow) {
	    /* move data down to bottom of expanded screen */
	    move_down = Min((int) (nrow - oldrow), TScreenOf(xw)->savedlines);
	}
    }

    setupLineData(screen, newBufHead, *sbufaddr, nrow, ncol);
    extractScrnData(screen, newBufHead, oldBufHead, minrows,
#if OPT_SAVE_LINES
		    0
#else
		    (unsigned) move_down
#endif
	);
    free(oldBufHead);

    /* Now free the old data */
    free(oldBufData);

    TRACE(("...Reallocate %dx%d ->%p\n", nrow, ncol, (void *) newBufHead));
    return move_down ? move_down : -move_up;	/* convert to rows */
}

#if OPT_WIDE_CHARS
/*
 * This function reallocates memory if changing the number of Buf offsets.
 * The code is based on Reallocate().
 */
static void
ReallocateBufOffsets(XtermWidget xw,
		     ScrnBuf * sbuf,
		     Char ** sbufaddr,
		     unsigned nrow,
		     unsigned ncol)
{
    TScreen *screen = TScreenOf(xw);
    unsigned i;
    ScrnBuf newBufHead;
    Char *oldBufData;
    ScrnBuf oldBufHead;

    unsigned old_jump = scrnHeadSize(screen, 1);
    unsigned new_jump;
    unsigned new_ptrs = 1 + (unsigned) (screen->max_combining);
    unsigned dstCols = ncol;
    unsigned srcCols = ncol;
    LineData *dstPtrs;
    LineData *srcPtrs;
    Char *nextPtr;

    assert(nrow != 0);
    assert(ncol != 0);

    oldBufData = *sbufaddr;
    oldBufHead = *sbuf;

    /*
     * Allocate a new LineData array, retain the old one until we've copied
     * the data that it points to, as well as non-pointer data, e.g., bufHead.
     *
     * Turn on wide-chars temporarily when constructing pointers, since that is
     * used to decide whether to address the combData[] array, which affects
     * the length of the LineData structure.
     */
    screen->wide_chars = True;

    new_jump = scrnHeadSize(screen, 1);
    newBufHead = allocScrnHead(screen, nrow);
    *sbufaddr = allocScrnData(screen, nrow, ncol);
    setupLineData(screen, newBufHead, *sbufaddr, nrow, ncol);

    screen->wide_chars = False;

    nextPtr = *sbufaddr;

    srcPtrs = (LineData *) oldBufHead;
    dstPtrs = (LineData *) newBufHead;
    for (i = 0; i < nrow; i++) {
	dstPtrs->bufHead = srcPtrs->bufHead;
	ExtractScrnData(attribs);
#if OPT_ISO_COLORS
	ExtractScrnData(color);
#endif
	ExtractScrnData(charData);

	nextPtr += ncol * new_ptrs;
	srcPtrs = LineDataAddr(srcPtrs, old_jump);
	dstPtrs = LineDataAddr(dstPtrs, new_jump);
    }

    /* Now free the old data */
    free(oldBufData);
    free(oldBufHead);

    *sbuf = newBufHead;

    TRACE(("ReallocateBufOffsets %dx%d ->%p\n", nrow, ncol, *sbufaddr));
}

/*
 * This function dynamically adds support for wide-characters.
 */
void
ChangeToWide(XtermWidget xw)
{
    TScreen *screen = TScreenOf(xw);
    int savelines = screen->scrollWidget ? screen->savelines : 0;

    if (screen->wide_chars)
	return;

    TRACE(("ChangeToWide\n"));
    if (xtermLoadWideFonts(xw, True)) {
	int whichBuf = screen->whichBuf;

	if (savelines < 0)
	    savelines = 0;

	/*
	 * If we're displaying the alternate screen, switch the pointers back
	 * temporarily so ReallocateBufOffsets() will operate on the proper
	 * data in the alternate buffer.
	 */
	if (screen->whichBuf)
	    SwitchBufPtrs(screen, 0);

#if OPT_SAVE_LINES
#if !OPT_FIFO_LINES
	ReallocateBufOffsets(xw,
			     &screen->saveBuf_index,
			     &screen->saveBuf_data,
			     (unsigned) savelines,
			     (unsigned) MaxCols(screen));
#endif
	if (screen->editBuf_index[0]) {
	    ReallocateBufOffsets(xw,
				 &screen->editBuf_index[0],
				 &screen->editBuf_data[0],
				 (unsigned) MaxRows(screen),
				 (unsigned) MaxCols(screen));
	}
#else
	ReallocateBufOffsets(xw,
			     &screen->saveBuf_index,
			     &screen->saveBuf_data,
			     (unsigned) (MaxRows(screen) + savelines),
			     (unsigned) MaxCols(screen));
#endif
	if (screen->editBuf_index[1]) {
	    ReallocateBufOffsets(xw,
				 &screen->editBuf_index[1],
				 &screen->editBuf_data[1],
				 (unsigned) MaxRows(screen),
				 (unsigned) MaxCols(screen));
	}

	screen->wide_chars = True;
	screen->visbuf = VisBuf(screen);

	/*
	 * Switch the pointers back before we start painting on the screen.
	 */
	if (whichBuf)
	    SwitchBufPtrs(screen, whichBuf);

	update_font_utf8_mode();
	SetVTFont(xw, screen->menu_font_number, True, NULL);
    }
    TRACE(("...ChangeToWide\n"));
}
#endif

/*
 * Clear cells, no side-effects.
 */
void
ClearCells(XtermWidget xw, int flags, unsigned len, int row, int col)
{
    if (len != 0) {
	TScreen *screen = TScreenOf(xw);
	LineData *ld;
	unsigned n;

	ld = getLineData(screen, row);

	UIntSet(flags, TERM_COLOR_FLAGS(xw));

	for (n = 0; n < len; ++n)
	    ld->charData[(unsigned) col + n] = (CharData) ' ';

	memset(ld->attribs + col, flags, (size_t) len);

	if_OPT_ISO_COLORS(screen, {
	    CellColor p = xtermColorPair(xw);
	    for (n = 0; n < len; ++n) {
		ld->color[(unsigned) col + n] = p;
	    }
	});
	if_OPT_WIDE_CHARS(screen, {
	    size_t off;
	    for_each_combData(off, ld) {
		memset(ld->combData[off] + col, 0, (size_t) len * sizeof(CharData));
	    }
	});
    }
}

/*
 * Clear data in the screen-structure (no I/O).
 * Check for wide-character damage as well, clearing the damaged cells.
 */
void
ScrnClearCells(XtermWidget xw, int row, int col, unsigned len)
{
#if OPT_WIDE_CHARS
    TScreen *screen = TScreenOf(xw);
#endif
    int flags = 0;

    if_OPT_WIDE_CHARS(screen, {
	int kl;
	int kr;

	if (DamagedCells(screen, len, &kl, &kr, row, col)
	    && kr >= kl) {
	    ClearCells(xw, flags, (unsigned) (kr - kl + 1), row, kl);
	}
    });
    ClearCells(xw, flags, len, row, col);
}

/*
 * Disown the selection and repaint the area that is highlighted so it is no
 * longer highlighted.
 */
void
ScrnDisownSelection(XtermWidget xw)
{
    if (ScrnHaveSelection(TScreenOf(xw))) {
	if (TScreenOf(xw)->keepSelection) {
	    UnhiliteSelection(xw);
	} else {
	    DisownSelection(xw);
	}
    }
}

/*
 * Writes str into buf at screen's current row and column.  Characters are set
 * to match flags.
 */
void
ScrnWriteText(XtermWidget xw,
	      IChar * str,
	      unsigned flags,
	      unsigned cur_fg_bg,
	      unsigned length)
{
    TScreen *screen = TScreenOf(xw);
    LineData *ld;
#if OPT_ISO_COLORS
    CellColor *fb = 0;
#endif
    Char *attrs;
    int avail = MaxCols(screen) - screen->cur_col;
    IChar *chars;
#if OPT_WIDE_CHARS
    IChar starcol1;
#endif
    unsigned n;
    unsigned real_width = visual_width(str, length);

    (void) cur_fg_bg;

    if (real_width + (unsigned) screen->cur_col > (unsigned) MaxCols(screen)) {
	real_width = (unsigned) (MaxCols(screen) - screen->cur_col);
    }

    if (avail <= 0)
	return;
    if (length > (unsigned) avail)
	length = (unsigned) avail;
    if (length == 0 || real_width == 0)
	return;

    ld = getLineData(screen, screen->cur_row);

    chars = ld->charData + screen->cur_col;
    attrs = ld->attribs + screen->cur_col;

    if_OPT_ISO_COLORS(screen, {
	fb = ld->color + screen->cur_col;
    });

#if OPT_WIDE_CHARS
    starcol1 = *chars;
#endif

    /* write blanks if we're writing invisible text */
    for (n = 0; n < length; ++n) {
	if ((flags & INVISIBLE))
	    chars[n] = ' ';
	else
	    chars[n] = str[n];
    }

#if OPT_BLINK_TEXT
    if ((flags & BLINK) && !(screen->blink_as_bold)) {
	LineSetBlinked(ld);
    }
#endif

    if_OPT_WIDE_CHARS(screen, {

	if (real_width != length) {
	    IChar *char1 = chars;
	    if (screen->cur_col
		&& starcol1 == HIDDEN_CHAR
		&& isWide((int) char1[-1])) {
		char1[-1] = (CharData) ' ';
	    }
	    /* if we are overwriting the right hand half of a
	       wide character, make the other half vanish */
	    while (length) {
		int ch = (int) str[0];

		*char1++ = *str++;
		length--;

		if (isWide(ch)) {
		    *char1++ = (CharData) HIDDEN_CHAR;
		}
	    }

	    if (*char1 == HIDDEN_CHAR
		&& char1[-1] == HIDDEN_CHAR) {
		*char1 = (CharData) ' ';
	    }
	    /* if we are overwriting the left hand half of a
	       wide character, make the other half vanish */
	} else {
	    if (screen->cur_col
		&& starcol1 == HIDDEN_CHAR
		&& isWide((int) chars[-1])) {
		chars[-1] = (CharData) ' ';
	    }
	    /* if we are overwriting the right hand half of a
	       wide character, make the other half vanish */
	    if (chars[length] == HIDDEN_CHAR
		&& isWide((int) chars[length - 1])) {
		chars[length] = (CharData) ' ';
	    }
	}
    });

    flags &= ATTRIBUTES;
    flags |= CHARDRAWN;
    memset(attrs, (Char) flags, (size_t) real_width);

    if_OPT_WIDE_CHARS(screen, {
	size_t off;
	for_each_combData(off, ld) {
	    memset(ld->combData[off] + screen->cur_col,
		   0,
		   real_width * sizeof(CharData));
	}
    });
    if_OPT_ISO_COLORS(screen, {
	unsigned j;
	for (j = 0; j < real_width; ++j)
	    fb[j] = (CellColor) cur_fg_bg;
    });

    if_OPT_WIDE_CHARS(screen, {
	screen->last_written_col = screen->cur_col + (int) real_width - 1;
	screen->last_written_row = screen->cur_row;
    });

    if_OPT_XMC_GLITCH(screen, {
	Resolve_XMC(xw);
    });

    return;
}

/*
 * Saves pointers to the n lines beginning at sb + where, and clears the lines
 */
static void
ScrnClearLines(XtermWidget xw, ScrnBuf sb, int where, unsigned n, unsigned size)
{
    TScreen *screen = TScreenOf(xw);
    ScrnPtr *base;
    unsigned jump = scrnHeadSize(screen, 1);
    unsigned i;
    LineData *work;
    unsigned flags = TERM_COLOR_FLAGS(xw);
#if OPT_ISO_COLORS
    unsigned j;
#endif

    TRACE(("ScrnClearLines(%s:where %d, n %d, size %d)\n",
	   (sb == screen->saveBuf_index) ? "save" : "edit",
	   where, n, size));

    assert(n != 0);
    assert(size != 0);

    /* save n lines at where */
    SaveLineData(sb, (unsigned) where, (size_t) n);

    /* clear contents of old rows */
    base = screen->save_ptr;
    for (i = 0; i < n; ++i) {
	work = (LineData *) base;
	work->bufHead = 0;
#if OPT_DEC_CHRSET
	SetLineDblCS(work, 0);
#endif

	memset(work->charData, 0, size * sizeof(CharData));
	if (TERM_COLOR_FLAGS(xw)) {
	    memset(work->attribs, (int) flags, (size_t) size);
#if OPT_ISO_COLORS
	    {
		CellColor p = xtermColorPair(xw);
		for (j = 0; j < size; ++j) {
		    work->color[j] = p;
		}
	    }
#endif
	} else {
	    memset(work->attribs, 0, (size_t) size);
#if OPT_ISO_COLORS
	    memset(work->color, 0, size * sizeof(work->color[0]));
#endif
	}
#if OPT_WIDE_CHARS
	if (screen->wide_chars) {
	    size_t off;

	    for (off = 0; off < work->combSize; ++off) {
		memset(work->combData[off], 0, size * sizeof(CharData));
	    }
	}
#endif
	base = ScrnBufAddr(base, jump);
    }
}

/*
 * We're always ensured of having a visible buffer, but may not have saved
 * lines.  Check the pointer that's sure to work.
 */
#if OPT_SAVE_LINES
#define OkAllocBuf(screen) (screen->editBuf_index[0] != 0)
#else
#define OkAllocBuf(screen) (screen->saveBuf_index != 0)
#endif

void
ScrnAllocBuf(XtermWidget xw)
{
    TScreen *screen = TScreenOf(xw);

    if (!OkAllocBuf(screen)) {
	int nrows = MaxRows(screen);
#if !OPT_SAVE_LINES
	int savelines = screen->scrollWidget ? screen->savelines : 0;
#endif

	TRACE(("ScrnAllocBuf %dx%d (%d)\n",
	       nrows, MaxCols(screen), screen->savelines));

#if OPT_SAVE_LINES
	if (screen->savelines != 0) {
#if OPT_FIFO_LINES
	    /* for FIFO, we only need space for the index - addScrollback inits */
	    screen->saveBuf_index = allocScrnHead(screen,
						  (unsigned) (screen->savelines));
#else
	    screen->saveBuf_index = allocScrnBuf(xw,
						 (unsigned) screen->savelines,
						 (unsigned) MaxCols(screen),
						 &screen->saveBuf_data);
#endif
	} else {
	    screen->saveBuf_index = 0;
	}
	screen->editBuf_index[0] = allocScrnBuf(xw,
						(unsigned) nrows,
						(unsigned) MaxCols(screen),
						&screen->editBuf_data[0]);
#else /* !OPT_SAVE_LINES */
	screen->saveBuf_index = allocScrnBuf(xw,
					     (unsigned) (nrows + screen->savelines),
					     (unsigned) (MaxCols(screen)),
					     &screen->saveBuf_data);
#endif /* OPT_SAVE_LINES */
	screen->visbuf = VisBuf(screen);
    }
    return;
}

size_t
ScrnPointers(TScreen * screen, size_t len)
{
    size_t result = scrnHeadSize(screen, (unsigned) len);

    if (result > screen->save_len) {
	if (screen->save_len)
	    screen->save_ptr = (ScrnPtr *) realloc(screen->save_ptr, result);
	else
	    screen->save_ptr = (ScrnPtr *) malloc(result);
	screen->save_len = len;
	if (screen->save_ptr == 0)
	    SysError(ERROR_SAVE_PTR);
    }
    TRACE2(("ScrnPointers %ld ->%p\n", (long) len, screen->save_ptr));
    return result;
}

/*
 * Inserts n blank lines at sb + where, treating last as a bottom margin.
 */
void
ScrnInsertLine(XtermWidget xw, ScrnBuf sb, int last, int where, unsigned n)
{
    TScreen *screen = TScreenOf(xw);
    unsigned size = (unsigned) MaxCols(screen);

    TRACE(("ScrnInsertLine(last %d, where %d, n %d, size %d)\n",
	   last, where, n, size));

    assert(where >= 0);
    assert(last >= (int) n);
    assert(last >= where);

    assert(n != 0);
    assert(size != 0);

    /* save n lines at bottom */
    ScrnClearLines(xw, sb, (last -= (int) n - 1), n, size);

    /*
     * WARNING, overlapping copy operation.  Move down lines (pointers).
     *
     *   +----|---------|--------+
     *
     * is copied in the array to:
     *
     *   +--------|---------|----+
     */
    assert(last >= where);
    /*
     * This will never shift from the saveBuf to editBuf, so there is no need
     * to handle that case.
     */
    MoveLineData(sb,
		 (unsigned) (where + (int) n),
		 (unsigned) where,
		 (unsigned) (last - where));

    /* reuse storage for new lines at where */
    RestoreLineData(sb, (unsigned) where, n);
}

/*
 * Deletes n lines at sb + where, treating last as a bottom margin.
 */
void
ScrnDeleteLine(XtermWidget xw, ScrnBuf sb, int last, int where, unsigned n)
{
    TScreen *screen = TScreenOf(xw);
    unsigned size = (unsigned) MaxCols(screen);

    TRACE(("ScrnDeleteLine(%s:last %d, where %d, n %d, size %d)\n",
	   (sb == screen->saveBuf_index) ? "save" : "edit",
	   last, where, n, size));

    assert(where >= 0);
    assert(last >= where + (int) n - 1);

    assert(n != 0);
    assert(size != 0);

    /* move up lines */
    last -= ((int) n - 1);
#if OPT_SAVE_LINES
    if (inSaveBuf(screen, sb, where)) {
#if !OPT_FIFO_LINES
	int from = where + n;
#endif

	/* we shouldn't be editing the saveBuf, only scroll into it */
	assert(last >= screen->savelines);

	if (sb != 0) {
#if OPT_FIFO_LINES
	    /* copy lines from editBuf to saveBuf (allocating as we go...) */
	    saveEditBufLines(screen, sb, n);
#else
	    ScrnClearLines(xw, sb, where, n, size);

	    /* move the pointers within saveBuf */
	    TRACE(("...%smoving pointers in saveBuf (compare %d %d)\n",
		   ((screen->savelines > from)
		    ? ""
		    : "SKIP "),
		   screen->savelines,
		   from));
	    if (screen->savelines > from) {
		MoveLineData(sb,
			     (unsigned) where,
			     (unsigned) from,
			     (unsigned) (screen->savelines - from));
	    }

	    /* reuse storage in saveBuf */
	    TRACE(("...reuse %d lines storage in saveBuf\n", n));
	    RestoreLineData(sb, (unsigned) screen->savelines - n, n);

	    /* copy lines from editBuf to saveBuf (into the reused storage) */
	    saveEditBufLines(screen, sb, n);
#endif
	}

	/* adjust variables to fall-thru into changes only to editBuf */
	TRACE(("...adjusting variables, to work on editBuf alone\n"));
	last -= screen->savelines;
	where = 0;
	sb = screen->visbuf;
    }
#endif
    /*
     * Scroll the visible buffer (editBuf).
     */
    ScrnClearLines(xw, sb, where, n, size);

    MoveLineData(sb,
		 (unsigned) where,
		 (unsigned) (where + (int) n),
		 (size_t) (last - where));

    /* reuse storage for new bottom lines */
    RestoreLineData(sb, (unsigned) last, n);
}

/*
 * Inserts n blanks in screen at current row, col.  Size is the size of each
 * row.
 */
void
ScrnInsertChar(XtermWidget xw, unsigned n)
{
#define MemMove(data) \
    	for (j = last - 1; j >= (col + (int) n); --j) \
	    data[j] = data[j - (int) n]

    TScreen *screen = TScreenOf(xw);
    int last = MaxCols(screen);
    int row = screen->cur_row;
    int col = screen->cur_col;
    int j, nbytes;
    LineData *ld;

    if (last <= (col + (int) n)) {
	if (last <= col)
	    return;
	n = (unsigned) (last - col);
    }
    nbytes = (last - (col + (int) n));

    assert(screen->cur_col >= 0);
    assert(screen->cur_row >= 0);
    assert(n > 0);
    assert(last > (int) n);

    if_OPT_WIDE_CHARS(screen, {
	int xx = screen->cur_row;
	int kl;
	int kr = screen->cur_col;
	if (DamagedCells(screen, n, &kl, (int *) 0, xx, kr) && kr > kl) {
	    ClearCells(xw, 0, (unsigned) (kr - kl + 1), row, kl);
	}
	kr = screen->max_col - (int) n + 1;
	if (DamagedCells(screen, n, &kl, (int *) 0, xx, kr) && kr > kl) {
	    ClearCells(xw, 0, (unsigned) (kr - kl + 1), row, kl);
	}
    });

    if ((ld = getLineData(screen, row)) != 0) {
	MemMove(ld->charData);
	MemMove(ld->attribs);

	if_OPT_ISO_COLORS(screen, {
	    MemMove(ld->color);
	});
	if_OPT_WIDE_CHARS(screen, {
	    size_t off;
	    for_each_combData(off, ld) {
		MemMove(ld->combData[off]);
	    }
	});
    }
    ClearCells(xw, CHARDRAWN, n, row, col);

#undef MemMove
}

/*
 * Deletes n characters at current row, col.
 */
void
ScrnDeleteChar(XtermWidget xw, unsigned n)
{
#define MemMove(data) \
    	for (j = col; j < last - (int) n; ++j) \
	    data[j] = data[j + (int) n]

    TScreen *screen = TScreenOf(xw);
    int last = MaxCols(screen);
    int row = screen->cur_row;
    int col = screen->cur_col;
    int j, nbytes;
    LineData *ld;

    if (last <= (col + (int) n)) {
	if (last <= col)
	    return;
	n = (unsigned) (last - col);
    }
    nbytes = (last - (col + (int) n));

    assert(screen->cur_col >= 0);
    assert(screen->cur_row >= 0);
    assert(n > 0);
    assert(last > (int) n);

    if_OPT_WIDE_CHARS(screen, {
	int kl;
	int kr;
	if (DamagedCells(screen, n, &kl, &kr,
			 screen->cur_row,
			 screen->cur_col))
	    ClearCells(xw, 0, (unsigned) (kr - kl + 1), row, kl);
    });

    if ((ld = getLineData(screen, row)) != 0) {
	MemMove(ld->charData);
	MemMove(ld->attribs);

	if_OPT_ISO_COLORS(screen, {
	    MemMove(ld->color);
	});
	if_OPT_WIDE_CHARS(screen, {
	    size_t off;
	    for_each_combData(off, ld) {
		MemMove(ld->combData[off]);
	    }
	});
	LineClrWrapped(ld);
    }
    ClearCells(xw, 0, n, row, (last - (int) n));

#undef MemMove
}

/*
 * Repaints the area enclosed by the parameters.
 * Requires: (toprow, leftcol), (toprow + nrows, leftcol + ncols) are
 * 	     coordinates of characters in screen;
 *	     nrows and ncols positive.
 *	     all dimensions are based on single-characters.
 */
void
ScrnRefresh(XtermWidget xw,
	    int toprow,
	    int leftcol,
	    int nrows,
	    int ncols,
	    Bool force)		/* ... leading/trailing spaces */
{
    TScreen *screen = TScreenOf(xw);
    LineData *ld;
    int y = toprow * FontHeight(screen) + screen->border;
    int row;
    int maxrow = toprow + nrows - 1;
    int scrollamt = screen->scroll_amt;
    unsigned gc_changes = 0;
#ifdef __CYGWIN__
    static char first_time = 1;
#endif
    static int recurse = 0;

    TRACE(("ScrnRefresh top %d (%d,%d) - (%d,%d)%s {{\n",
	   screen->topline, toprow, leftcol,
	   nrows, ncols,
	   force ? " force" : ""));

    if (screen->cursorp.col >= leftcol
	&& screen->cursorp.col <= (leftcol + ncols - 1)
	&& screen->cursorp.row >= ROW2INX(screen, toprow)
	&& screen->cursorp.row <= ROW2INX(screen, maxrow))
	screen->cursor_state = OFF;

    for (row = toprow; row <= maxrow; y += FontHeight(screen), row++) {
#if OPT_ISO_COLORS
	CellColor *fb = 0;
#define ColorOf(col) fb[col]
#endif
#if OPT_WIDE_CHARS
	int wideness = 0;
#endif
#define BLANK_CEL(cell) (chars[cell] == ' ')
	IChar *chars;
	Char *attrs;
	int col = leftcol;
	int maxcol = leftcol + ncols - 1;
	int hi_col = maxcol;
	int lastind;
	unsigned flags;
	unsigned test;
	CellColor fg_bg = 0;
	unsigned fg = 0, bg = 0;
	int x;
	GC gc;
	Bool hilite;

	(void) fg;
	(void) bg;
#if !OPT_ISO_COLORS
	fg_bg = 0;
#endif

	if (row < screen->top_marg || row > screen->bot_marg)
	    lastind = row;
	else
	    lastind = row - scrollamt;

	TRACE2(("ScrnRefresh row=%d lastind=%d ->%d\n",
		row, lastind, ROW2INX(screen, lastind)));

	if ((ld = getLineData(screen, ROW2INX(screen, lastind))) == 0
	    || ld->charData == 0
	    || ld->attribs == 0) {
	    continue;
	}
	if (maxcol >= (int) ld->lineSize) {
	    maxcol = ld->lineSize - 1;
	    hi_col = maxcol;
	}

	chars = ld->charData;
	attrs = ld->attribs;
	assert(chars != 0);
	assert(attrs != 0);

	if_OPT_WIDE_CHARS(screen, {
	    /* This fixes an infinite recursion bug, that leads
	       to display anomalies. It seems to be related to
	       problems with the selection. */
	    if (recurse < 3) {
		/* adjust to redraw all of a widechar if we just wanted
		   to draw the right hand half */
		if (leftcol > 0 &&
		    chars[leftcol] == HIDDEN_CHAR &&
		    isWide((int) chars[leftcol - 1])) {
		    leftcol--;
		    ncols++;
		    col = leftcol;
		}
	    } else {
		fprintf(stderr, "This should not happen. Why is it so?\n");
	    }
	});

	if (row < screen->startH.row || row > screen->endH.row ||
	    (row == screen->startH.row && maxcol < screen->startH.col) ||
	    (row == screen->endH.row && col >= screen->endH.col)) {
#if OPT_DEC_CHRSET
	    /*
	     * Temporarily change dimensions to double-sized characters so
	     * we can reuse the recursion on this function.
	     */
	    if (CSET_DOUBLE(GetLineDblCS(ld))) {
		col /= 2;
		maxcol /= 2;
	    }
#endif
	    /*
	     * If row does not intersect selection; don't hilite blanks.
	     */
	    if (!force) {
		while (col <= maxcol && (attrs[col] & ~BOLD) == 0 &&
		       BLANK_CEL(col))
		    col++;

		while (col <= maxcol && (attrs[maxcol] & ~BOLD) == 0 &&
		       BLANK_CEL(maxcol))
		    maxcol--;
	    }
#if OPT_DEC_CHRSET
	    if (CSET_DOUBLE(GetLineDblCS(ld))) {
		col *= 2;
		maxcol *= 2;
	    }
#endif
	    hilite = False;
	} else {
	    /* row intersects selection; split into pieces of single type */
	    if (row == screen->startH.row && col < screen->startH.col) {
		recurse++;
		ScrnRefresh(xw, row, col, 1, screen->startH.col - col,
			    force);
		col = screen->startH.col;
	    }
	    if (row == screen->endH.row && maxcol >= screen->endH.col) {
		recurse++;
		ScrnRefresh(xw, row, screen->endH.col, 1,
			    maxcol - screen->endH.col + 1, force);
		maxcol = screen->endH.col - 1;
	    }

	    /*
	     * If we're highlighting because the user is doing cut/paste,
	     * trim the trailing blanks from the highlighted region so we're
	     * showing the actual extent of the text that'll be cut.  If
	     * we're selecting a blank line, we'll highlight one column
	     * anyway.
	     *
	     * We don't do this if the mouse-hilite mode is set because that
	     * would be too confusing.
	     *
	     * The default if the highlightSelection resource isn't set will
	     * highlight the whole width of the terminal, which is easy to
	     * see, but harder to use (because trailing blanks aren't as
	     * apparent).
	     */
	    if (screen->highlight_selection
		&& screen->send_mouse_pos != VT200_HIGHLIGHT_MOUSE) {
		hi_col = screen->max_col;
		while (hi_col > 0 && !(attrs[hi_col] & CHARDRAWN))
		    hi_col--;
	    }

	    /* remaining piece should be hilited */
	    hilite = True;
	}

	if (col > maxcol)
	    continue;

	/*
	 * Go back to double-sized character dimensions if the line has
	 * double-width characters.  Note that 'hi_col' is already in the
	 * right units.
	 */
	if_OPT_DEC_CHRSET({
	    if (CSET_DOUBLE(GetLineDblCS(ld))) {
		col /= 2;
		maxcol /= 2;
	    }
	});

	flags = attrs[col];

	if_OPT_WIDE_CHARS(screen, {
	    wideness = isWide((int) chars[col]);
	});

	if_OPT_ISO_COLORS(screen, {
	    fb = ld->color;
	    fg_bg = ColorOf(col);
	    fg = extract_fg(xw, fg_bg, flags);
	    bg = extract_bg(xw, fg_bg, flags);
	});

	gc = updatedXtermGC(xw, flags, fg_bg, hilite);
	gc_changes |= (flags & (FG_COLOR | BG_COLOR));

	x = LineCursorX(screen, ld, col);
	lastind = col;

	for (; col <= maxcol; col++) {
	    if ((attrs[col] != flags)
		|| (hilite && (col > hi_col))
#if OPT_ISO_COLORS
		|| ((flags & FG_COLOR)
		    && (extract_fg(xw, ColorOf(col), attrs[col]) != fg))
		|| ((flags & BG_COLOR)
		    && (extract_bg(xw, ColorOf(col), attrs[col]) != bg))
#endif
#if OPT_WIDE_CHARS
		|| (isWide((int) chars[col]) != wideness
		    && chars[col] != HIDDEN_CHAR)
#endif
		) {
		assert(col >= lastind);
		TRACE(("ScrnRefresh looping drawXtermText %d..%d:%s\n",
		       lastind, col,
		       visibleIChars((&chars[lastind]),
				     (unsigned) (col - lastind))));

		test = flags;
		checkVeryBoldColors(test, fg);

		x = drawXtermText(xw, test & DRAWX_MASK, gc, x, y,
				  GetLineDblCS(ld),
				  &chars[lastind],
				  (unsigned) (col - lastind), 0);

		if_OPT_WIDE_CHARS(screen, {
		    int i;
		    size_t off;

		    for_each_combData(off, ld) {
			IChar *com_off = ld->combData[off];

			for (i = lastind; i < col; i++) {
			    int my_x = LineCursorX(screen, ld, i);
			    IChar base = chars[i];

			    if (isWide((int) base))
				my_x = LineCursorX(screen, ld, i - 1);

			    if (com_off[i] != 0)
				drawXtermText(xw,
					      (test & DRAWX_MASK)
					      | NOBACKGROUND,
					      gc, my_x, y,
					      GetLineDblCS(ld),
					      com_off + i,
					      1, isWide((int) base));
			}
		    }
		});

		resetXtermGC(xw, flags, hilite);

		lastind = col;

		if (hilite && (col > hi_col))
		    hilite = False;

		flags = attrs[col];
		if_OPT_ISO_COLORS(screen, {
		    fg_bg = ColorOf(col);
		    fg = extract_fg(xw, fg_bg, flags);
		    bg = extract_bg(xw, fg_bg, flags);
		});
		if_OPT_WIDE_CHARS(screen, {
		    wideness = isWide((int) chars[col]);
		});

		gc = updatedXtermGC(xw, flags, fg_bg, hilite);
		gc_changes |= (flags & (FG_COLOR | BG_COLOR));
	    }

	    if (chars[col] == 0) {
		chars[col] = ' ';
	    }
	}

	assert(col >= lastind);
	TRACE(("ScrnRefresh calling drawXtermText %d..%d:%s\n",
	       lastind, col,
	       visibleIChars(&chars[lastind], (unsigned) (col - lastind))));

	test = flags;
	checkVeryBoldColors(test, fg);

	drawXtermText(xw, test & DRAWX_MASK, gc, x, y,
		      GetLineDblCS(ld),
		      &chars[lastind],
		      (unsigned) (col - lastind), 0);

	if_OPT_WIDE_CHARS(screen, {
	    int i;
	    size_t off;

	    for_each_combData(off, ld) {
		IChar *com_off = ld->combData[off];

		for (i = lastind; i < col; i++) {
		    int my_x = LineCursorX(screen, ld, i);
		    int base = (int) chars[i];

		    if (isWide(base))
			my_x = LineCursorX(screen, ld, i - 1);

		    if (com_off[i] != 0)
			drawXtermText(xw,
				      (test & DRAWX_MASK)
				      | NOBACKGROUND,
				      gc, my_x, y,
				      GetLineDblCS(ld),
				      com_off + i,
				      1, isWide(base));
		}
	    }
	});

	resetXtermGC(xw, flags, hilite);
    }

    /*
     * If we're in color mode, reset the various GC's to the current
     * screen foreground and background so that other functions (e.g.,
     * ClearRight) will get the correct colors.
     */
    if_OPT_ISO_COLORS(screen, {
	if (gc_changes & FG_COLOR)
	    SGR_Foreground(xw, xw->cur_foreground);
	if (gc_changes & BG_COLOR)
	    SGR_Background(xw, xw->cur_background);
    });

#if defined(__CYGWIN__) && defined(TIOCSWINSZ)
    if (first_time == 1) {
	TTYSIZE_STRUCT ts;

	first_time = 0;
	TTYSIZE_ROWS(ts) = nrows;
	TTYSIZE_COLS(ts) = ncols;
	ts.ws_xpixel = xw->core.width;
	ts.ws_ypixel = xw->core.height;
	SET_TTYSIZE(screen->respond, ts);
    }
#endif
    recurse--;

    TRACE(("...}} ScrnRefresh\n"));
    return;
}

/*
 * Call this wrapper to ScrnRefresh() when the data has changed.  If the
 * refresh region overlaps the selection, we will release the primary selection.
 */
void
ScrnUpdate(XtermWidget xw,
	   int toprow,
	   int leftcol,
	   int nrows,
	   int ncols,
	   Bool force)		/* ... leading/trailing spaces */
{
    TScreen *screen = TScreenOf(xw);

    if (ScrnHaveSelection(screen)
	&& (toprow <= screen->endH.row)
	&& (toprow + nrows - 1 >= screen->startH.row)) {
	ScrnDisownSelection(xw);
    }
    ScrnRefresh(xw, toprow, leftcol, nrows, ncols, force);
}

/*
 * Sets the rows first though last of the buffer of screen to spaces.
 * Requires first <= last; first, last are rows of screen->buf.
 */
void
ClearBufRows(XtermWidget xw,
	     int first,
	     int last)
{
    TScreen *screen = TScreenOf(xw);
    unsigned len = (unsigned) MaxCols(screen);
    int row;

    TRACE(("ClearBufRows %d..%d\n", first, last));
    for (row = first; row <= last; row++) {
	LineData *ld = getLineData(screen, row);
	if (ld != 0) {
	    if_OPT_DEC_CHRSET({
		/* clearing the whole row resets the doublesize characters */
		SetLineDblCS(ld, CSET_SWL);
	    });
	    LineClrWrapped(ld);
	    ClearCells(xw, 0, len, row, 0);
	}
    }
}

/*
  Resizes screen:
  1. If new window would have fractional characters, sets window size so as to
  discard fractional characters and returns -1.
  Minimum screen size is 1 X 1.
  Note that this causes another ExposeWindow event.
  2. Enlarges screen->buf if necessary.  New space is appended to the bottom
  and to the right
  3. Reduces  screen->buf if necessary.  Old space is removed from the bottom
  and from the right
  4. Cursor is positioned as closely to its former position as possible
  5. Sets screen->max_row and screen->max_col to reflect new size
  6. Maintains the inner border (and clears the border on the screen).
  7. Clears origin mode and sets scrolling region to be entire screen.
  8. Returns 0
  */
int
ScreenResize(XtermWidget xw,
	     int width,
	     int height,
	     unsigned *flags)
{
    TScreen *screen = TScreenOf(xw);
    int code, rows, cols;
    int border = 2 * screen->border;
    int move_down_by = 0;
#ifdef TTYSIZE_STRUCT
    TTYSIZE_STRUCT ts;
#endif
    Window tw = VWindow(screen);

    TRACE(("ScreenResize %dx%d border %d font %dx%d\n",
	   height, width, border,
	   FontHeight(screen), FontWidth(screen)));

    assert(width > 0);
    assert(height > 0);

    if (screen->is_running) {
	/* clear the right and bottom internal border because of NorthWest
	   gravity might have left junk on the right and bottom edges */
	if (width >= (int) FullWidth(screen)) {
	    XClearArea(screen->display, tw,
		       FullWidth(screen), 0,	/* right edge */
		       0, (unsigned) height,	/* from top to bottom */
		       False);
	}
	if (height >= (int) FullHeight(screen)) {
	    XClearArea(screen->display, tw,
		       0, FullHeight(screen),	/* bottom */
		       (unsigned) width, 0,	/* all across the bottom */
		       False);
	}
    }

    TRACE(("...computing rows/cols: %.2f %.2f\n",
	   (double) (height - border) / FontHeight(screen),
	   (double) (width - border - ScrollbarWidth(screen)) / FontWidth(screen)));

    rows = (height - border) / FontHeight(screen);
    cols = (width - border - ScrollbarWidth(screen)) / FontWidth(screen);
    if (rows < 1)
	rows = 1;
    if (cols < 1)
	cols = 1;

    /* update buffers if the screen has changed size */
    if (MaxRows(screen) != rows || MaxCols(screen) != cols) {
	int whichBuf = 0;
	int delta_rows = rows - MaxRows(screen);
#if OPT_TRACE
	int delta_cols = cols - MaxCols(screen);
#endif

	TRACE(("...ScreenResize chars %dx%d delta %dx%d\n",
	       rows, cols, delta_rows, delta_cols));

	if (screen->is_running) {
#if !OPT_FIFO_LINES
	    int savelines = (screen->scrollWidget
			     ? screen->savelines
			     : 0);
#endif
	    if (screen->cursor_state)
		HideCursor();
#if OPT_SAVE_LINES
	    /*
	     * The non-visible buffer is simple, since we will not copy data
	     * to/from the saved-lines.  Do that first.
	     */
	    if (screen->editBuf_index[!screen->whichBuf]) {
		(void) Reallocate(xw,
				  &screen->editBuf_index[!screen->whichBuf],
				  &screen->editBuf_data[!screen->whichBuf],
				  (unsigned) rows,
				  (unsigned) cols,
				  (unsigned) MaxRows(screen),
				  (unsigned) MaxCols(screen));
	    }

	    /*
	     * The save-lines buffer may change width, but will not change its
	     * height.  Deal with the cases where we copy data to/from the
	     * saved-lines buffer.
	     */
	    if (GravityIsSouthWest(xw)
		&& delta_rows
		&& screen->saveBuf_index != 0) {

		move_down_by = delta_rows;

		if (delta_rows < 0) {
		    unsigned move_up = (unsigned) (-delta_rows);
		    ScrnBuf dst = screen->saveBuf_index;

#if OPT_FIFO_LINES
		    int amount = ((MaxRows(screen) - (int) move_up - 1)
				  - screen->cur_row);

		    if (amount < 0) {
			/* move line-data from visible-buffer to save-buffer */
			saveEditBufLines(screen, dst, (unsigned) -amount);
			move_up = (unsigned) -amount;
			move_down_by = amount;
		    } else {
			move_down_by = 0;
		    }
#else /* !OPT_FIFO_LINES */
		    int amount = screen->savelines - (int) move_up;

		    TRACE_SCRNBUF("before save", screen, dst, screen->savelines);

		    /* shift lines in save-buffer to make room */
		    TRACE(("...%smoving pointers in saveBuf (compare %d %d)\n",
			   (amount > 0
			    ? ""
			    : "SKIP "),
			   screen->savelines,
			   move_up));
		    if (amount > 0) {
			SaveLineData(dst, 0, move_up);

			MoveLineData(dst,
				     0,
				     move_up,
				     (unsigned) amount);

			TRACE(("...reuse %d lines storage in saveBuf\n", move_up));
			RestoreLineData(dst,
					(unsigned) amount,
					move_up);
			TRACE_SCRNBUF("restoresave", screen, dst, screen->savelines);
		    }

		    /* copy line-data from visible-buffer to save-buffer */
		    saveEditBufLines(screen, dst, move_up);

		    /* after data is copied, reallocate saved-lines */
		    (void) Reallocate(xw,
				      &screen->saveBuf_index,
				      &screen->saveBuf_data,
				      (unsigned) savelines,
				      (unsigned) cols,
				      (unsigned) savelines,
				      (unsigned) MaxCols(screen));
		    TRACE_SCRNBUF("reallocSAVE",
				  screen,
				  screen->saveBuf_index,
				  savelines);
#endif /* OPT_FIFO_LINES */

		    /* decrease size of visible-buffer */
		    (void) Reallocate(xw,
				      &screen->editBuf_index[screen->whichBuf],
				      &screen->editBuf_data[screen->whichBuf],
				      (unsigned) rows,
				      (unsigned) cols,
				      (unsigned) MaxRows(screen),
				      (unsigned) MaxCols(screen));
		    TRACE_SCRNBUF("reallocEDIT",
				  screen,
				  screen->editBuf_index[screen->whichBuf],
				  rows);
		} else {
		    unsigned move_down = (unsigned) delta_rows;
#if OPT_FIFO_LINES
		    long unsave_fifo;
#else
		    ScrnBuf src = screen->saveBuf_index;
#endif
		    ScrnBuf dst;
		    int amount;

		    if ((int) move_down > screen->savedlines) {
			move_down = (unsigned) screen->savedlines;
		    }
		    move_down_by = (int) move_down;
		    amount = rows - (int) move_down;

		    /* increase size of visible-buffer */
		    (void) Reallocate(xw,
				      &screen->editBuf_index[screen->whichBuf],
				      &screen->editBuf_data[screen->whichBuf],
				      (unsigned) rows,
				      (unsigned) cols,
				      (unsigned) MaxRows(screen),
				      (unsigned) MaxCols(screen));

		    dst = screen->editBuf_index[screen->whichBuf];
		    TRACE_SCRNBUF("reallocEDIT", screen, dst, rows);

		    TRACE(("...%smoving pointers in editBuf (compare %d %d)\n",
			   (amount > 0
			    ? ""
			    : "SKIP "),
			   rows,
			   move_down));
		    if (amount > 0) {
			/* shift lines in visible-buffer to make room */
			SaveLineData(dst, (unsigned) amount, (size_t) move_down);

			MoveLineData(dst,
				     move_down,
				     0,
				     (unsigned) amount);

			TRACE(("...reuse %d lines storage in editBuf\n", move_down));
			RestoreLineData(dst,
					0,
					move_down);

			TRACE_SCRNBUF("shifted", screen, dst, rows);
		    }

		    /* copy line-data from save-buffer to visible-buffer */
		    unsaveEditBufLines(screen, dst, move_down);
		    TRACE_SCRNBUF("copied", screen, dst, rows);

#if OPT_FIFO_LINES
		    unsave_fifo = (long) move_down;
		    if (screen->saved_fifo < (int) unsave_fifo)
			unsave_fifo = screen->saved_fifo;

		    /* free up storage in fifo from the copied lines */
		    while (unsave_fifo-- > 0) {
			deleteScrollback(screen, -1);
			screen->saved_fifo--;
		    }
#else
		    amount = (screen->savelines - (int) move_down);
		    TRACE(("...%smoving pointers in saveBuf (compare %d %d)\n",
			   (amount > 0
			    ? ""
			    : "SKIP "),
			   rows,
			   move_down));
		    if (amount > 0) {
			/* shift lines in save-buffer to account for copy */
			src = screen->saveBuf_index;
			SaveLineData(src, amount, move_down);

			MoveLineData(src,
				     move_down,
				     0,
				     (unsigned) amount);

			TRACE(("...reuse %d lines storage in saveBuf\n", move_down));
			RestoreLineData(src,
					0,
					move_down);
		    }
#endif

		    /* recover storage in save-buffer */
		}
	    } else {
#if !OPT_FIFO_LINES
		(void) Reallocate(xw,
				  &screen->saveBuf_index,
				  &screen->saveBuf_data,
				  (unsigned) savelines,
				  (unsigned) cols,
				  (unsigned) savelines,
				  (unsigned) MaxCols(screen));
#endif
		(void) Reallocate(xw,
				  &screen->editBuf_index[screen->whichBuf],
				  &screen->editBuf_data[screen->whichBuf],
				  (unsigned) rows,
				  (unsigned) cols,
				  (unsigned) MaxRows(screen),
				  (unsigned) MaxCols(screen));
	    }
#else /* !OPT_SAVE_LINES */
	    if (screen->whichBuf
		&& GravityIsSouthWest(xw)) {
		/* swap buffer pointers back to make this work */
		whichBuf = screen->whichBuf;
		SwitchBufPtrs(screen, 0);
	    } else {
		whichBuf = 0;
	    }
	    if (screen->editBuf_index[1])
		(void) Reallocate(xw,
				  &screen->editBuf_index[1],
				  &screen->editBuf_data[1],
				  (unsigned) rows,
				  (unsigned) cols,
				  (unsigned) MaxRows(screen),
				  (unsigned) MaxCols(screen));
	    move_down_by = Reallocate(xw,
				      &screen->saveBuf_index,
				      &screen->saveBuf_data,
				      (unsigned) (rows + savelines),
				      (unsigned) cols,
				      (unsigned) (MaxRows(screen) + savelines),
				      (unsigned) MaxCols(screen));
#endif /* OPT_SAVE_LINES */
	    screen->visbuf = VisBuf(screen);
	}

	AdjustSavedCursor(xw, move_down_by);
	set_max_row(screen, screen->max_row + delta_rows);
	set_max_col(screen, cols - 1);

	if (screen->is_running) {
	    if (GravityIsSouthWest(xw)) {
		screen->savedlines -= move_down_by;
		if (screen->savedlines < 0)
		    screen->savedlines = 0;
		if (screen->savedlines > screen->savelines)
		    screen->savedlines = screen->savelines;
		if (screen->topline < -screen->savedlines)
		    screen->topline = -screen->savedlines;
		set_cur_row(screen, screen->cur_row + move_down_by);
		screen->cursorp.row += move_down_by;
		ScrollSelection(screen, move_down_by, True);

		if (whichBuf)
		    SwitchBufPtrs(screen, whichBuf);	/* put the pointers back */
	    }
	}

	/* adjust scrolling region */
	set_tb_margins(screen, 0, screen->max_row);
	UIntClr(*flags, ORIGIN);

	if (screen->cur_row > screen->max_row)
	    set_cur_row(screen, screen->max_row);
	if (screen->cur_col > screen->max_col)
	    set_cur_col(screen, screen->max_col);

	screen->fullVwin.height = height - border;
	screen->fullVwin.width = width - border - screen->fullVwin.sb_info.width;

    } else if (FullHeight(screen) == height && FullWidth(screen) == width)
	return (0);		/* nothing has changed at all */

    screen->fullVwin.fullheight = (Dimension) height;
    screen->fullVwin.fullwidth = (Dimension) width;

    ResizeScrollBar(xw);
    ResizeSelection(screen, rows, cols);

#ifndef NO_ACTIVE_ICON
    if (screen->iconVwin.window) {
	XWindowChanges changes;
	screen->iconVwin.width =
	    MaxCols(screen) * screen->iconVwin.f_width;

	screen->iconVwin.height =
	    MaxRows(screen) * screen->iconVwin.f_height;

	changes.width = screen->iconVwin.fullwidth =
	    (Dimension) (screen->iconVwin.width + 2 * xw->misc.icon_border_width);
	changes.height = screen->iconVwin.fullheight =
	    (Dimension) (screen->iconVwin.height + 2 * xw->misc.icon_border_width);
	changes.border_width = (int) xw->misc.icon_border_width;

	TRACE(("resizing icon window %dx%d\n", changes.height, changes.width));
	XConfigureWindow(XtDisplay(xw), screen->iconVwin.window,
			 CWWidth | CWHeight | CWBorderWidth, &changes);
    }
#endif /* NO_ACTIVE_ICON */

#ifdef TTYSIZE_STRUCT
    /* Set tty's idea of window size */
    TTYSIZE_ROWS(ts) = rows;
    TTYSIZE_COLS(ts) = cols;
#ifdef USE_STRUCT_WINSIZE
    ts.ws_xpixel = width;
    ts.ws_ypixel = height;
#endif
    code = SET_TTYSIZE(screen->respond, ts);
    TRACE(("return %d from SET_TTYSIZE %dx%d\n", code, rows, cols));
    (void) code;

#if defined(SIGWINCH) && defined(USE_STRUCT_TTYSIZE)
    if (screen->pid > 1) {
	int pgrp;

	TRACE(("getting process-group\n"));
	if (ioctl(screen->respond, TIOCGPGRP, &pgrp) != -1) {
	    TRACE(("sending SIGWINCH to process group %d\n", pgrp));
	    kill_process_group(pgrp, SIGWINCH);
	}
    }
#endif /* SIGWINCH */

#else
    TRACE(("ScreenResize cannot do anything to pty\n"));
#endif /* TTYSIZE_STRUCT */
    return (0);
}

/*
 * Return true if any character cell starting at [row,col], for len-cells is
 * nonnull.
 */
Bool
non_blank_line(TScreen * screen,
	       int row,
	       int col,
	       int len)
{
    int i;
    Bool found = False;
    LineData *ld = getLineData(screen, row);

    if (ld != 0) {
	for (i = col; i < len; i++) {
	    if (ld->charData[i]) {
		found = True;
		break;
	    }
	}
    }
    return found;
}

/*
 * Rectangle parameters start from one.
 */
#define minRectRow(screen) (getMinRow(screen) + 1)
#define minRectCol(screen) (getMinCol(screen) + 1)
#define maxRectRow(screen) (getMaxRow(screen) + 1)
#define maxRectCol(screen) (getMaxCol(screen) + 1)

static int
limitedParseRow(XtermWidget xw, TScreen * screen, int row)
{
    int min_row = minRectRow(screen);
    int max_row = maxRectRow(screen);

    if (row < min_row)
	row = min_row;
    else if (row > max_row)
	row = max_row;
    return row;
}

static int
limitedParseCol(XtermWidget xw, TScreen * screen, int col)
{
    int min_col = minRectCol(screen);
    int max_col = maxRectCol(screen);

    (void) xw;
    if (col < min_col)
	col = min_col;
    else if (col > max_col)
	col = max_col;
    return col;
}

#define LimitedParse(num, func, dft) \
	func(xw, screen, (nparams > num) ? params[num] : dft)

/*
 * Copy the rectangle boundaries into a struct, providing default values as
 * needed.
 */
void
xtermParseRect(XtermWidget xw, int nparams, int *params, XTermRect * target)
{
    TScreen *screen = TScreenOf(xw);

    memset(target, 0, sizeof(*target));
    target->top = LimitedParse(0, limitedParseRow, minRectRow(screen));
    target->left = LimitedParse(1, limitedParseCol, minRectCol(screen));
    target->bottom = LimitedParse(2, limitedParseRow, maxRectRow(screen));
    target->right = LimitedParse(3, limitedParseCol, maxRectCol(screen));
    TRACE(("parsed rectangle %d,%d %d,%d\n",
	   target->top,
	   target->left,
	   target->bottom,
	   target->right));
}

static Bool
validRect(XtermWidget xw, XTermRect * target)
{
    TScreen *screen = TScreenOf(xw);

    TRACE(("comparing against screensize %dx%d\n",
	   maxRectRow(screen),
	   maxRectCol(screen)));
    return (target != 0
	    && target->top >= minRectRow(screen)
	    && target->left >= minRectCol(screen)
	    && target->top <= target->bottom
	    && target->left <= target->right
	    && target->top <= maxRectRow(screen)
	    && target->right <= maxRectCol(screen));
}

/*
 * Fills a rectangle with the given 8-bit character and video-attributes.
 * Colors and double-size attribute are unmodified.
 */
void
ScrnFillRectangle(XtermWidget xw,
		  XTermRect * target,
		  int value,
		  unsigned flags,
		  Bool keepColors)
{
    TScreen *screen = TScreenOf(xw);

    TRACE(("filling rectangle with '%c' flags %#x\n", value, flags));
    if (validRect(xw, target)) {
	LineData *ld;
	unsigned left = (unsigned) (target->left - 1);
	unsigned size = (unsigned) (target->right - (int) left);
	unsigned attrs = flags;
	int row, col;

	(void) size;

	attrs &= ATTRIBUTES;
	attrs |= CHARDRAWN;
	for (row = target->bottom - 1; row >= (target->top - 1); row--) {
	    ld = getLineData(screen, row);

	    TRACE(("filling %d [%d..%d]\n", row, left, left + size));

	    /*
	     * Fill attributes, preserving "protected" flag, as well as
	     * colors if asked.
	     */
	    for (col = (int) left; col < target->right; ++col) {
		unsigned temp = ld->attribs[col];

		if (!keepColors) {
		    UIntClr(temp, (FG_COLOR | BG_COLOR));
		}
		temp = attrs | (temp & (FG_COLOR | BG_COLOR | PROTECTED));
		temp |= CHARDRAWN;
		ld->attribs[col] = (Char) temp;
#if OPT_ISO_COLORS
		if (attrs & (FG_COLOR | BG_COLOR)) {
		    if_OPT_ISO_COLORS(screen, {
			ld->color[col] = xtermColorPair(xw);
		    });
		}
#endif
	    }

	    for (col = (int) left; col < target->right; ++col)
		ld->charData[col] = (CharData) value;

	    if_OPT_WIDE_CHARS(screen, {
		size_t off;
		for_each_combData(off, ld) {
		    memset(ld->combData[off] + left, 0, size * sizeof(CharData));
		}
	    })
	}
	ScrnUpdate(xw,
		   target->top - 1,
		   target->left - 1,
		   (target->bottom - target->top) + 1,
		   (target->right - target->left) + 1,
		   False);
    }
}

#if OPT_DEC_RECTOPS
/*
 * Copies the source rectangle to the target location, including video
 * attributes.
 *
 * This implementation ignores page numbers.
 *
 * The reference manual does not indicate if it handles overlapping copy
 * properly - so we make a local copy of the source rectangle first, then apply
 * the target from that.
 */
void
ScrnCopyRectangle(XtermWidget xw, XTermRect * source, int nparam, int *params)
{
    TScreen *screen = TScreenOf(xw);

    TRACE(("copying rectangle\n"));

    if (validRect(xw, source)) {
	XTermRect target;
	xtermParseRect(xw,
		       ((nparam > 3) ? 2 : (nparam - 1)),
		       params,
		       &target);
	if (validRect(xw, &target)) {
	    Cardinal high = (Cardinal) (source->bottom - source->top) + 1;
	    Cardinal wide = (Cardinal) (source->right - source->left) + 1;
	    Cardinal size = (high * wide);
	    int row, col;
	    Cardinal j, k;
	    LineData *ld;

	    CellData *cells = newCellData(xw, size);

	    if (cells != 0) {

		TRACE(("OK - make copy %dx%d\n", high, wide));
		target.bottom = target.top + (int) (high - 1);
		target.right = target.left + (int) (wide - 1);

		for (row = source->top - 1; row < source->bottom; ++row) {
		    ld = getLineData(screen, row);
		    j = (Cardinal) (row - (source->top - 1));
		    for (col = source->left - 1; col < source->right; ++col) {
			k = (Cardinal) (col - (source->left - 1));
			saveCellData(screen, cells,
				     (j * wide) + k,
				     ld, col);
		    }
		}
		for (row = target.top - 1; row < target.bottom; ++row) {
		    ld = getLineData(screen, row);
		    j = (Cardinal) (row - (target.top - 1));
		    for (col = target.left - 1; col < target.right; ++col) {
			k = (Cardinal) (col - (target.left - 1));
			if (row >= getMinRow(screen)
			    && row <= getMaxRow(screen)
			    && col >= getMinCol(screen)
			    && col <= getMaxCol(screen)) {
			    if (j < high && k < wide) {
				restoreCellData(screen, cells,
						(j * wide) + k,
						ld, col);
			    } else {
				/* FIXME - clear the target cell? */
			    }
			    ld->attribs[col] |= CHARDRAWN;
			}
		    }
		}
		free(cells);

		ScrnUpdate(xw,
			   (target.top - 1),
			   (target.left - 1),
			   (target.bottom - target.top) + 1,
			   ((target.right - target.left) + 1),
			   False);
	    }
	}
    }
}

/*
 * Modifies the video-attributes only - so selection (not a video attribute) is
 * unaffected.  Colors and double-size flags are unaffected as well.
 *
 * FIXME: our representation for "invisible" does not work with this operation,
 * since the attribute byte is fully-allocated for other flags.  The logic
 * is shown for INVISIBLE because it's harmless, and useful in case the
 * CHARDRAWN or PROTECTED flags are reassigned.
 */
void
ScrnMarkRectangle(XtermWidget xw,
		  XTermRect * target,
		  Bool reverse,
		  int nparam,
		  int *params)
{
    TScreen *screen = TScreenOf(xw);
    Bool exact = (screen->cur_decsace == 2);

    TRACE(("%s %s\n",
	   reverse ? "reversing" : "marking",
	   (exact
	    ? "rectangle"
	    : "region")));

    if (validRect(xw, target)) {
	LineData *ld;
	int top = target->top - 1;
	int bottom = target->bottom - 1;
	int row, col;
	int n;

	for (row = top; row <= bottom; ++row) {
	    int left = ((exact || (row == top))
			? (target->left - 1)
			: getMinCol(screen));
	    int right = ((exact || (row == bottom))
			 ? (target->right - 1)
			 : getMaxCol(screen));

	    ld = getLineData(screen, row);

	    TRACE(("marking %d [%d..%d]\n", row, left, right));
	    for (col = left; col <= right; ++col) {
		unsigned flags = ld->attribs[col];

		for (n = 0; n < nparam; ++n) {
#if OPT_TRACE
		    if (row == top && col == left)
			TRACE(("attr param[%d] %d\n", n + 1, params[n]));
#endif
		    if (reverse) {
			switch (params[n]) {
			case 1:
			    flags ^= BOLD;
			    break;
			case 4:
			    flags ^= UNDERLINE;
			    break;
			case 5:
			    flags ^= BLINK;
			    break;
			case 7:
			    flags ^= INVERSE;
			    break;
			case 8:
			    flags ^= INVISIBLE;
			    break;
			}
		    } else {
			switch (params[n]) {
			case 0:
			    UIntClr(flags, SGR_MASK);
			    break;
			case 1:
			    flags |= BOLD;
			    break;
			case 4:
			    flags |= UNDERLINE;
			    break;
			case 5:
			    flags |= BLINK;
			    break;
			case 7:
			    flags |= INVERSE;
			    break;
			case 8:
			    flags |= INVISIBLE;
			    break;
			case 22:
			    UIntClr(flags, BOLD);
			    break;
			case 24:
			    UIntClr(flags, UNDERLINE);
			    break;
			case 25:
			    UIntClr(flags, BLINK);
			    break;
			case 27:
			    UIntClr(flags, INVERSE);
			    break;
			case 28:
			    UIntClr(flags, INVISIBLE);
			    break;
			}
		    }
		}
#if OPT_TRACE
		if (row == top && col == left)
		    TRACE(("first mask-change is %#x\n",
			   ld->attribs[col] ^ flags));
#endif
		ld->attribs[col] = (Char) flags;
	    }
	}
	ScrnRefresh(xw,
		    (target->top - 1),
		    (exact ? (target->left - 1) : getMinCol(screen)),
		    (target->bottom - target->top) + 1,
		    (exact
		     ? ((target->right - target->left) + 1)
		     : (getMaxCol(screen) - getMinCol(screen) + 1)),
		    False);
    }
}

/*
 * Resets characters to space, except where prohibited by DECSCA.  Video
 * attributes (including color) are untouched.
 */
void
ScrnWipeRectangle(XtermWidget xw,
		  XTermRect * target)
{
    TScreen *screen = TScreenOf(xw);

    TRACE(("wiping rectangle\n"));

    if (validRect(xw, target)) {
	LineData *ld;
	int top = target->top - 1;
	int bottom = target->bottom - 1;
	int row, col;

	for (row = top; row <= bottom; ++row) {
	    int left = (target->left - 1);
	    int right = (target->right - 1);

	    TRACE(("wiping %d [%d..%d]\n", row, left, right));

	    ld = getLineData(screen, row);
	    for (col = left; col <= right; ++col) {
		if (!((screen->protected_mode == DEC_PROTECT)
		      && (ld->attribs[col] & PROTECTED))) {
		    ld->attribs[col] |= CHARDRAWN;
		    ld->charData[col] = ' ';
		    if_OPT_WIDE_CHARS(screen, {
			size_t off;
			for_each_combData(off, ld) {
			    ld->combData[off][col] = '\0';
			}
		    })
		}
	    }
	}
	ScrnUpdate(xw,
		   (target->top - 1),
		   (target->left - 1),
		   (target->bottom - target->top) + 1,
		   ((target->right - target->left) + 1),
		   False);
    }
}
#endif /* OPT_DEC_RECTOPS */