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
|
//////////////////////////////////////////////////////////////////////////
// pfterm environment settings
//////////////////////////////////////////////////////////////////////////
#ifdef _PFTERM_TEST_MAIN
#define USE_PFTERM
#define EXP_PFTERM
#define DBCSAWARE
#define FT_DBCS_NOINTRESC 1
#define DBG_TEXT_FD
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#else
#define HAVE_GRAYOUT
#include "bbs.h"
#ifdef DBCS_NOINTRESC
// # ifdef CONVERT
// extern int bbs_convert_type;
// # define FT_DBCS_NOINTRESC (
// (cuser.uflag & DBCS_NOINTRESC) ||
// (bbs_convert_type == CONV_UTF8))
// # else
# define FT_DBCS_NOINTRESC (cuser.uflag & DBCS_NOINTRESC)
// # endif
#else
# define FT_DBCS_NOINTRESC 0
#endif
#endif
//////////////////////////////////////////////////////////////////////////
// pfterm debug settings
//////////////////////////////////////////////////////////////////////////
// #define DBG_SHOW_DIRTY
// #define DBG_SHOW_REPRINT // will not work if you enable SHOW_DIRTY.
// #define DBG_DISABLE_OPTMOVE
// #define DBG_DISABLE_REPRINT
//////////////////////////////////////////////////////////////////////////
// pmore style ansi
// #include "ansi.h"
//////////////////////////////////////////////////////////////////////////
#ifndef PMORE_STYLE_ANSI
#define ESC_CHR '\x1b'
#define ESC_STR "\x1b"
#define ANSI_COLOR(x) ESC_STR "[" #x "m"
#define ANSI_RESET ESC_STR "[m"
#endif // PMORE_STYLE_ANSI
#ifndef ANSI_IS_PARAM
#define ANSI_IS_PARAM(c) (c == ';' || (c >= '0' && c <= '9'))
#endif // ANSI_IS_PARAM
//////////////////////////////////////////////////////////////////////////
// grayout advanced control
// #include "grayout.h"
//////////////////////////////////////////////////////////////////////////
#ifndef GRAYOUT_DARK
#define GRAYOUT_COLORBOLD (-2)
#define GRAYOUT_BOLD (-1)
#define GRAYOUT_DARK (0)
#define GRAYOUT_NORM (1)
#define GRAYOUT_COLORNORM (+2)
#endif // GRAYOUT_DARK
//////////////////////////////////////////////////////////////////////////
// pfterm: piaip's flat terminal system, a new replacement for 'screen'.
// pfterm can also be read as "Perfect Term"
//
// piaip's new implementation of terminal system (term/screen) with dirty
// map, designed and optimized for ANSI based output.
//
// "pfterm" is "piaip's flat terminal" or "perfect term", not "PTT's term"!!!
// pfterm is designed for general maple-family BBS systems, not
// specific to any branch.
//
// Author: Hung-Te Lin (piaip), Dec. 2007.
// <piaip@csie.ntu.edu.tw>
// All Rights Reserved.
// You are free to use, modify, redistribute this program
// in any BBS style systems, or any other non-commercial usage.
// You must keep these copyright information.
//
// MAJOR IMPROVEMENTS:
// - Interpret ANSI code and maintain a virtual terminal
// - Dual buffer for dirty map and optimized output
//
// TODO AND DONE:
// - DBCS aware and prevent interrupting DBCS [done]
// - optimization with relative movement [done]
// - optimization with ENTER/clrtoeol [done]
// - ncurses-like API [done]
// - inansistr to output escaped string [done]
// - handle incomplete DBCS characters [done]
//
// DEPRECATED:
// - standout() [rework getdata() and namecomplete()]
// - talk.c (big_picture) [rework talk.c]
//
//////////////////////////////////////////////////////////////////////////
// Reference:
// http://en.wikipedia.org/wiki/ANSI_escape_code
// http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-048.pdf
//////////////////////////////////////////////////////////////////////////
// Experimental now
#if defined(EXP_PFTERM) || defined(USE_PFTERM)
//////////////////////////////////////////////////////////////////////////
// pfterm Configurations
//////////////////////////////////////////////////////////////////////////
// Prevent invalid DBCS characters
#define FTCONF_PREVENT_INVALID_DBCS
// Some terminals use current attribute to erase background
#define FTCONF_CLEAR_SETATTR
// Some terminals prefer VT100 style scrolling, including Win/DOS telnet
#undef FTCONF_USE_ANSI_SCROLL
// Few poor terminals do not have relative move (ABCD).
#undef FTCONF_USE_ANSI_RELMOVE
//////////////////////////////////////////////////////////////////////////
// Flat Terminal Definition
//////////////////////////////////////////////////////////////////////////
#define FTSZ_DEFAULT_ROW (24)
#define FTSZ_DEFAULT_COL (80)
#define FTSZ_MIN_ROW (24)
#define FTSZ_MAX_ROW (100)
#define FTSZ_MIN_COL (80)
#define FTSZ_MAX_COL (320)
#define FTCHAR_ERASE (' ')
#define FTATTR_ERASE (0x07)
#define FTCHAR_BLANK (' ')
#define FTATTR_DEFAULT (FTATTR_ERASE)
#define FTCHAR_INVALID_DBCS ('?')
// #define FTATTR_TRANSPARENT (0x80)
#define FTDIRTY_CHAR (0x1)
#define FTDIRTY_ATTR (0x2)
#define FTDIRTY_DBCS (0x4)
#define FTDIRTY_INVALID_DBCS (0x8)
#define FTCMD_MAXLEN (63) // max escape command sequence length
#define FTATTR_MINCMD (16)
#ifndef FTCONF_USE_ANSI_RELMOVE
# define FTMV_COST (8) // always ESC[m;nH will costs avg 8 bytes
#else
# define FTMV_COST (5) // ESC[ABCD with ESC[m;nH costs avg 4+ bytes
#endif
//////////////////////////////////////////////////////////////////////////
// Flat Terminal Data Type
//////////////////////////////////////////////////////////////////////////
typedef unsigned char ftchar; // primitive character type
typedef unsigned char ftattr; // primitive attribute type
//////////////////////////////////////////////////////////////////////////
// Flat Terminal Structure
//////////////////////////////////////////////////////////////////////////
typedef struct
{
ftchar **cmap[2]; // character map
ftattr **amap[2]; // attribute map
ftchar *dmap; // dirty map
ftchar *dcmap; // processed display map
ftattr attr;
int rows, cols;
int y, x;
int sy,sx; // stored cursor
int mi; // map index, mi = current map and (1-mi) = old map
int dirty;
int scroll;
// raw terminal status
int ry, rx;
ftattr rattr;
// memory allocation
int mrows, mcols;
// escape command
ftchar cmd[FTCMD_MAXLEN+1];
int szcmd;
} FlatTerm;
static FlatTerm ft;
//////////////////////////////////////////////////////////////////////////
// Flat Terminal Utility Macro
//////////////////////////////////////////////////////////////////////////
// ftattr: 0| FG(3) | BOLD(1) | BG(3) | BLINK(1) |8
#define FTATTR_FGSHIFT (0)
#define FTATTR_BGSHIFT (4)
#define FTATTR_GETFG(x) ((x >> FTATTR_FGSHIFT) & 0x7)
#define FTATTR_GETBG(x) ((x >> FTATTR_BGSHIFT) & 0x7)
#define FTATTR_FGMASK ((ftattr)(0x7 << FTATTR_FGSHIFT))
#define FTATTR_BGMASK ((ftattr)(0x7 << FTATTR_BGSHIFT))
#define FTATTR_BOLD (0x08)
#define FTATTR_BLINK (0x80)
#define FTATTR_DEFAULT_FG (FTATTR_GETFG(FTATTR_DEFAULT))
#define FTATTR_DEFAULT_BG (FTATTR_GETBG(FTATTR_DEFAULT))
#define FTATTR_MAKE(f,b) (((f)<<FTATTR_FGSHIFT)|((b)<<FTATTR_BGSHIFT))
#define FTCHAR_ISBLANK(x) ((x) == (FTCHAR_BLANK))
#define FTCMAP ft.cmap[ft.mi]
#define FTAMAP ft.amap[ft.mi]
#define FTCROW FTCMAP[ft.y]
#define FTAROW FTAMAP[ft.y]
#define FTC FTCROW[ft.x]
#define FTA FTAROW[ft.x]
#define FTD ft.dmap
#define FTDC ft.dcmap
#define FTPC (FTCROW+ft.x)
#define FTPA (FTAROW+ft.x)
#define FTOCMAP ft.cmap[1-ft.mi]
#define FTOAMAP ft.amap[1-ft.mi]
// for fast checking, we use reduced range here.
// Big5: LEAD = 0x81-0xFE, TAIL = 0x40-0x7E/0xA1-0xFE
#define FTDBCS_ISLEAD(x) (((unsigned char)(x))>=(0x80))
#define FTDBCS_ISTAIL(x) (((unsigned char)(x))>=(0x40))
// - 0xFF is used as telnet IAC, don't use it!
// - 0x80 is invalid for Big5.
#define FTDBCS_ISBADLEAD(x) ((((unsigned char)(x)) == 0x80) || (((unsigned char)(x)) == 0xFF))
// even faster:
// #define FTDBCS_ISLEAD(x) (((unsigned char)(x)) & 0x80)
// #define FTDBCS_ISTAIL(x) (((unsigned char)(x)) & ((unsigned char)~0x3F))
#define FTDBCS_ISSBCSPRINT(x) \
(((unsigned char)(x))>=' ' && ((unsigned char)(x))<0x80)
#ifndef min
#define min(x,y) (((x)<(y))?(x):(y))
#endif
#ifndef max
#define max(x,y) (((x)>(y))?(x):(y))
#endif
#ifndef abs
#define abs(x) (((x)>0)?(x):-(x))
#endif
#define ranged(x,vmin,vmax) (max(min(x,vmax),vmin))
//////////////////////////////////////////////////////////////////////////
// Flat Terminal API
//////////////////////////////////////////////////////////////////////////
//// common ncurse-like library interface
// initialization
void initscr (void);
int resizeterm (int rows, int cols);
int endwin (void);
// attributes
ftattr attrget (void);
void attrset (ftattr attr);
void attrsetfg (ftattr attr);
void attrsetbg (ftattr attr);
// cursor
void getyx (int *y, int *x);
void move (int y, int x);
// clear
void clear (void); // clrscr + move(0,0)
void clrtoeol (void); // end of line
void clrtobot (void);
// clear (non-ncurses)
void clrtoln (int ln); // clear down to ln ( excluding ln, as [y,ln) )
void clrcurln (void); // whole line
void clrtobeg (void); // begin of line
void clrtohome (void);
void clrscr (void); // clear and keep cursor untouched
void clrregion (int r1, int r2); // clear [r1,r2], bi-directional.
// flushing
void refresh (void); // optimized refresh
void redrawwin (void); // invalidate whole screen
// scrolling
void scroll (void); // scroll up
void rscroll (void); // scroll down
void scrl (int rows);
// output (non-ncurses)
void outc (unsigned char c);
void outs (const char *s);
void outstr (const char *str); // prepare and print a complete string.
// readback
int instr (char *str);
int innstr (char *str, int n); // n includes \0
int inansistr (char *str, int n); // n includes \0
// deprecated
void standout (void);
void standend (void);
// grayout advanced control
void grayout (int y, int end, int level);
//// flat-term internal processor
int fterm_inbuf (void); // raw input adapter
void fterm_rawc (int c); // raw output adapter
void fterm_rawnewline(void); // raw output adapter
void fterm_rawflush (void); // raw output adapter
void fterm_raws (const char *s);
void fterm_rawnc (int c, int n);
void fterm_rawnum (int arg);
void fterm_rawcmd (int arg, int defval, char c);
void fterm_rawcmd2 (int arg1, int arg2, int defval, char c);
void fterm_rawattr (ftattr attr); // optimized changing attribute
void fterm_rawclear (void);
void fterm_rawclreol (void);
void fterm_rawhome (void);
void fterm_rawscroll (int dy);
void fterm_rawcursor (void);
void fterm_rawmove (int y, int x);
void fterm_rawmove_opt(int y, int x);
void fterm_rawmove_rel(int dy, int dx);
int fterm_chattr (char *s, ftattr oa, ftattr na); // size(s) > FTATTR_MINCMD
void fterm_exec (void); // execute ft.cmd
void fterm_flippage (void);
void fterm_dupe2bk (void);
void fterm_markdirty (void); // mark as dirty
int fterm_strdlen (const char *s); // length of string for display
int fterm_prepare_str(int len);
//////////////////////////////////////////////////////////////////////////
// Flat Terminal Implementation
//////////////////////////////////////////////////////////////////////////
// initialization
void
initscr(void)
{
memset(&ft, sizeof(ft), 0);
resizeterm(FTSZ_DEFAULT_ROW, FTSZ_DEFAULT_COL);
ft.attr = ft.rattr = FTATTR_DEFAULT;
// clear both pages
ft.mi = 0; clrscr();
ft.mi = 1; clrscr();
ft.mi = 0;
fterm_rawclear();
move(0, 0);
}
int
endwin(void)
{
int r, mi = 0;
// fterm_rawclear();
for (mi = 0; mi < 2; mi++)
{
for (r = 0; r < ft.mrows; r++)
{
free(ft.cmap[mi][r]);
free(ft.amap[mi][r]);
}
}
free(ft.dmap);
free(ft.dcmap);
memset(&ft, sizeof(ft), 0);
return 0;
}
int
resizeterm(int rows, int cols)
{
int dirty = 0, mi = 0, i = 0;
rows = ranged(rows, FTSZ_MIN_ROW, FTSZ_MAX_ROW);
cols = ranged(cols, FTSZ_MIN_COL, FTSZ_MAX_COL);
// adjust memory only for increasing buffer
if (rows > ft.mrows || cols > ft.mcols)
{
for (mi = 0; mi < 2; mi++)
{
// allocate rows
if (rows > ft.mrows)
{
ft.cmap[mi] = (ftchar**)realloc(ft.cmap[mi],
sizeof(ftchar*) * rows);
ft.amap[mi] = (ftattr**)realloc(ft.amap[mi],
sizeof(ftattr*) * rows);
// allocate new columns
for (i = ft.mrows; i < rows; i++)
{
ft.cmap[mi][i] = (ftchar*)malloc((cols+1) * sizeof(ftchar));
ft.amap[mi][i] = (ftattr*)malloc((cols+1) * sizeof(ftattr));
// zero at end to prevent over-run
ft.cmap[mi][i][cols] = 0;
ft.amap[mi][i][cols] = 0;
}
}
// resize cols
if (cols > ft.mcols)
{
for (i = 0; i < ft.mrows; i++)
{
ft.cmap[mi][i] = (ftchar*)realloc(ft.cmap[mi][i],
(cols+1) * sizeof(ftchar));
ft.amap[mi][i] = (ftattr*)realloc(ft.amap[mi][i],
(cols+1) * sizeof(ftattr));
// zero at end to prevent over-run
ft.cmap[mi][i][cols] = 0;
ft.amap[mi][i][cols] = 0;
}
}
}
// adjusts dirty and display map.
// no need to initialize anyway.
if (cols > ft.mcols)
{
ft.dmap = (ftchar*) realloc(ft.dmap,
(cols+1) * sizeof(ftchar));
ft.dcmap = (ftchar*) realloc(ft.dcmap,
(cols+1) * sizeof(ftchar));
}
// do mrows/mcols assignment here, because we had 2 maps running loop above.
if (cols > ft.mcols) ft.mcols = cols;
if (rows > ft.mrows) ft.mrows = rows;
dirty = 1;
}
// clear new exposed buffer after resized
// because we will redawwin(), so need to change front buffer only.
for (i = ft.rows; i < rows; i++)
{
memset(FTCMAP[i], FTCHAR_ERASE,
(cols) * sizeof(ftchar));
memset(FTAMAP[i], FTATTR_ERASE,
(cols) * sizeof(ftattr));
}
if (cols > ft.cols)
{
for (i = 0; i < ft.rows; i++)
{
memset(FTCMAP[i]+ft.cols, FTCHAR_ERASE,
(cols-ft.cols) * sizeof(ftchar));
memset(FTAMAP[i]+ft.cols, FTATTR_ERASE,
(cols-ft.cols) * sizeof(ftattr));
}
}
if (ft.rows != rows || ft.cols != cols)
{
ft.rows = rows;
ft.cols = cols;
redrawwin();
}
return dirty;
}
// attributes
ftattr
attrget(void)
{
return ft.attr;
}
void
attrset(ftattr attr)
{
ft.attr = attr;
}
void
attrsetfg(ftattr attr)
{
ft.attr &= (~FTATTR_FGMASK);
ft.attr |= ((attr & FTATTR_FGMASK) << FTATTR_FGSHIFT);
}
void
attrsetbg(ftattr attr)
{
ft.attr &= (~FTATTR_BGMASK);
ft.attr |= ((attr & FTATTR_FGMASK) << FTATTR_BGSHIFT);
}
// clear
void
clrscr(void)
{
int r;
for (r = 0; r < ft.rows; r++)
memset(FTCMAP[r], FTCHAR_ERASE, ft.cols * sizeof(ftchar));
for (r = 0; r < ft.rows; r++)
memset(FTAMAP[r], FTATTR_ERASE, ft.cols * sizeof(ftattr));
fterm_markdirty();
}
void
clear(void)
{
clrscr();
move(0,0);
}
void
clrtoeol(void)
{
memset(FTPC, FTCHAR_ERASE, ft.cols - ft.x);
memset(FTPA, FTATTR_ERASE, ft.cols - ft.x);
fterm_markdirty();
}
void
clrtobeg(void)
{
memset(FTCROW, FTCHAR_ERASE, ft.x+1);
memset(FTAROW, FTATTR_ERASE, ft.x+1);
fterm_markdirty();
}
void
clrcurrline(void)
{
memset(FTCROW, FTCHAR_ERASE, ft.cols);
memset(FTAROW, FTATTR_ERASE, ft.cols);
fterm_markdirty();
}
void
clrtoln(int line)
{
if (line <= ft.y)
return;
clrregion(ft.y, line-1);
}
void
clrregion(int r1, int r2)
{
// bi-direction
if (r1 > r2)
{
int r = r1;
r1 = r2; r2 = r;
}
// check r1, r2 range
r1 = ranged(r1, 0, ft.rows-1);
r2 = ranged(r2, 0, ft.rows-1);
for (; r1 <= r2; r1++)
{
memset(FTCMAP[r1], FTCHAR_ERASE, ft.cols);
memset(FTAMAP[r1], FTATTR_ERASE, ft.cols);
}
fterm_markdirty();
}
void
clrtobot(void)
{
clrtoeol();
clrregion(ft.y+1, ft.rows-1);
}
void
clrtohome(void)
{
clrtobeg();
clrregion(ft.y-1, 0);
}
// dirty and flushing
void
redrawwin(void)
{
// flip page
fterm_flippage();
clrscr();
// clear raw terminal
fterm_rawclear();
// flip page again
fterm_flippage();
// mark for refresh.
fterm_markdirty();
}
void
refresh(void)
{
int y, x;
char touched = 0;
// prevent passive update
if(fterm_inbuf())
return;
if (!ft.dirty)
{
fterm_rawcursor();
return;
}
// if scroll, do it first
if (ft.scroll)
fterm_rawscroll(ft.scroll);
// calculate and optimize dirty
for (y = 0; y < ft.rows; y++)
{
int len = ft.cols, ds = 0, derase = 0;
char dbcs = 0, odbcs = 0; // 0: none, 1: lead, 2: tail
// reset dirty and display map
memset(FTD, 0, ft.cols * sizeof(ftchar));
memcpy(FTDC,FTCMAP[y], ft.cols * sizeof(ftchar));
// first run: character diff
for (x = 0; x < len; x++)
{
// build base dirty information
if (FTCMAP[y][x] != FTOCMAP[y][x])
FTD[x] |= FTDIRTY_CHAR, ds++;
if (FTAMAP[y][x] != FTOAMAP[y][x])
FTD[x] |= FTDIRTY_ATTR, ds++;
// determine DBCS status
if (dbcs == 1)
{
#ifdef FTCONF_PREVENT_INVALID_DBCS
// (1) check if lead is really valid.
// (2) check if tail is valid.
// - if not valid, only SBCS safe characters can be print.
if ((!FTDBCS_ISBADLEAD(FTCMAP[y][x-1])) &&
FTDBCS_ISTAIL(FTCMAP[y][x]) )
{
FTD[x-1] &= ~FTDIRTY_INVALID_DBCS;
FTDC[x-1] = FTCMAP[y][x-1];
}
else if (!FTDBCS_ISSBCSPRINT(FTCMAP[y][x]))
{
FTD[x] |= FTDIRTY_INVALID_DBCS;
FTDC[x] = FTCHAR_INVALID_DBCS;
}
#endif // FTCONF_PREVENT_INVALID_DBCS
dbcs = 2;
// TAIL: dirty prev and me if any is dirty.
if (FTD[x] || FTD[x-1])
{
FTD[x] |= FTDIRTY_DBCS;
FTD[x-1]|= FTDIRTY_CHAR;
}
}
else if (FTDBCS_ISLEAD(FTCMAP[y][x]))
{
// LEAD: clear dirty when tail was found.
dbcs = 1;
FTD[x] |= FTDIRTY_INVALID_DBCS;
FTDC[x] = FTCHAR_INVALID_DBCS;
}
else
{
// NON-DBCS
dbcs = 0;
}
if (odbcs == 1)
{
// TAIL: dirty prev and me if any is dirty.
odbcs = 2;
if (FTD[x] || FTD[x-1])
{
FTD[x] |= FTDIRTY_CHAR;
FTD[x-1]|= FTDIRTY_CHAR;
}
}
else if (FTDBCS_ISLEAD(FTOCMAP[y][x]))
{
// LEAD: dirty next?
odbcs = 1;
}
else
{
odbcs = 0;
}
}
#ifndef DBG_SHOW_DIRTY
if (!ds)
continue;
#endif // DBG_SHOW_DIRTY
// Optimization: calculate ERASE section
// TODO ERASE takes 3 bytes (ESC [ K), so enable only if derase >= 3?
// TODO ERASE then print can avoid lots of space, optimize in future.
for (x = ft.cols - 1; x >= 0; x--)
if (FTCMAP[y][x] != FTCHAR_ERASE ||
FTAMAP[y][x] != FTATTR_ERASE)
break;
else if (FTD[x])
derase++;
len = x+1;
for (x = 0; x < len; x++)
{
#ifndef DBG_SHOW_DIRTY
if (!FTD[x])
continue;
#endif // !DBG_SHOW_DIRTY
// Optimization: re-print or move?
#ifndef DBG_DISABLE_REPRINT
while (ft.ry == y && x > ft.rx && abs(x-ft.rx) < FTMV_COST)
{
int i;
// Special case: we may be in position of DBCS tail...
// Inside a refresh() loop, this will never happen.
// However it may occur for the first print entering refresh.
// So enable only space if this is the first run (!touched).
// if we don't need to change attributes,
// just print remaining characters
for (i = ft.rx; i < x; i++)
{
// if same attribute, simply accept.
if (FTAROW[i] == ft.rattr && touched)
continue;
// XXX spaces may accept (BG=OBG),
// but that will also change cached attribute.
if (!FTCHAR_ISBLANK(FTCROW[i]))
break;
if (FTATTR_GETBG(FTAROW[i]) != FTATTR_GETBG(FTOAMAP[y][i]))
break;
}
if (i != x)
break;
// safe to print all!
// printf("[re-print %d chars]", i-ft.rx);
#ifdef DBG_SHOW_REPRINT
// reverse to hint this is a re-print
fterm_rawattr(FTATTR_MAKE(0, 7) | FTATTR_BOLD);
#endif // DBG_SHOW_REPRINT
for (i = ft.rx; i < x; i++)
{
fterm_rawc(FTDC[i]);
FTAROW[i] = FTOAMAP[y][i]; // spaces will change attribute...
ft.rx++;
}
break;
}
#endif // !DBG_DISABLE_REPRINT
if (y != ft.ry || x != ft.rx)
fterm_rawmove_opt(y, x);
#ifdef DBCSAWARE
if ((FTD[x] & FTDIRTY_DBCS) && (FT_DBCS_NOINTRESC))
{
// prevent changing attributes inside DBCS
}
else
#endif // DBCSAWARE
#ifdef DBG_SHOW_DIRTY
fterm_rawattr(FTD[x] ?
(FTAMAP[y][x] | FTATTR_BOLD) : (FTAMAP[y][x] & ~FTATTR_BOLD));
#else // !DBG_SHOW_DIRTY
fterm_rawattr(FTAMAP[y][x]);
#endif // !DBG_SHOW_DIRTY
fterm_rawc(FTDC[x]);
ft.rx++;
touched = 1;
}
if (derase)
{
fterm_rawmove_opt(y, len);
fterm_rawclreol();
}
}
fterm_dupe2bk();
fterm_rawcursor();
ft.dirty = 0;
}
// cursor management
void
getyx(int *y, int *x)
{
if (y)
*y = ft.y;
if (x)
*x = ft.x;
}
void
move(int y, int x)
{
y = ranged(y, 0, ft.rows-1);
x = ranged(x, 0, ft.cols-1);
ft.y = y;
ft.x = x;
}
// scrolling
void
scrl(int rows)
{
if (!rows)
return;
if (rows > 0)
{
for (; rows > 0; rows--)
scroll();
} else {
for (; rows < 0; rows++)
rscroll();
}
}
void
scroll()
{
// scroll up
int y;
ftchar *c0 = FTCMAP[0], *oc0 = FTOCMAP[0];
ftattr *a0 = FTAMAP[0], *oa0 = FTOAMAP[0];
// prevent mixing buffered scroll up+down
if (ft.scroll < 0)
fterm_rawscroll(ft.scroll);
// smart scroll: move pointers
for (y = 0; y < ft.rows-1; y++)
{
FTCMAP[y] = FTCMAP[y+1];
FTAMAP[y] = FTAMAP[y+1];
FTOCMAP[y]= FTOCMAP[y+1];
FTOAMAP[y]= FTOAMAP[y+1];
}
FTCMAP[y] = c0;
FTAMAP[y] = a0;
FTOCMAP[y]= oc0;
FTOAMAP[y]= oa0;
// XXX also clear backup buffer
// must carefully consider if up then down scrolling.
fterm_flippage();
clrregion(ft.rows-1, ft.rows-1);
fterm_flippage();
clrregion(ft.rows-1, ft.rows-1);
ft.scroll ++;
// fterm_markdirty(); // should be already dirty
}
void
rscroll()
{
// scroll down
int y;
ftchar *c0 = FTCMAP[ft.rows -1], *oc0 = FTOCMAP[ft.rows -1];
ftattr *a0 = FTAMAP[ft.rows -1], *oa0 = FTOAMAP[ft.rows -1];
// prevent mixing buffered scroll up+down
if (ft.scroll > 0)
fterm_rawscroll(ft.scroll);
// smart scroll: move pointers
for (y = ft.rows -1; y > 0; y--)
{
FTCMAP[y] = FTCMAP[y-1];
FTAMAP[y] = FTAMAP[y-1];
FTOCMAP[y]= FTOCMAP[y-1];
FTOAMAP[y]= FTOAMAP[y-1];
}
FTCMAP[y] = c0;
FTAMAP[y] = a0;
FTOCMAP[y]= oc0;
FTOAMAP[y]= oa0;
// XXX also clear backup buffer
// must carefully consider if up then down scrolling.
fterm_flippage();
clrregion(0, 0);
fterm_flippage();
clrregion(0, 0);
ft.scroll --;
// fterm_markdirty(); // should be already dirty
}
// output
void
outs(const char *s)
{
if (!s)
return;
while (*s)
outc(*s++);
}
void
outstr(const char *str)
{
if (!str)
{
fterm_prepare_str(0);
return;
}
// calculate real length of str (stripping escapes)
// TODO only print by the returned size
fterm_prepare_str(fterm_strdlen(str));
outs(str);
// maybe the source string itself is broken...
// basically this check should be done by clients, not term library.
#if 0
{
int isdbcs = 0;
while (*str)
{
if (isdbcs == 1) isdbcs = 2;
else if (FTDBCS_ISLEAD(*str)) isdbcs = 1;
else isdbcs = 0;
str++;
}
if (isdbcs == 1) // incomplete string!
outs("\b?");
}
#endif
}
void
outc(unsigned char c)
{
fterm_markdirty();
if (ft.szcmd)
{
// collecting commands
ft.cmd[ft.szcmd++] = c;
if ((ft.szcmd == 2 && c == '[') ||
(ANSI_IS_PARAM(c) && ft.szcmd < FTCMD_MAXLEN))
return;
// process as command
fterm_exec();
ft.szcmd = 0;
}
else if (c == ESC_CHR)
{
// start of escaped commands
ft.cmd[ft.szcmd++] = c;
}
else if (c == '\t')
{
// tab: move by 8
int x = ft.x;
if (x % 8 == 0)
x += 8;
else
x += (8-x);
ft.x = ranged(x, 0, ft.rows-1);
}
else if (c == '\b')
{
ft.x = ranged(ft.x-1, 0, ft.rows-1);
}
else if (c == '\r' || c == '\n')
{
// new line: cursor movement, and do not print anything
// XXX old screen.c also calls clrtoeol() for newlins.
clrtoeol();
ft.x = 0;
ft.y ++;
while (ft.y >= ft.rows)
{
// XXX scroll at next dirty?
// screen.c ignored such scroll.
// scroll();
ft.y --;
}
}
else if (iscntrl((unsigned char)c))
{
// unknown control characters: ignore
}
else // normal characters
{
// XXX allow x == ft.cols?
if (ft.x >= ft.cols)
{
ft.x = 0;
ft.y ++;
while (ft.y >= ft.rows)
{
// XXX scroll at next dirty?
// screen.c ignored such scroll.
// scroll();
ft.y --;
}
}
// normal characters
FTC = c;
#ifdef FTATTR_TRANSPARENT
if (ft.attr != FTATTR_TRANSPARENT)
#endif // FTATTR_TRANSPARENT
FTA = ft.attr;
ft.x ++;
}
}
// readback
int
instr (char *str)
{
int x = ft.cols -1;
*str = 0;
if (ft.y < 0 || ft.y >= ft.rows || ft.x < 0 || ft.x >= ft.cols)
return 0;
// determine stopping location
while (x >= ft.x && FTCROW[x] == FTCHAR_ERASE)
x--;
if (x < ft.x) return 0;
x = x - ft.x + 1;
memcpy(str, FTCROW+ft.x, x);
str[x] = 0;
return x;
}
int
innstr (char *str, int n)
{
int on = n;
int x = ranged(ft.x + n-1, 0, ft.cols-1);
*str = 0;
n = x - ft.x+1;
if (on < 1 || ft.y < 0 || ft.y >= ft.rows || ft.x < 0 || ft.x >= ft.cols)
return 0;
// determine stopping location
while (x >= ft.x && FTCROW[x] == FTCHAR_ERASE)
x--;
if (x < ft.x) return 0;
n = x - ft.x + 1;
if (n >= on) n = on-1;
memcpy(str, FTCROW+ft.x, n);
str[n] = 0;
return n;
}
int
inansistr (char *str, int n)
{
int x = ft.cols -1, i = 0, szTrail = 0;
char *ostr = str;
char cmd[FTATTR_MINCMD*2] = "";
ftattr a = FTATTR_DEFAULT;
*str = 0;
if (ft.y < 0 || ft.y >= ft.rows || ft.x < 0 || ft.x >= ft.cols)
return 0;
if (n < 1)
return 0;
n--; // preserve last zero
// determine stopping location
while (x >= ft.x && FTCROW[x] == FTCHAR_ERASE && FTAROW[x] == FTATTR_ERASE)
x--;
// retrieve [rt.x, x]
if (x < ft.x) return 0;
// preserve some bytes if last attribute is not FTATTR_DEFAULT
for (i = ft.x; n > szTrail && i <= x; i++)
{
*str = 0;
if (a != FTAROW[i])
{
fterm_chattr(cmd, a, FTAROW[i]);
a = FTAROW[i];
if (a != FTATTR_DEFAULT)
szTrail = 3; // ESC [ m
else
szTrail = 0;
if (strlen(cmd) >= n-szTrail)
break;
strcpy(str, cmd);
n -= strlen(cmd);
str += strlen(cmd);
}
// n should > szTrail
*str ++ = FTCROW[i];
n--;
}
if (szTrail && n >= szTrail)
{
*str++ = ESC_CHR; *str++ = '['; *str++ = 'm';
}
*str = 0;
return (str - ostr);
}
// internal core of piaip's flat-term
void
fterm_flippage (void)
{
// we have only 2 pages now.
ft.mi = 1 - ft.mi;
}
void
fterm_markdirty (void)
{
ft.dirty = 1;
}
void fterm_dupe2bk(void)
{
int r = 0;
for (r = 0; r < ft.rows; r++)
{
memcpy(FTOCMAP[r], FTCMAP[r], ft.cols * sizeof(ftchar));
memcpy(FTOAMAP[r], FTAMAP[r], ft.cols * sizeof(ftattr));
}
}
int
fterm_prepare_str(int len)
{
// clear and make (cursor, +len) as DBCS-ready.
int x = ranged(ft.x, 0, ft.cols-1);
int y = ranged(ft.y, 0, ft.rows-1);
int dbcs = 0, sdbcs = 0;
// TODO what if x+len is outside range?
// check if (x,y) is in valid range
if (x != ft.x || y != ft.y)
return -1;
len = ranged(x+len, x, ft.cols);
for (x = 0; x < len; x++)
{
// determine DBCS status
if (dbcs == 1)
dbcs = 2; // TAIL
else if (FTDBCS_ISLEAD(FTCROW[x]))
dbcs = 1; // LEAD
else
dbcs = 0;
if (x == ft.x) sdbcs = dbcs;
}
x = ft.x;
// fix start and end
if(sdbcs == 2) // TAIL, remove word
x--;
if (dbcs == 1) // LEAD, remove word
len ++;
len = ranged(len, 0, ft.rows);
len -= x;
memset(FTCROW + x, FTCHAR_ERASE, len);
return len;
}
void
fterm_exec(void)
{
ftchar cmd = ft.cmd[ft.szcmd-1];
char *p = (char*)ft.cmd + 2; // ESC [
int n = -1, x, y;
ft.cmd[ft.szcmd] = 0;
if (isdigit(*p))
{
n = atoi(p);
while (*p && isdigit(*p))
p++;
if (*p == ';')
p++;
// p points to next param now
}
switch(cmd)
{
// Cursor Movement
case 'A': // CUU: CSI n A
case 'B': // CUD: CSI n B
case 'C': // CUF: CSI n C
case 'D': // CUB: CSI n D
// Moves the cursor n (default 1) cells in the given direction.
// If the cursor is already at the edge of the screen, this has no effect.
if (n < 1)
n = 1;
getyx(&y, &x);
if (cmd == 'A') { y -= n; }
else if (cmd == 'B') { y += n; }
else if (cmd == 'C') { x += n; }
else if (cmd == 'D') { x -= n; }
move(y, x);
break;
case 'E': // CNL: CSI n E
case 'F': // CPL: CSI n F
// Moves cursor to beginning of the line
// n (default 1) lines up/down (next/previous line).
if (n < 1)
n = 1;
getyx(&y, &x);
if (cmd == 'E') { y -= n; }
else if (cmd == 'F') { y += n; }
move(y, 0);
break;
case 'G': // CHA: CSI n G
// Moves the cursor to column n.
getyx(&y, &x);
move(y, n-1);
break;
case 'H': // CUP: CSI n ; m H
case 'f': // HVP: CSI n ; m f
// Moves the cursor to row n, column m.
// The values are 1-based, and default to 1 (top left corner) if omitted.
// A sequence such as CSI ;5H is a synonym for CSI 1;5H as well as
// CSI 17;H is the same as CSI 17H and CSI 17;1H
y = n;
if (y >= 0 && isdigit(*p))
x = atoi((char*)p);
if (y < 0) y = 1;
if (x < 0) x = 1;
move(y-1, x-1);
break;
// Clear
case 'J': // ED: CSI n J
// Clears part of the screen.
// If n is zero (or missing), clear from cursor to end of screen.
// If n is one, clear from cursor to beginning of the screen.
// If n is two, clear entire screen
if (n == 0 || n < 0)
clrtobot();
else if (n == 1)
clrtohome();
else if (n == 2)
{
clrregion(0, ft.rows-1);
}
break;
case 'K': // EL: CSI n K
// Erases part of the line.
// If n is zero (or missing), clear from cursor to the end of the line.
// If n is one, clear from cursor to beginning of the line.
// If n is two, clear entire line. Cursor position does not change.
if (n == 0 || n < 0)
clrtoeol();
else if (n == 1)
clrtobeg();
else if (n == 2)
clrcurrline();
break;
case 's': // SCP: CSI s
// Saves the cursor position.
getyx(&ft.sy, &ft.sx);
break;
case 'u': // RCP: CSI u
// Restores the cursor position.
move(ft.sy, ft.sx);
break;
case 'S': // SU: CSI n S
// Scroll whole page up by n (default 1) lines.
// New lines are added at the bottom.
if (n < 1)
n = 1;
scrl(n);
break;
case 'T': // SD: CSI n T
// Scroll whole page down by n (default 1) lines.
// New lines are added at the top.
if (n < 1)
n = 1;
scrl(-n);
break;
case 'm': // SGR: CSI n [;k] m
// Sets SGR (Select Graphic Rendition) parameters.
// After CSI can be zero or more parameters separated with ;.
// With no parameters, CSI m is treated as CSI 0 m (reset / normal),
// which is typical of most of the ANSI codes.
// ---------------------------------------------------------
// SGR implementation:
// SGR 0 (reset/normal) is supported.
// SGR 1 (intensity: bold) is supported.
// SGR 2 (intensity: faint) is not supported.
// SGR 3 (italic: on) is not supported. (converted to inverse?)
// SGR 4 (underline: single) is not supported.
// SGR 5 (blink: slow) is supported.
// SGR 6 (blink: rapid) is converted to (blink: slow)
// SGR 7 (image: negative) is partially supported (not a really attribute).
// SGR 8 (conceal) is not supported.
// SGR 21(underline: double) is not supported.
// SGR 22(intensity: normal) is supported.
// SGR 24(underline: none) is not supported.
// SGR 25(blink: off) is supported.
// SGR 27(image: positive) is not supported.
// SGR 28(reveal) is not supported.
// SGR 30-37 (FG) is supported.
// SGR 39 (FG-reset) is supported.
// SGR 40-47 (BG) is supported.
// SGR 49 (BG-reset) is supported.
if (n == -1) // first param
n = 0;
while (n > -1)
{
if (n >= 30 && n <= 37)
{
// set foreground
attrsetfg(n - 30);
}
else if (n >= 40 && n <= 47)
{
// set background
attrsetbg(n - 40);
}
else switch(n)
{
case 0:
attrset(FTATTR_DEFAULT);
break;
case 1:
attrset(attrget() | FTATTR_BOLD);
break;
case 22:
attrset(attrget() & ~FTATTR_BOLD);
break;
case 5:
case 6:
attrset(attrget() | FTATTR_BLINK);
break;
case 25:
attrset(attrget() & ~FTATTR_BLINK);
break;
case 3:
case 7:
{
ftattr a = attrget();
attrsetfg(FTATTR_GETBG(a));
attrsetbg(FTATTR_GETFG(a));
}
break;
case 39:
attrsetfg(FTATTR_DEFAULT_FG);
break;
case 49:
attrsetbg(FTATTR_DEFAULT_BG);
break;
}
// parse next command
n = -1;
if (*p == ';')
{
n = 0;
p++;
}
else if (isdigit(*p))
{
n = atoi(p);
while (isdigit(*p)) p++;
if (*p == ';')
p++;
}
}
break;
default: // unknown command.
break;
}
}
int
fterm_chattr(char *s, ftattr oattr, ftattr nattr)
{
ftattr
fg, bg, bold, blink,
ofg, obg, obold, oblink;
char lead = 1;
if (oattr == nattr)
return 0;
*s++ = ESC_CHR;
*s++ = '[';
fg = FTATTR_GETFG(nattr);
bg = FTATTR_GETBG(nattr);
bold = (nattr & FTATTR_BOLD) ? 1 : 0;
blink = (nattr & FTATTR_BLINK)? 1 : 0;
ofg = FTATTR_GETFG(oattr);
obg = FTATTR_GETBG(oattr);
obold = (oattr & FTATTR_BOLD) ? 1 : 0;
oblink = (oattr & FTATTR_BLINK)? 1 : 0;
if ((oblink != blink && !blink) ||
(obold != bold && !bold) )
{
if (lead) lead = 0; else *s++ = ';';
*s++ = '0';
ofg = FTATTR_DEFAULT_FG;
obg = FTATTR_DEFAULT_BG;
obold = 0; oblink = 0;
}
if (bold && !obold)
{
if (lead) lead = 0; else *s++ = ';';
*s++ = '1';
}
if (blink && !oblink)
{
if (lead) lead = 0; else *s++ = ';';
*s++ = '5'; // XXX 5(slow) or 6(fast)?
}
if (ofg != fg)
{
if (lead) lead = 0; else *s++ = ';';
*s++ = '3';
*s++ = '0' + fg;
}
if (obg != bg)
{
if (lead) lead = 0; else *s++ = ';';
*s++ = '4';
*s++ = '0' + bg;
}
*s++ = 'm';
*s++ = 0;
return 1;
}
int
fterm_strdlen(const char *s)
{
char ansi = 0;
int sz = 0;
// the logic should match outc().
while (s && *s)
{
if (!ansi) // ansi == 0
{
switch(*s)
{
case ESC_CHR:
ansi++;
break;
case '\r':
case '\n':
break;
case '\b':
if (sz) sz--;
break;
case '\t':
// XXX how to deal with this?
sz ++;
break;
default:
if (!iscntrl((unsigned char)*s))
sz++;
break;
}
}
else if (ansi == 1)
{
if (*s == '[')
ansi++;
else
ansi = 0;
}
else if (!ANSI_IS_PARAM(*s)) // ansi == 2
{
// TODO outc() take max to FTCMD_MAXLEN now...
ansi = 0;
}
s++;
}
return sz;
}
void
fterm_rawattr(ftattr rattr)
{
static char cmd[FTATTR_MINCMD*2];
if (!fterm_chattr(cmd, ft.rattr, rattr))
return;
fterm_raws(cmd);
ft.rattr = rattr;
}
void
fterm_rawnum(int arg)
{
if (arg < 0 || arg > 99)
{
// complex. use printf.
char sarg[16]; // max int
sprintf(sarg, "%d", arg);
fterm_raws(sarg);
} else if (arg < 10) {
// 0 .. 10
fterm_rawc('0' + arg);
} else {
fterm_rawc('0' + arg/10);
fterm_rawc('0' + arg%10);
}
}
void
fterm_rawcmd(int arg, int defval, char c)
{
fterm_rawc(ESC_CHR);
fterm_rawc('[');
if (arg != defval)
fterm_rawnum(arg);
fterm_rawc(c);
}
void
fterm_rawcmd2(int arg1, int arg2, int defval, char c)
{
fterm_rawc(ESC_CHR);
fterm_rawc('[');
// XXX Win/DOS telnet does now accept omitting first value
// ESC[nX and ESC[n;X works, but ESC[;mX does not work.
if (arg1 != defval || arg2 != defval)
{
fterm_rawnum(arg1);
if (arg2 != defval)
{
fterm_rawc(';');
fterm_rawnum(arg2);
}
}
fterm_rawc(c);
}
void
fterm_rawclear(void)
{
fterm_rawhome();
// ED: CSI n J, 0 = cursor to bottom, 2 = whole
fterm_raws(ESC_STR "[2J");
}
void
fterm_rawclreol(void)
{
#ifdef FTCONF_CLEAR_SETATTR
ftattr oattr = ft.rattr;
// XXX If we skip with "backround only" here, future updating
// may get wrong attributes. Or not? (consider DBCS...)
// if (FTATTR_GETBG(oattr) != FTATTR_GETBG(FTATTR_ERASE))
fterm_rawattr(FTATTR_ERASE);
#endif
// EL: CSI n K, n = 0
fterm_raws(ESC_STR "[K");
#ifdef FTCONF_CLEAR_SETATTR
fterm_rawattr(oattr);
#endif
}
void
fterm_rawhome(void)
{
// CUP: CSI n ; m H
fterm_raws(ESC_STR "[H");
ft.rx = ft.ry = 0;
}
void
fterm_rawmove_rel(int dy, int dx)
{
#ifndef FTCONF_USE_ANSI_RELMOVE
// Old BBS system does not output relative moves (ESC[ABCD) .
// Poor terminals (ex, pcman-1.0.5-FF20.xpi)
// do not support relmoves
fterm_rawmove(ft.ry + dy, ft.rx + dx);
#else
if (!dx)
{
int y = ranged(dy + ft.ry, 0, ft.rows-1);
dy = y - ft.ry;
if (!dy)
return;
fterm_rawcmd(abs(dy), 1, dy < 0 ? 'A' : 'B');
ft.ry = y;
}
else if (!dy)
{
int x = ranged(dx + ft.rx, 0, ft.cols-1);
dx = x - ft.rx;
if (!dx)
return;
fterm_rawcmd(abs(dx), 1, dx < 0 ? 'D' : 'C');
ft.rx = x;
}
else
{
// (dy, dx) are given - use fterm_move.
fterm_rawmove(ft.ry + dy, ft.rx + dx);
}
#endif
}
void
fterm_rawmove(int y, int x)
{
y = ranged(y, 0, ft.rows-1);
x = ranged(x, 0, ft.cols-1);
if (y == ft.ry && x == ft.rx)
return;
// CUP: CSI n ; m H
fterm_rawcmd2(y+1, x+1, 1, 'H');
ft.ry = y;
ft.rx = x;
}
void
fterm_rawmove_opt(int y, int x)
{
// optimized move
int ady = abs(y-ft.ry), adx=abs(x-ft.rx);
if (!adx && !ady)
return;
#ifdef DBG_DISABLE_OPTMOVE
return fterm_rawmove(y, x);
#endif
// known hacks: \r = (x=0), \b=(x--), \n = (y++)
//
// Warning: any optimization here should not change displayed content,
// because we don't have information about content variation information
// (eg, invalid DBCS bytes will become special marks) here.
// Any hacks which will try to display data from FTCMAP should be done
// inside dirty-map calculation, for ex, using spaces to move right,
// or re-print content.
#ifndef DBG_TEXT_FD
// x=0: the cheapest output. However not work for text mode fd output.
if (adx && x == 0)
{
fterm_rawc('\r');
ft.rx = x = adx = 0;
}
#endif // !DBG_TEXT_FD
// x--: compare with FTMV_COST: ESC[m;nH costs 5-8 bytes
if (x < ft.rx && y >= ft.ry && (adx+ady) < FTMV_COST)
{
while (adx > 0)
fterm_rawc('\b'), adx--;
ft.rx = x;
}
// finishing movement
if (y > ft.ry && ady < FTMV_COST && adx == 0)
{
while (ft.ry++ < y)
fterm_rawc('\n');
ft.ry = y;
}
else if (ady && adx)
{
fterm_rawmove(y, x);
}
else if (ady)
{
fterm_rawmove_rel(y-ft.ry, 0);
}
else if (adx)
{
fterm_rawmove_rel(0, x-ft.rx);
}
}
void
fterm_rawcursor(void)
{
fterm_rawattr(ft.attr);
fterm_rawmove_opt(ft.y, ft.x);
fterm_rawflush();
}
void
fterm_rawscroll (int dy)
{
#ifdef FTCONF_USE_ANSI_SCROLL
// SU: CSI n S (up)
// SD: CSI n T (down)
char cmd = (dy > 0) ? 'S' : 'T';
int ady = abs(dy);
if (ady == 0)
return;
if (ady >= ft.rows) ady = ft.rows;
fterm_rawcmd(ady, 1, cmd);
ft.scroll -= dy;
#else
// VT100 flavor:
// * ESC D: cursor down - at bottom of region, scroll up
// * ESC M: cursor up - at top of region, scroll down
// Elder BBS systems do \n at (rows-1) as scroll()
// and ESC-M at(0) as rscoll().
// SCP: CSI s / RCP: CSI u
// Warning: cannot use SCP/RCP here, because on Win/DOS telnet
// the position will change after scrolling (ex, (25,0)->(24,0).
//
// Since scroll does not happen very often, let's relax and not
// optimize these commands here...
int ady = abs(dy);
if (ady == 0)
return;
if (ady >= ft.rows) ady = ft.rows;
// we are not going to preserve (rx,ry)
// so don't use fterm_move*.
if (dy > 0)
fterm_rawcmd2(ft.rows, 1, 1, 'H');
else
fterm_rawcmd2(1, 1, 1, 'H');
for (; ady > 0; ady--)
{
if (dy >0)
{
// Win/DOS telnet may have extra text in new line,
// because of the IME line.
fterm_raws("\n" ESC_STR "[K");
} else {
fterm_raws(ESC_STR "M"); // ESC_STR "[K");
}
}
// Do not use optimized move here, because in poor terminals
// the coordinates are already out of sync.
fterm_rawcmd2(ft.ry+1, ft.rx+1, 1, 'H');
ft.scroll -= dy;
#endif
}
void
fterm_raws(const char *s)
{
while (*s)
fterm_rawc(*s++);
}
void
fterm_rawnc(int c, int n)
{
while (n-- > 0)
fterm_rawc(c);
}
//////////////////////////////////////////////////////////////////////////
// grayout advanced control
//////////////////////////////////////////////////////////////////////////
void
grayout(int y, int end, int level)
{
char grattr = FTATTR_DEFAULT;
y = ranged(y, 0, ft.rows-1);
end = ranged(end, 0, ft.rows-1);
if (level == GRAYOUT_COLORBOLD)
{
int x = 0;
for (; y < end; y++)
{
for (x = 0; x < ft.cols-1; x++)
FTAMAP[y][x] |= FTATTR_BOLD;
}
return;
}
if (level == GRAYOUT_COLORNORM)
{
int x = 0;
for (; y < end; y++)
{
for (x = 0; x < ft.cols-1; x++)
FTAMAP[y][x] &= ~(FTATTR_BLINK | FTATTR_BOLD);
}
return;
}
if (level == GRAYOUT_BOLD)
{
grattr |= FTATTR_BOLD;
}
else if (level == GRAYOUT_DARK)
{
grattr = FTATTR_MAKE(0,0);
grattr |= FTATTR_BOLD;
}
else if (level == GRAYOUT_NORM)
{
// normal text
}
else
{
// not supported yet
}
for (; y <= end; y++)
{
memset(FTAMAP[y], grattr, ft.cols);
}
}
//////////////////////////////////////////////////////////////////////////
// deprecated api
//////////////////////////////////////////////////////////////////////////
void
standout(void)
{
outs(ANSI_COLOR(7));
}
void
standend(void)
{
outs(ANSI_RESET);
}
#ifndef _PFTERM_TEST_MAIN
void
scr_dump(screen_backup_t *psb)
{
int y = 0;
void *p = NULL;
psb->row= ft.rows;
psb->col= ft.cols;
psb->y = ft.y;
psb->x = ft.x;
p = psb->raw_memory =
malloc (ft.rows * ft.cols * (sizeof(ftchar) + sizeof(ftattr)));
for (y = 0; y < ft.rows; y++)
{
memcpy(p, FTCMAP[y], ft.cols * sizeof(ftchar));
p += ft.cols * sizeof(ftchar);
memcpy(p, FTAMAP[y], ft.cols * sizeof(ftattr));
p += ft.cols * sizeof(ftattr);
}
}
void
scr_restore(const screen_backup_t *psb)
{
int y = 0;
void *p = NULL;
int c = ft.cols, r = ft.rows;
if (!psb || !psb->raw_memory)
return;
p = psb->raw_memory;
c = ranged(c, 0, psb->col);
r = ranged(r, 0, psb->row);
ft.y = psb->y;
ft.x = psb->x;
ft.y = ranged(ft.y, 0, ft.rows-1);
ft.x = ranged(ft.x, 0, ft.cols-1);
clrscr();
for (y = 0; y < r; y++)
{
memcpy(FTCMAP[y], p, c * sizeof(ftchar));
p += psb->col * sizeof(ftchar);
memcpy(FTAMAP[y], p, c * sizeof(ftattr));
p += psb->col * sizeof(ftattr);
}
free(psb->raw_memory);
ft.dirty = 1;
refresh();
}
void
move_ansi(int y, int x)
{
move(y, x);
}
void
region_scroll_up(int top, int bottom)
{
int i;
ftchar *c0;
ftattr *a0;
// logic same with old screen.c
if (top > bottom) {
i = top;
top = bottom;
bottom = i;
}
if (top < 0 || bottom >= ft.rows)
return;
c0 = FTCMAP[top];
a0 = FTAMAP[top];
for (i = top; i < bottom; i++)
{
FTCMAP[i] = FTCMAP[i+1];
FTAMAP[i] = FTAMAP[i+1];
}
FTCMAP[bottom] = c0;
FTAMAP[bottom] = a0;
clrregion(bottom, bottom);
fterm_markdirty();
}
#endif
//////////////////////////////////////////////////////////////////////////
// adapter
//////////////////////////////////////////////////////////////////////////
int
fterm_inbuf(void)
{
#ifdef _PFTERM_TEST_MAIN
return 0;
#else
return num_in_buf();
#endif
}
void
fterm_rawc(int c)
{
#ifdef _PFTERM_TEST_MAIN
// if (c == ESC_CHR) putchar('*'); else
putchar(c);
#else
ochar(c);
#endif
}
void
fterm_rawnewline(void)
{
#ifdef _PFTERM_TEST_MAIN
putchar('\n');
#else
ochar('\r');
ochar('\n');
#endif
}
void
fterm_rawflush(void)
{
#ifdef _PFTERM_TEST_MAIN
fflush(stdout);
#else
oflush();
#endif
}
//////////////////////////////////////////////////////////////////////////
// test
//////////////////////////////////////////////////////////////////////////
#ifdef _PFTERM_TEST_MAIN
int main(int argc, char* argv[])
{
char buf[512];
char *a1 = NULL;
initscr();
if (argc < 2)
{
// DBCS test
a1 = ANSI_COLOR(1;33) "測試" ANSI_COLOR(34) "中文"
ANSI_COLOR(7) "測試" ANSI_RESET "測試"
"測試a" ANSI_RESET "\n";
#if 0
outstr(a1);
move(0, 2);
outstr("中文1");
outstr(ANSI_COLOR(1;33)"中文2");
outstr(" 中\x85");
outstr("okok herer\x8a");
move(0, 8);
inansistr(buf, sizeof(buf)-1);
move(3,5); outs(ANSI_RESET "(From inansistr:) "); outs(buf);
move(7, 3);
sprintf(buf, "strlen()=%d\n", fterm_strdlen(a1));
outstr(buf);
refresh();
getchar();
outs(ANSI_COLOR(1;33) "test " ANSI_COLOR(34) "x"
ANSI_RESET "te" ANSI_COLOR(43;0;1;35) " st"
ANSI_COLOR(0) "testx\n");
refresh();
getchar();
clear();
outs("中文中文中文中文中文中文中文中文中文中文中文中文");
move(0, 0);
outs(" this\xFF (ff)is te.(80 tail)->\x80 (80)");
refresh();
getchar();
#endif
// test resize
clear();
move(1, 0);
outs("test resize\n");
refresh();
getchar();
resizeterm(26, 81);
move(2, 0);
outs("2nd line\n");
refresh();
getchar();
#if 0
// test optimization
clear();
move(1, 0);
outs("x++ optimization test\n");
outs("1 2 3 4 5 6 7 8 9 0\n");
outs("1122233334444455555566666667777777788888888899999999990\n");
refresh();
getchar();
move(2, 0);
outs("1122233334444455555566666667777777788888888899999999990\n");
outs("1 2 3 4 5 6 7 8 9 0\n");
refresh();
getchar();
rscroll();
refresh();
getchar();
#endif
} else {
FILE *fp = fopen(argv[1], "r");
int c = 0;
while (fp && (c=getc(fp)) > 0)
{
outc(c);
}
fclose(fp);
refresh();
}
endwin();
printf("\ncomplete. enter to exit.\n");
getchar();
return 0;
}
#endif // _PFTERM_TEST_MAIN
#endif // defined(EXP_PFTERM) || defined(USE_PFTERM)
// vim:ts=4:sw=4
|