summaryrefslogtreecommitdiff
path: root/src/bin/termptyesc.c
blob: 25da608016303e06895288b627334f31622de5f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
#include "private.h"
#include <Elementary.h>
#include <stdint.h>
#include <assert.h>
#include "col.h"
#include "termio.h"
#include "termpty.h"
#include "termptydbl.h"
#include "termptyesc.h"
#include "termptyops.h"
#include "termptyext.h"
#if defined(ENABLE_TESTS)
#include "tytest.h"
#endif

#undef CRITICAL
#undef ERR
#undef WRN
#undef INF
#undef DBG

#define CRITICAL(...) EINA_LOG_DOM_CRIT(_termpty_log_dom, __VA_ARGS__)
#define ERR(...)      EINA_LOG_DOM_ERR(_termpty_log_dom, __VA_ARGS__)
#define WRN(...)      EINA_LOG_DOM_WARN(_termpty_log_dom, __VA_ARGS__)
#define INF(...)      EINA_LOG_DOM_INFO(_termpty_log_dom, __VA_ARGS__)
#define DBG(...)      EINA_LOG_DOM_DBG(_termpty_log_dom, __VA_ARGS__)

#define ST 0x9c // String Terminator
#define BEL 0x07 // Bell
#define ESC 033 // Escape
#define CSI 0x9b
#define OSC 0x9d
#define DEL 0x7f

#define TERMPTY_WRITE_STR(_S) \
   termpty_write(ty, _S, strlen(_S))


/* XXX: all handle_ functions return the number of bytes successfully read, 0
 * if not enough bytes could be read
 */

static const char *const ASCII_CHARS_TABLE[] =
{
   "NUL", // '\0'
   "SOH", // '\001'
   "STX", // '\002'
   "ETX", // '\003'
   "EOT", // '\004'
   "ENQ", // '\005'
   "ACK", // '\006'
   "BEL", // '\007'
   "BS",  // '\010'
   "HT",  // '\011'
   "LF",  // '\012'
   "VT",  // '\013'
   "FF",  // '\014'
   "CR" , // '\015'
   "SO",  // '\016'
   "SI",  // '\017'
   "DLE", // '\020'
   "DC1", // '\021'
   "DC2", // '\022'
   "DC3", // '\023'
   "DC4", // '\024'
   "NAK", // '\025'
   "SYN", // '\026'
   "ETB", // '\027'
   "CAN", // '\030'
   "EM",  // '\031'
   "SUB", // '\032'
   "ESC", // '\033'
   "FS",  // '\034'
   "GS",  // '\035'
   "RS",  // '\036'
   "US"   // '\037'
};

static const char *
_safechar(unsigned int c)
{
   static char _str[9];

   // This should avoid 'BEL' and 'ESC' in particular, which would
   // have side effects in the parent terminal (esp. ESC).
   if (c < (sizeof(ASCII_CHARS_TABLE) / sizeof(ASCII_CHARS_TABLE[0])))
     return ASCII_CHARS_TABLE[c];

   if (c == DEL)
     return "DEL";

   // The rest should be safe (?)
   snprintf(_str, 9, "%c", c);
   _str[8] = '\0';
   return _str;
}

static Eina_Bool
_cursor_is_within_margins(const Termpty *ty)
{
   return !(
      ((ty->termstate.top_margin > 0)
       && (ty->cursor_state.cy < ty->termstate.top_margin))
      || ((ty->termstate.bottom_margin > 0)
          && (ty->cursor_state.cy >= ty->termstate.bottom_margin))
      || ((ty->termstate.left_margin > 0)
          && (ty->cursor_state.cx < ty->termstate.left_margin))
      || ((ty->termstate.right_margin > 0)
          && (ty->cursor_state.cx >= ty->termstate.right_margin))
      );
}

enum csi_arg_error {
     CSI_ARG_NO_VALUE = 1,
     CSI_ARG_ERROR = 2
};

static int
_csi_arg_get(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int sum = 0;

   if ((b == NULL) || (*b == '\0'))
     {
        *ptr = NULL;
        return -CSI_ARG_NO_VALUE;
     }

   /* Skip potential '?', '>'.... */
   while ((*b) && ( (*b) != ';' && ((*b) < '0' || (*b) > '9')))
     b++;

   if (*b == ';')
     {
        b++;
        *ptr = b;
        return -CSI_ARG_NO_VALUE;
     }

   if (*b == '\0')
     {
        *ptr = NULL;
        return -CSI_ARG_NO_VALUE;
     }

   while ((*b >= '0') && (*b <= '9'))
     {
        if (sum > INT32_MAX/10 )
          {
             ERR("Invalid sequence: argument is too large");
             ty->decoding_error = EINA_TRUE;
             goto error;
          }
        sum *= 10;
        sum += *b - '0';
        b++;
     }

   if ((*b == ';') || (*b == ':'))
     {
        if (b[1])
          b++;
        *ptr = b;
     }
   else if (*b == '\0')
     {
        *ptr = NULL;
     }
   else
     {
        *ptr = b;
     }
   return sum;

error:
   ERR("Invalid CSI argument");
   ty->decoding_error = EINA_TRUE;
   *ptr = NULL;
   return -CSI_ARG_ERROR;
}

static void
_tab_forward(Termpty *ty, int n)
{
   int cx = ty->cursor_state.cx;

   for (; n > 0; n--)
     {
        do
          {
             cx++;
          }
        while ((cx < ty->w) && (!TAB_TEST(ty, cx)));
     }

   ty->cursor_state.cx = cx;
   TERMPTY_RESTRICT_FIELD(ty->cursor_state.cx, 0, ty->w);
}

static void
_cursor_to_start_of_line(Termpty *ty)
{
   ty->cursor_state.cx = ty->termstate.left_margin;
}

static void
_handle_cursor_control(Termpty *ty, const Eina_Unicode *cc)
{
   Termcell *cell;

   switch (*cc)
     {
      case 0x07: // BEL '\a' (bell)
         if (ty->cb.bell.func) ty->cb.bell.func(ty->cb.bell.data);
         return;
      case 0x08: // BS  '\b' (backspace)
         DBG("->BS");
         ty->termstate.wrapnext = 0;
         ty->cursor_state.cx--;
         TERMPTY_RESTRICT_FIELD(ty->cursor_state.cx, 0, ty->w);
         return;
      case 0x09: // HT  '\t' (horizontal tab)
         DBG("->HT");
         cell = &(TERMPTY_SCREEN(ty, ty->cursor_state.cx, ty->cursor_state.cy));
         cell->att.tab_inserted = 1;
         _tab_forward(ty, 1);
         cell = &(TERMPTY_SCREEN(ty, ty->cursor_state.cx -1, ty->cursor_state.cy));
         cell->att.tab_last = 1;
         return;
      case 0x0a: // LF  '\n' (new line)
      case 0x0b: // VT  '\v' (vertical tab)
      case 0x0c: // FF  '\f' (form feed)
         DBG("->LF");
         ty->termstate.wrapnext = 0;
         if (ty->termstate.crlf)
           _cursor_to_start_of_line(ty);
         ty->cursor_state.cy++;
         termpty_text_scroll_test(ty, EINA_TRUE);
         return;
      case 0x0d: // CR  '\r' (carriage ret)
         DBG("->CR");
         if (ty->cursor_state.cx != 0)
           {
              ty->termstate.had_cr_x = ty->cursor_state.cx;
              ty->termstate.had_cr_y = ty->cursor_state.cy;
              ty->termstate.wrapnext = 0;
           }
         _cursor_to_start_of_line(ty);
         return;
      default:
         return;
     }
}

static void
_switch_to_alternative_screen(Termpty *ty, int mode)
{
   // swap screen content now
   if (mode != ty->altbuf)
     termpty_screen_swap(ty);
}

static void
_move_cursor_to_origin(Termpty *ty)
{
  if (ty->termstate.restrict_cursor)
    {
      ty->cursor_state.cx = ty->termstate.left_margin;
      TERMPTY_RESTRICT_FIELD(ty->cursor_state.cx, 0, ty->w);
      ty->cursor_state.cy = ty->termstate.top_margin;
      TERMPTY_RESTRICT_FIELD(ty->cursor_state.cy, 0, ty->h);
    }
  else
    {
      ty->cursor_state.cx = 0;
      ty->cursor_state.cy = 0;
    }
}


static void
_handle_esc_csi_reset_mode(Termpty *ty, Eina_Unicode cc, Eina_Unicode *b,
                           const Eina_Unicode * const end)
{
   int mode = 0, priv = 0, arg;

   if (cc == 'h')
     mode = 1;
   if (*b == '?')
     {
        priv = 1;
        b++;
     }
   if (priv) /* DEC Private Mode Reset (DECRST) */
     {
        while (b && b <= end)
          {
             arg = _csi_arg_get(ty, &b);
             // complete-ish list here:
             // http://ttssh2.sourceforge.jp/manual/en/about/ctrlseq.html
             switch (arg)
               {
                case -CSI_ARG_ERROR:
                   return;
              /* TODO: -CSI_ARG_NO_VALUE */
                case 1:
                   ty->termstate.appcursor = mode;
                   break;
                case 2:
                   DBG("DECANM - ANSI MODE - VT52");
                   ty->termstate.kbd_lock = mode;
                   break;
                case 3: // 132 column mode… should we handle this?
#if defined(SUPPORT_80_132_COLUMNS)
                   if (ty->termstate.att.is_80_132_mode_allowed)
                     {
                        /* ONLY FOR TESTING PURPOSE FTM */
                        Evas_Object *wn;
                        int w, h;

                        wn = termio_win_get(ty->obj);
                        elm_win_size_step_get(wn, &w, &h);
                        evas_object_resize(wn,
                                           4 +
                                           (mode ? 132 : 80) * w,
                                           4 + ty->h * h);
                        termpty_resize(ty, mode ? 132 : 80,
                                       ty->h);
                        termpty_reset_state(ty);
                        termpty_clear_screen(ty,
                                             TERMPTY_CLR_ALL);
                     }
#endif
                   break;
                case 4:
                   DBG("scrolling mode (DECSCLM): %i (always fast mode)", mode);
                   break;
                case 5:
                   ty->termstate.reverse = mode;
                   break;
                case 6:
                   /* DECOM */
                   if (mode)
                     {
                        /* set, within margins */
                        ty->termstate.restrict_cursor = 1;
                     }
                   else
                     {
                        ty->termstate.restrict_cursor = 0;
                     }
                   _move_cursor_to_origin(ty);
                   DBG("DECOM: mode (%d): cursor is at 0,0"
                       " cursor limited to screen/start point"
                       " for line #'s depends on top margin",
                       mode);
                   break;
                case 7:
                   DBG("DECAWM: set/reset wrap mode to %i", mode);
                   ty->termstate.wrap = mode;
                   break;
                case 8:
                   ty->termstate.no_autorepeat = !mode;
                   DBG("DECARM - auto repeat %i", mode);
                   break;
                case 9:
                   DBG("set mouse (X10) %i", mode);
                   if (mode) ty->mouse_mode = MOUSE_X10;
                   else ty->mouse_mode = MOUSE_OFF;
                   break;
                case 12: // ignore
                   WRN("TODO: set blinking cursor to (stop?) %i or local echo (ignored)", mode);
                   break;
                case 19: // never seen this - what to do?
                   WRN("TODO: set print extent to full screen");
                   ty->decoding_error = EINA_TRUE;
                   break;
                case 20: // crfl==1 -> cur moves to col 0 on LF, FF or VT, ==0 -> mode is cr+lf
                   ty->termstate.crlf = mode;
                   break;
                case 25:
                   ty->termstate.hide_cursor = !mode;
                   DBG("hide cursor: %d", !mode);
                   break;
                case 30: // ignore
                   WRN("TODO: set scrollbar mapping %i", mode);
                   ty->decoding_error = EINA_TRUE;
                   break;
                case 33: // ignore
                   WRN("TODO: Stop cursor blink %i", mode);
                   break;
                case 34: // ignore
                   WRN("TODO: Underline cursor mode %i", mode);
                   ty->decoding_error = EINA_TRUE;
                   break;
                case 35: // ignore
                   WRN("TODO: set shift keys %i", mode);
                   ty->decoding_error = EINA_TRUE;
                   break;
                case 38: // ignore
                   WRN("TODO: switch to tek window %i", mode);
                   ty->decoding_error = EINA_TRUE;
                   break;
                case 40:
                   DBG("Allow 80 -> 132 Mode %i", mode);
#if defined(SUPPORT_80_132_COLUMNS)
                   ty->termstate.att.is_80_132_mode_allowed = mode;
#endif
                   break;
                case 45: // ignore
                   WRN("TODO: Reverse-wraparound Mode");
                   ty->decoding_error = EINA_TRUE;
                   break;
                case 47:
                   _switch_to_alternative_screen(ty, mode);
                   break;
                case 59: // ignore
                   WRN("TODO: kanji terminal mode %i", mode);
                   ty->decoding_error = EINA_TRUE;
                   break;
                case 66:
                   WRN("TODO: app keypad mode %i", mode);
                   ty->decoding_error = EINA_TRUE;
                   break;
                case 67:
                   ty->termstate.send_bs = mode;
                   DBG("backspace send bs not del = %i", mode);
                   break;
                case 69:
                   ty->termstate.lr_margins = mode;
                   if (!mode)
                     {
                        ty->termstate.left_margin = 0;
                        ty->termstate.right_margin = 0;
                     }
                   break;
                case 98:
                   DBG("DECARSM Set/Reset Auto Resize Mode: %d", mode);
                   break;
                case 100:
                   DBG("DECAAM Set/Reset Auto Answerback Mode: %d", mode);
                   break;
                case 101:
                   DBG("DECCANSM Set/Reset Conceal Answerback Message Mode: %d", mode);
                   break;
                case 109:
                   DBG("DECCAPSLK Set/Reset Caps Lock Mode: %d", mode);
                   break;
                case 1000:
                   if (mode) ty->mouse_mode = MOUSE_NORMAL;
                   else ty->mouse_mode = MOUSE_OFF;
                   DBG("set mouse (press+release only) to %i", mode);
                   break;
                case 1001:
                   WRN("TODO: x11 mouse highlighting %i", mode);
                   ty->decoding_error = EINA_TRUE;
                   break;
                case 1002:
                   if (mode) ty->mouse_mode = MOUSE_NORMAL_BTN_MOVE;
                   else ty->mouse_mode = MOUSE_OFF;
                   DBG("set mouse (press+release+motion while pressed) %i", mode);
                   break;
                case 1003:
                   if (mode) ty->mouse_mode = MOUSE_NORMAL_ALL_MOVE;
                   else ty->mouse_mode = MOUSE_OFF;
                   DBG("set mouse (press+release+all motion) %i", mode);
                   break;
                case 1004: // i dont know what focus reporting is?
                   WRN("TODO: enable focus reporting %i", mode);
                   ty->decoding_error = EINA_TRUE;
                   break;
                case 1005:
                   if (mode) ty->mouse_ext = MOUSE_EXT_UTF8;
                   else ty->mouse_ext = MOUSE_EXT_NONE;
                   DBG("set mouse (xterm utf8 style) %i", mode);
                   break;
                case 1006:
                   if (mode) ty->mouse_ext = MOUSE_EXT_SGR;
                   else ty->mouse_ext = MOUSE_EXT_NONE;
                   DBG("set mouse (xterm sgr style) %i", mode);
                   break;
                case 1010: // ignore
                   WRN("TODO: set home on tty output %i", mode);
                   ty->decoding_error = EINA_TRUE;
                   break;
                case 1012: // ignore
                   WRN("TODO: set home on tty input %i", mode);
                   ty->decoding_error = EINA_TRUE;
                   break;
                case 1015:
                   if (mode) ty->mouse_ext = MOUSE_EXT_URXVT;
                   else ty->mouse_ext = MOUSE_EXT_NONE;
                   DBG("set mouse (rxvt-unicode style) %i", mode);
                   break;
                case 1034: // ignore
                   /* libreadline6 emits it but it shouldn't.
                      See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=577012
                      */
                   WRN("Ignored screen mode %i", arg);
                   break;
                case 1047:
                   if (!mode && ty->altbuf)
                     /* clear screen before switching back to normal */
                     termpty_clear_screen(ty, TERMPTY_CLR_ALL);
                   _switch_to_alternative_screen(ty, mode);
                   break;
                case 1048:
                   termpty_cursor_copy(ty, mode);
                   break;
                case 1049:
                   if (mode)
                     {
                        // switch to altbuf
                        termpty_cursor_copy(ty, mode);
                        _switch_to_alternative_screen(ty, mode);
                        if (ty->altbuf)
                          /* clear screen before switching back to normal */
                          termpty_clear_screen(ty, TERMPTY_CLR_ALL);
                     }
                   else
                     {
                        if (ty->altbuf)
                          /* clear screen before switching back to normal */
                          termpty_clear_screen(ty, TERMPTY_CLR_ALL);
                        _switch_to_alternative_screen(ty, mode);
                        termpty_cursor_copy(ty, mode);
                     }
                   break;
                case 2004:
                   ty->bracketed_paste = mode;
                   break;
                case 7727: // ignore
                   WRN("TODO: enable application escape mode %i", mode);
                   ty->decoding_error = EINA_TRUE;
                   break;
                case 7786: // ignore
                   WRN("TODO: enable mouse wheel -> cursor key xlation %i", mode);
                   ty->decoding_error = EINA_TRUE;
                   break;
                default:
                   WRN("Unhandled DEC Private Reset Mode arg %i", arg);
                   ty->decoding_error = EINA_TRUE;
                   break;
               }
          }
     }
   else /* Reset Mode (RM) */
     {
        while (b && b <= end)
          {
             arg = _csi_arg_get(ty, &b);

             switch (arg)
               {
                case -CSI_ARG_ERROR:
                   return;
              /* TODO: -CSI_ARG_NO_VALUE */
                case 1:
                   ty->termstate.appcursor = mode;
                   break;
                case 3:
                   WRN("CRM - Show Control Character Mode: %i", mode);
                   ty->decoding_error = EINA_TRUE;
                   break;
                case 4:
                   DBG("set insert mode to %i", mode);
                   ty->termstate.insert = mode;
                   break;
                case 34:
                   WRN("TODO: hebrew keyboard mapping: %i", mode);
                   ty->decoding_error = EINA_TRUE;
                   break;
                case 36:
                   WRN("TODO: hebrew encoding mode: %i", mode);
                   ty->decoding_error = EINA_TRUE;
                   break;
                default:
                   WRN("Unhandled ANSI Reset Mode arg %i", arg);
                   ty->decoding_error = EINA_TRUE;
               }
          }
     }
}

static int
_csi_truecolor_arg_get(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int sum = 0;
   char separator;

   if ((b == NULL) || (*b == '\0'))
     {
        *ptr = NULL;
        return -CSI_ARG_NO_VALUE;
     }

   /* by construction, shall be the same separator as the following ones */
   separator = *(b-1);
   if ((separator != ';') && (separator != ':'))
     {
        *ptr = NULL;
        return -CSI_ARG_NO_VALUE;
     }

   if (*b == separator)
     {
        b++;
        *ptr = b;
        return -CSI_ARG_NO_VALUE;
     }

   if (*b == '\0')
     {
        *ptr = NULL;
        return -CSI_ARG_NO_VALUE;
     }
   /* invalid values */
   if ((*b < '0') || (*b > '9'))
     {
        *ptr = NULL;
        return -CSI_ARG_ERROR;
     }

   while ((*b >= '0') && (*b <= '9'))
     {
        if (sum > INT32_MAX/10 )
          {
             *ptr = NULL;
             ERR("Invalid sequence: argument is too large");
             ty->decoding_error = EINA_TRUE;
             return -CSI_ARG_ERROR;
          }
        sum *= 10;
        sum += *b - '0';
        b++;
     }
   if (*b == separator)
     {
        b++;
        *ptr = b;
     }
   else if (*b == '\0')
     {
        *ptr = NULL;
     }
   else
     {
        *ptr = b;
     }
   return sum;
}


static int
_approximate_truecolor_rgb(Termpty *ty, int r0, int g0, int b0)
{
   int chosen_color = COL_DEF;
/* TODO: use the function in tests */
#if defined(ENABLE_FUZZING)
   (void) ty;
   (void) r0;
   (void) g0;
   (void) b0;
#else
   int c;
   int distance_min = INT_MAX;
   Evas_Object *textgrid;

   DBG("approximating r:%d g:%d b:%d", r0, g0, b0);

   textgrid = termio_textgrid_get(ty->obj);
   for (c = 0; c < 256; c++)
     {
        int r1 = 0, g1 = 0, b1 = 0, a1 = 0;
        int delta_red_sq, delta_green_sq, delta_blue_sq, middle_red;
        int distance;

        evas_object_textgrid_palette_get(textgrid,
                                         EVAS_TEXTGRID_PALETTE_EXTENDED,
                                         c, &r1, &g1, &b1, &a1);
        /* Compute the color distance
         * XXX: this is inacurate but should give good enough results.
         * See * https://en.wikipedia.org/wiki/Color_difference
         */
        middle_red = (r0 + r1) / 2;
        delta_red_sq = (r0 - r1) * (r0 - r1);
        delta_green_sq = (g0 - g1) * (g0 - g1);
        delta_blue_sq = (b0 - b1) * (b0 - b1);

        distance = 2 * delta_red_sq
           + 4 * delta_green_sq
           + 3 * delta_blue_sq
           + ((middle_red) * (delta_red_sq - delta_blue_sq) / 256);
        if (distance < distance_min)
          {
             distance_min = distance;
             chosen_color = c;
          }
     }
#endif
   return chosen_color;
}

static int
_handle_esc_csi_truecolor_rgb(Termpty *ty, Eina_Unicode **ptr)
{
   int r, g, b;
   Eina_Unicode *u = *ptr;
   char separator;

   if ((u == NULL) || (*u == '\0'))
     {
        return COL_DEF;
     }
   separator = *(u-1);

   r = _csi_truecolor_arg_get(ty, ptr);
   g = _csi_truecolor_arg_get(ty, ptr);
   b = _csi_truecolor_arg_get(ty, ptr);
   if ((r == -CSI_ARG_ERROR) ||
       (g == -CSI_ARG_ERROR) ||
       (b == -CSI_ARG_ERROR))
     return COL_DEF;

   if (separator == ':' && *ptr)
     {
        if (**ptr != ';')
          {
             /* then the first parameter was a color-space-id (ignored) */
             r = g;
             g = b;
             b = _csi_truecolor_arg_get(ty, ptr);
             /* Skip other parameters */
             while ((*ptr) && (**ptr != ';'))
               {
                  int arg = _csi_truecolor_arg_get(ty, ptr);
                  if (arg == -CSI_ARG_ERROR)
                    break;
               }
          }
        if ((*ptr) && (**ptr == ';'))
          {
             *ptr = (*ptr) + 1;
          }
     }

   if (r == -CSI_ARG_NO_VALUE)
     r = 0;
   if (g == -CSI_ARG_NO_VALUE)
     g = 0;
   if (b == -CSI_ARG_NO_VALUE)
     b = 0;

   return _approximate_truecolor_rgb(ty, r, g, b);
}

static int
_handle_esc_csi_truecolor_cmy(Termpty *ty, Eina_Unicode **ptr)
{
   int r, g, b, c, m, y;
   Eina_Unicode *u = *ptr;
   char separator;

   if ((u == NULL) || (*u == '\0'))
     {
        return COL_DEF;
     }
   separator = *(u-1);

   /* Considering CMY stored as percents */
   c = _csi_truecolor_arg_get(ty, ptr);
   m = _csi_truecolor_arg_get(ty, ptr);
   y = _csi_truecolor_arg_get(ty, ptr);

   if ((c == -CSI_ARG_ERROR) ||
       (m == -CSI_ARG_ERROR) ||
       (y == -CSI_ARG_ERROR))
     return COL_DEF;

   if (separator == ':' && *ptr)
     {
        if (**ptr != ';')
          {
             /* then the first parameter was a color-space-id (ignored) */
             c = m;
             m = y;
             y = _csi_truecolor_arg_get(ty, ptr);
             /* Skip other parameters */
             while ((*ptr) && (**ptr != ';'))
               {
                  int arg = _csi_truecolor_arg_get(ty, ptr);
                  if (arg == -CSI_ARG_ERROR)
                    break;
               }
          }
        if ((*ptr) && (**ptr == ';'))
          {
             *ptr = (*ptr) + 1;
          }
     }

   if (c == -CSI_ARG_NO_VALUE)
     c = 0;
   if (m == -CSI_ARG_NO_VALUE)
     m = 0;
   if (y == -CSI_ARG_NO_VALUE)
     y = 0;

   r = 255 - ((c * 255) / 100);
   g = 255 - ((m * 255) / 100);
   b = 255 - ((y * 255) / 100);

   return _approximate_truecolor_rgb(ty, r, g, b);
}

static int
_handle_esc_csi_truecolor_cmyk(Termpty *ty, Eina_Unicode **ptr)
{
   int r, g, b, c, m, y, k;
   Eina_Unicode *u = *ptr;
   char separator;

   if ((u == NULL) || (*u == '\0'))
     {
        return COL_DEF;
     }
   separator = *(u-1);

   /* Considering CMYK stored as percents */
   c = _csi_truecolor_arg_get(ty, ptr);
   m = _csi_truecolor_arg_get(ty, ptr);
   y = _csi_truecolor_arg_get(ty, ptr);
   k = _csi_truecolor_arg_get(ty, ptr);

   if ((c == -CSI_ARG_ERROR) ||
       (m == -CSI_ARG_ERROR) ||
       (y == -CSI_ARG_ERROR) ||
       (k == -CSI_ARG_ERROR))
     return COL_DEF;

   if (separator == ':' && *ptr)
     {
        if (**ptr != ';')
          {
             /* then the first parameter was a color-space-id (ignored) */
             c = m;
             m = y;
             y = k;
             k = _csi_truecolor_arg_get(ty, ptr);
             /* Skip other parameters */
             while ((*ptr) && (**ptr != ';'))
               {
                  int arg = _csi_truecolor_arg_get(ty, ptr);
                  if (arg == -CSI_ARG_ERROR)
                    break;
               }
          }
        if ((*ptr) && (**ptr == ';'))
          {
             *ptr = (*ptr) + 1;
          }
     }

   if (c == -CSI_ARG_NO_VALUE)
     c = 0;
   if (m == -CSI_ARG_NO_VALUE)
     m = 0;
   if (y == -CSI_ARG_NO_VALUE)
     y = 0;
   if (k == -CSI_ARG_NO_VALUE)
     k = 0;

   r = (255 * (100 - c) * (100 - k)) / 100 / 100;
   g = (255 * (100 - m) * (100 - k)) / 100 / 100;
   b = (255 * (100 - y) * (100 - k)) / 100 / 100;

   return _approximate_truecolor_rgb(ty, r, g, b);
}

static void
_handle_esc_csi_color_set(Termpty *ty, Eina_Unicode **ptr,
                          const Eina_Unicode * const end)
{
   Eina_Unicode *b = *ptr;

   if (b && (*b == '>'))
     { // key resources used by xterm
        WRN("TODO: set/reset key resources used by xterm");
        ty->decoding_error = EINA_TRUE;
        return;
     }
   DBG("color set");
   while (b && b <= end)
     {
        int arg = _csi_arg_get(ty, &b);
        switch (arg)
          {
           case -CSI_ARG_ERROR:
              return;
           case -CSI_ARG_NO_VALUE:
              EINA_FALLTHROUGH;
           case 0: // reset to normal
              termpty_reset_att(&(ty->termstate.att));
              break;
           case 1: // bold/bright
              ty->termstate.att.bold = 1;
              break;
           case 2: // faint
              ty->termstate.att.faint = 1;
              break;
           case 3: // italic
              ty->termstate.att.italic = 1;
              break;
           case 4: // underline
              ty->termstate.att.underline = 1;
              break;
           case 5: // blink
              ty->termstate.att.blink = 1;
              break;
           case 6: // blink rapid
              ty->termstate.att.blink2 = 1;
              break;
           case 7: // reverse
              ty->termstate.att.inverse = 1;
              break;
           case 8: // invisible
              ty->termstate.att.invisible = 1;
              break;
           case 9: // strikethrough
              ty->termstate.att.strike = 1;
              break;
           case 20: // fraktur!
              ty->termstate.att.fraktur = 1;
              break;
           case 21: // no bold/bright
              ty->termstate.att.bold = 0;
              break;
           case 22: // no bold/bright, no faint
              ty->termstate.att.bold = 0;
              ty->termstate.att.faint = 0;
              break;
           case 23: // no italic, not fraktur
              ty->termstate.att.italic = 0;
              ty->termstate.att.fraktur = 0;
              break;
           case 24: // no underline
              ty->termstate.att.underline = 0;
              break;
           case 25: // no blink
              ty->termstate.att.blink = 0;
              ty->termstate.att.blink2 = 0;
              break;
           case 27: // no reverse
              ty->termstate.att.inverse = 0;
              break;
           case 28: // no invisible
              ty->termstate.att.invisible = 0;
              break;
           case 29: // no strikethrough
              ty->termstate.att.strike = 0;
              break;
           case 30: // fg
           case 31:
           case 32:
           case 33:
           case 34:
           case 35:
           case 36:
           case 37:
              ty->termstate.att.fg256 = 0;
              ty->termstate.att.fg = (arg - 30) + COL_BLACK;
              ty->termstate.att.fgintense = 0;
              break;
           case 38: // xterm 256 fg color ???
              arg = _csi_arg_get(ty, &b);
              switch (arg)
                {
                 case -CSI_ARG_ERROR:
                    return;
                   /* TODO: -CSI_ARG_NO_VALUE */
                 case 1:
                    ty->termstate.att.fg256 = 0;
                    ty->termstate.att.fg = COL_INVIS;
                    break;
                 case 2:
                    ty->termstate.att.fg256 = 1;
                    ty->termstate.att.fg =
                       _handle_esc_csi_truecolor_rgb(ty, &b);
                    DBG("truecolor RGB fg: approximation got color %d",
                        ty->termstate.att.fg);
                    break;
                 case 3:
                    ty->termstate.att.fg256 = 1;
                    ty->termstate.att.fg =
                       _handle_esc_csi_truecolor_cmy(ty, &b);
                    DBG("truecolor CMY fg: approximation got color %d",
                        ty->termstate.att.fg);
                    break;
                 case 4:
                    ty->termstate.att.fg256 = 1;
                    ty->termstate.att.fg =
                       _handle_esc_csi_truecolor_cmyk(ty, &b);
                    DBG("truecolor CMYK fg: approximation got color %d",
                        ty->termstate.att.fg);
                    break;
                 case 5:
                    // then get next arg - should be color index 0-255
                    arg = _csi_arg_get(ty, &b);
                    if (arg <= -CSI_ARG_ERROR || arg > 255)
                      {
                         ERR("Invalid fg color %d", arg);
                         ty->decoding_error = EINA_TRUE;
                      }
                    else
                      {
                         if (arg == -CSI_ARG_NO_VALUE)
                           arg = 0;
                         ty->termstate.att.fg256 = 1;
                         ty->termstate.att.fg = arg;
                      }
                    break;
                 default:
                    ERR("Failed xterm 256 color fg (got %d)", arg);
                    ty->decoding_error = EINA_TRUE;
                }
              ty->termstate.att.fgintense = 0;
              break;
           case 39: // default fg color
              ty->termstate.att.fg256 = 0;
              ty->termstate.att.fg = COL_DEF;
              ty->termstate.att.fgintense = 0;
              break;
           case 40: // bg
           case 41:
           case 42:
           case 43:
           case 44:
           case 45:
           case 46:
           case 47:
              ty->termstate.att.bg256 = 0;
              ty->termstate.att.bg = (arg - 40) + COL_BLACK;
              ty->termstate.att.bgintense = 0;
              break;
           case 48: // xterm 256 bg color ???
              arg = _csi_arg_get(ty, &b);
              switch (arg)
                {
                 case -CSI_ARG_ERROR:
                    return;
                   /* TODO: -CSI_ARG_NO_VALUE */
                 case 1:
                    ty->termstate.att.bg256 = 0;
                    ty->termstate.att.bg = COL_INVIS;
                    break;
                 case 2:
                    ty->termstate.att.bg256 = 1;
                    ty->termstate.att.bg =
                       _handle_esc_csi_truecolor_rgb(ty, &b);
                    DBG("truecolor RGB bg: approximation got color %d",
                        ty->termstate.att.bg);
                    break;
                 case 3:
                    ty->termstate.att.bg256 = 1;
                    ty->termstate.att.bg =
                       _handle_esc_csi_truecolor_cmy(ty, &b);
                    DBG("truecolor CMY bg: approximation got color %d",
                        ty->termstate.att.bg);
                    break;
                 case 4:
                    ty->termstate.att.bg256 = 1;
                    ty->termstate.att.bg =
                       _handle_esc_csi_truecolor_cmyk(ty, &b);
                    DBG("truecolor CMYK bg: approximation got color %d",
                        ty->termstate.att.bg);
                    break;
                 case 5:
                    // then get next arg - should be color index 0-255
                    arg = _csi_arg_get(ty, &b);
                    if (arg <= -CSI_ARG_ERROR || arg > 255)
                      {
                         ERR("Invalid bg color %d", arg);
                         ty->decoding_error = EINA_TRUE;
                      }
                    else
                      {
                         if (arg == -CSI_ARG_NO_VALUE)
                           arg = 0;
                         ty->termstate.att.bg256 = 1;
                         ty->termstate.att.bg = arg;
                      }
                    break;
                 default:
                    ERR("Failed xterm 256 color bg (got %d)", arg);
                    ty->decoding_error = EINA_TRUE;
                }
              ty->termstate.att.bgintense = 0;
              break;
           case 49: // default bg color
              ty->termstate.att.bg256 = 0;
              ty->termstate.att.bg = COL_DEF;
              ty->termstate.att.bgintense = 0;
              break;
           case 51:
              WRN("TODO: support SGR 51 - framed attribute");
              ty->termstate.att.framed = 1;
              break;
           case 52:
              ty->termstate.att.encircled = 1;
              break;
           case 53:
              WRN("TODO: support SGR 51 - overlined attribute");
              ty->termstate.att.overlined = 1;
              break;
           case 54:
              ty->termstate.att.framed = 0;
              ty->termstate.att.encircled = 0;
              break;
           case 55:
              ty->termstate.att.overlined = 0;
              break;
           case 90: // fg
           case 91:
           case 92:
           case 93:
           case 94:
           case 95:
           case 96:
           case 97:
              ty->termstate.att.fg256 = 0;
              ty->termstate.att.fg = (arg - 90) + COL_BLACK;
              ty->termstate.att.fgintense = 1;
              break;
           case 99: // default fg color
              ty->termstate.att.fg256 = 0;
              ty->termstate.att.fg = COL_DEF;
              ty->termstate.att.fgintense = 1;
              break;
           case 100: // bg
           case 101:
           case 102:
           case 103:
           case 104:
           case 105:
           case 106:
           case 107:
              ty->termstate.att.bg256 = 0;
              ty->termstate.att.bg = (arg - 100) + COL_BLACK;
              ty->termstate.att.bgintense = 1;
              break;
           case 109: // default bg color
              ty->termstate.att.bg256 = 0;
              ty->termstate.att.bg = COL_DEF;
              ty->termstate.att.bgintense = 1;
              break;
           default: //  not handled???
              WRN("Unhandled color cmd [%i]", arg);
              ty->decoding_error = EINA_TRUE;
              break;
          }
     }
}

static void
_handle_esc_csi_cnl(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);
   int max = ty->h;

   if (arg == -CSI_ARG_ERROR)
     return;
   if (arg < 1)
     arg = 1;

   DBG("CNL - Cursor Next Line: %d", arg);
   ty->termstate.wrapnext = 0;
   ty->cursor_state.cy += arg;
   if (ty->termstate.bottom_margin)
     {
        max = ty->termstate.bottom_margin;
     }
   TERMPTY_RESTRICT_FIELD(ty->cursor_state.cy,
                          ty->termstate.top_margin,
                          max);
   ty->cursor_state.cx = ty->termstate.left_margin;
}

static void
_handle_esc_csi_cpl(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);
   int max = ty->h;

   if (arg == -CSI_ARG_ERROR)
     return;
   if (arg < 1)
     arg = 1;

   DBG("CPL - Cursor Previous Line: %d", arg);
   ty->termstate.wrapnext = 0;
   ty->cursor_state.cy -= arg;
   if (ty->termstate.bottom_margin)
     {
        max = ty->termstate.bottom_margin;
     }
   TERMPTY_RESTRICT_FIELD(ty->cursor_state.cy,
                          ty->termstate.top_margin,
                          max);
   ty->cursor_state.cx = ty->termstate.left_margin;
}

static void
_handle_esc_csi_dch(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);
   Termcell *cells;
   int x, lim, max;

   if (arg == -CSI_ARG_ERROR)
     return;

   DBG("DCH - Delete Character: %d chars", arg);

   cells = &(TERMPTY_SCREEN(ty, 0, ty->cursor_state.cy));
   max = ty->w;
   if (ty->termstate.left_margin)
     {
        if (ty->cursor_state.cx < ty->termstate.left_margin)
          return;
     }
   if (ty->termstate.right_margin)
     {
        if (ty->cursor_state.cx > ty->termstate.right_margin)
          return;
        max = ty->termstate.right_margin;
     }
   TERMPTY_RESTRICT_FIELD(arg, 1, max + 1);
   lim = max - arg;
   for (x = ty->cursor_state.cx; x < max; x++)
     {
        if (x < lim)
          TERMPTY_CELL_COPY(ty, &(cells[x + arg]), &(cells[x]), 1);
        else
          {
             cells[x].codepoint = ' ';
             if (EINA_UNLIKELY(cells[x].att.link_id))
               term_link_refcount_dec(ty, cells[x].att.link_id, 1);
             cells[x].att = ty->termstate.att;
             cells[x].att.link_id = 0;
             cells[x].att.dblwidth = 0;
          }
     }
}


static void
_handle_esc_csi_dsr(Termpty *ty, Eina_Unicode *b)
{
   int arg, len;
   char bf[32];
   Eina_Bool question_mark = EINA_FALSE;

   if (*b == '>')
     {
        WRN("TODO: disable key resources used by xterm");
        ty->decoding_error = EINA_TRUE;
        return;
     }
   if (*b == '?')
     {
        question_mark = EINA_TRUE;
        b++;
     }
   arg = _csi_arg_get(ty, &b);
   switch (arg)
     {
      case -CSI_ARG_ERROR:
         return;
      case 5:
         if (question_mark)
           {
              WRN("unhandled DSR (dec specific: %s) %d",
                  (question_mark)? "yes": "no", arg);
              ty->decoding_error = EINA_TRUE;
           }
         else
           {
              /* DSR-OS (Operating Status)
               * Reply Ok */
              termpty_write(ty, "\033[0n",
                            strlen("\033[0n"));
           }
         break;
      case 6:
         DBG("CPR - Cursor Position Report");
           {
              int cx = ty->cursor_state.cx,
                  cy = ty->cursor_state.cy;
              if (ty->termstate.restrict_cursor)
                {
                   if (ty->termstate.top_margin)
                     cy -= ty->termstate.top_margin;
                   if (ty->termstate.left_margin)
                     cx -= ty->termstate.left_margin;
                }
              if (question_mark)
                {
                   len = snprintf(bf, sizeof(bf), "\033[?%d;%d;1R",
                                  cy + 1,
                                  cx + 1);
                }
              else
                {
                   len = snprintf(bf, sizeof(bf), "\033[%d;%dR",
                                  cy + 1,
                                  cx + 1);
                }
              termpty_write(ty, bf, len);
           }
         break;
      case 15:
         if (question_mark)
           {
              /* DSR-PP (Printer Port)
               * Reply None */
              termpty_write(ty, "\033[?13n",
                            strlen("\033[?13n"));
           }
         else
           {
              WRN("unhandled DSR (dec specific: %s) %d",
                  (question_mark)? "yes": "no", arg);
              ty->decoding_error = EINA_TRUE;
           }
         break;
      case 25:
         if (question_mark)
           {
              /* DSR-UDK (User-Defined Keys)
               * Reply Unlocked */
              termpty_write(ty, "\033[?20n",
                            strlen("\033[?20n"));
           }
         else
           {
              WRN("unhandled DSR (dec specific: %s) %d",
                  (question_mark)? "yes": "no", arg);
              ty->decoding_error = EINA_TRUE;
           }
         break;
      case 26:
         if (question_mark)
           {
              /* DSR-KBD (Keyboard)
               * Reply North American */
              termpty_write(ty, "\033[?27;1;0;0n",
                            strlen("\033[?27;1;0;0n"));
           }
         else
           {
              WRN("unhandled DSR (dec specific: %s) %d",
                  (question_mark)? "yes": "no", arg);
              ty->decoding_error = EINA_TRUE;
           }
         break;
      case 62:
         if (question_mark)
           {
              /* DSR-MSR (Macro Space Report)
               * Reply 0 */
              termpty_write(ty, "\033[0000*{",
                            strlen("\033[0000*{"));
           }
         else
           {
              WRN("unhandled DSR (dec specific: %s) %d",
                  (question_mark)? "yes": "no", arg);
              ty->decoding_error = EINA_TRUE;
           }
         break;
      case 63:
         if (question_mark)
           {
              /* DSR-DECCKSR (Memory Checksum) */
              int pid = _csi_arg_get(ty, &b);
              if (pid == -CSI_ARG_NO_VALUE)
                pid = 65535;
              len = snprintf(bf, sizeof(bf), "\033P%u!~0000\033\\",
                             ((unsigned int)pid) % 65536);
              termpty_write(ty, bf, len);
           }
         else
           {
              WRN("unhandled DSR (dec specific: %s) %d",
                  (question_mark)? "yes": "no", arg);
              ty->decoding_error = EINA_TRUE;
           }
         break;
      case 75:
         if (question_mark)
           {
              /* DSR-DIR (Data Integrity Report) */
              termpty_write(ty, "\033[?70n", strlen("\033[?70n"));
           }
         else
           {
              WRN("unhandled DSR (dec specific: %s) %d",
                  (question_mark)? "yes": "no", arg);
              ty->decoding_error = EINA_TRUE;
           }
         break;
      /* TODO: -CSI_ARG_NO_VALUE */
      default:
         WRN("unhandled DSR (dec specific: %s) %d",
             (question_mark)? "yes": "no", arg);
         ty->decoding_error = EINA_TRUE;
         break;
     }
}

static void
_handle_esc_csi_decslrm(Termpty *ty, Eina_Unicode **b)
{
  int left = _csi_arg_get(ty, b);
  int right = _csi_arg_get(ty, b);

  DBG("DECSLRM (%d;%d) Set Left and Right Margins", left, right);
  if ((left == -CSI_ARG_ERROR) || (right == -CSI_ARG_ERROR))
    goto bad;

  TERMPTY_RESTRICT_FIELD(left, 1, ty->w);
  if (right < 1)
    right = ty->w;
  TERMPTY_RESTRICT_FIELD(right, 3, ty->w+1);

  if (left >= right)
    goto bad;
  if (right - left < 2)
    goto bad;

  if (right == ty->w)
    right = 0;

  ty->termstate.left_margin = left  - 1;
  ty->termstate.right_margin = right;
  _move_cursor_to_origin(ty);

  return;

bad:
  ty->termstate.left_margin = 0;
  ty->termstate.right_margin = 0;
}

static void
_handle_esc_csi_decstbm(Termpty *ty, Eina_Unicode **b)
{
  int top = _csi_arg_get(ty, b);
  int bottom = _csi_arg_get(ty, b);

  DBG("DECSTBM (%d;%d) Set Top and Bottom Margins", top, bottom);
  if ((top == -CSI_ARG_ERROR) || (bottom == -CSI_ARG_ERROR))
    goto bad;

  TERMPTY_RESTRICT_FIELD(top, 1, ty->h);
  TERMPTY_RESTRICT_FIELD(bottom, 1, ty->h+1);

  if (top >= bottom) goto bad;

  if (bottom == ty->h)
    bottom = 0;

  ty->termstate.top_margin = top - 1;
  ty->termstate.bottom_margin = bottom;

  _move_cursor_to_origin(ty);
  return;

bad:
  ty->termstate.top_margin = 0;
  ty->termstate.bottom_margin = 0;
}

static int
_clean_up_rect_coordinates(Termpty *ty,
                           int *top_ptr,
                           int *left_ptr,
                           int *bottom_ptr,
                           int *right_ptr)
{
   int top = *top_ptr;
   int left = *left_ptr;
   int bottom = *bottom_ptr;
   int right = *right_ptr;

   TERMPTY_RESTRICT_FIELD(top, 1, ty->h);
   if (ty->termstate.restrict_cursor)
     {
        top += ty->termstate.top_margin;
        if (ty->termstate.bottom_margin && top >= ty->termstate.bottom_margin)
          top = ty->termstate.bottom_margin;
     }
   top--;

   TERMPTY_RESTRICT_FIELD(left, 1, ty->w);
   if (ty->termstate.restrict_cursor)
     {
        left += ty->termstate.left_margin;
        if (ty->termstate.right_margin && left >= ty->termstate.right_margin)
          left = ty->termstate.right_margin;
     }
   left--;

   if (right < 1)
     right = ty->w;
   if (ty->termstate.restrict_cursor)
     {
        right += ty->termstate.left_margin;
        if (ty->termstate.right_margin && right >= ty->termstate.right_margin)
          right = ty->termstate.right_margin;
     }
   if (right > ty->w)
     right = ty->w;

   if (bottom < 1)
     bottom = ty->h;
   if (ty->termstate.restrict_cursor)
     {
        bottom += ty->termstate.top_margin;
        if (ty->termstate.bottom_margin && bottom >= ty->termstate.bottom_margin)
          bottom = ty->termstate.bottom_margin;
     }
   bottom--;
   if (bottom > ty->h)
     bottom = ty->h - 1;

   if ((bottom < top) || (right < left))
     return -1;

   *top_ptr = top;
   *left_ptr = left;
   *bottom_ptr = bottom;
   *right_ptr = right;

   return 0;
}

static int
_clean_up_from_to_coordinates(Termpty *ty,
                              int *top_ptr,
                              int *left_ptr,
                              int *bottom_ptr,
                              int *right_ptr,
                              int *left_border,
                              int *right_border)
{
   int top = *top_ptr;
   int left = *left_ptr;
   int bottom = *bottom_ptr;
   int right = *right_ptr;

   TERMPTY_RESTRICT_FIELD(top, 1, ty->h);
   if (ty->termstate.restrict_cursor)
     {
        top += ty->termstate.top_margin;
        if (ty->termstate.bottom_margin && top >= ty->termstate.bottom_margin)
          top = ty->termstate.bottom_margin;
     }
   top--;

   TERMPTY_RESTRICT_FIELD(left, 1, ty->w);
   if (ty->termstate.restrict_cursor)
     {
        left += ty->termstate.left_margin;
        if (ty->termstate.right_margin && left >= ty->termstate.right_margin)
          left = ty->termstate.right_margin;
     }
   left--;

   if (right < 1)
     right = ty->w;
   if (ty->termstate.restrict_cursor)
     {
        right += ty->termstate.left_margin;
        if (ty->termstate.right_margin && right >= ty->termstate.right_margin)
          right = ty->termstate.right_margin;
     }
   if (right > ty->w)
     right = ty->w;

   if (bottom < 1)
     bottom = ty->h;
   if (ty->termstate.restrict_cursor)
     {
        bottom += ty->termstate.top_margin;
        if (ty->termstate.bottom_margin && bottom >= ty->termstate.bottom_margin)
          bottom = ty->termstate.bottom_margin;
     }
   bottom--;
   if (bottom > ty->h)
     bottom = ty->h - 1;

   if ((bottom == top) && (right < left))
     return -1;

   *left_border = 0;
   *right_border = ty->w-1;
   if (ty->termstate.restrict_cursor)
     {
        *left_border = ty->termstate.left_margin;
        *right_border = ty->termstate.right_margin;
     }

   *top_ptr = top;
   *left_ptr = left;
   *bottom_ptr = bottom;
   *right_ptr = right;

   return 0;
}

static void
_handle_esc_csi_decfra(Termpty *ty, Eina_Unicode **b)
{
   int c = _csi_arg_get(ty, b);

   int top = _csi_arg_get(ty, b);
   int left = _csi_arg_get(ty, b);
   int bottom = _csi_arg_get(ty, b);
   int right = _csi_arg_get(ty, b);
   int len;

   DBG("DECFRA (%d; %d;%d;%d;%d) Fill Rectangular Area",
       c, top, left, bottom, right);
   if ((c == -CSI_ARG_ERROR) ||
       (c == -CSI_ARG_NO_VALUE) ||
       (top == -CSI_ARG_ERROR) ||
       (left == -CSI_ARG_ERROR) ||
       (bottom == -CSI_ARG_ERROR) ||
       (right == -CSI_ARG_ERROR))
     return;

   if (! ((c >= 32 && c <= 126) || (c >= 160 && c <= 255)))
     return;

   if (_clean_up_rect_coordinates(ty, &top, &left, &bottom, &right) < 0)
     return;

   len = right - left;

   for (; top <= bottom; top++)
     {
        Termcell *cells = &(TERMPTY_SCREEN(ty, left, top));
        termpty_cells_att_fill_preserve_colors(ty, cells, c, len);
     }
}

static void
_deccara(Termcell *cells, int len,
         Eina_Bool set_bold, Eina_Bool reset_bold,
         Eina_Bool set_underline, Eina_Bool reset_underline,
         Eina_Bool set_blink, Eina_Bool reset_blink,
         Eina_Bool set_inverse, Eina_Bool reset_inverse)
{
   int i;

   for (i = 0; i < len; i++)
     {
        Termatt * att = &cells[i].att;
        if (set_bold)
          att->bold = 1;
        if (set_underline)
          att->underline = 1;
        if (set_blink)
          att->blink = 1;
        if (set_inverse)
          att->inverse = 1;
        if (reset_bold)
          att->bold = 0;
        if (reset_underline)
          att->underline = 0;
        if (reset_blink)
          att->blink = 0;
        if (reset_inverse)
          att->inverse = 0;
     }
}

static void
_handle_esc_csi_deccara(Termpty *ty, Eina_Unicode **ptr,
                        const Eina_Unicode * const end)
{
   Eina_Unicode *b = *ptr;
   Termcell *cells;
   int top;
   int left;
   int bottom;
   int right;
   int len;
   Eina_Bool set_bold = EINA_FALSE, reset_bold = EINA_FALSE;
   Eina_Bool set_underline = EINA_FALSE, reset_underline = EINA_FALSE;
   Eina_Bool set_blink = EINA_FALSE, reset_blink = EINA_FALSE;
   Eina_Bool set_inverse = EINA_FALSE, reset_inverse = EINA_FALSE;

   top = _csi_arg_get(ty, &b);
   left = _csi_arg_get(ty, &b);
   bottom = _csi_arg_get(ty, &b);
   right = _csi_arg_get(ty, &b);

   DBG("DECCARA (%d;%d;%d;%d) Change Attributes in Rectangular Area",
       top, left, bottom, right);
   if ((top == -CSI_ARG_ERROR) ||
       (left == -CSI_ARG_ERROR) ||
       (bottom == -CSI_ARG_ERROR) ||
       (right == -CSI_ARG_ERROR))
     return;

   while (b && b < end)
     {
        int arg = _csi_arg_get(ty, &b);
        switch (arg)
          {
           case -CSI_ARG_ERROR:
              return;
           case -CSI_ARG_NO_VALUE:
              EINA_FALLTHROUGH;
           case 0:
              set_bold = set_underline = set_blink = set_inverse = EINA_FALSE;
              reset_bold = reset_underline = reset_blink = reset_inverse = EINA_TRUE;
              break;
           case 1:
              set_bold = EINA_TRUE;
              reset_bold = EINA_FALSE;
              break;
           case 4:
              set_underline = EINA_TRUE;
              reset_underline = EINA_FALSE;
              break;
           case 5:
              set_blink = EINA_TRUE;
              reset_blink = EINA_FALSE;
              break;
           case 7:
              set_inverse = EINA_TRUE;
              reset_inverse = EINA_FALSE;
              break;
           case 22:
              set_bold = EINA_FALSE;
              reset_bold = EINA_TRUE;
              break;
           case 24:
              set_underline = EINA_FALSE;
              reset_underline = EINA_TRUE;
              break;
           case 25:
              set_blink = EINA_FALSE;
              reset_blink = EINA_TRUE;
              break;
           case 27:
              set_inverse = EINA_FALSE;
              reset_inverse = EINA_TRUE;
              break;
           default:
              WRN("Invalid change attribute [%i]", arg);
              ty->decoding_error = EINA_TRUE;
              return;
          }
     }

   if (ty->termstate.sace_rectangular)
     {
        if (_clean_up_rect_coordinates(ty, &top, &left, &bottom, &right) < 0)
          return;

        len = right - left;

        for (; top <= bottom; top++)
          {
             cells = &(TERMPTY_SCREEN(ty, left, top));
             _deccara(cells, len, set_bold, reset_bold, set_underline,
                      reset_underline, set_blink, reset_blink, set_inverse,
                      reset_inverse);
          }
     }
   else
     {
        int left_border = 0;
        int right_border = ty->w - 1;

        if (_clean_up_from_to_coordinates(ty, &top, &left, &bottom, &right,
                                          &left_border, &right_border) < 0)
          return;
        if (top == bottom)
          {
             cells = &(TERMPTY_SCREEN(ty, left, top));
             len = right - left;
             _deccara(cells, len, set_bold, reset_bold,
                      set_underline, reset_underline,
                      set_blink, reset_blink,
                      set_inverse, reset_inverse);
          }
        else
          {
             /* First line */
             cells = &(TERMPTY_SCREEN(ty, left, top));
             len = right_border - left;
             _deccara(cells, len, set_bold, reset_bold,
                      set_underline, reset_underline,
                      set_blink, reset_blink,
                      set_inverse, reset_inverse);

             /* Middle */
             len = right_border - left_border;
             for (top = top + 1; top < bottom; top++)
               {
                  cells = &(TERMPTY_SCREEN(ty, left_border, top));
                  _deccara(cells, len, set_bold, reset_bold,
                           set_underline, reset_underline,
                           set_blink, reset_blink,
                           set_inverse, reset_inverse);
               }

             /* Last line */
             cells = &(TERMPTY_SCREEN(ty, left_border, bottom));
             len = right - left_border;
             _deccara(cells, len, set_bold, reset_bold,
                      set_underline, reset_underline,
                      set_blink, reset_blink,
                      set_inverse, reset_inverse);
          }
     }
}

static void
_decrara(Termcell *cells, int len,
         Eina_Bool reverse_bold,
         Eina_Bool reverse_underline,
         Eina_Bool reverse_blink,
         Eina_Bool reverse_inverse)
{
   int i;

   for (i = 0; i < len; i++)
     {
        Termatt * att = &cells[i].att;
        if (reverse_bold)
          att->bold = !att->bold;
        if (reverse_underline)
          att->underline = !att->underline;
        if (reverse_blink)
          att->blink = !att->blink;
        if (reverse_inverse)
          att->inverse = !att->inverse;
     }
}

static void
_handle_esc_csi_decrara(Termpty *ty, Eina_Unicode **ptr,
                        const Eina_Unicode * const end)
{
   Eina_Unicode *b = *ptr;
   Termcell *cells;
   int top;
   int left;
   int bottom;
   int right;
   int len;
   Eina_Bool reverse_bold = EINA_FALSE;
   Eina_Bool reverse_underline = EINA_FALSE;
   Eina_Bool reverse_blink = EINA_FALSE;
   Eina_Bool reverse_inverse = EINA_FALSE;

   top = _csi_arg_get(ty, &b);
   left = _csi_arg_get(ty, &b);
   bottom = _csi_arg_get(ty, &b);
   right = _csi_arg_get(ty, &b);

   DBG("DECRARA (%d;%d;%d;%d) Reverse Attributes in Rectangular Area",
       top, left, bottom, right);
   if ((top == -CSI_ARG_ERROR) ||
       (left == -CSI_ARG_ERROR) ||
       (bottom == -CSI_ARG_ERROR) ||
       (right == -CSI_ARG_ERROR))
     return;

   while (b && b < end)
     {
        int arg = _csi_arg_get(ty, &b);
        switch (arg)
          {
           case -CSI_ARG_ERROR:
              return;
           case -CSI_ARG_NO_VALUE:
              EINA_FALLTHROUGH;
           case 0:
              reverse_bold = reverse_underline = reverse_blink = reverse_inverse = EINA_TRUE;
              break;
           case 1:
              reverse_bold = EINA_TRUE;
              break;
           case 4:
              reverse_underline = EINA_TRUE;
              break;
           case 5:
              reverse_blink = EINA_TRUE;
              break;
           case 7:
              reverse_inverse = EINA_TRUE;
              break;
           default:
              WRN("Invalid change attribute [%i]", arg);
              ty->decoding_error = EINA_TRUE;
              return;
          }
     }

   if (ty->termstate.sace_rectangular)
     {
        if (_clean_up_rect_coordinates(ty, &top, &left, &bottom, &right) < 0)
          return;

        len = right - left;

        for (; top <= bottom; top++)
          {
             cells = &(TERMPTY_SCREEN(ty, left, top));
             _decrara(cells, len, reverse_bold, reverse_underline,
                      reverse_blink, reverse_inverse);
          }
     }
   else
     {
        int left_border = 0;
        int right_border = ty->w - 1;

        if (_clean_up_from_to_coordinates(ty, &top, &left, &bottom, &right,
                                          &left_border, &right_border) < 0)
          return;
        if (top == bottom)
          {
             cells = &(TERMPTY_SCREEN(ty, left, top));
             len = right - left;
             _decrara(cells, len, reverse_bold, reverse_underline,
                      reverse_blink, reverse_inverse);
          }
        else
          {
             /* First line */
             cells = &(TERMPTY_SCREEN(ty, left, top));
             len = right_border - left;
             _decrara(cells, len, reverse_bold, reverse_underline,
                      reverse_blink, reverse_inverse);

             /* Middle */
             len = right_border - left_border;
             for (top = top + 1; top < bottom; top++)
               {
                  cells = &(TERMPTY_SCREEN(ty, left_border, top));
                  _decrara(cells, len, reverse_bold, reverse_underline,
                           reverse_blink, reverse_inverse);
               }

             /* Last line */
             cells = &(TERMPTY_SCREEN(ty, left_border, bottom));
             len = right - left_border;
             _decrara(cells, len, reverse_bold, reverse_underline,
                      reverse_blink, reverse_inverse);
          }
     }
}

static void
_handle_esc_csi_decera(Termpty *ty, Eina_Unicode **b)
{
   int top = _csi_arg_get(ty ,b);
   int left = _csi_arg_get(ty, b);
   int bottom = _csi_arg_get(ty, b);
   int right = _csi_arg_get(ty, b);
   int len;

   DBG("DECERA (%d;%d;%d;%d) Erase Rectangular Area",
       top, left, bottom, right);

   if ((top == -CSI_ARG_ERROR) ||
       (left == -CSI_ARG_ERROR) ||
       (bottom == -CSI_ARG_ERROR) ||
       (right == -CSI_ARG_ERROR))
     return;

   if (_clean_up_rect_coordinates(ty, &top, &left, &bottom, &right) < 0)
     return;

   len = right - left;
   for (; top <= bottom; top++)
     {
        Termcell *cells = &(TERMPTY_SCREEN(ty, left, top));
        termpty_cells_set_content(ty, cells, ' ', len);
     }
}

static void
_handle_esc_csi_deccra(Termpty *ty, Eina_Unicode **b)
{
   int top = _csi_arg_get(ty, b);
   int left = _csi_arg_get(ty, b);
   int bottom = _csi_arg_get(ty, b);
   int right = _csi_arg_get(ty, b);
   int p1 = _csi_arg_get(ty, b);
   int to_top = _csi_arg_get(ty, b);
   int to_left = _csi_arg_get(ty, b);
   int p2 = _csi_arg_get(ty, b);
   int to_bottom = ty->h - 1;
   int to_right = ty->w;
   int len;

   DBG("DECFRA (%d;%d;%d;%d -> %d;%d) Copy Rectangular Area",
       top, left, bottom, right, to_top, to_left);
   if ((top == -CSI_ARG_ERROR) ||
       (left == -CSI_ARG_ERROR) ||
       (bottom == -CSI_ARG_ERROR) ||
       (right == -CSI_ARG_ERROR) ||
       (p1 == -CSI_ARG_ERROR) ||
       (to_top == -CSI_ARG_ERROR) ||
       (to_left == -CSI_ARG_ERROR) ||
       (p2 == -CSI_ARG_ERROR))
     return;

   if (_clean_up_rect_coordinates(ty, &top, &left, &bottom, &right) < 0)
     return;

   TERMPTY_RESTRICT_FIELD(to_top, 1, ty->h);
   if (ty->termstate.restrict_cursor)
     {
        to_top += ty->termstate.top_margin;
        if (ty->termstate.bottom_margin)
          {
             if (to_top >= ty->termstate.bottom_margin)
               to_top = ty->termstate.bottom_margin;
             to_bottom = ty->termstate.bottom_margin - 1;
          }
     }
   to_top--;
   if (to_bottom - to_top > bottom - top)
     to_bottom = to_top + bottom - top;
   TERMPTY_RESTRICT_FIELD(to_left, 1, ty->w);
   if (ty->termstate.restrict_cursor)
     {
        to_left += ty->termstate.left_margin;
        if (ty->termstate.right_margin)
          {
             if (to_left >= ty->termstate.right_margin)
               to_left = ty->termstate.right_margin;
             to_right = ty->termstate.right_margin;
          }
     }
   to_left--;

   len = MIN(right - left, to_right - to_left);

   if (to_top < top)
     {
        /* Up -> Bottom */
        for (; top <= bottom && to_top <= to_bottom; top++, to_top++)
          {
             Termcell *cells_src = &(TERMPTY_SCREEN(ty, left, top));
             Termcell *cells_dst = &(TERMPTY_SCREEN(ty, to_left, to_top));
             int x;
             if (to_left <= left)
               {
                  /* -> */
                  for (x = 0; x < len; x++)
                    {
                       if (&(cells_src[x]) != &(cells_dst[x]))
                         {
                            TERMPTY_CELL_COPY(ty, &(cells_src[x]), &(cells_dst[x]), 1);
                         }
                    }
               }
             else
               {
                  /* <- */
                  for (x = len - 1; x >= 0; x--)
                    {
                       if (&(cells_src[x]) != &(cells_dst[x]))
                         {
                            TERMPTY_CELL_COPY(ty, &(cells_src[x]), &(cells_dst[x]), 1);
                         }
                    }
               }
          }
     }
   else
     {
        /* Bottom -> Up */
        for (; bottom >= top && to_bottom >= to_top; bottom--, to_bottom--)
          {
             Termcell *cells_src = &(TERMPTY_SCREEN(ty, left, bottom));
             Termcell *cells_dst = &(TERMPTY_SCREEN(ty, to_left, to_bottom));
             int x;
             if (to_left <= left)
               {
                  /* -> */
                  for (x = 0; x < len; x++)
                    {
                       if (&(cells_src[x]) != &(cells_dst[x]))
                         {
                            TERMPTY_CELL_COPY(ty, &(cells_src[x]), &(cells_dst[x]), 1);
                         }
                    }
               }
             else
               {
                  /* <- */
                  for (x = len - 1; x >= 0; x--)
                    {
                       if (&(cells_src[x]) != &(cells_dst[x]))
                         {
                            TERMPTY_CELL_COPY(ty, &(cells_src[x]), &(cells_dst[x]), 1);
                         }
                    }
               }
          }
     }
}

static void
_handle_esc_csi_cursor_pos_set(Termpty *ty, Eina_Unicode **b,
                               const Eina_Unicode *cc)
{
   int cx = 0, cy = 0;
   ty->termstate.wrapnext = 0;
   cy = _csi_arg_get(ty, b);
   cx = _csi_arg_get(ty, b);

   if ((cx == -CSI_ARG_ERROR) || (cy == -CSI_ARG_ERROR))
     return;

   DBG("cursor pos set (%s) (%d;%d)", (*cc == 'H') ? "CUP" : "HVP",
       cx, cy);
   cx--;
   if (cx < 0)
     cx = 0;
   if (ty->termstate.restrict_cursor)
     {
        cx += ty->termstate.left_margin;
        if (ty->termstate.right_margin > 0 && cx >= ty->termstate.right_margin)
          cx = ty->termstate.right_margin - 1;
     }
   if (cx >= ty->w)
     cx = ty->w -1;
   ty->cursor_state.cx = cx;


   cy--;
   if (cy < 0)
     cy = 0;
   if (ty->termstate.restrict_cursor)
     {
        cy += ty->termstate.top_margin;
        if (ty->termstate.bottom_margin > 0 && cy >= ty->termstate.bottom_margin)
          cy = ty->termstate.bottom_margin - 1;
     }
   if (cy >= ty->h)
     cy = ty->h - 1;
   ty->cursor_state.cy = cy;
}

static void
_handle_esc_csi_decscusr(Termpty *ty, Eina_Unicode **b)
{
  int arg = _csi_arg_get(ty, b);
  Cursor_Shape shape = CURSOR_SHAPE_BLOCK;

  DBG("DECSCUSR (%d) Set Cursor Shape", arg);

  switch (arg)
    {
     case -CSI_ARG_ERROR:
        return;
     case -CSI_ARG_NO_VALUE:
        EINA_FALLTHROUGH;
     case 0:
        EINA_FALLTHROUGH;
     case 1:
        EINA_FALLTHROUGH;
     case 2:
        shape = CURSOR_SHAPE_BLOCK;
        break;
     case 3:
        EINA_FALLTHROUGH;
     case 4:
        shape = CURSOR_SHAPE_UNDERLINE;
        break;
     case 5:
        EINA_FALLTHROUGH;
     case 6:
        shape = CURSOR_SHAPE_BAR;
        break;
     default:
        WRN("Invalid DECSCUSR %d", arg);
        ty->decoding_error = EINA_TRUE;
        return;
    }

  termio_set_cursor_shape(ty->obj, shape);
}

static void
_handle_esc_csi_decsace(Termpty *ty, Eina_Unicode **b)
{
  int arg = _csi_arg_get(ty, b);

  DBG("DECSACE (%d) Select Attribute Change Extent", arg);

  switch (arg)
    {
     case -CSI_ARG_ERROR:
        return;
     case -CSI_ARG_NO_VALUE:
        EINA_FALLTHROUGH;
     case 0:
        EINA_FALLTHROUGH;
     case 1:
        ty->termstate.sace_rectangular = 0;
        break;
     case 2:
        ty->termstate.sace_rectangular = 1;
        break;
     default:
        WRN("Invalid DECSACE %d", arg);
        ty->decoding_error = EINA_TRUE;
        return;
    }
}

static void
_handle_esc_csi_decic(Termpty *ty, Eina_Unicode **b)
{
   int arg = _csi_arg_get(ty, b);
   int old_insert = ty->termstate.insert;
   Eina_Unicode blank[1] = { ' ' };
   int top = 0;
   int bottom = ty->h;
   int old_cx = ty->cursor_state.cx;
   int old_cy = ty->cursor_state.cy;

   DBG("DECIC Insert %d Column", arg);

   if (arg == -CSI_ARG_ERROR)
     return;
   if (arg < 1)
     arg = 1;
   if (ty->termstate.top_margin > 0)
     {
        if (ty->cursor_state.cy < ty->termstate.top_margin)
          return;
        top = ty->termstate.top_margin;
     }
   if (ty->termstate.bottom_margin != 0)
     {
        if (ty->cursor_state.cy >= ty->termstate.bottom_margin)
          return;
        bottom = ty->termstate.bottom_margin;
     }

   if (((ty->termstate.left_margin > 0)
        && (ty->cursor_state.cx < ty->termstate.left_margin))
       || ((ty->termstate.right_margin > 0)
           && (ty->cursor_state.cx >= ty->termstate.right_margin)))
     return;

   ty->termstate.insert = 1;
   for (; top < bottom; top++)
     {
        int i;

        /* Insert a left column */
        ty->cursor_state.cy = top;
        ty->cursor_state.cx = old_cx;
        ty->termstate.wrapnext = 0;
        for (i = 0; i < arg; i++)
          termpty_text_append(ty, blank, 1);
     }
   ty->termstate.insert = old_insert;
   ty->cursor_state.cx = old_cx;
   ty->cursor_state.cy = old_cy;
}

static void
_handle_esc_csi_decdc(Termpty *ty, Eina_Unicode **b)
{
   int arg = _csi_arg_get(ty, b);
   int y = 0;
   int max_y = ty->h;
   int max_x = ty->w;
   int lim;

   DBG("DECDC Delete %d Column", arg);

   if (arg == -CSI_ARG_ERROR)
     return;
   if (arg < 1)
     arg = 1;
   if (ty->termstate.top_margin > 0)
     {
        if (ty->cursor_state.cy < ty->termstate.top_margin)
          return;
        y = ty->termstate.top_margin;
     }
   if (ty->termstate.bottom_margin != 0)
     {
        if (ty->cursor_state.cy >= ty->termstate.bottom_margin)
          return;
        max_y = ty->termstate.bottom_margin;
     }

   if (ty->termstate.right_margin > 0)
     {
        if (ty->cursor_state.cx >= ty->termstate.right_margin)
          return;
        max_x = ty->termstate.right_margin;
     }

   if (((ty->termstate.left_margin > 0)
        && (ty->cursor_state.cx < ty->termstate.left_margin)))
     return;

   TERMPTY_RESTRICT_FIELD(arg, 1, max_x + 1);
   lim = max_x - arg;
   for (; y < max_y; y++)
     {
        int x;
        Termcell *cells = &(TERMPTY_SCREEN(ty, 0, y));

        for (x = ty->cursor_state.cx; x < max_x; x++)
          {
             if (x < lim)
               TERMPTY_CELL_COPY(ty, &(cells[x + arg]), &(cells[x]), 1);
             else
               {
                  cells[x].codepoint = ' ';
                  if (EINA_UNLIKELY(cells[x].att.link_id))
                    term_link_refcount_dec(ty, cells[x].att.link_id, 1);
                  cells[x].att = ty->termstate.att;
                  cells[x].att.link_id = 0;
                  cells[x].att.dblwidth = 0;
               }
          }
     }
}

static void
_handle_esc_csi_ich(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode blank[1] = { ' ' };
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);
   int i;
   int old_insert = ty->termstate.insert;
   int old_cx = ty->cursor_state.cx;
   int max = ty->w;

   if (arg == -CSI_ARG_ERROR)
     return;
   TERMPTY_RESTRICT_FIELD(arg, 1, ty->w * ty->h);

   DBG("ICH - Insert %d Characters", arg);

   if (ty->termstate.lr_margins)
     {
        if ((ty->termstate.left_margin)
            && (ty->cursor_state.cx < ty->termstate.left_margin))
          {
             return;
          }
        if (ty->termstate.right_margin)
          {
             if (ty->cursor_state.cx >= ty->termstate.right_margin)
               {
                  return;
               }
             max = ty->termstate.right_margin;
          }
     }

   if (ty->cursor_state.cx + arg > max)
     {
        arg = max - ty->cursor_state.cx;
     }

   ty->termstate.wrapnext = 0;
   ty->termstate.insert = 1;
   for (i = 0; i < arg; i++)
     termpty_text_append(ty, blank, 1);
   ty->termstate.insert = old_insert;
   ty->cursor_state.cx = old_cx;
}

static void
_handle_esc_csi_cuu(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);

   if (arg == -CSI_ARG_ERROR)
     return;
   if (arg < 1)
     arg = 1;
   DBG("CUU - Cursor Up %d", arg);
   ty->termstate.wrapnext = 0;
   ty->cursor_state.cy = MAX(0, ty->cursor_state.cy - arg);
   TERMPTY_RESTRICT_FIELD(ty->cursor_state.cy, 0, ty->h);
   if (ty->termstate.restrict_cursor && (ty->termstate.top_margin > 0)
       && (ty->cursor_state.cy < ty->termstate.top_margin))
     {
        ty->cursor_state.cy = ty->termstate.top_margin;
     }
}

static void
_handle_esc_csi_cud_or_vpr(Termpty *ty, Eina_Unicode **ptr,
                           const Eina_Unicode *cc)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);

   if (arg == -CSI_ARG_ERROR)
     return;

   if (arg < 1)
     arg = 1;

   if (*cc == 'e')
     {
        DBG("VPR - Vertical Position Relative: %d", arg);
     }
   else
     {
        DBG("CUD - Cursor Down: %d", arg);
     }

   ty->termstate.wrapnext = 0;
   ty->cursor_state.cy = MIN(ty->h - 1, ty->cursor_state.cy + arg);
   TERMPTY_RESTRICT_FIELD(ty->cursor_state.cy, 0, ty->h);
   if (ty->termstate.restrict_cursor && (ty->termstate.bottom_margin > 0)
       && (ty->cursor_state.cy >= ty->termstate.bottom_margin))
     {
        ty->cursor_state.cy = ty->termstate.bottom_margin - 1;
     }
}

static void
_handle_esc_csi_cuf(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);

   if (arg == -CSI_ARG_ERROR)
     return;
   if (arg < 1)
     arg = 1;
   DBG("CUF - Cursor Forward %d", arg);
   ty->termstate.wrapnext = 0;
   ty->cursor_state.cx += arg;
   TERMPTY_RESTRICT_FIELD(ty->cursor_state.cx, 0, ty->w);
   if (ty->termstate.restrict_cursor && (ty->termstate.right_margin != 0)
       && (ty->cursor_state.cx >= ty->termstate.right_margin))
     {
        ty->cursor_state.cx = ty->termstate.right_margin - 1;
     }
}

static void
_handle_esc_csi_cub(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);

   if (arg == -CSI_ARG_ERROR)
     return;
   if (arg < 1)
     arg = 1;
   DBG("CUB - Cursor Backward %d", arg);
   ty->termstate.wrapnext = 0;
   ty->cursor_state.cx -= arg;
   TERMPTY_RESTRICT_FIELD(ty->cursor_state.cx, 0, ty->w);
   if (ty->termstate.restrict_cursor && (ty->termstate.left_margin != 0)
       && (ty->cursor_state.cx < ty->termstate.left_margin))
     {
        ty->cursor_state.cx = ty->termstate.left_margin;
     }
}

static void
_handle_esc_csi_cha(Termpty *ty, Eina_Unicode **ptr,
                    const Eina_Unicode *cc)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);
   int min = 0;
   int max = ty->w;

   if (*cc == '`')
     {
        DBG("HPA - Horizontal Position Absolute: %d", arg);
     }
   else
     {
        DBG("CHA - Cursor Horizontal Absolute: %d", arg);
     }
   if (arg == -CSI_ARG_ERROR)
     return;
   if (arg < 1)
     arg = 1;
   ty->termstate.wrapnext = 0;
   if (ty->termstate.restrict_cursor)
     {
        if (ty->termstate.left_margin)
          {
             arg += ty->termstate.left_margin;
          }
        if (ty->termstate.right_margin)
          {
             max = ty->termstate.right_margin;
          }
     }
   ty->cursor_state.cx = arg - 1;
   TERMPTY_RESTRICT_FIELD(ty->cursor_state.cx, min, max);
}

static void
_handle_esc_csi_cht(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);

   if (arg == -CSI_ARG_ERROR)
     return;
   TERMPTY_RESTRICT_FIELD(arg, 1, ty->w);
   DBG("CHT - Cursor Forward Tabulation: %d", arg);
   _tab_forward(ty, arg);
}

static void
_handle_esc_csi_ed(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);

   if (arg == -CSI_ARG_ERROR)
     return;
   if (arg < 1)
     arg = 0;
   /* 3J erases the backlog,
    * 2J erases the screen,
    * 1J erase from screen start to cursor,
    * 0J erase form cursor to end of screen
    */
   DBG("ED/DECSED %d: erase in display", arg);
   switch (arg)
     {
      case TERMPTY_CLR_END /* 0 */:
      case TERMPTY_CLR_BEGIN /* 1 */:
      case TERMPTY_CLR_ALL /* 2 */:
         termpty_clear_screen(ty, arg);
         break;
      case 3:
         termpty_clear_backlog(ty);
         break;
      default:
         ERR("invalid EL/DECSEL argument %d", arg);
         ty->decoding_error = EINA_TRUE;
     }
   TERMPTY_RESTRICT_FIELD(arg, 1, ty->w);
}

static void
_handle_esc_csi_decsed(Termpty *ty, Eina_Unicode **ptr)
{
   WRN("DECSED - Selective Erase in Display: Unsupported");
   _handle_esc_csi_ed(ty, ptr);
}

static void
_handle_esc_csi_el(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);

   if (arg == -CSI_ARG_ERROR)
     return;
   if (arg < 1)
     arg = 0;
   DBG("EL - Erase in Line: %d", arg);
   switch (arg)
     {
      case TERMPTY_CLR_END:
      case TERMPTY_CLR_BEGIN:
      case TERMPTY_CLR_ALL:
         termpty_clear_line(ty, arg, ty->w);
         break;
      default:
         ERR("invalid EL/DECSEL argument %d", arg);
         ty->decoding_error = EINA_TRUE;
     }
}

static void
_handle_esc_csi_decsel(Termpty *ty, Eina_Unicode **ptr)
{
   WRN("DECSEL - Selective Erase in Line: Unsupported");
   _handle_esc_csi_el(ty, ptr);
}

static void
_handle_esc_csi_il(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);
   int sy1, sy2, i;

   if (arg == -CSI_ARG_ERROR)
     return;

   TERMPTY_RESTRICT_FIELD(arg, 1, ty->h);
   DBG("IL - Insert Lines: %d", arg);

   if (!_cursor_is_within_margins(ty))
     return;

   sy1 = ty->termstate.top_margin;
   sy2 = ty->termstate.bottom_margin;
   if (ty->termstate.bottom_margin == 0)
     {
        ty->termstate.top_margin = ty->cursor_state.cy;
        ty->termstate.bottom_margin = ty->h;
     }
   else
     {
        ty->termstate.top_margin = ty->cursor_state.cy;
        if (ty->termstate.bottom_margin <= ty->termstate.top_margin)
          ty->termstate.bottom_margin = ty->termstate.top_margin + 1;
     }
   for (i = 0; i < arg; i++)
     {
        termpty_text_scroll_rev(ty, EINA_TRUE);
     }
   ty->termstate.top_margin = sy1;
   ty->termstate.bottom_margin = sy2;
   ty->cursor_state.cx = ty->termstate.left_margin;
}

static void
_handle_esc_csi_dl(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);
   int sy1, sy2, i;

   if (arg == -CSI_ARG_ERROR)
     return;

   TERMPTY_RESTRICT_FIELD(arg, 1, ty->h);
   DBG("DL - Delete Lines: %d", arg);

   if (!_cursor_is_within_margins(ty))
     return;

   sy1 = ty->termstate.top_margin;
   sy2 = ty->termstate.bottom_margin;
   if (ty->termstate.bottom_margin == 0)
     {
        ty->termstate.top_margin = ty->cursor_state.cy;
        ty->termstate.bottom_margin = ty->h;
     }
   else
     {
        ty->termstate.top_margin = ty->cursor_state.cy;
        if (ty->termstate.bottom_margin <= ty->termstate.top_margin)
          ty->termstate.bottom_margin = ty->termstate.top_margin + 1;
     }
   for (i = 0; i < arg; i++)
     {
        termpty_text_scroll(ty, EINA_TRUE);
     }
   ty->termstate.top_margin = sy1;
   ty->termstate.bottom_margin = sy2;
   ty->cursor_state.cx = ty->termstate.left_margin;
}

static void
_handle_esc_csi_su(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);
   int i;

   if (arg == -CSI_ARG_ERROR)
     return;

   TERMPTY_RESTRICT_FIELD(arg, 1, ty->h);
   DBG("SU - Scroll Up: %d", arg);
   for (i = 0; i < arg; i++)
     termpty_text_scroll(ty, EINA_TRUE);
}

static void
_handle_esc_csi_sd(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);
   int i;

   if (arg == -CSI_ARG_ERROR)
     return;
   if (arg == 0)
     {
        WRN("Track Mouse: TODO");
        return;
     }

   TERMPTY_RESTRICT_FIELD(arg, 1, ty->h);
   DBG("SD - Scroll Down: %d", arg);
   for (i = 0; i < arg; i++)
     termpty_text_scroll_rev(ty, EINA_TRUE);
}

static void
_handle_xterm_unset_title_modes(Termpty *ty EINA_UNUSED,
                                Eina_Unicode **ptr EINA_UNUSED,
                                const Eina_Unicode * const end EINA_UNUSED)
{
   DBG("Unset Title Modes: TODO");
}

static void
_handle_sixel_regis_graphics_attributes(Termpty *ty EINA_UNUSED,
                                        Eina_Unicode **ptr EINA_UNUSED)
{
   DBG("Sixel/ReGIS Graphics Attributes: TODO");
}

static void
_handle_esc_csi_decst8c(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);
   int i;

   if (arg == -CSI_ARG_ERROR)
     return;
   if ((arg != -CSI_ARG_NO_VALUE) && (arg != 5))
     {
        ERR("Invalid DECST8C argument");
        ty->decoding_error = EINA_TRUE;
        return;
     }

   DBG("DECST8C - Set Tab at Every 8 Columns: %d", arg);
   termpty_clear_tabs_on_screen(ty);
   for (i = 0; i < ty->w; i += TAB_WIDTH)
     {
        TAB_SET(ty, i);
     }
}

static void
_handle_esc_csi_ctc(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);

   if (arg == -CSI_ARG_ERROR)
     return;

   DBG("CTC - Cursor Tab Control: %d", arg);
   switch (arg)
     {
      case -CSI_ARG_NO_VALUE:
         EINA_FALLTHROUGH;
      case 0:
        TAB_SET(ty, ty->cursor_state.cx);
        break;
      case 2:
        TAB_UNSET(ty, ty->cursor_state.cx);
        break;
      case 4:
        EINA_FALLTHROUGH;
      case 5:
        termpty_clear_tabs_on_screen(ty);
        break;
      default:
         ERR("invalid CTC argument %d", arg);
         ty->decoding_error = EINA_TRUE;
     }
}

static void
_handle_esc_csi_tbc(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);

   if (arg == -CSI_ARG_ERROR)
     return;
   DBG("TBC - Tab Clear: %d", arg);
   switch (arg)
     {
      case -CSI_ARG_NO_VALUE:
         EINA_FALLTHROUGH;
      case 0:
        TAB_UNSET(ty, ty->cursor_state.cx);
        break;
      case 2:
         EINA_FALLTHROUGH;
      case 3:
         EINA_FALLTHROUGH;
      case 5:
        termpty_clear_tabs_on_screen(ty);
        break;
      default:
        ERR("Tabulation Clear (TBC) with invalid argument: %d", arg);
        ty->decoding_error = EINA_TRUE;
     }
}

static void
_handle_esc_csi_ech(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);

   if (arg == -CSI_ARG_ERROR)
     return;
   DBG("ECH - Erase Character: %d", arg);
   TERMPTY_RESTRICT_FIELD(arg, 1, ty->w);
   termpty_clear_line(ty, TERMPTY_CLR_END, arg);
}

static void
_handle_esc_csi_cbt(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int cx = ty->cursor_state.cx;
   int arg = _csi_arg_get(ty, &b);

   if (arg == -CSI_ARG_ERROR)
     return;
   DBG("CBT - Cursor Horizontal Backward Tabulation: %d", arg);

   TERMPTY_RESTRICT_FIELD(arg, 1, ty->w);
   for (; arg > 0; arg--)
     {
        do
          {
             cx--;
          }
        while ((cx >= 0) && (!TAB_TEST(ty, cx)));
     }

   ty->cursor_state.cx = cx;
   TERMPTY_RESTRICT_FIELD(ty->cursor_state.cx, 0, ty->w);
}

static void
_handle_esc_csi_rep(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);

   if (arg == -CSI_ARG_ERROR)
     return;
   DBG("REP - Repeat last character %d times", arg);

   if (ty->last_char)
     {
        int screen_size = ty->w * ty->h;
        int i;

        if (arg <= 0)
          {
             arg = 1;
          }
        else if (arg > screen_size)
          {
             /* if value is too large, restrict it to something that makes
              * rendering correct (but not in the backlog, but who cares…)
              */
             arg = screen_size + (arg % screen_size);
          }
        for (i = 0; i < arg; i++)
          {
             termpty_text_append(ty, &ty->last_char, 1);
          }
     }
}

static void
_handle_esc_csi_da(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   char bf[32];
   char start = 'X';
   int arg;
   int len;

   if (b)
     {
        start = *b;
     }
   arg = _csi_arg_get(ty, &b);

   if ((arg == -CSI_ARG_ERROR) || (arg > 0))
     return;

   DBG("DA - Device Attributes");
   switch (start)
     {
      case '=':
        /* Tertiary device attributes
         * Device ID is set to ~~TY in ascii:
         * - '~' is 7E
         * - 'T' is 54
         * - 'Y' is 59
         */
        len = snprintf(bf, sizeof(bf), "\033P!|7E7E5459\033\\");
        break;
      case '>':
        /* Secondary device attributes
         *  0 → VT100
         *  1 → VT220
         *  2 → VT240
         * 18 → VT330
         * 19 → VT340
         * 24 → VT320
         * 41 → VT420
         * 61 → VT510
         * 64 → VT520
         * 65 → VT525
         */
        len = snprintf(bf, sizeof(bf), "\033[>61;337;%ic", 0);
        break;
      default:
        /* Primary device attributes
         * 1       132 columns
         * 2       Printer port
         * 4       Sixel
         * 6       Selective erase
         * 7       Soft character set (DRCS)
         * 8       User-defined keys (UDKs)
         * 9       National replacement character sets (NRCS) (International terminal only)
         * 12      Yugoslavian (SCS)
         * 15      Technical character set
         * 18      Windowing capability
         * 21      Horizontal scrolling
         * 22      Color
         * 23      Greek
         * 24      Turkish
         * 42      ISO Latin-2 character set
         * 44      PCTerm
         * 45      Soft key map
         * 46      ASCII emulation
         */
        len = snprintf(bf, sizeof(bf), "\033[?64;1;9;15;18;21;22c");
     }
   termpty_write(ty, bf, len);
}

static void
_handle_esc_csi_uts(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);

   if (arg == -CSI_ARG_ERROR)
     return;
   DBG("UTS - Unset Tab Stop: %d", arg);
   TERMPTY_RESTRICT_FIELD(arg, 0, ty->w);
   TAB_UNSET(ty, arg);
}

static void
_handle_esc_csi_vpa(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);
   int max = ty->h + 1;

   if (arg == -CSI_ARG_ERROR)
     return;
   DBG("VPA - Cursor Vertical Position Absolute: %d", arg);
   if (ty->termstate.restrict_cursor && (ty->termstate.bottom_margin > 0))
     {
        max = ty->termstate.bottom_margin + 1;
     }
   TERMPTY_RESTRICT_FIELD(arg, 1, max);
   ty->termstate.wrapnext = 0;
   ty->cursor_state.cy = arg - 1;
}

static void
_handle_esc_csi_decswbv(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);

   if (arg == -CSI_ARG_ERROR)
     return;
   DBG("DECSWBV - Set Warning Bell Volume: %d", arg);
   switch (arg)
     {
      case 1:
         DBG("Bell is off");
         break;
      case 2:
         EINA_FALLTHROUGH;
      case 3:
         EINA_FALLTHROUGH;
      case 4:
         DBG("Bell volume is low");
         break;
      default:
         DBG("Bell volume is high");
     }
}

static void
_handle_resize_by_chars(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int w, h;

   h = _csi_arg_get(ty, &b);
   w = _csi_arg_get(ty, &b);

   if ((w == -CSI_ARG_ERROR) || (h == -CSI_ARG_ERROR))
     return;
   if (w == -CSI_ARG_NO_VALUE)
     {
        w = ty->w;
     }
   if (h == -CSI_ARG_NO_VALUE)
     {
        h = ty->h;
     }
   if ((w == ty->w) && (h == ty->h))
     {
        return;
     }
   DBG("Window manipulation: resize to %dx%d", w, h);

   /* ONLY FOR TESTING PURPOSE FTM */
#if defined(ENABLE_TESTS) || defined(ENABLE_TEST_UI)
     {
#if defined(ENABLE_TEST_UI)
        Evas_Object *wn;
        int step_w = 0, step_h = 0, base_w = 0, base_h = 0;

        wn = termio_win_get(ty->obj);
        elm_win_size_base_get(wn, &base_w, &base_h);
        elm_win_size_step_get(wn, &step_w, &step_h);
        evas_object_resize(wn,
                           base_w + step_w * w,
                           base_h + step_h * h);
#else
        tytest_termio_resize(w, h);
#endif
        termpty_resize(ty, w, h);
     }
#endif
}

static void
_handle_window_manipulation(Termpty *ty, Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int arg = _csi_arg_get(ty, &b);

   if (arg == -CSI_ARG_ERROR)
     return;
   DBG("Window manipulation: %d", arg);
   switch (arg)
     {
      case 8:
         _handle_resize_by_chars(ty, &b);
         break;
      default:
        // many others
        WRN("unhandled window manipulation %d", arg);
        ty->decoding_error = EINA_TRUE;
        break;
     }
}

static int
_handle_esc_csi(Termpty *ty, const Eina_Unicode *c, const Eina_Unicode *ce)
{
   const Eina_Unicode *cc, *be;
   Eina_Unicode buf[4096], *b;

   cc = (Eina_Unicode *)c;
   b = buf;
   be = buf + sizeof(buf) / sizeof(buf[0]);
   while ((cc < ce) && (*cc <= '?') && (b < be))
     {
        _handle_cursor_control(ty, cc);
        *b = *cc;
        b++;
        cc++;
     }
   if (b == be)
     {
        ERR("csi parsing overflowed, skipping the whole buffer (binary data?)");
        return cc - c;
     }
   if (cc == ce) return 0;
   *b = 0;
   be = b;
   b = buf;
   DBG(" CSI: '%s' args '%s'", _safechar(*cc), (char *) buf);
   switch (*cc)
     {
        /* sorted by ascii value */
      case '@':
         /* TODO: SL */
         _handle_esc_csi_ich(ty, &b);
        break;
      case 'A':
        /* TODO: SR */
         _handle_esc_csi_cuu(ty, &b);
        break;
      case 'B':
        _handle_esc_csi_cud_or_vpr(ty, &b, cc);
        break;
      case 'C':
        _handle_esc_csi_cuf(ty, &b);
        break;
      case 'D':
        _handle_esc_csi_cub(ty, &b);
        break;
      case 'E':
        _handle_esc_csi_cnl(ty, &b);
        break;
      case 'F':
        _handle_esc_csi_cpl(ty, &b);
        break;
      case 'G':
        _handle_esc_csi_cha(ty, &b, cc);
        break;
      case 'H':
        _handle_esc_csi_cursor_pos_set(ty, &b, cc);
        break;
      case 'I':
        _handle_esc_csi_cht(ty, &b);
        break;
      case 'J':
        if (*b == '?')
          _handle_esc_csi_decsed(ty, &b);
        else
          _handle_esc_csi_ed(ty, &b);
        break;
      case 'K':
        if (*b == '?')
          _handle_esc_csi_decsel(ty, &b);
        else
          _handle_esc_csi_el(ty, &b);
        break;
      case 'L':
        _handle_esc_csi_il(ty, &b);
        break;
      case 'M':
        _handle_esc_csi_dl(ty, &b);
        break;
      case 'P':
        _handle_esc_csi_dch(ty, &b);
        break;
      case 'S':
        if (*b == '?')
          _handle_sixel_regis_graphics_attributes(ty, &b);
        else
          _handle_esc_csi_su(ty, &b);
        break;
      case 'T':
        if (*b == '?')
          _handle_xterm_unset_title_modes(ty, &b, be);
        else
          _handle_esc_csi_sd(ty, &b);
        break;
      case 'W':
        if (*b == '?')
          _handle_esc_csi_decst8c(ty, &b);
        else
          _handle_esc_csi_ctc(ty, &b);
        break;
      case 'X':
        _handle_esc_csi_ech(ty, &b);
        break;
      case 'Z':
        _handle_esc_csi_cbt(ty, &b);
        break;
      case '`':
        _handle_esc_csi_cha(ty, &b, cc);
        break;
      case 'a':
        _handle_esc_csi_cuf(ty, &b);
        break;
      case 'b':
        _handle_esc_csi_rep(ty, &b);
        break;
      case 'c':
        _handle_esc_csi_da(ty, &b);
        break;
      case 'd':
        if (*(cc-1) == ' ')
          _handle_esc_csi_uts(ty, &b);
        else
          _handle_esc_csi_vpa(ty, &b);
        break;
      case 'e':
        _handle_esc_csi_cud_or_vpr(ty, &b, cc);
        break;
      case 'f':
        _handle_esc_csi_cursor_pos_set(ty, &b, cc);
       break;
      case 'g':
        _handle_esc_csi_tbc(ty, &b);
        break;
      case 'h':
        _handle_esc_csi_reset_mode(ty, *cc, b, be);
        break;
      case 'i':
        WRN("TODO: Media Copy (?:%s)", (*b == '?') ? "yes": "no");
        ty->decoding_error = EINA_TRUE;
        break;
      case 'j':
        _handle_esc_csi_cub(ty, &b);
        break;
      case 'k':
        _handle_esc_csi_cuu(ty, &b);
        break;
      case 'l':
        _handle_esc_csi_reset_mode(ty, *cc, b, be);
        break;
      case 'm': // color set
        _handle_esc_csi_color_set(ty, &b, be);
        break;
      case 'n':
        _handle_esc_csi_dsr(ty, b);
        break;
      case 'p': // define key assignments based on keycode
        if (b && *b == '!')
          {
             DBG("soft reset (DECSTR)");
             termpty_soft_reset_state(ty);
          }
        else
          {
             goto unhandled;
          }
        break;
      case 'q':
        if (*(cc-1) == ' ')
          _handle_esc_csi_decscusr(ty, &b);
        else if (*(cc-1) == '"')
          {
             WRN("TODO: select character protection attribute (DECSCA)");
             ty->decoding_error = EINA_TRUE;
          }
        else
          {
             WRN("TODO: Load LEDs (DECLL)");
             ty->decoding_error = EINA_TRUE;
          }
        break;
      case 'r':
        if (*(cc-1) == '$')
          _handle_esc_csi_deccara(ty, &b, be-1);
        else
          _handle_esc_csi_decstbm(ty, &b);
        break;
      case 's':
        if (ty->termstate.lr_margins)
          {
            _handle_esc_csi_decslrm(ty, &b);
          }
        else
          {
            DBG("SCOSC: Save Current Cursor Position");
            termpty_cursor_copy(ty, EINA_TRUE);
          }
        break;
      case 't':
        if (*(cc-1) == '$')
          _handle_esc_csi_decrara(ty, &b, be-1);
        else if (*(cc-1) == ' ')
          {
             _handle_esc_csi_decswbv(ty, &b);
          }
        else
          {
             _handle_window_manipulation(ty, &b);
          }
        break;
      case 'u': // restore cursor pos
        termpty_cursor_copy(ty, EINA_FALSE);
        break;
      case 'v':
        if (*(cc-1) == '$')
          _handle_esc_csi_deccra(ty, &b);
        else
          {
             ERR("unhandled 'v' CSI escape code");
             ty->decoding_error = EINA_TRUE;
          }
        break;
      case 'x':
        if (*(cc-1) == '$')
          _handle_esc_csi_decfra(ty, &b);
        else if (*(cc-1) == '*')
          _handle_esc_csi_decsace(ty, &b);
        else
          {
             ERR("unhandled 'x' CSI escape code");
             ty->decoding_error = EINA_TRUE;
          }
        break;
      case 'z':
        if (*(cc-1) == '$')
          _handle_esc_csi_decera(ty, &b);
        else
          {
             ERR("unhandled 'z' CSI escape code");
             ty->decoding_error = EINA_TRUE;
          }
        break;
      case '}':
        if (*(cc-1) == '\'')
          _handle_esc_csi_decic(ty, &b);
        else
          {
             ERR("unhandled '}' CSI escape code");
             ty->decoding_error = EINA_TRUE;
          }
        break;
      case '~':
        if (*(cc-1) == '\'')
          _handle_esc_csi_decdc(ty, &b);
        else
          {
             ERR("unhandled '~' CSI escape code");
             ty->decoding_error = EINA_TRUE;
          }
        break;
      default:
        ERR("unhandled '0x%x' CSI escape code", *cc);
        goto unhandled;
     }
   cc++;
   return cc - c;
unhandled:
#if !defined(ENABLE_FUZZING) && !defined(ENABLE_TESTS)
   if (eina_log_domain_level_check(_termpty_log_dom, EINA_LOG_LEVEL_WARN))
     {
        int i;
        Eina_Strbuf *bf = eina_strbuf_new();

        for (i = 0; c + i <= cc && i < 100; i++)
          {
             if ((c[i] < ' ') || (c[i] >= 0x7f))
               eina_strbuf_append_printf(bf, "\033[35m%08x\033[0m",
                                         (unsigned int) c[i]);
             else
               eina_strbuf_append_char(bf, c[i]);
          }
        WRN("unhandled CSI '%s': %s", _safechar(*cc), eina_strbuf_string_get(bf));
        eina_strbuf_free(bf);
     }
#endif
   ty->decoding_error = EINA_TRUE;
   cc++;
   return cc - c;
}

static int
_osc_arg_get(Eina_Unicode **ptr)
{
   Eina_Unicode *b = *ptr;
   int sum = 0;

   while (*b >= '0' && *b <= '9')
     {
        sum *= 10;
        sum += *b - '0';
        b++;
     }
   if (*b != ';')
     sum = -1;
   else
     b++;
   *ptr = b;
   return sum;
}

static int
_eina_unicode_to_hex(Eina_Unicode u)
{
   if (u >= '0' && u <= '9')
     return u - '0';
   if (u >= 'a' && u <= 'f')
     return 10 + u - 'a';
   if (u >= 'A' && u <= 'F')
     return 10 + u - 'A';
   return -1;
}

#if !defined(HAVE_STRCHRNUL)
char *
strchrnul(const char *s, int c)
{
   const char *p = s;

   while (*p)
     {
        if (*p == c)
          return (char *)p;

        ++p;
     }
   return (char *)  (p);
}
#endif

static int
_xterm_parse_color(Termpty *ty, Eina_Unicode **ptr,
                   unsigned char *r, unsigned char *g, unsigned char *b,
                   int len)
{
   Eina_Unicode *p = *ptr;
   int i;

   if (*p != '#')
     {
        WRN("unsupported xterm color");
        ty->decoding_error = EINA_TRUE;
        return -1;
     }
   p++;
   len--;
   if (len == 7)
     {
        i = _eina_unicode_to_hex(p[0]);
        if (i < 0) goto err;
        *r = i;
        i = _eina_unicode_to_hex(p[1]);
        if (i < 0) goto err;
        *r = *r * 16 + i;

        i = _eina_unicode_to_hex(p[2]);
        if (i < 0) goto err;
        *g = i;
        i = _eina_unicode_to_hex(p[3]);
        if (i < 0) goto err;
        *g = *g * 16 + i;

        i = _eina_unicode_to_hex(p[4]);
        if (i < 0) goto err;
        *b = i;
        i = _eina_unicode_to_hex(p[5]);
        if (i < 0) goto err;
        *b = *b * 16 + i;
     }
   else if (len == 4)
     {
        i = _eina_unicode_to_hex(p[0]);
        if (i < 0) goto err;
        *r = i;
        i = _eina_unicode_to_hex(p[1]);
        if (i < 0) goto err;
        *g = i;
        i = _eina_unicode_to_hex(p[2]);
        if (i < 0) goto err;
        *b = i;
     }
   else
     {
        goto err;
     }

   return 0;

err:
   WRN("invalid xterm color");
   ty->decoding_error = EINA_TRUE;
   return -1;
}

static void
_handle_hyperlink(Termpty *ty,
                  char *s,
                  int len)
{
    const char *url = NULL;
    const char *key = NULL;
    Term_Link *hl = NULL;

    if (!s || len <= 0)
      {
         ERR("invalid hyperlink escape code (len:%d s:%p)",
             len, s);
         ty->decoding_error = EINA_TRUE;
         return;
      }

    if (len == 1 && *s == ';')
      {
         /* Closing escape code */
         if (ty->termstate.att.link_id)
           {
              ty->termstate.att.link_id = 0;
           }
         else
           {
              ERR("invalid hyperlink escape code: no hyperlink to close"
                  " (len:%d s:%.*s)", len, len, s);
              ty->decoding_error = EINA_TRUE;
           }
         goto end;
      }

    if (*s != ';')
      {
         /* Parse parameters */
         char *end;

         /* /!\ we expect ';' and ':' to be escaped in params */
         end = memchr(s+1, ';', len);
         if (!end)
           {
              ERR("invalid hyperlink escape code: missing ';'"
                  " (len:%d s:%.*s)", len, len, s);
              ty->decoding_error = EINA_TRUE;
              goto end;
           }
         *end = '\0';
         do
           {
              char *end_param;

              end_param = strchrnul(s, ':');

              if (len > 3 && strncmp(s, "id=", 3) == 0)
                {
                   eina_stringshare_del(key);

                   s += 3;
                   len -= 3;
                   key = eina_stringshare_add_length(s, end_param - s);
                }
              len -= end_param - s;
              s = end_param;
              if (*end_param)
                {
                   s++;
                   len--;
                }
           }
         while (s < end);
         *end = ';';
      }
    s++;
    len--;

    url = eina_stringshare_add_length(s, len);
    if (!url)
      goto end;

    hl = term_link_new(ty);
    if (!hl)
      goto end;
    hl->key = key;
    hl->url = url;
    key = NULL;
    url = NULL;

    ty->termstate.att.link_id = hl - ty->hl.links;
    hl = NULL;

end:
    term_link_free(ty, hl);
    eina_stringshare_del(url);
    eina_stringshare_del(key);
}

static void
_handle_xterm_50_command(Termpty *ty,
                         char *s,
                         int len)
{
  int pattern_len = strlen(":size=");
  while (len > pattern_len)
    {
       if (strncmp(s, ":size=", pattern_len) == 0)
         {
            char *endptr = NULL;
            int size;

            s += pattern_len;
            errno = 0;
            size = strtol(s, &endptr, 10);
            if (endptr != s && errno == 0)
               termio_font_size_set(ty->obj, size);
         }
       len--;
       s++;
    }
}

static void
_handle_xterm_777_command(Termpty *ty,
                          char *s, int _len EINA_UNUSED)
{
   char *cmd_end = NULL,
        *title = NULL,
        *title_end = NULL,
        *message = NULL;

   if (strncmp(s, "notify;", strlen("notify;")))
     {
        WRN("unrecognized xterm 777 command %s", s);
        ty->decoding_error = EINA_TRUE;
        return;
     }

   if (!elm_need_sys_notify())
     {
        WRN("no elementary system notification support");
        return;
     }
   cmd_end = s + strlen("notify");
   if (*cmd_end != ';')
     return;
   *cmd_end = '\0';
   title = cmd_end + 1;
   title_end = strchr(title, ';');
   if (!title_end)
     {
        *cmd_end = ';';
        return;
     }
   *title_end = '\0';
   message = title_end + 1;

   elm_sys_notify_send(0, "dialog-information", title, message,
                       ELM_SYS_NOTIFY_URGENCY_NORMAL, -1,
                       NULL, NULL);
   *cmd_end = ';';
   *title_end = ';';
}

static void
_handle_xterm_11_command(Termpty *ty, Eina_Unicode *p)
{
   int r = 0, g = 0, b = 0;
   char buf[32];
   size_t l;

   if (!*p)
     goto err;

   /* only support query mode for the moment */
   if (*p != '?')
     goto err;

   if (termpty_color_class_get(ty, "BG", &r, &g, &b, NULL) != 0)
     {
        ERR("error getting color class 'BG'");
     }
   TERMPTY_WRITE_STR("\033]11;rgb:");
   l = snprintf(buf, sizeof(buf), "%.2x%.2x/%.2x%.2x/%.2x%.2x",
                r, r, g, g, b, b);
   termpty_write(ty, buf, l);
   TERMPTY_WRITE_STR("\033\\");

   return;
err:
   ty->decoding_error = EINA_TRUE;
}

static int
_handle_esc_osc(Termpty *ty, const Eina_Unicode *c, const Eina_Unicode *ce)
{
   const Eina_Unicode *cc, *be;
   Eina_Unicode buf[4096], *p;
   char *s;
   int len = 0;
   int arg;

   cc = c;
   p = buf;
   be = buf + sizeof(buf) / sizeof(buf[0]);
   while ((cc < ce) && (*cc != ST) && (*cc != BEL) && (p < be))
     {
        if ((cc < ce - 1) &&
            (((*cc == ESC) && (*(cc + 1) == '\\')) ||
             (*cc == ST)))
          {
             cc++;
             break;
          }
        *p = *cc;
        p++;
        cc++;
     }
   if (p == be)
     {
        ERR("OSC parsing overflowed, skipping the whole buffer (binary data?)");
        return cc - c;
     }
   *p = '\0';
   p = buf;
   if ((*cc == ST) || (*cc == BEL) || (*cc == '\\'))
     cc++;
   else
     return 0;

   arg = _osc_arg_get(&p);
   switch (arg)
     {
      case -1:
         goto err;
      case 0:
        // title + icon name
        if (!*p)
          goto err;
        s = eina_unicode_unicode_to_utf8(p, &len);
        if (ty->prop.title) eina_stringshare_del(ty->prop.title);
        if (ty->prop.icon) eina_stringshare_del(ty->prop.icon);
        if (s)
          {
             ty->prop.title = eina_stringshare_add(s);
             ty->prop.icon = eina_stringshare_add(s);
             free(s);
          }
        else
          {
             ty->prop.title = NULL;
             ty->prop.icon = NULL;
          }
        if (ty->cb.set_title.func)
          ty->cb.set_title.func(ty->cb.set_title.data);
        if (ty->cb.set_icon.func) ty->cb.set_icon.func(ty->cb.set_icon.data);
        break;
      case 1:
        // icon name
        if (!*p)
          goto err;
        s = eina_unicode_unicode_to_utf8(p, &len);
        if (ty->prop.icon) eina_stringshare_del(ty->prop.icon);
        if (s)
          {
             ty->prop.icon = eina_stringshare_add(s);
             free(s);
          }
        else
          {
             ty->prop.icon = NULL;
          }
        if (ty->cb.set_icon.func) ty->cb.set_icon.func(ty->cb.set_icon.data);
        break;
      case 2:
        // Title
        if (!*p)
          goto err;
        s = eina_unicode_unicode_to_utf8(p, &len);
        if (ty->prop.title) eina_stringshare_del(ty->prop.title);
        if (s)
          {
             ty->prop.title = eina_stringshare_add(s);
             free(s);
          }
        else
          {
             ty->prop.title = NULL;
          }
        if (ty->cb.set_title.func) ty->cb.set_title.func(ty->cb.set_title.data);
        break;
      case 4:
        if (!*p)
          goto err;
        // XXX: set palette entry. not supported.
        ty->decoding_error = EINA_TRUE;
        WRN("set palette, not supported");
        if ((cc - c) < 3)
          return 0;
        break;
      case 8:
        DBG("hyperlink");
        s = eina_unicode_unicode_to_utf8(p, &len);
        _handle_hyperlink(ty, s, len);
        break;
      case 10:
        if (!*p)
          goto err;
        if (*p == '?')
          {
             char bf[7];
             Config *config = termio_config_get(ty->obj);
             TERMPTY_WRITE_STR("\033]10;#");
             snprintf(bf, sizeof(bf), "%.2X%.2X%.2X",
                      config->colors[0].r,
                      config->colors[0].g,
                      config->colors[0].b);
             termpty_write(ty, bf, 6);
             TERMPTY_WRITE_STR("\007");
          }
        else
          {
             unsigned char r, g, b;
             len = cc - c - (p - buf);
             if (_xterm_parse_color(ty, &p, &r, &g, &b, len) < 0)
               goto err;
#if !defined(ENABLE_FUZZING) && !defined(ENABLE_TESTS)
             evas_object_textgrid_palette_set(
                termio_textgrid_get(ty->obj),
                EVAS_TEXTGRID_PALETTE_STANDARD, 0,
                r, g, b, 0xff);
#endif
          }
        break;
      case 11:
        _handle_xterm_11_command(ty, p);
        break;
      case 50:
        DBG("xterm font support");
        if (!*p)
          goto err;
        s = eina_unicode_unicode_to_utf8(p, &len);
        if (s)
          {
             _handle_xterm_50_command(ty, s, len);
             free(s);
          }
        break;
      case 110:
        DBG("Reset VT100 text foreground color");
        break;
      case 111:
        DBG("Reset VT100 text background color");
        break;
      case 112:
        DBG("Reset text cursor color");
        break;
      case 113:
        DBG("Reset mouse foreground color");
        break;
      case 114:
        DBG("Reset mouse background color");
        break;
      case 115:
        DBG("Reset Tektronix foreground color");
        break;
      case 116:
        DBG("Reset Tektronix background color");
        break;
      case 117:
        DBG("Reset highlight color");
        break;
      case 118:
        DBG("Reset Tektronix cursor color");
        break;
      case 119:
        DBG("Reset highlight foreground color");
        break;
      case 777:
        DBG("xterm notification support");
        s = eina_unicode_unicode_to_utf8(p, &len);
        if (s)
          {
             _handle_xterm_777_command(ty, s, len);
             free(s);
          }
        break;
      default:
        // many others
        WRN("unhandled xterm esc %d", arg);
        ty->decoding_error = EINA_TRUE;
        break;
     }

    return cc - c;
err:
    WRN("invalid xterm sequence");
    ty->decoding_error = EINA_TRUE;
    return cc - c;
}

static int
_handle_esc_terminology(Termpty *ty, const Eina_Unicode *c, const Eina_Unicode *ce)
{
   Eina_Unicode *cc, *cc_zero = NULL;
   const Eina_Unicode *buf;
   char *cmd;
   size_t blen = 0;
   Config *config;

   if (!ty->buf_have_zero)
     return 0;

   config = termio_config_get(ty->obj);

   cc = (Eina_Unicode *)c;
   if ((cc < ce) && (*cc == 0x0))
     cc_zero = cc;
   while ((cc < ce) && (*cc != 0x0))
     {
        blen++;
        cc++;
     }
   if ((cc < ce) && (*cc == 0x0))
     cc_zero = cc;
   if (!cc_zero)
     return 0;
   buf = (Eina_Unicode *)c;
   cc = cc_zero;

   // commands are stored in the buffer, 0 bytes not allowed (end marker)
   cmd = eina_unicode_unicode_to_utf8(buf, NULL);
   ty->cur_cmd = cmd;
   if ((!config->ty_escapes) || (!termpty_ext_handle(ty, buf, blen)))
     {
        if (ty->cb.command.func)
          ty->cb.command.func(ty->cb.command.data);
     }
   ty->cur_cmd = NULL;
   free(cmd);

   assert((size_t)(cc - c) == blen);

   return cc - c;
}

static int
_handle_esc_dcs(Termpty *ty,
                const Eina_Unicode *c,
                const Eina_Unicode *ce)
{
   const Eina_Unicode *cc, *be;
   Eina_Unicode buf[4096], *b;
   int len = 0;

   cc = c;
   b = buf;
   be = buf + sizeof(buf) / sizeof(buf[0]);
   while ((cc < ce) && (*cc != ST) && (b < be))
     {
        if ((cc < ce - 1) &&
            (((*cc == ESC) && (*(cc + 1) == '\\')) ||
             (*cc == ST)))
          {
             cc++;
             break;
          }
        *b = *cc;
        b++;
        cc++;
     }
   if (b == be)
     {
        ERR("dcs parsing overflowed, skipping the whole buffer (binary data?)");
        len = cc - c;
        goto end;
     }
   *b = 0;
   if ((*cc == ST) || (*cc == '\\')) cc++;
   else return 0;
   len = cc - c;
   switch (buf[0])
     {
      case '+':
         if (len < 4)
           goto end;
         switch (buf[1])
           {
            case 'q':
              WRN("unhandled dsc request to get termcap/terminfo");
              ty->decoding_error = EINA_TRUE;
              /* TODO */
              goto end;
               break;
            case 'p':
              WRN("unhandled dsc request to set termcap/terminfo");
              ty->decoding_error = EINA_TRUE;
              /* TODO */
              goto end;
               break;
            default:
              ERR("invalid dsc request about termcap/terminfo");
              ty->decoding_error = EINA_TRUE;
              goto end;
           }
         break;
      case '$':
         /* Request status string */
         if (len > 1 && buf[1] != 'q')
           {
              WRN("invalid/unhandled dsc esc '$%s' (expected '$q')", _safechar(buf[1]));
              ty->decoding_error = EINA_TRUE;
              goto end;
           }
         if (len < 4)
           goto end;
         switch (buf[2])
           {
            case '"':
               if (buf[3] == 'p') /* DECSCL */
                 {
                    char bf[32];
                    snprintf(bf, sizeof(bf), "\033P1$r64;1\"p\033\\");
                    termpty_write(ty, bf, strlen(bf));
                 }
               else if (buf[3] == 'q') /* DECSCA */
                 {
                    WRN("unhandled DECSCA '$qq'");
                    ty->decoding_error = EINA_TRUE;
                    goto end;
                 }
               else
                 {
                    WRN("invalid/unhandled dsc esc '$q\"%s'", _safechar(buf[3]));
                    ty->decoding_error = EINA_TRUE;
                    goto end;
                 }
               break;
            case 'm': /* SGR */
               /* TODO: */
            case 'r': /* DECSTBM */
               /* TODO: */
            default:
               ty->decoding_error = EINA_TRUE;
               WRN("unhandled dsc request status string '$q%s'", _safechar(buf[2]));
               goto end;
           }
         break;
      default:
        // many others
        WRN("Unhandled DCS escape '%s'", _safechar(buf[0]));
        ty->decoding_error = EINA_TRUE;
        break;
     }
end:
   return len;
}

static void
_handle_decaln(Termpty *ty)
{
   int size;
   Termcell *cells;

   DBG("DECALN - fill screen with E");
   ty->termstate.top_margin = 0;
   ty->termstate.bottom_margin = 0;
   ty->termstate.left_margin = 0;
   ty->termstate.right_margin = 0;
   ty->termstate.had_cr_x = 0;
   ty->termstate.had_cr_y = 0;
   ty->cursor_state.cx = 0;
   ty->cursor_state.cy = 0;
   ty->termstate.att.link_id = 0;

   termpty_clear_screen(ty, TERMPTY_CLR_ALL);
   if (ty->cb.cancel_sel.func)
     ty->cb.cancel_sel.func(ty->cb.cancel_sel.data);
   cells = ty->screen;
   size = ty->w * ty->h;
   if (cells)
     {
        Termatt att;

        memset((&att), 0, sizeof(att));
        termpty_cell_codepoint_att_fill(ty, 'E', att, cells, size);
     }
}

static void
_handle_decbi(Termpty *ty)
{
   DBG("DECBI - Back Index");
   if (ty->cursor_state.cx == ty->termstate.left_margin)
     {
        Eina_Unicode blank[1] = { ' ' };
        int old_insert = ty->termstate.insert;
        int old_cx = ty->cursor_state.cx;
        int old_cy = ty->cursor_state.cy;
        int y;
        int max = ty->h;

        if (((ty->termstate.lr_margins != 0) && (ty->cursor_state.cx == 0))
            || ((ty->termstate.top_margin != 0)
                && (ty->cursor_state.cy < ty->termstate.top_margin))
            || ((ty->termstate.bottom_margin != 0)
                && (ty->cursor_state.cy >= ty->termstate.bottom_margin)))
          {
             return;
          }
        if (ty->termstate.bottom_margin != 0)
          max = ty->termstate.bottom_margin;
        ty->termstate.insert = 1;
        for (y = ty->termstate.top_margin; y < max; y++)
          {
             /* Insert a left column */
             ty->cursor_state.cy = y;
             ty->cursor_state.cx = old_cx;
             ty->termstate.wrapnext = 0;
             termpty_text_append(ty, blank, 1);
          }
        ty->termstate.insert = old_insert;
        ty->cursor_state.cx = old_cx;
        ty->cursor_state.cy = old_cy;
     }
   else
     {
        if ((ty->cursor_state.cx == 0) && (ty->termstate.lr_margins != 0))
          return;
        /* cursor backward */
        ty->cursor_state.cx--;
     }
}

static void
_handle_decfi(Termpty *ty)
{
   DBG("DECFI - Forward Index");
   if ((ty->cursor_state.cx == ty->w - 1)
       || ((ty->termstate.right_margin > 0)
           && (ty->cursor_state.cx == ty->termstate.right_margin - 1)))
     {
        int y;
        int max_x = ty->w - 1;
        int max_y = ty->h;

        if (((ty->termstate.lr_margins != 0)
             && (ty->cursor_state.cx == ty->w - 1))
            || ((ty->termstate.top_margin != 0)
                && (ty->cursor_state.cy < ty->termstate.top_margin))
            || ((ty->termstate.bottom_margin != 0)
                && (ty->cursor_state.cy >= ty->termstate.bottom_margin)))
          {
             return;
          }
        if (ty->termstate.bottom_margin != 0)
          max_y = ty->termstate.bottom_margin;
        if (ty->termstate.right_margin != 0)
          max_x = ty->termstate.right_margin - 1;

        for (y = ty->termstate.top_margin; y < max_y; y++)
          {
             int x;
             Termcell *cells = &(TERMPTY_SCREEN(ty, 0, y));

             for (x = ty->termstate.left_margin; x <= max_x; x++)
               {
                  if (x < max_x)
                    TERMPTY_CELL_COPY(ty, &(cells[x + 1]), &(cells[x]), 1);
                  else
                    {
                       cells[x].codepoint = ' ';
                       if (EINA_UNLIKELY(cells[x].att.link_id))
                         term_link_refcount_dec(ty, cells[x].att.link_id, 1);
                       cells[x].att = ty->termstate.att;
                       cells[x].att.link_id = 0;
                       cells[x].att.dblwidth = 0;
                    }
               }
          }
     }
   else
     {
        if ((ty->cursor_state.cx == ty->w - 1)
            && (ty->termstate.lr_margins != 0))
          return;
        /* cursor forward */
        ty->cursor_state.cx++;
     }
}

static int
_handle_esc(Termpty *ty, const Eina_Unicode *c, const Eina_Unicode *ce)
{
   int len = ce - c;

   if (len < 1) return 0;
   DBG("ESC: '%s'", _safechar(c[0]));
   switch (c[0])
     {
      case '[':
        len = _handle_esc_csi(ty, c + 1, ce);
        if (len == 0) return 0;
        return 1 + len;
      case ']':
        len = _handle_esc_osc(ty, c + 1, ce);
        if (len == 0) return 0;
        return 1 + len;
      case '}':
        len = _handle_esc_terminology(ty, c + 1, ce);
        if (len == 0) return 0;
        return 1 + len;
      case 'P':
        len =  _handle_esc_dcs(ty, c + 1, ce);
        if (len == 0) return 0;
        return 1 + len;
      case '=': // set alternate keypad mode
        ty->termstate.alt_kp = 1;
        return 1;
      case '>': // set numeric keypad mode
        ty->termstate.alt_kp = 0;
        return 1;
      case 'M': // move to prev line
        DBG("move to prev line");
        ty->termstate.wrapnext = 0;
        ty->cursor_state.cy--;
        termpty_text_scroll_rev_test(ty, EINA_TRUE);
        return 1;
      case 'D': // move to next line
        DBG("move to next line");
        ty->termstate.wrapnext = 0;
        ty->cursor_state.cy++;
        termpty_text_scroll_test(ty, EINA_FALSE);
        return 1;
      case 'E': // add \n\r
        DBG("add \\n\\r");
        ty->termstate.wrapnext = 0;
        ty->cursor_state.cx = 0;
        ty->cursor_state.cy++;
        termpty_text_scroll_test(ty, EINA_FALSE);
        return 1;
      case 'Z': // same a 'ESC [ Pn c'
        _term_txt_write(ty, "\033[?1;2C");
        return 1;
      case 'c': // reset terminal to initial state
        DBG("reset to init mode and clear");
        termpty_reset_state(ty);
        termpty_clear_screen(ty, TERMPTY_CLR_ALL);
        if (ty->cb.cancel_sel.func)
          ty->cb.cancel_sel.func(ty->cb.cancel_sel.data);
        return 1;
      case '"':
        if (len < 2)
          return 0;
        /* Seems like this sequence activates C1... */
        if (c[1] != 'C')
          {
             ERR("invalid 0x1b 0x22 sequence");
             ty->decoding_error = 0;
          }
        return 2;
      case '(': // charset 0
        if (len < 2) return 0;
        ty->termstate.chset[0] = c[1];
        ty->termstate.multibyte = 0;
        ty->termstate.charsetch = c[1];
        return 2;
      case ')': // charset 1
        if (len < 2) return 0;
        ty->termstate.chset[1] = c[1];
        ty->termstate.multibyte = 0;
        return 2;
      case '*': // charset 2
        if (len < 2) return 0;
        ty->termstate.chset[2] = c[1];
        ty->termstate.multibyte = 0;
        return 2;
      case '+': // charset 3
        if (len < 2) return 0;
        ty->termstate.chset[3] = c[1];
        ty->termstate.multibyte = 0;
        return 2;
      case '$': // charset -2
        if (len < 2) return 0;
        ty->termstate.chset[2] = c[1];
        ty->termstate.multibyte = 1;
        return 2;
      case '#': // #8 == test mode -> fill screen with "E";
        if (len < 2) return 0;
        if (c[1] == '8')
          _handle_decaln(ty);
        return 2;
      case '@': // just consume this plus next char
        if (len < 2) return 0;
        return 2;
      case '6':
        _handle_decbi(ty);
        return 1;
      case '7': // save cursor pos
        termpty_cursor_copy(ty, EINA_TRUE);
        return 1;
      case '8': // restore cursor pos
        termpty_cursor_copy(ty, EINA_FALSE);
        return 1;
      case '9':
        _handle_decfi(ty);
        return 1;
      case 'H': // set tab at current column
        DBG("Character Tabulation Set (HTS) at x:%d", ty->cursor_state.cx);
        TAB_SET(ty, ty->cursor_state.cx);
        return 1;
/*
      case 'G': // query gfx mode
        return 2;
      case 'n': // single shift 2
        return 1;
      case 'o': // single shift 3
        return 1;
 */
      default:
        ty->decoding_error = EINA_TRUE;
        WRN("Unhandled escape '%s' (0x%02x)", _safechar(c[0]), (unsigned int) c[0]);
        return 1;
     }
   return 0;
}


/* XXX: ce is excluded */
int
termpty_handle_seq(Termpty *ty, const Eina_Unicode *c, const Eina_Unicode *ce)
{
   Eina_Unicode *cc;
   Eina_Unicode last_char = 0;
   int len = 0;
   ty->decoding_error = EINA_FALSE;

   if (c[0] < 0x20)
     {
        switch (c[0])
          {
           case 0x07: // BEL '\a' (bell)
           case 0x08: // BS  '\b' (backspace)
           case 0x09: // HT  '\t' (horizontal tab)
           case 0x0a: // LF  '\n' (new line)
           case 0x0b: // VT  '\v' (vertical tab)
           case 0x0c: // FF  '\f' (form feed)
           case 0x0d: // CR  '\r' (carriage ret)
             _handle_cursor_control(ty, c);
             len = 1;
             goto end;

           case 0x0e: // SO  (shift out) // Maps G1 character set into GL.
             ty->termstate.charset = 1;
             ty->termstate.charsetch = ty->termstate.chset[1];
             len = 1;
             goto end;
           case 0x0f: // SI  (shift in) // Maps G0 character set into GL.
             ty->termstate.charset = 0;
             ty->termstate.charsetch = ty->termstate.chset[0];
             len = 1;
             goto end;
           case 0x1b: // ESC (escape)
             len = _handle_esc(ty, c + 1, ce);
             if (len == 0)
               goto end;
             len++;
             goto end;
           default:
             //ERR("unhandled char 0x%02x", c[0]);
             len = 1;
             goto end;
          }
     }
   else if (c[0] == DEL)
     {
        WRN("Unhandled char 0x%02x [DEL]", (unsigned int) c[0]);
        ty->decoding_error = EINA_TRUE;
        len = 1;
        goto end;
     }
   else if (c[0] == CSI)
     {
        len = _handle_esc_csi(ty, c + 1, ce);
        if (len == 0)
          goto end;
        len++;
        goto end;
     }
   else if (c[0] == OSC)
     {
        len = _handle_esc_osc(ty, c + 1, ce);
        if (len == 0)
          goto end;
        len++;
        goto end;
     }
   else if ((ty->block.expecting) && (ty->block.on))
     {
        Termexp *ex;
        Eina_List *l;

        EINA_LIST_FOREACH(ty->block.expecting, l, ex)
          {
             if (c[0] == ex->ch)
               {
                  Eina_Unicode cp;

                  cp = (1 << 31) | ((ex->id & 0x1fff) << 18) |
                    ((ex->x & 0x1ff) << 9) | (ex->y & 0x1ff);
                  ex->x++;
                  if (ex->x >= ex->w)
                    {
                       ex->x = 0;
                       ex->y++;
                    }
                  ex->left--;
                  termpty_text_append(ty, &cp, 1);
                  if (ex->left <= 0)
                    {
                       ty->block.expecting =
                         eina_list_remove_list(ty->block.expecting, l);
                       free(ex);
                    }
                  else
                    ty->block.expecting =
                    eina_list_promote_list(ty->block.expecting, l);
                  len = 1;
                  goto end;
               }
          }
        termpty_text_append(ty, c, 1);
        len = 1;
        goto end;
     }
   cc = (Eina_Unicode *)c;

   DBG("txt: [");
   while ((cc < ce) && (*cc >= 0x20) && (*cc != DEL) && (*cc != CSI)
          && (*cc != OSC))
     {
        DBG("%s", _safechar(*cc));
        cc++;
        len++;
     }
   DBG("]");
   termpty_text_append(ty, c, len);
   if (len > 0)
       last_char = c[len-1];

end:
#if !defined(ENABLE_FUZZING) && !defined(ENABLE_TESTS)
   if (ty->decoding_error)
     {
      int j;
      for (j = 0; c + j < ce && j < len; j++)
        {
           if ((c[j] < ' ') || (c[j] >= 0x7f))
             printf("\033[35m%08x\033[0m", c[j]);
           else
             printf("%s", _safechar(c[j]));
        }
      printf("\n");
     }
#endif
   ty->decoding_error = EINA_FALSE;
   ty->last_char = last_char;
   return len;
}