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
 4470
 4471
 4472
 4473
 4474
 4475
 4476
 4477
 4478
 4479
 4480
 4481
 4482
 4483
 4484
 4485
 4486
 4487
 4488
 4489
 4490
 4491
 4492
 4493
 4494
 4495
 4496
 4497
 4498
 4499
 4500
 4501
 4502
 4503
 4504
 4505
 4506
 4507
 4508
 4509
 4510
 4511
 4512
 4513
 4514
 4515
 4516
 4517
 4518
 4519
 4520
 4521
 4522
 4523
 4524
 4525
 4526
 4527
 4528
 4529
 4530
 4531
 4532
 4533
 4534
 4535
 4536
 4537
 4538
 4539
 4540
 4541
 4542
 4543
 4544
 4545
 4546
 4547
 4548
 4549
 4550
 4551
 4552
 4553
 4554
 4555
 4556
 4557
 4558
 4559
 4560
 4561
 4562
 4563
 4564
 4565
 4566
 4567
 4568
 4569
 4570
 4571
 4572
 4573
 4574
 4575
 4576
 4577
 4578
 4579
 4580
 4581
 4582
 4583
 4584
 4585
 4586
 4587
 4588
 4589
 4590
 4591
 4592
 4593
 4594
 4595
 4596
 4597
 4598
 4599
 4600
 4601
 4602
 4603
 4604
 4605
 4606
 4607
 4608
 4609
 4610
 4611
 4612
 4613
 4614
 4615
 4616
 4617
 4618
 4619
 4620
 4621
 4622
 4623
 4624
 4625
 4626
 4627
 4628
 4629
 4630
 4631
 4632
 4633
 4634
 4635
 4636
 4637
 4638
 4639
 4640
 4641
 4642
 4643
 4644
 4645
 4646
 4647
 4648
 4649
 4650
 4651
 4652
 4653
 4654
 4655
 4656
 4657
 4658
 4659
 4660
 4661
 4662
 4663
 4664
 4665
 4666
 4667
 4668
 4669
 4670
 4671
 4672
 4673
 4674
 4675
 4676
 4677
 4678
 4679
 4680
 4681
 4682
 4683
 4684
 4685
 4686
 4687
 4688
 4689
 4690
 4691
 4692
 4693
 4694
 4695
 4696
 4697
 4698
 4699
 4700
 4701
 4702
 4703
 4704
 4705
 4706
 4707
 4708
 4709
 4710
 4711
 4712
 4713
 4714
 4715
 4716
 4717
 4718
 4719
 4720
 4721
 4722
 4723
 4724
 4725
 4726
 4727
 4728
 4729
 4730
 4731
 4732
 4733
 4734
 4735
 4736
 4737
 4738
 4739
 4740
 4741
 4742
 4743
 4744
 4745
 4746
 4747
 4748
 4749
 4750
 4751
 4752
 4753
 4754
 4755
 4756
 4757
 4758
 4759
 4760
 4761
 4762
 4763
 4764
 4765
 4766
 4767
 4768
 4769
 4770
 4771
 4772
 4773
 4774
 4775
 4776
 4777
 4778
 4779
 4780
 4781
 4782
 4783
 4784
 4785
 4786
 4787
 4788
 4789
 4790
 4791
 4792
 4793
 4794
 4795
 4796
 4797
 4798
 4799
 4800
 4801
 4802
 4803
 4804
 4805
 4806
 4807
 4808
 4809
 4810
 4811
 4812
 4813
 4814
 4815
 4816
 4817
 4818
 4819
 4820
 4821
 4822
 4823
 4824
 4825
 4826
 4827
 4828
 4829
 4830
 4831
 4832
 4833
 4834
 4835
 4836
 4837
 4838
 4839
 4840
 4841
 4842
 4843
 4844
 4845
 4846
 4847
 4848
 4849
 4850
 4851
 4852
 4853
 4854
 4855
 4856
 4857
 4858
 4859
 4860
 4861
 4862
 4863
 4864
 4865
 4866
 4867
 4868
 4869
 4870
 4871
 4872
 4873
 4874
 4875
 4876
 4877
 4878
 4879
 4880
 4881
 4882
 4883
 4884
 4885
 4886
 4887
 4888
 4889
 4890
 4891
 4892
 4893
 4894
 4895
 4896
 4897
 4898
 4899
 4900
 4901
 4902
 4903
 4904
 4905
 4906
 4907
 4908
 4909
 4910
 4911
 4912
 4913
 4914
 4915
 4916
 4917
 4918
 4919
 4920
 4921
 4922
 4923
 4924
 4925
 4926
 4927
 4928
 4929
 4930
 4931
 4932
 4933
 4934
 4935
 4936
 4937
 4938
 4939
 4940
 4941
 4942
 4943
 4944
 4945
 4946
 4947
 4948
 4949
 4950
 4951
 4952
 4953
 4954
 4955
 4956
 4957
 4958
 4959
 4960
 4961
 4962
 4963
 4964
 4965
 4966
 4967
 4968
 4969
 4970
 4971
 4972
 4973
 4974
 4975
 4976
 4977
 4978
 4979
 4980
 4981
 4982
 4983
 4984
 4985
 4986
 4987
 4988
 4989
 4990
 4991
 4992
 4993
 4994
 4995
 4996
 4997
 4998
 4999
 5000
 5001
 5002
 5003
 5004
 5005
 5006
 5007
 5008
 5009
 5010
 5011
 5012
 5013
 5014
 5015
 5016
 5017
 5018
 5019
 5020
 5021
 5022
 5023
 5024
 5025
 5026
 5027
 5028
 5029
 5030
 5031
 5032
 5033
 5034
 5035
 5036
 5037
 5038
 5039
 5040
 5041
 5042
 5043
 5044
 5045
 5046
 5047
 5048
 5049
 5050
 5051
 5052
 5053
 5054
 5055
 5056
 5057
 5058
 5059
 5060
 5061
 5062
 5063
 5064
 5065
 5066
 5067
 5068
 5069
 5070
 5071
 5072
 5073
 5074
 5075
 5076
 5077
 5078
 5079
 5080
 5081
 5082
 5083
 5084
 5085
 5086
 5087
 5088
 5089
 5090
 5091
 5092
 5093
 5094
 5095
 5096
 5097
 5098
 5099
 5100
 5101
 5102
 5103
 5104
 5105
 5106
 5107
 5108
 5109
 5110
 5111
 5112
 5113
 5114
 5115
 5116
 5117
 5118
 5119
 5120
 5121
 5122
 5123
 5124
 5125
 5126
 5127
 5128
 5129
 5130
 5131
 5132
 5133
 5134
 5135
 5136
 5137
 5138
 5139
 5140
 5141
 5142
 5143
 5144
 5145
 5146
 5147
 5148
 5149
 5150
 5151
 5152
 5153
 5154
 5155
 5156
 5157
 5158
 5159
 5160
 5161
 5162
 5163
 5164
 5165
 5166
 5167
 5168
 5169
 5170
 5171
 5172
 5173
 5174
 5175
 5176
 5177
 5178
 5179
 5180
 5181
 5182
 5183
 5184
 5185
 5186
 5187
 5188
 5189
 5190
 5191
 5192
 5193
 5194
 5195
 5196
 5197
 5198
 5199
 5200
 5201
 5202
 5203
 5204
 5205
 5206
 5207
 5208
 5209
 5210
 5211
 5212
 5213
 5214
 5215
 5216
 5217
 5218
 5219
 5220
 5221
 5222
 5223
 5224
 5225
 5226
 5227
 5228
 5229
 5230
 5231
 5232
 5233
 5234
 5235
 5236
 5237
 5238
 5239
 5240
 5241
 5242
 5243
 5244
 5245
 5246
 5247
 5248
 5249
 5250
 5251
 5252
 5253
 5254
 5255
 5256
 5257
 5258
 5259
 5260
 5261
 5262
 5263
 5264
 5265
 5266
 5267
 5268
 5269
 5270
 5271
 5272
 5273
 5274
 5275
 5276
 5277
 5278
 5279
 5280
 5281
 5282
 5283
 5284
 5285
 5286
 5287
 5288
 5289
 5290
 5291
 5292
 5293
 5294
 5295
 5296
 5297
 5298
 5299
 5300
 5301
 5302
 5303
 5304
 5305
 5306
 5307
 5308
 5309
 5310
 5311
 5312
 5313
 5314
 5315
 5316
 5317
 5318
 5319
 5320
 5321
 5322
 5323
 5324
 5325
 5326
 5327
 5328
 5329
 5330
 5331
 5332
 5333
 5334
 5335
 5336
 5337
 5338
 5339
 5340
 5341
 5342
 5343
 5344
 5345
 5346
 5347
 5348
 5349
 5350
 5351
 5352
 5353
 5354
 5355
 5356
 5357
 5358
 5359
 5360
 5361
 5362
 5363
 5364
 5365
 5366
 5367
 5368
 5369
 5370
 5371
 5372
 5373
 5374
 5375
 5376
 5377
 5378
 5379
 5380
 5381
 5382
 5383
 5384
 5385
 5386
 5387
 5388
 5389
 5390
 5391
 5392
 5393
 5394
 5395
 5396
 5397
 5398
 5399
 5400
 5401
 5402
 5403
 5404
 5405
 5406
 5407
 5408
 5409
 5410
 5411
 5412
 5413
 5414
 5415
 5416
 5417
 5418
 5419
 5420
 5421
 5422
 5423
 5424
 5425
 5426
 5427
 5428
 5429
 5430
 5431
 5432
 5433
 5434
 5435
 5436
 5437
 5438
 5439
 5440
 5441
 5442
 5443
 5444
 5445
 5446
 5447
 5448
 5449
 5450
 5451
 5452
 5453
 5454
 5455
 5456
 5457
 5458
 5459
 5460
 5461
 5462
 5463
 5464
 5465
 5466
 5467
 5468
 5469
 5470
 5471
 5472
 5473
 5474
 5475
 5476
 5477
 5478
 5479
 5480
 5481
 5482
 5483
 5484
 5485
 5486
 5487
 5488
 5489
 5490
 5491
 5492
 5493
 5494
 5495
 5496
 5497
 5498
 5499
 5500
 5501
 5502
 5503
 5504
 5505
 5506
 5507
 5508
 5509
 5510
 5511
 5512
 5513
 5514
 5515
 5516
 5517
 5518
 5519
 5520
 5521
 5522
 5523
 5524
 5525
 5526
 5527
 5528
 5529
 5530
 5531
 5532
 5533
 5534
 5535
 5536
 5537
 5538
 5539
 5540
 5541
 5542
 5543
 5544
 5545
 5546
 5547
 5548
 5549
 5550
 5551
 5552
 5553
 5554
 5555
 5556
 5557
 5558
 5559
 5560
 5561
 5562
 5563
 5564
 5565
 5566
 5567
 5568
 5569
 5570
 5571
 5572
 5573
 5574
 5575
 5576
 5577
 5578
 5579
 5580
 5581
 5582
 5583
 5584
 5585
 5586
 5587
 5588
 5589
 5590
 5591
 5592
 5593
 5594
 5595
 5596
 5597
 5598
 5599
 5600
 5601
 5602
 5603
 5604
 5605
 5606
 5607
 5608
 5609
 5610
 5611
 5612
 5613
 5614
 5615
 5616
 5617
 5618
 5619
 5620
 5621
 5622
 5623
 5624
 5625
 5626
 5627
 5628
 5629
 5630
 5631
 5632
 5633
 5634
 5635
 5636
 5637
 5638
 5639
 5640
 5641
 5642
 5643
 5644
 5645
 5646
 5647
 5648
 5649
 5650
 5651
 5652
 5653
 5654
 5655
 5656
 5657
 5658
 5659
 5660
 5661
 5662
 5663
 5664
 5665
 5666
 5667
 5668
 5669
 5670
 5671
 5672
 5673
 5674
 5675
 5676
 5677
 5678
 5679
 5680
 5681
 5682
 5683
 5684
 5685
 5686
 5687
 5688
 5689
 5690
 5691
 5692
 5693
 5694
 5695
 5696
 5697
 5698
 5699
 5700
 5701
 5702
 5703
 5704
 5705
 5706
 5707
 5708
 5709
 5710
 5711
 5712
 5713
 5714
 5715
 5716
 5717
 5718
 5719
 5720
 5721
 5722
 5723
 5724
 5725
 5726
 5727
 5728
 5729
 5730
 5731
 5732
 5733
 5734
 5735
 5736
 5737
 5738
 5739
 5740
 5741
 5742
 5743
 5744
 5745
 5746
 5747
 5748
 5749
 5750
 5751
 5752
 5753
 5754
 5755
 5756
 5757
 5758
 5759
 5760
 5761
 5762
 5763
 5764
 5765
 5766
 5767
 5768
 5769
 5770
 5771
 5772
 5773
 5774
 5775
 5776
 5777
 5778
 5779
 5780
 5781
 5782
 5783
 5784
 5785
 5786
 5787
 5788
 5789
 5790
 5791
 5792
 5793
 5794
 5795
 5796
 5797
 5798
 5799
 5800
 5801
 5802
 5803
 5804
 5805
 5806
 5807
 5808
 5809
 5810
 5811
 5812
 5813
 5814
 5815
 5816
 5817
 5818
 5819
 5820
 5821
 5822
 5823
 5824
 5825
 5826
 5827
 5828
 5829
 5830
 5831
 5832
 5833
 5834
 5835
 5836
 5837
 5838
 5839
 5840
 5841
 5842
 5843
 5844
 5845
 5846
 5847
 5848
 5849
 5850
 5851
 5852
 5853
 5854
 5855
 5856
 5857
 5858
 5859
 5860
 5861
 5862
 5863
 5864
 5865
 5866
 5867
 5868
 5869
 5870
 5871
 5872
 5873
 5874
 5875
 5876
 5877
 5878
 5879
 5880
 5881
 5882
 5883
 5884
 5885
 5886
 5887
 5888
 5889
 5890
 5891
 5892
 5893
 5894
 5895
 5896
 5897
 5898
 5899
 5900
 5901
 5902
 5903
 5904
 5905
 5906
 5907
 5908
 5909
 5910
 5911
 5912
 5913
 5914
 5915
 5916
 5917
 5918
 5919
 5920
 5921
 5922
 5923
 5924
 5925
 5926
 5927
 5928
 5929
 5930
 5931
 5932
 5933
 5934
 5935
 5936
 5937
 5938
 5939
 5940
 5941
 5942
 5943
 5944
 5945
 5946
 5947
 5948
 5949
 5950
 5951
 5952
 5953
 5954
 5955
 5956
 5957
 5958
 5959
 5960
 5961
 5962
 5963
 5964
 5965
 5966
 5967
 5968
 5969
 5970
 5971
 5972
 5973
 5974
 5975
 5976
 5977
 5978
 5979
 5980
 5981
 5982
 5983
 5984
 5985
 5986
 5987
 5988
 5989
 5990
 5991
 5992
 5993
 5994
 5995
 5996
 5997
 5998
 5999
 6000
 6001
 6002
 6003
 6004
 6005
 6006
 6007
 6008
 6009
 6010
 6011
 6012
 6013
 6014
 6015
 6016
 6017
 6018
 6019
 6020
 6021
 6022
 6023
 6024
 6025
 6026
 6027
 6028
 6029
 6030
 6031
 6032
 6033
 6034
 6035
 6036
 6037
 6038
 6039
 6040
 6041
 6042
 6043
 6044
 6045
 6046
 6047
 6048
 6049
 6050
 6051
 6052
 6053
 6054
 6055
 6056
 6057
 6058
 6059
 6060
 6061
 6062
 6063
 6064
 6065
 6066
 6067
 6068
 6069
 6070
 6071
 6072
 6073
 6074
 6075
 6076
 6077
 6078
 6079
 6080
 6081
 6082
 6083
 6084
 6085
 6086
 6087
 6088
 6089
 6090
 6091
 6092
 6093
 6094
 6095
 6096
 6097
 6098
 6099
 6100
 6101
 6102
 6103
 6104
 6105
 6106
 6107
 6108
 6109
 6110
 6111
 6112
 6113
 6114
 6115
 6116
 6117
 6118
 6119
 6120
 6121
 6122
 6123
 6124
 6125
 6126
 6127
 6128
 6129
 6130
 6131
 6132
 6133
 6134
 6135
 6136
 6137
 6138
 6139
 6140
 6141
 6142
 6143
 6144
 6145
 6146
 6147
 6148
 6149
 6150
 6151
 6152
 6153
 6154
 6155
 6156
 6157
 6158
 6159
 6160
 6161
 6162
 6163
 6164
 6165
 6166
 6167
 6168
 6169
 6170
 6171
 6172
 6173
 6174
 6175
 6176
 6177
 6178
 6179
 6180
 6181
 6182
 6183
 6184
 6185
 6186
 6187
 6188
 6189
 6190
 6191
 6192
 6193
 6194
 6195
 6196
 6197
 6198
 6199
 6200
 6201
 6202
 6203
 6204
 6205
 6206
 6207
 6208
 6209
 6210
 6211
 6212
 6213
 6214
 6215
 6216
 6217
 6218
 6219
 6220
 6221
 6222
 6223
 6224
 6225
 6226
 6227
 6228
 6229
 6230
 6231
 6232
 6233
 6234
 6235
 6236
 6237
 6238
 6239
 6240
 6241
 6242
 6243
 6244
 6245
 6246
 6247
 6248
 6249
 6250
 6251
 6252
 6253
 6254
 6255
 6256
 6257
 6258
 6259
 6260
 6261
 6262
 6263
 6264
 6265
 6266
 6267
 6268
 6269
 6270
 6271
 6272
 6273
 6274
 6275
 6276
 6277
 6278
 6279
 6280
 6281
 6282
 6283
 6284
 6285
 6286
 6287
 6288
 6289
 6290
 6291
 6292
 6293
 6294
 6295
 6296
 6297
 6298
 6299
 6300
 6301
 6302
 6303
 6304
 6305
 6306
 6307
 6308
 6309
 6310
 6311
 6312
 6313
 6314
 6315
 6316
 6317
 6318
 6319
 6320
 6321
 6322
 6323
 6324
 6325
 6326
 6327
 6328
 6329
 6330
 6331
 6332
 6333
 6334
 6335
 6336
 6337
 6338
 6339
 6340
 6341
 6342
 6343
 6344
 6345
 6346
 6347
 6348
 6349
 6350
 6351
 6352
 6353
 6354
 6355
 6356
 6357
 6358
 6359
 6360
 6361
 6362
 6363
 6364
 6365
 6366
 6367
 6368
 6369
 6370
 6371
 6372
 6373
 6374
 6375
 6376
 6377
 6378
 6379
 6380
 6381
 6382
 6383
 6384
 6385
 6386
 6387
 6388
 6389
 6390
 6391
 6392
 6393
 6394
 6395
 6396
 6397
 6398
 6399
 6400
 6401
 6402
 6403
 6404
 6405
 6406
 6407
 6408
 6409
 6410
 6411
 6412
 6413
 6414
 6415
 6416
 6417
 6418
 6419
 6420
 6421
 6422
 6423
 6424
 6425
 6426
 6427
 6428
 6429
 6430
 6431
 6432
 6433
 6434
 6435
 6436
 6437
 6438
 6439
 6440
 6441
 6442
 6443
 6444
 6445
 6446
 6447
 6448
 6449
 6450
 6451
 6452
 6453
 6454
 6455
 6456
 6457
 6458
 6459
 6460
 6461
 6462
 6463
 6464
 6465
 6466
 6467
 6468
 6469
 6470
 6471
 6472
 6473
 6474
 6475
 6476
 6477
 6478
 6479
 6480
 6481
 6482
 6483
 6484
 6485
 6486
 6487
 6488
 6489
 6490
 6491
 6492
 6493
 6494
 6495
 6496
 6497
 6498
 6499
 6500
 6501
 6502
 6503
 6504
 6505
 6506
 6507
 6508
 6509
 6510
 6511
 6512
 6513
 6514
 6515
 6516
 6517
 6518
 6519
 6520
 6521
 6522
 6523
 6524
 6525
 6526
 6527
 6528
 6529
 6530
 6531
 6532
 6533
 6534
 6535
 6536
 6537
 6538
 6539
 6540
 6541
 6542
 6543
 6544
 6545
 6546
 6547
 6548
 6549
 6550
 6551
 6552
 6553
 6554
 6555
 6556
 6557
 6558
 6559
 6560
 6561
 6562
 6563
 6564
 6565
 6566
 6567
 6568
 6569
 6570
 6571
 6572
 6573
 6574
 6575
 6576
 6577
 6578
 6579
 6580
 6581
 6582
 6583
 6584
 6585
 6586
 6587
 6588
 6589
 6590
 6591
 6592
 6593
 6594
 6595
 6596
 6597
 6598
 6599
 6600
 6601
 6602
 6603
 6604
 6605
 6606
 6607
 6608
 6609
 6610
 6611
 6612
 6613
 6614
 6615
 6616
 6617
 6618
 6619
 6620
 6621
 6622
 6623
 6624
 6625
 6626
 6627
 6628
 6629
 6630
 6631
 6632
 6633
 6634
 6635
 6636
 6637
 6638
 6639
 6640
 6641
 6642
 6643
 6644
 6645
 6646
 6647
 6648
 6649
 6650
 6651
 6652
 6653
 6654
 6655
 6656
 6657
 6658
 6659
 6660
 6661
 6662
 6663
 6664
 6665
 6666
 6667
 6668
 6669
 6670
 6671
 6672
 6673
 6674
 6675
 6676
 6677
 6678
 6679
 6680
 6681
 6682
 6683
 6684
 6685
 6686
 6687
 6688
 6689
 6690
 6691
 6692
 6693
 6694
 6695
 6696
 6697
 6698
 6699
 6700
 6701
 6702
 6703
 6704
 6705
 6706
 6707
 6708
 6709
 6710
 6711
 6712
 6713
 6714
 6715
 6716
 6717
 6718
 6719
 6720
 6721
 6722
 6723
 6724
 6725
 6726
 6727
 6728
 6729
 6730
 6731
 6732
 6733
 6734
 6735
 6736
 6737
 6738
 6739
 6740
 6741
 6742
 6743
 6744
 6745
 6746
 6747
 6748
 6749
 6750
 6751
 6752
 6753
 6754
 6755
 6756
 6757
 6758
 6759
 6760
 6761
 6762
 6763
 6764
 6765
 6766
 6767
 6768
 6769
 6770
 6771
 6772
 6773
 6774
 6775
 6776
 6777
 6778
 6779
 6780
 6781
 6782
 6783
 6784
 6785
 6786
 6787
 6788
 6789
 6790
 6791
 6792
 6793
 6794
 6795
 6796
 6797
 6798
 6799
 6800
 6801
 6802
 6803
 6804
 6805
 6806
 6807
 6808
 6809
 6810
 6811
 6812
 6813
 6814
 6815
 6816
 6817
 6818
 6819
 6820
 6821
 6822
 6823
 6824
 6825
 6826
 6827
 6828
 6829
 6830
 6831
 6832
 6833
 6834
 6835
 6836
 6837
 6838
 6839
 6840
 6841
 6842
 6843
 6844
 6845
 6846
 6847
 6848
 6849
 6850
 6851
 6852
 6853
 6854
 6855
 6856
 6857
 6858
 6859
 6860
 6861
 6862
 6863
 6864
 6865
 6866
 6867
 6868
 6869
 6870
 6871
 6872
 6873
 6874
 6875
 6876
 6877
 6878
 6879
 6880
 6881
 6882
 6883
 6884
 6885
 6886
 6887
 6888
 6889
 6890
 6891
 6892
 6893
 6894
 6895
 6896
 6897
 6898
 6899
 6900
 6901
 6902
 6903
 6904
 6905
 6906
 6907
 6908
 6909
 6910
 6911
 6912
 6913
 6914
 6915
 6916
 6917
 6918
 6919
 6920
 6921
 6922
 6923
 6924
 6925
 6926
 6927
 6928
 6929
 6930
 6931
 6932
 6933
 6934
 6935
 6936
 6937
 6938
 6939
 6940
 6941
 6942
 6943
 6944
 6945
 6946
 6947
 6948
 6949
 6950
 6951
 6952
 6953
 6954
 6955
 6956
 6957
 6958
 6959
 6960
 6961
 6962
 6963
 6964
 6965
 6966
 6967
 6968
 6969
 6970
 6971
 6972
 6973
 6974
 6975
 6976
 6977
 6978
 6979
 6980
 6981
 6982
 6983
 6984
 6985
 6986
 6987
 6988
 6989
 6990
 6991
 6992
 6993
 6994
 6995
 6996
 6997
 6998
 6999
 7000
 7001
 7002
 7003
 7004
 7005
 7006
 7007
 7008
 7009
 7010
 7011
 7012
 7013
 7014
 7015
 7016
 7017
 7018
 7019
 7020
 7021
 7022
 7023
 7024
 7025
 7026
 7027
 7028
 7029
 7030
 7031
 7032
 7033
 7034
 7035
 7036
 7037
 7038
 7039
 7040
 7041
 7042
 7043
 7044
 7045
 7046
 7047
 7048
 7049
 7050
 7051
 7052
 7053
 7054
 7055
 7056
 7057
 7058
 7059
 7060
 7061
 7062
 7063
 7064
 7065
 7066
 7067
 7068
 7069
 7070
 7071
 7072
 7073
 7074
 7075
 7076
 7077
 7078
 7079
 7080
 7081
 7082
 7083
 7084
 7085
 7086
 7087
 7088
 7089
 7090
 7091
 7092
 7093
 7094
 7095
 7096
 7097
 7098
 7099
 7100
 7101
 7102
 7103
 7104
 7105
 7106
 7107
 7108
 7109
 7110
 7111
 7112
 7113
 7114
 7115
 7116
 7117
 7118
 7119
 7120
 7121
 7122
 7123
 7124
 7125
 7126
 7127
 7128
 7129
 7130
 7131
 7132
 7133
 7134
 7135
 7136
 7137
 7138
 7139
 7140
 7141
 7142
 7143
 7144
 7145
 7146
 7147
 7148
 7149
 7150
 7151
 7152
 7153
 7154
 7155
 7156
 7157
 7158
 7159
 7160
 7161
 7162
 7163
 7164
 7165
 7166
 7167
 7168
 7169
 7170
 7171
 7172
 7173
 7174
 7175
 7176
 7177
 7178
 7179
 7180
 7181
 7182
 7183
 7184
 7185
 7186
 7187
 7188
 7189
 7190
 7191
 7192
 7193
 7194
 7195
 7196
 7197
 7198
 7199
 7200
 7201
 7202
 7203
 7204
 7205
 7206
 7207
 7208
 7209
 7210
 7211
 7212
 7213
 7214
 7215
 7216
 7217
 7218
 7219
 7220
 7221
 7222
 7223
 7224
 7225
 7226
 7227
 7228
 7229
 7230
 7231
 7232
 7233
 7234
 7235
 7236
 7237
 7238
 7239
 7240
 7241
 7242
 7243
 7244
 7245
 7246
 7247
 7248
 7249
 7250
 7251
 7252
 7253
 7254
 7255
 7256
 7257
 7258
 7259
 7260
 7261
 7262
 7263
 7264
 7265
 7266
 7267
 7268
 7269
 7270
 7271
 7272
 7273
 7274
 7275
 7276
 7277
 7278
 7279
 7280
 7281
 7282
 7283
 7284
 7285
 7286
 7287
 7288
 7289
 7290
 7291
 7292
 7293
 7294
 7295
 7296
 7297
 7298
 7299
 7300
 7301
 7302
 7303
 7304
 7305
 7306
 7307
 7308
 7309
 7310
 7311
 7312
 7313
 7314
 7315
 7316
 7317
 7318
 7319
 7320
 7321
 7322
 7323
 7324
 7325
 7326
 7327
 7328
 7329
 7330
 7331
 7332
 7333
 7334
 7335
 7336
 7337
 7338
 7339
 7340
 7341
 7342
 7343
 7344
 7345
 7346
 7347
 7348
 7349
 7350
 7351
 7352
 7353
 7354
 7355
 7356
 7357
 7358
 7359
 7360
 7361
 7362
 7363
 7364
 7365
 7366
 7367
 7368
 7369
 7370
 7371
 7372
 7373
 7374
 7375
 7376
 7377
 7378
 7379
 7380
 7381
 7382
 7383
 7384
 7385
 7386
 7387
 7388
 7389
 7390
 7391
 7392
 7393
 7394
 7395
 7396
 7397
 7398
 7399
 7400
 7401
 7402
 7403
 7404
 7405
 7406
 7407
 7408
 7409
 7410
 7411
 7412
 7413
 7414
 7415
 7416
 7417
 7418
 7419
 7420
 7421
 7422
 7423
 7424
 7425
 7426
 7427
 7428
 7429
 7430
 7431
 7432
 7433
 7434
 7435
 7436
 7437
 7438
 7439
 7440
 7441
 7442
 7443
 7444
 7445
 7446
 7447
 7448
 7449
 7450
 7451
 7452
 7453
 7454
 7455
 7456
 7457
 7458
 7459
 7460
 7461
 7462
 7463
 7464
 7465
 7466
 7467
 7468
 7469
 7470
 7471
 7472
 7473
 7474
 7475
 7476
 7477
 7478
 7479
 7480
 7481
 7482
 7483
 7484
 7485
 7486
 7487
 7488
 7489
 7490
 7491
 7492
 7493
 7494
 7495
 7496
 7497
 7498
 7499
 7500
 7501
 7502
 7503
 7504
 7505
 7506
 7507
 7508
 7509
 7510
 7511
 7512
 7513
 7514
 7515
 7516
 7517
 7518
 7519
 7520
 7521
 7522
 7523
 7524
 7525
 7526
 7527
 7528
 7529
 7530
 7531
 7532
 7533
 7534
 7535
 7536
 7537
 7538
 7539
 7540
 7541
 7542
 7543
 7544
 7545
 7546
 7547
 7548
 7549
 7550
 7551
 7552
 7553
 7554
 7555
 7556
 7557
 7558
 7559
 7560
 7561
 7562
 7563
 7564
 7565
 7566
 7567
 7568
 7569
 7570
 7571
 7572
 7573
 7574
 7575
 7576
 7577
 7578
 7579
 7580
 7581
 7582
 7583
 7584
 7585
 7586
 7587
 7588
 7589
 7590
 7591
 7592
 7593
 7594
 7595
 7596
 7597
 7598
 7599
 7600
 7601
 7602
 7603
 7604
 7605
 7606
 7607
 7608
 7609
 7610
 7611
 7612
 7613
 7614
 7615
 7616
 7617
 7618
 7619
 7620
 7621
 7622
 7623
 7624
 7625
 7626
 7627
 7628
 7629
 7630
 7631
 7632
 7633
 7634
 7635
 7636
 7637
 7638
 7639
 7640
 7641
 7642
 7643
 7644
 7645
 7646
 7647
 7648
 7649
 7650
 7651
 7652
 7653
 7654
 7655
 7656
 7657
 7658
 7659
 7660
 7661
 7662
 7663
 7664
 7665
 7666
 7667
 7668
 7669
 7670
 7671
 7672
 7673
 7674
 7675
 7676
 7677
 7678
 7679
 7680
 7681
 7682
 7683
 7684
 7685
 7686
 7687
 7688
 7689
 7690
 7691
 7692
 7693
 7694
 7695
 7696
 7697
 7698
 7699
 7700
 7701
 7702
 7703
 7704
 7705
 7706
 7707
 7708
 7709
 7710
 7711
 7712
 7713
 7714
 7715
 7716
 7717
 7718
 7719
 7720
 7721
 7722
 7723
 7724
 7725
 7726
 7727
 7728
 7729
 7730
 7731
 7732
 7733
 7734
 7735
 7736
 7737
 7738
 7739
 7740
 7741
 7742
 7743
 7744
 7745
 7746
 7747
 7748
 7749
 7750
 7751
 7752
 7753
 7754
 7755
 7756
 7757
 7758
 7759
 7760
 7761
 7762
 7763
 7764
 7765
 7766
 7767
 7768
 7769
 7770
 7771
 7772
 7773
 7774
 7775
 7776
 7777
 7778
 7779
 7780
 7781
 7782
 7783
 7784
 7785
 7786
 7787
 7788
 7789
 7790
 7791
 7792
 7793
 7794
 7795
 7796
 7797
 7798
 7799
 7800
 7801
 7802
 7803
 7804
 7805
 7806
 7807
 7808
 7809
 7810
 7811
 7812
 7813
 7814
 7815
 7816
 7817
 7818
 7819
 7820
 7821
 7822
 7823
 7824
 7825
 7826
 7827
 7828
 7829
 7830
 7831
 7832
 7833
 7834
 7835
 7836
 7837
 7838
 7839
 7840
 7841
 7842
 7843
 7844
 7845
 7846
 7847
 7848
 7849
 7850
 7851
 7852
 7853
 7854
 7855
 7856
 7857
 7858
 7859
 7860
 7861
 7862
 7863
 7864
 7865
 7866
 7867
 7868
 7869
 7870
 7871
 7872
 7873
 7874
 7875
 7876
 7877
 7878
 7879
 7880
 7881
 7882
 7883
 7884
 7885
 7886
 7887
 7888
 7889
 7890
 7891
 7892
 7893
 7894
 7895
 7896
 7897
 7898
 7899
 7900
 7901
 7902
 7903
 7904
 7905
 7906
 7907
 7908
 7909
 7910
 7911
 7912
 7913
 7914
 7915
 7916
 7917
 7918
 7919
 7920
 7921
 7922
 7923
 7924
 7925
 7926
 7927
 7928
 7929
 7930
 7931
 7932
 7933
 7934
 7935
 7936
 7937
 7938
 7939
 7940
 7941
 7942
 7943
 7944
 7945
 7946
 7947
 7948
 7949
 7950
 7951
 7952
 7953
 7954
 7955
 7956
 7957
 7958
 7959
 7960
 7961
 7962
 7963
 7964
 7965
 7966
 7967
 7968
 7969
 7970
 7971
 7972
 7973
 7974
 7975
 7976
 7977
 7978
 7979
 7980
 7981
 7982
 7983
 7984
 7985
 7986
 7987
 7988
 7989
 7990
 7991
 7992
 7993
 7994
 7995
 7996
 7997
 7998
 7999
 8000
 8001
 8002
 8003
 8004
 8005
 8006
 8007
 8008
 8009
 8010
 8011
 8012
 8013
 8014
 8015
 8016
 8017
 8018
 8019
 8020
 8021
 8022
 8023
 8024
 8025
 8026
 8027
 8028
 8029
 8030
 8031
 8032
 8033
 8034
 8035
 8036
 8037
 8038
 8039
 8040
 8041
 8042
 8043
 8044
 8045
 8046
 8047
 8048
 8049
 8050
 8051
 8052
 8053
 8054
 8055
 8056
 8057
 8058
 8059
 8060
 8061
 8062
 8063
 8064
 8065
 8066
 8067
 8068
 8069
 8070
 8071
 8072
 8073
 8074
 8075
 8076
 8077
 8078
 8079
 8080
 8081
 8082
 8083
 8084
 8085
 8086
 8087
 8088
 8089
 8090
 8091
 8092
 8093
 8094
 8095
 8096
 8097
 8098
 8099
 8100
 8101
 8102
 8103
 8104
 8105
 8106
 8107
 8108
 8109
 8110
 8111
 8112
 8113
 8114
 8115
 8116
 8117
 8118
 8119
 8120
 8121
 8122
 8123
 8124
 8125
 8126
 8127
 8128
 8129
 8130
 8131
 8132
 8133
 8134
 8135
 8136
 8137
 8138
 8139
 8140
 8141
 8142
 8143
 8144
 8145
 8146
 8147
 8148
 8149
 8150
 8151
 8152
 8153
 8154
 8155
 8156
 8157
 8158
 8159
 8160
 8161
 8162
 8163
 8164
 8165
 8166
 8167
 8168
 8169
 8170
 8171
 8172
 8173
 8174
 8175
 8176
 8177
 8178
 8179
 8180
 8181
 8182
 8183
 8184
 8185
 8186
 8187
 8188
 8189
 8190
 8191
 8192
 8193
 8194
 8195
 8196
 8197
 8198
 8199
 8200
 8201
 8202
 8203
 8204
 8205
 8206
 8207
 8208
 8209
 8210
 8211
 8212
 8213
 8214
 8215
 8216
 8217
 8218
 8219
 8220
 8221
 8222
 8223
 8224
 8225
 8226
 8227
 8228
 8229
 8230
 8231
 8232
 8233
 8234
 8235
 8236
 8237
 8238
 8239
 8240
 8241
 8242
 8243
 8244
 8245
 8246
 8247
 8248
 8249
 8250
 8251
 8252
 8253
 8254
 8255
 8256
 8257
 8258
 8259
 8260
 8261
 8262
 8263
 8264
 8265
 8266
 8267
 8268
 8269
 8270
 8271
 8272
 8273
 8274
 8275
 8276
 8277
 8278
 8279
 8280
 8281
 8282
 8283
 8284
 8285
 8286
 8287
 8288
 8289
 8290
 8291
 8292
 8293
 8294
 8295
 8296
 8297
 8298
 8299
 8300
 8301
 8302
 8303
 8304
 8305
 8306
 8307
 8308
 8309
 8310
 8311
 8312
 8313
 8314
 8315
 8316
 8317
 8318
 8319
 8320
 8321
 8322
 8323
 8324
 8325
 8326
 8327
 8328
 8329
 8330
 8331
 8332
 8333
 8334
 8335
 8336
 8337
 8338
 8339
 8340
 8341
 8342
 8343
 8344
 8345
 8346
 8347
 8348
 8349
 8350
 8351
 8352
 8353
 8354
 8355
 8356
 8357
 8358
 8359
 8360
 8361
 8362
 8363
 8364
 8365
 8366
 8367
 8368
 8369
 8370
 8371
 8372
 8373
 8374
 8375
 8376
 8377
 8378
 8379
 8380
 8381
 8382
 8383
 8384
 8385
 8386
 8387
 8388
 8389
 8390
 8391
 8392
 8393
 8394
 8395
 8396
 8397
 8398
 8399
 8400
 8401
 8402
 8403
 8404
 8405
 8406
 8407
 8408
 8409
 8410
 8411
 8412
 8413
 8414
 8415
 8416
 8417
 8418
 8419
 8420
 8421
 8422
 8423
 8424
 8425
 8426
 8427
 8428
 8429
 8430
 8431
 8432
 8433
 8434
 8435
 8436
 8437
 8438
 8439
 8440
 8441
 8442
 8443
 8444
 8445
 8446
 8447
 8448
 8449
 8450
 8451
 8452
 8453
 8454
 8455
 8456
 8457
 8458
 8459
 8460
 8461
 8462
 8463
 8464
 8465
 8466
 8467
 8468
 8469
 8470
 8471
 8472
 8473
 8474
 8475
 8476
 8477
 8478
 8479
 8480
 8481
 8482
 8483
 8484
 8485
 8486
 8487
 8488
 8489
 8490
 8491
 8492
 8493
 8494
 8495
 8496
 8497
 8498
 8499
 8500
 8501
 8502
 8503
 8504
 8505
 8506
 8507
 8508
 8509
 8510
 8511
 8512
 8513
 8514
 8515
 8516
 8517
 8518
 8519
 8520
 8521
 8522
 8523
 8524
 8525
 8526
 8527
 8528
 8529
 8530
 8531
 8532
 8533
 8534
 8535
 8536
 8537
 8538
 8539
 8540
 8541
 8542
 8543
 8544
 8545
 8546
 8547
 8548
 8549
 8550
 8551
 8552
 8553
 8554
 8555
 8556
 8557
 8558
 8559
 8560
 8561
 8562
 8563
 8564
 8565
 8566
 8567
 8568
 8569
 8570
 8571
 8572
 8573
 8574
 8575
 8576
 8577
 8578
 8579
 8580
 8581
 8582
 8583
 8584
 8585
 8586
 8587
 8588
 8589
 8590
 8591
 8592
 8593
 8594
 8595
 8596
 8597
 8598
 8599
 8600
 8601
 8602
 8603
 8604
 8605
 8606
 8607
 8608
 8609
 8610
 8611
 8612
 8613
 8614
 8615
 8616
 8617
 8618
 8619
 8620
 8621
 8622
 8623
 8624
 8625
 8626
 8627
 8628
 8629
 8630
 8631
 8632
 8633
 8634
 8635
 8636
 8637
 8638
 8639
 8640
 8641
 8642
 8643
 8644
 8645
 8646
 8647
 8648
 8649
 8650
 8651
 8652
 8653
 8654
 8655
 8656
 8657
 8658
 8659
 8660
 8661
 8662
 8663
 8664
 8665
 8666
 8667
 8668
 8669
 8670
 8671
 8672
 8673
 8674
 8675
 8676
 8677
 8678
 8679
 8680
 8681
 8682
 8683
 8684
 8685
 8686
 8687
 8688
 8689
 8690
 8691
 8692
 8693
 8694
 8695
 8696
 8697
 8698
 8699
 8700
 8701
 8702
 8703
 8704
 8705
 8706
 8707
 8708
 8709
 8710
 8711
 8712
 8713
 8714
 8715
 8716
 8717
 8718
 8719
 8720
 8721
 8722
 8723
 8724
 8725
 8726
 8727
 8728
 8729
 8730
 8731
 8732
 8733
 8734
 8735
 8736
 8737
 8738
 8739
 8740
 8741
 8742
 8743
 8744
 8745
 8746
 8747
 8748
 8749
 8750
 8751
 8752
 8753
 8754
 8755
 8756
 8757
 8758
 8759
 8760
 8761
 8762
 8763
 8764
 8765
 8766
 8767
 8768
 8769
 8770
 8771
 8772
 8773
 8774
 8775
 8776
 8777
 8778
 8779
 8780
 8781
 8782
 8783
 8784
 8785
 8786
 8787
 8788
 8789
 8790
 8791
 8792
 8793
 8794
 8795
 8796
 8797
 8798
 8799
 8800
 8801
 8802
 8803
 8804
 8805
 8806
 8807
 8808
 8809
 8810
 8811
 8812
 8813
 8814
 8815
 8816
 8817
 8818
 8819
 8820
 8821
 8822
 8823
 8824
 8825
 8826
 8827
 8828
 8829
 8830
 8831
 8832
 8833
 8834
 8835
 8836
 8837
 8838
 8839
 8840
 8841
 8842
 8843
 8844
 8845
 8846
 8847
 8848
 8849
 8850
 8851
 8852
 8853
 8854
 8855
 8856
 8857
 8858
 8859
 8860
 8861
 8862
 8863
 8864
 8865
 8866
 8867
 8868
 8869
 8870
 8871
 8872
 8873
 8874
 8875
 8876
 8877
 8878
 8879
 8880
 8881
 8882
 8883
 8884
 8885
 8886
 8887
 8888
 8889
 8890
 8891
 8892
 8893
 8894
 8895
 8896
 8897
 8898
 8899
 8900
 8901
 8902
 8903
 8904
 8905
 8906
 8907
 8908
 8909
 8910
 8911
 8912
 8913
 8914
 8915
 8916
 8917
 8918
 8919
 8920
 8921
 8922
 8923
 8924
 8925
 8926
 8927
 8928
 8929
 8930
 8931
 8932
 8933
 8934
 8935
 8936
 8937
 8938
 8939
 8940
 8941
 8942
 8943
 8944
 8945
 8946
 8947
 8948
 8949
 8950
 8951
 8952
 8953
 8954
 8955
 8956
 8957
 8958
 8959
 8960
 8961
 8962
 8963
 8964
 8965
 8966
 8967
 8968
 8969
 8970
 8971
 8972
 8973
 8974
 8975
 8976
 8977
 8978
 8979
 8980
 8981
 8982
 8983
 8984
 8985
 8986
 8987
 8988
 8989
 8990
 8991
 8992
 8993
 8994
 8995
 8996
 8997
 8998
 8999
 9000
 9001
 9002
 9003
 9004
 9005
 9006
 9007
 9008
 9009
 9010
 9011
 9012
 9013
 9014
 9015
 9016
 9017
 9018
 9019
 9020
 9021
 9022
 9023
 9024
 9025
 9026
 9027
 9028
 9029
 9030
 9031
 9032
 9033
 9034
 9035
 9036
 9037
 9038
 9039
 9040
 9041
 9042
 9043
 9044
 9045
 9046
 9047
 9048
 9049
 9050
 9051
 9052
 9053
 9054
 9055
 9056
 9057
 9058
 9059
 9060
 9061
 9062
 9063
 9064
 9065
 9066
 9067
 9068
 9069
 9070
 9071
 9072
 9073
 9074
 9075
 9076
 9077
 9078
 9079
 9080
 9081
 9082
 9083
 9084
 9085
 9086
 9087
 9088
 9089
 9090
 9091
 9092
 9093
 9094
 9095
 9096
 9097
 9098
 9099
 9100
 9101
 9102
 9103
 9104
 9105
 9106
 9107
 9108
 9109
 9110
 9111
 9112
 9113
 9114
 9115
 9116
 9117
 9118
 9119
 9120
 9121
 9122
 9123
 9124
 9125
 9126
 9127
 9128
 9129
 9130
 9131
 9132
 9133
 9134
 9135
 9136
 9137
 9138
 9139
 9140
 9141
 9142
 9143
 9144
 9145
 9146
 9147
 9148
 9149
 9150
 9151
 9152
 9153
 9154
 9155
 9156
 9157
 9158
 9159
 9160
 9161
 9162
 9163
 9164
 9165
 9166
 9167
 9168
 9169
 9170
 9171
 9172
 9173
 9174
 9175
 9176
 9177
 9178
 9179
 9180
 9181
 9182
 9183
 9184
 9185
 9186
 9187
 9188
 9189
 9190
 9191
 9192
 9193
 9194
 9195
 9196
 9197
 9198
 9199
 9200
 9201
 9202
 9203
 9204
 9205
 9206
 9207
 9208
 9209
 9210
 9211
 9212
 9213
 9214
 9215
 9216
 9217
 9218
 9219
 9220
 9221
 9222
 9223
 9224
 9225
 9226
 9227
 9228
 9229
 9230
 9231
 9232
 9233
 9234
 9235
 9236
 9237
 9238
 9239
 9240
 9241
 9242
 9243
 9244
 9245
 9246
 9247
 9248
 9249
 9250
 9251
 9252
 9253
 9254
 9255
 9256
 9257
 9258
 9259
 9260
 9261
 9262
 9263
 9264
 9265
 9266
 9267
 9268
 9269
 9270
 9271
 9272
 9273
 9274
 9275
 9276
 9277
 9278
 9279
 9280
 9281
 9282
 9283
 9284
 9285
 9286
 9287
 9288
 9289
 9290
 9291
 9292
 9293
 9294
 9295
 9296
 9297
 9298
 9299
 9300
 9301
 9302
 9303
 9304
 9305
 9306
 9307
 9308
 9309
 9310
 9311
 9312
 9313
 9314
 9315
 9316
 9317
 9318
 9319
 9320
 9321
 9322
 9323
 9324
 9325
 9326
 9327
 9328
 9329
 9330
 9331
 9332
 9333
 9334
 9335
 9336
 9337
 9338
 9339
 9340
 9341
 9342
 9343
 9344
 9345
 9346
 9347
 9348
 9349
 9350
 9351
 9352
 9353
 9354
 9355
 9356
 9357
 9358
 9359
 9360
 9361
 9362
 9363
 9364
 9365
 9366
 9367
 9368
 9369
 9370
 9371
 9372
 9373
 9374
 9375
 9376
 9377
 9378
 9379
 9380
 9381
 9382
 9383
 9384
 9385
 9386
 9387
 9388
 9389
 9390
 9391
 9392
 9393
 9394
 9395
 9396
 9397
 9398
 9399
 9400
 9401
 9402
 9403
 9404
 9405
 9406
 9407
 9408
 9409
 9410
 9411
 9412
 9413
 9414
 9415
 9416
 9417
 9418
 9419
 9420
 9421
 9422
 9423
 9424
 9425
 9426
 9427
 9428
 9429
 9430
 9431
 9432
 9433
 9434
 9435
 9436
 9437
 9438
 9439
 9440
 9441
 9442
 9443
 9444
 9445
 9446
 9447
 9448
 9449
 9450
 9451
 9452
 9453
 9454
 9455
 9456
 9457
 9458
 9459
 9460
 9461
 9462
 9463
 9464
 9465
 9466
 9467
 9468
 9469
 9470
 9471
 9472
 9473
 9474
 9475
 9476
 9477
 9478
 9479
 9480
 9481
 9482
 9483
 9484
 9485
 9486
 9487
 9488
 9489
 9490
 9491
 9492
 9493
 9494
 9495
 9496
 9497
 9498
 9499
 9500
 9501
 9502
 9503
 9504
 9505
 9506
 9507
 9508
 9509
 9510
 9511
 9512
 9513
 9514
 9515
 9516
 9517
 9518
 9519
 9520
 9521
 9522
 9523
 9524
 9525
 9526
 9527
 9528
 9529
 9530
 9531
 9532
 9533
 9534
 9535
 9536
 9537
 9538
 9539
 9540
 9541
 9542
 9543
 9544
 9545
 9546
 9547
 9548
 9549
 9550
 9551
 9552
 9553
 9554
 9555
 9556
 9557
 9558
 9559
 9560
 9561
 9562
 9563
 9564
 9565
 9566
 9567
 9568
 9569
 9570
 9571
 9572
 9573
 9574
 9575
 9576
 9577
 9578
 9579
 9580
 9581
 9582
 9583
 9584
 9585
 9586
 9587
 9588
 9589
 9590
 9591
 9592
 9593
 9594
 9595
 9596
 9597
 9598
 9599
 9600
 9601
 9602
 9603
 9604
 9605
 9606
 9607
 9608
 9609
 9610
 9611
 9612
 9613
 9614
 9615
 9616
 9617
 9618
 9619
 9620
 9621
 9622
 9623
 9624
 9625
 9626
 9627
 9628
 9629
 9630
 9631
 9632
 9633
 9634
 9635
 9636
 9637
 9638
 9639
 9640
 9641
 9642
 9643
 9644
 9645
 9646
 9647
 9648
 9649
 9650
 9651
 9652
 9653
 9654
 9655
 9656
 9657
 9658
 9659
 9660
 9661
 9662
 9663
 9664
 9665
 9666
 9667
 9668
 9669
 9670
 9671
 9672
 9673
 9674
 9675
 9676
 9677
 9678
 9679
 9680
 9681
 9682
 9683
 9684
 9685
 9686
 9687
 9688
 9689
 9690
 9691
 9692
 9693
 9694
 9695
 9696
 9697
 9698
 9699
 9700
 9701
 9702
 9703
 9704
 9705
 9706
 9707
 9708
 9709
 9710
 9711
 9712
 9713
 9714
 9715
 9716
 9717
 9718
 9719
 9720
 9721
 9722
 9723
 9724
 9725
 9726
 9727
 9728
 9729
 9730
 9731
 9732
 9733
 9734
 9735
 9736
 9737
 9738
 9739
 9740
 9741
 9742
 9743
 9744
 9745
 9746
 9747
 9748
 9749
 9750
 9751
 9752
 9753
 9754
 9755
 9756
 9757
 9758
 9759
 9760
 9761
 9762
 9763
 9764
 9765
 9766
 9767
 9768
 9769
 9770
 9771
 9772
 9773
 9774
 9775
 9776
 9777
 9778
 9779
 9780
 9781
 9782
 9783
 9784
 9785
 9786
 9787
 9788
 9789
 9790
 9791
 9792
 9793
 9794
 9795
 9796
 9797
 9798
 9799
 9800
 9801
 9802
 9803
 9804
 9805
 9806
 9807
 9808
 9809
 9810
 9811
 9812
 9813
 9814
 9815
 9816
 9817
 9818
 9819
 9820
 9821
 9822
 9823
 9824
 9825
 9826
 9827
 9828
 9829
 9830
 9831
 9832
 9833
 9834
 9835
 9836
 9837
 9838
 9839
 9840
 9841
 9842
 9843
 9844
 9845
 9846
 9847
 9848
 9849
 9850
 9851
 9852
 9853
 9854
 9855
 9856
 9857
 9858
 9859
 9860
 9861
 9862
 9863
 9864
 9865
 9866
 9867
 9868
 9869
 9870
 9871
 9872
 9873
 9874
 9875
 9876
 9877
 9878
 9879
 9880
 9881
 9882
 9883
 9884
 9885
 9886
 9887
 9888
 9889
 9890
 9891
 9892
 9893
 9894
 9895
 9896
 9897
 9898
 9899
 9900
 9901
 9902
 9903
 9904
 9905
 9906
 9907
 9908
 9909
 9910
 9911
 9912
 9913
 9914
 9915
 9916
 9917
 9918
 9919
 9920
 9921
 9922
 9923
 9924
 9925
 9926
 9927
 9928
 9929
 9930
 9931
 9932
 9933
 9934
 9935
 9936
 9937
 9938
 9939
 9940
 9941
 9942
 9943
 9944
 9945
 9946
 9947
 9948
 9949
 9950
 9951
 9952
 9953
 9954
 9955
 9956
 9957
 9958
 9959
 9960
 9961
 9962
 9963
 9964
 9965
 9966
 9967
 9968
 9969
 9970
 9971
 9972
 9973
 9974
 9975
 9976
 9977
 9978
 9979
 9980
 9981
 9982
 9983
 9984
 9985
 9986
 9987
 9988
 9989
 9990
 9991
 9992
 9993
 9994
 9995
 9996
 9997
 9998
 9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
/*
 * Copyright (C) 2001-2004,2009,2010 Red Hat, Inc.
 * Copyright © 2008, 2009, 2010 Christian Persch
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "config.h"

#include <math.h>
#include <search.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <fcntl.h>
#ifdef HAVE_SYS_TERMIOS_H
#include <sys/termios.h>
#endif

#include <glib.h>
#include <glib-unix.h>
#include <glib/gi18n-lib.h>

#include <bte/bte.h>
#include "bteinternal.hh"
#include "bidi.hh"
#include "buffer.h"
#include "debug.h"
#include "reaper.hh"
#include "ring.hh"
#include "ringview.hh"
#include "caps.hh"
#include "widget.hh"

#ifdef HAVE_WCHAR_H
#include <wchar.h>
#endif
#ifdef HAVE_SYS_SYSLIMITS_H
#include <sys/syslimits.h>
#endif
#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#include <glib.h>
#include <glib-object.h>
#include <cdk/cdk.h>
#include <ctk/ctk.h>
#include <pango/pango.h>
#include "keymap.h"
#include "marshal.h"
#include "btepty.h"
#include "btectk.hh"
#include "cxx-utils.hh"
#include "gobject-glue.hh"

#ifdef WITH_A11Y
#include "bteaccess.h"
#endif

#include <new> /* placement new */

using namespace std::literals;

#ifndef HAVE_ROUND
static inline double round(double x) {
	if(x - floor(x) < 0.5) {
		return floor(x);
	} else {
		return ceil(x);
	}
}
#endif

#define WORD_CHAR_EXCEPTIONS_DEFAULT "-#%&+,./=?@\\_~\302\267"sv

#define I_(string) (g_intern_static_string(string))

#define BTE_DRAW_OPAQUE (1.0)

namespace bte {
namespace terminal {

static int _bte_unichar_width(gunichar c, int utf8_ambiguous_width);
static void stop_processing(bte::terminal::Terminal* that);
static void add_process_timeout(bte::terminal::Terminal* that);
static void add_update_timeout(bte::terminal::Terminal* that);
static void remove_update_timeout(bte::terminal::Terminal* that);

static gboolean process_timeout (gpointer data) noexcept;
static gboolean update_timeout (gpointer data) noexcept;
static cairo_region_t *bte_cairo_get_clip_region (cairo_t *cr);

/* these static variables are guarded by the CDK mutex */
static guint process_timeout_tag = 0;
static gboolean in_process_timeout;
static guint update_timeout_tag = 0;
static gboolean in_update_timeout;
static GList *g_active_terminals;

static int
_bte_unichar_width(gunichar c, int utf8_ambiguous_width)
{
        if (G_LIKELY (c < 0x80))
                return 1;
        if (G_UNLIKELY (g_unichar_iszerowidth (c)))
                return 0;
        if (G_UNLIKELY (g_unichar_iswide (c)))
                return 2;
        if (G_LIKELY (utf8_ambiguous_width == 1))
                return 1;
        if (G_UNLIKELY (g_unichar_iswide_cjk (c)))
                return 2;
        return 1;
}

static void
bte_g_array_fill(GArray *array, gconstpointer item, guint final_size)
{
	if (array->len >= final_size)
		return;

	final_size -= array->len;
	do {
		g_array_append_vals(array, item, 1);
	} while (--final_size);
}

void
Terminal::unset_widget() noexcept
{
        m_real_widget = nullptr;
        m_terminal = nullptr;
        m_widget = nullptr;
}

// FIXMEchpe replace this with a method on BteRing
BteRowData*
Terminal::ring_insert(bte::grid::row_t position,
                                bool fill)
{
	BteRowData *row;
	BteRing *ring = m_screen->row_data;
        bool const not_default_bg = (m_color_defaults.attr.back() != BTE_DEFAULT_BG);

	while (G_UNLIKELY (_bte_ring_next (ring) < position)) {
                row = _bte_ring_append (ring, get_bidi_flags());
                if (not_default_bg)
                        _bte_row_data_fill (row, &m_color_defaults, m_column_count);
	}
        row = _bte_ring_insert (ring, position, get_bidi_flags());
        if (fill && not_default_bg)
                _bte_row_data_fill (row, &m_color_defaults, m_column_count);
	return row;
}

// FIXMEchpe replace this with a method on BteRing
BteRowData*
Terminal::ring_append(bool fill)
{
	return ring_insert(_bte_ring_next(m_screen->row_data), fill);
}

// FIXMEchpe replace this with a method on BteRing
void
Terminal::ring_remove(bte::grid::row_t position)
{
	_bte_ring_remove(m_screen->row_data, position);
}

/* Reset defaults for character insertion. */
void
Terminal::reset_default_attributes(bool reset_hyperlink)
{
        auto const hyperlink_idx_save = m_defaults.attr.hyperlink_idx;
        m_defaults = m_color_defaults = basic_cell;
        if (!reset_hyperlink)
                m_defaults.attr.hyperlink_idx = hyperlink_idx_save;
}

//FIXMEchpe this function is bad
inline bte::view::coord_t
Terminal::scroll_delta_pixel() const
{
        return round(m_screen->scroll_delta * m_cell_height);
}

/*
 * Terminal::pixel_to_row:
 * @y: Y coordinate is relative to viewport, top padding excluded
 *
 * Returns: absolute row
 */
inline bte::grid::row_t
Terminal::pixel_to_row(bte::view::coord_t y) const
{
        return (scroll_delta_pixel() + y) / m_cell_height;
}

/*
 * Terminal::pixel_to_row:
 * @row: absolute row
 *
 * Returns: Y coordinate relative to viewport with top padding excluded. If the row is
 *   outside the viewport, may return any value < 0 or >= height
 */
inline bte::view::coord_t
Terminal::row_to_pixel(bte::grid::row_t row) const
{
        // FIXMEchpe this is bad!
        return row * m_cell_height - (glong)round(m_screen->scroll_delta * m_cell_height);
}

inline bte::grid::row_t
Terminal::first_displayed_row() const
{
        return pixel_to_row(0);
}

inline bte::grid::row_t
Terminal::last_displayed_row() const
{
        /* Get the logical row number displayed at the bottom pixel position */
        auto r = pixel_to_row(m_view_usable_extents.height() - 1);

        /* If we have an extra padding at the bottom which is currently unused,
         * this number is one too big. Adjust here.
         * E.g. have a terminal of size 80 x 24.5.
         * Initially the bottom displayed row is (0-based) 23, but r is now 24.
         * After producing more than a screenful of content and scrolling back
         * all the way to the top, the bottom displayed row is (0-based) 24. */
        r = MIN (r, m_screen->insert_delta + m_row_count - 1);
        return r;
}

/* Checks if the cursor is potentially at least partially onscreen.
 * An outline cursor has an additional height of BTE_LINE_WIDTH pixels.
 * It's also intentionally painted over the padding, up to BTE_LINE_WIDTH
 * pixels under the real contents area. This method takes these into account.
 * Only checks the cursor's row; not its visibility, shape, or offscreen column.
 */
inline bool
Terminal::cursor_is_onscreen() const noexcept
{
        /* Note: the cursor can only be offscreen below the visible area, not above. */
        auto cursor_top = row_to_pixel (m_screen->cursor.row) - BTE_LINE_WIDTH;
        auto display_bottom = m_view_usable_extents.height() + MIN(m_padding.bottom, BTE_LINE_WIDTH);
        return cursor_top < display_bottom;
}

/* Invalidate the requested rows. This is to be used when only the desired
 * rendering changes but not the underlying data, e.g. moving or blinking
 * cursor, highligthing with the mouse etc.
 *
 * Note that row_end is inclusive. This is not as nice as end-exclusive,
 * but saves us from a +1 almost everywhere where this method is called.
 */
void
Terminal::invalidate_rows(bte::grid::row_t row_start,
                          bte::grid::row_t row_end /* inclusive */)
{
	if (G_UNLIKELY (!widget_realized()))
                return;

        if (m_invalidated_all)
		return;

        if (G_UNLIKELY (row_end < row_start))
                return;

	_bte_debug_print (BTE_DEBUG_UPDATES,
                          "Invalidating rows %ld..%ld.\n",
                          row_start, row_end);
	_bte_debug_print (BTE_DEBUG_WORK, "?");

        /* Scrolled back, visible parts didn't change. */
        if (row_start > last_displayed_row())
                return;

        /* Recognize if we're about to invalidate everything. */
        if (row_start <= first_displayed_row() &&
            row_end >= last_displayed_row()) {
		invalidate_all();
		return;
	}

        cairo_rectangle_int_t rect;
	/* Convert the column and row start and end to pixel values
	 * by multiplying by the size of a character cell.
	 * Always include the extra pixel border and overlap pixel.
	 */
        // FIXMEegmont invalidate the left and right padding too
        rect.x = -1;
        int xend = m_column_count * m_cell_width + 1;
        rect.width = xend - rect.x;

        /* Always add at least BTE_LINE_WIDTH pixels so the outline block cursor fits */
        rect.y = row_to_pixel(row_start) - std::max(cell_overflow_top(), BTE_LINE_WIDTH);
        int yend = row_to_pixel(row_end + 1) + std::max(cell_overflow_bottom(), BTE_LINE_WIDTH);
        rect.height = yend - rect.y;

	_bte_debug_print (BTE_DEBUG_UPDATES,
			"Invalidating pixels at (%d,%d)x(%d,%d).\n",
			rect.x, rect.y, rect.width, rect.height);

	if (m_active_terminals_link != nullptr) {
                g_array_append_val(m_update_rects, rect);
		/* Wait a bit before doing any invalidation, just in
		 * case updates are coming in really soon. */
		add_update_timeout(this);
	} else {
                auto allocation = get_allocated_rect();
                rect.x += allocation.x + m_padding.left;
                rect.y += allocation.y + m_padding.top;
                cairo_region_t *region = cairo_region_create_rectangle(&rect);
		ctk_widget_queue_draw_region(m_widget, region);
                cairo_region_destroy(region);
	}

	_bte_debug_print (BTE_DEBUG_WORK, "!");
}

/* Invalidate the requested rows, extending the region in both directions up to
 * an explicit newline (or a safety limit) to invalidate entire paragraphs of text.
 * This is to be used whenever the underlying data changes, because any such
 * change might alter the desired BiDi, syntax highlighting etc. of all other
 * rows of the involved paragraph(s).
 *
 * Note that row_end is inclusive. This is not as nice as end-exclusive,
 * but saves us from a +1 almost everywhere where this method is called.
 */
void
Terminal::invalidate_rows_and_context(bte::grid::row_t row_start,
                                      bte::grid::row_t row_end /* inclusive */)
{
        if (G_UNLIKELY (!widget_realized()))
                return;

        if (m_invalidated_all)
                return;

        if (G_UNLIKELY (row_end < row_start))
                return;

        _bte_debug_print (BTE_DEBUG_UPDATES,
                          "Invalidating rows %ld..%ld and context.\n",
                          row_start, row_end);

        /* Safety limit: Scrolled back by so much that changes to the
         * writable area may not affect the current viewport's rendering. */
        if (m_screen->insert_delta - BTE_RINGVIEW_PARAGRAPH_LENGTH_MAX > last_displayed_row())
                return;

        /* Extending the start is a bit tricky.
         * First extend it (towards lower numbered indices), but only up to
         * insert_delta - 1. Remember that the row at insert_delta - 1 is
         * still in the ring, hence checking its soft_wrapped flag is fast. */
        while (row_start >= m_screen->insert_delta) {
                if (!m_screen->row_data->is_soft_wrapped(row_start - 1))
                        break;
                row_start--;
        }

        /* If we haven't seen a newline yet, stop walking backwards row by row.
         * This is because we might need to access row_stream in order to check
         * the wrapped state, a way too expensive operation while processing
         * incoming data. Let displaying do extra work instead.
         * So just invalidate everything to the top. */
        if (row_start < m_screen->insert_delta) {
                row_start = first_displayed_row();
        }

        /* Extending the end is simple. Just walk until we go offscreen or
         * find an explicit newline. */
        while (row_end < last_displayed_row()) {
                if (!m_screen->row_data->is_soft_wrapped(row_end))
                        break;
                row_end++;
        }

        invalidate_rows(row_start, row_end);
}

/* Convenience methods */
void
Terminal::invalidate_row(bte::grid::row_t row)
{
        invalidate_rows(row, row);
}

void
Terminal::invalidate_row_and_context(bte::grid::row_t row)
{
        invalidate_rows_and_context(row, row);
}

/* This is only used by the selection code, so no need to extend the area. */
void
Terminal::invalidate(bte::grid::span const& s)
{
        if (!s.empty())
                invalidate_rows(s.start_row(), s.last_row());
}

/* Invalidates the symmetrical difference ("XOR" area) of the two spans.
 * This is only used by the selection code, so no need to extend the area. */
void
Terminal::invalidate_symmetrical_difference(bte::grid::span const& a, bte::grid::span const& b, bool block)
{
        if (a.empty() || b.empty() || a.start() >= b.end() || b.start() >= a.end()) {
                /* One or both are empty (invalidate() will figure out which), or disjoint intervals. */
                invalidate (a);
                invalidate (b);
                return;
        }

        if (block) {
                /* We could optimize when the columns don't change, probably not worth it. */
                invalidate_rows (std::min (a.start_row(), b.start_row()),
                                 std::max (a.last_row(),  b.last_row()));
        } else {
                if (a.start() != b.start()) {
                        invalidate_rows (std::min (a.start_row(), b.start_row()),
                                         std::max (a.start_row(), b.start_row()));
                }
                if (a.end() != b.end()) {
                        invalidate_rows (std::min (a.last_row(), b.last_row()),
                                         std::max (a.last_row(), b.last_row()));
                }
        }
}

void
Terminal::invalidate_all()
{
	if (G_UNLIKELY (!widget_realized()))
                return;

	if (m_invalidated_all) {
		return;
	}

	_bte_debug_print (BTE_DEBUG_WORK, "*");
	_bte_debug_print (BTE_DEBUG_UPDATES, "Invalidating all.\n");

	/* replace invalid regions with one covering the whole terminal */
	reset_update_rects();
	m_invalidated_all = TRUE;

        if (m_active_terminals_link != nullptr) {
                auto allocation = get_allocated_rect();
                cairo_rectangle_int_t rect;
                rect.x = -m_padding.left;
                rect.y = -m_padding.top;
                rect.width = allocation.width;
                rect.height = allocation.height;

                g_array_append_val(m_update_rects, rect);
		/* Wait a bit before doing any invalidation, just in
		 * case updates are coming in really soon. */
		add_update_timeout(this);
	} else {
                ctk_widget_queue_draw(m_widget);
	}
}

/* Find the row in the given position in the backscroll buffer.
 * Note that calling this method may invalidate the return value of
 * a previous find_row_data() call. */
// FIXMEchpe replace this with a method on BteRing
BteRowData const*
Terminal::find_row_data(bte::grid::row_t row) const
{
	BteRowData const* rowdata = nullptr;

	if (G_LIKELY(_bte_ring_contains(m_screen->row_data, row))) {
		rowdata = _bte_ring_index(m_screen->row_data, row);
	}
	return rowdata;
}

/* Find the row in the given position in the backscroll buffer. */
// FIXMEchpe replace this with a method on BteRing
BteRowData*
Terminal::find_row_data_writable(bte::grid::row_t row) const
{
	BteRowData *rowdata = nullptr;

	if (G_LIKELY (_bte_ring_contains(m_screen->row_data, row))) {
		rowdata = _bte_ring_index_writable(m_screen->row_data, row);
	}
	return rowdata;
}

/* Find the character an the given position in the backscroll buffer.
 * Note that calling this method may invalidate the return value of
 * a previous find_row_data() call. */
// FIXMEchpe replace this with a method on BteRing
BteCell const*
Terminal::find_charcell(bte::grid::column_t col,
                                  bte::grid::row_t row) const
{
	BteRowData const* rowdata;
	BteCell const* ret = nullptr;

	if (_bte_ring_contains(m_screen->row_data, row)) {
		rowdata = _bte_ring_index(m_screen->row_data, row);
		ret = _bte_row_data_get (rowdata, col);
	}
	return ret;
}

// FIXMEchpe replace this with a method on BteRing
bte::grid::column_t
Terminal::find_start_column(bte::grid::column_t col,
                                      bte::grid::row_t row) const
{
	BteRowData const* row_data = find_row_data(row);
	if (G_UNLIKELY (col < 0))
		return col;
	if (row_data != nullptr) {
		const BteCell *cell = _bte_row_data_get (row_data, col);
		while (col > 0 && cell != NULL && cell->attr.fragment()) {
			cell = _bte_row_data_get (row_data, --col);
		}
	}
	return MAX(col, 0);
}

// FIXMEchpe replace this with a method on BteRing
bte::grid::column_t
Terminal::find_end_column(bte::grid::column_t col,
                                    bte::grid::row_t row) const
{
	BteRowData const* row_data = find_row_data(row);
	gint columns = 0;
	if (G_UNLIKELY (col < 0))
		return col;
	if (row_data != NULL) {
		const BteCell *cell = _bte_row_data_get (row_data, col);
		while (col > 0 && cell != NULL && cell->attr.fragment()) {
			cell = _bte_row_data_get (row_data, --col);
		}
		if (cell) {
			columns = cell->attr.columns() - 1;
		}
	}
        // FIXMEchp m__column_count - 1 ?
	return MIN(col + columns, m_column_count);
}

/* Sets the line ending to hard wrapped (explicit newline).
 * Takes care of invalidating if this operation splits a paragraph into two. */
void
Terminal::set_hard_wrapped(bte::grid::row_t row)
{
        /* We can set the row just above insert_delta to hard wrapped. */
        g_assert_cmpint(row, >=, m_screen->insert_delta - 1);
        g_assert_cmpint(row, <, m_screen->insert_delta + m_row_count);

        BteRowData *row_data = find_row_data_writable(row);

        /* It's okay for this row not to be covered by the ring. */
        if (row_data == nullptr || !row_data->attr.soft_wrapped)
                return;

        row_data->attr.soft_wrapped = false;

        m_ringview.invalidate();
        invalidate_rows_and_context(row, row + 1);
}

/* Sets the line ending to soft wrapped (overflow to the next line).
 * Takes care of invalidating if this operation joins two paragraphs into one.
 * Also makes sure that the joined new paragraph receives the first one's bidi flags. */
void
Terminal::set_soft_wrapped(bte::grid::row_t row)
{
        g_assert_cmpint(row, >=, m_screen->insert_delta);
        g_assert_cmpint(row, <, m_screen->insert_delta + m_row_count);

        BteRowData *row_data = find_row_data_writable(row);
        g_assert(row_data != nullptr);

        if (row_data->attr.soft_wrapped)
                return;

        row_data->attr.soft_wrapped = true;

        /* Each paragraph has to have consistent bidi flags across all of its rows.
         * Spread the first paragraph's flags across the second one (if they differ). */
        guint8 bidi_flags = row_data->attr.bidi_flags;
        bte::grid::row_t i = row + 1;
        row_data = find_row_data_writable(i);
        if (row_data != nullptr && row_data->attr.bidi_flags != bidi_flags) {
                do {
                        row_data->attr.bidi_flags = bidi_flags;
                        if (!row_data->attr.soft_wrapped)
                                break;
                        row_data = find_row_data_writable(++i);
                } while (row_data != nullptr);
        }

        m_ringview.invalidate();
        invalidate_rows_and_context(row, row + 1);
}

/* Determine the width of the portion of the preedit string which lies
 * to the left of the cursor, or the entire string, in columns. */
// FIXMEchpe this is for the view, so use int not gssize
// FIXMEchpe this is only ever called with left_only=false, so remove the param
gssize
Terminal::get_preedit_width(bool left_only)
{
	gssize ret = 0;

        char const *preedit = m_im_preedit.c_str();
        for (int i = 0;
             // FIXMEchpe preddit is != NULL at the start, and next_char never returns NULL either
             (preedit != NULL) &&
		     (preedit[0] != '\0') &&
		     (!left_only || (i < m_im_preedit_cursor));
             i++) {
                gunichar c = g_utf8_get_char(preedit);
                ret += _bte_unichar_width(c, m_utf8_ambiguous_width);
                preedit = g_utf8_next_char(preedit);
        }

	return ret;
}

/* Determine the length of the portion of the preedit string which lies
 * to the left of the cursor, or the entire string, in gunichars. */
// FIXMEchpe this returns gssize but inside it uses int...
gssize
Terminal::get_preedit_length(bool left_only)
{
	ssize_t i = 0;

        char const *preedit = m_im_preedit.c_str();
        for (i = 0;
             // FIXMEchpe useless check, see above
             (preedit != NULL) &&
		     (preedit[0] != '\0') &&
		     (!left_only || (i < m_im_preedit_cursor));
             i++) {
                preedit = g_utf8_next_char(preedit);
        }

	return i;
}

void
Terminal::invalidate_cursor_once(bool periodic)
{
        if (G_UNLIKELY(!widget_realized()))
                return;

	if (m_invalidated_all) {
		return;
	}

	if (periodic) {
		if (!m_cursor_blinks) {
			return;
		}
	}

	if (m_modes_private.DEC_TEXT_CURSOR()) {
                auto row = m_screen->cursor.row;

		_bte_debug_print(BTE_DEBUG_UPDATES,
                                 "Invalidating cursor in row %ld.\n",
                                 row);
                invalidate_row(row);
	}
}

/* Invalidate the cursor repeatedly. */
// FIXMEchpe this continually adds and removes the blink timeout. Find a better solution
bool
Terminal::cursor_blink_timer_callback()
{
	m_cursor_blink_state = !m_cursor_blink_state;
	m_cursor_blink_time += m_cursor_blink_cycle;

	invalidate_cursor_once(true);

	/* only disable the blink if the cursor is currently shown.
	 * else, wait until next time.
	 */
	if (m_cursor_blink_time / 1000 >= m_cursor_blink_timeout &&
	    m_cursor_blink_state) {
		return false;
        }

        m_cursor_blink_timer.schedule(m_cursor_blink_cycle, bte::glib::Timer::Priority::eLOW);
        return false;
}

/* Emit a "selection_changed" signal. */
void
Terminal::emit_selection_changed()
{
	_bte_debug_print(BTE_DEBUG_SIGNALS,
			"Emitting `selection-changed'.\n");
	g_signal_emit(m_terminal, signals[SIGNAL_SELECTION_CHANGED], 0);
}

/* Emit a "commit" signal.
 * FIXMEchpe: remove this function
 */
void
Terminal::emit_commit(std::string_view const& str)
{
        if (str.size() == 0)
                return;

        if (!widget() || !widget()->should_emit_signal(SIGNAL_COMMIT))
                return;

	_bte_debug_print(BTE_DEBUG_SIGNALS,
                         "Emitting `commit' of %" G_GSSIZE_FORMAT" bytes.\n", str.size());

        // FIXMEchpe we do know for a fact that all uses of this function
        // actually passed a 0-terminated string, so we can use @str directly
        std::string result{str}; // 0-terminated

        _BTE_DEBUG_IF(BTE_DEBUG_KEYBOARD) {
                for (size_t i = 0; i < result.size(); i++) {
                        if ((((guint8) result[i]) < 32) ||
                            (((guint8) result[i]) > 127)) {
                                g_printerr(
                                           "Sending <%02x> "
                                           "to child.\n",
                                           result[i]);
                        } else {
                                g_printerr(
                                           "Sending '%c' "
                                           "to child.\n",
                                           result[i]);
                        }
                }
        }

	g_signal_emit(m_terminal, signals[SIGNAL_COMMIT], 0, result.c_str(), (guint)result.size());
}

void
Terminal::queue_contents_changed()
{
	_bte_debug_print(BTE_DEBUG_SIGNALS,
			"Queueing `contents-changed'.\n");
	m_contents_changed_pending = true;
}

//FIXMEchpe this has only one caller
void
Terminal::queue_cursor_moved()
{
	_bte_debug_print(BTE_DEBUG_SIGNALS,
			"Queueing `cursor-moved'.\n");
	m_cursor_moved_pending = true;
}

void
Terminal::emit_eof()
{
        if (widget())
                widget()->emit_eof();
}

static gboolean
emit_eof_idle_cb(BteTerminal *terminal)
try
{
        _bte_terminal_get_impl(terminal)->emit_eof();

        return G_SOURCE_REMOVE;
}
catch (...)
{
        bte::log_exception();
        return G_SOURCE_REMOVE;
}

void
Terminal::queue_eof()
{
        _bte_debug_print(BTE_DEBUG_SIGNALS, "Queueing `eof'.\n");

        g_idle_add_full(G_PRIORITY_HIGH,
                        (GSourceFunc)emit_eof_idle_cb,
                        g_object_ref(m_terminal),
                        g_object_unref);
}

void
Terminal::emit_child_exited()
{
        auto const status = m_child_exit_status;
        m_child_exit_status = -1;

        if (widget())
                widget()->emit_child_exited(status);
}

static gboolean
emit_child_exited_idle_cb(BteTerminal *terminal)
try
{
        _bte_terminal_get_impl(terminal)->emit_child_exited();

        return G_SOURCE_REMOVE;
}
catch (...)
{
        bte::log_exception();
        return G_SOURCE_REMOVE;
}

/* Emit a "child-exited" signal on idle, so that if the handler destroys
 * the terminal, we're not deep within terminal code callstack
 */
void
Terminal::queue_child_exited()
{
        _bte_debug_print(BTE_DEBUG_SIGNALS, "Queueing `child-exited'.\n");
        m_child_exited_after_eos_pending = false;

        g_idle_add_full(G_PRIORITY_HIGH,
                        (GSourceFunc)emit_child_exited_idle_cb,
                        g_object_ref(m_terminal),
                        g_object_unref);
}

bool
Terminal::child_exited_eos_wait_callback()
{
        /* If we get this callback, there has been some time elapsed
         * after child-exited, but no EOS yet. This happens for example
         * when the primary child started other processes in the background,
         * which inherited the PTY, and thus keep it open, see
         * https://gitlab.gnome.org/GNOME/bte/issues/204
         *
         * Force an EOS.
         */
        if (pty())
                pty_io_read(pty()->fd(), G_IO_HUP);

        return false; // don't run again
}

/* Emit a "char-size-changed" signal. */
void
Terminal::emit_char_size_changed(int width,
                                           int height)
{
	_bte_debug_print(BTE_DEBUG_SIGNALS,
			"Emitting `char-size-changed'.\n");
        /* FIXME on next API break, change the signature */
	g_signal_emit(m_terminal, signals[SIGNAL_CHAR_SIZE_CHANGED], 0,
			      (guint)width, (guint)height);
}

/* Emit an "increase-font-size" signal. */
void
Terminal::emit_increase_font_size()
{
	_bte_debug_print(BTE_DEBUG_SIGNALS,
			"Emitting `increase-font-size'.\n");
	g_signal_emit(m_terminal, signals[SIGNAL_INCREASE_FONT_SIZE], 0);
}

/* Emit a "decrease-font-size" signal. */
void
Terminal::emit_decrease_font_size()
{
	_bte_debug_print(BTE_DEBUG_SIGNALS,
			"Emitting `decrease-font-size'.\n");
	g_signal_emit(m_terminal, signals[SIGNAL_DECREASE_FONT_SIZE], 0);
}

/* Emit a "text-inserted" signal. */
void
Terminal::emit_text_inserted()
{
#ifdef WITH_A11Y
	if (!m_accessible_emit) {
		return;
	}
	_bte_debug_print(BTE_DEBUG_SIGNALS,
			"Emitting `text-inserted'.\n");
	g_signal_emit(m_terminal, signals[SIGNAL_TEXT_INSERTED], 0);
#endif
}

/* Emit a "text-deleted" signal. */
void
Terminal::emit_text_deleted()
{
#ifdef WITH_A11Y
	if (!m_accessible_emit) {
		return;
	}
	_bte_debug_print(BTE_DEBUG_SIGNALS,
			"Emitting `text-deleted'.\n");
	g_signal_emit(m_terminal, signals[SIGNAL_TEXT_DELETED], 0);
#endif
}

/* Emit a "text-modified" signal. */
void
Terminal::emit_text_modified()
{
#ifdef WITH_A11Y
	if (!m_accessible_emit) {
		return;
	}
	_bte_debug_print(BTE_DEBUG_SIGNALS,
                         "Emitting `text-modified'.\n");
	g_signal_emit(m_terminal, signals[SIGNAL_TEXT_MODIFIED], 0);
#endif
}

/* Emit a "text-scrolled" signal. */
void
Terminal::emit_text_scrolled(long delta)
{
#ifdef WITH_A11Y
	if (!m_accessible_emit) {
		return;
	}
	_bte_debug_print(BTE_DEBUG_SIGNALS,
			"Emitting `text-scrolled'(%ld).\n", delta);
        // FIXMEchpe fix signal signature?
	g_signal_emit(m_terminal, signals[SIGNAL_TEXT_SCROLLED], 0, (int)delta);
#endif
}

void
Terminal::emit_copy_clipboard()
{
	_bte_debug_print(BTE_DEBUG_SIGNALS, "Emitting 'copy-clipboard'.\n");
	g_signal_emit(m_terminal, signals[SIGNAL_COPY_CLIPBOARD], 0);
}

void
Terminal::emit_paste_clipboard()
{
	_bte_debug_print(BTE_DEBUG_SIGNALS, "Emitting 'paste-clipboard'.\n");
	g_signal_emit(m_terminal, signals[SIGNAL_PASTE_CLIPBOARD], 0);
}

/* Emit a "hyperlink_hover_uri_changed" signal. */
void
Terminal::emit_hyperlink_hover_uri_changed(const CdkRectangle *bbox)
{
        GObject *object = G_OBJECT(m_terminal);

        _bte_debug_print(BTE_DEBUG_SIGNALS,
                         "Emitting `hyperlink-hover-uri-changed'.\n");
        g_signal_emit(m_terminal, signals[SIGNAL_HYPERLINK_HOVER_URI_CHANGED], 0, m_hyperlink_hover_uri, bbox);
        g_object_notify_by_pspec(object, pspecs[PROP_HYPERLINK_HOVER_URI]);
}

void
Terminal::deselect_all()
{
        if (!m_selection_resolved.empty()) {
		_bte_debug_print(BTE_DEBUG_SELECTION,
				"Deselecting all text.\n");

                m_selection_origin = m_selection_last = { -1, -1, 1 };
                resolve_selection();

		/* Don't free the current selection, as we need to keep
		 * hold of it for async copying from the clipboard. */

		emit_selection_changed();
	}
}

/* Clear the cache of the screen contents we keep. */
void
Terminal::match_contents_clear()
{
	match_hilite_clear();
	if (m_match_contents != nullptr) {
		g_free(m_match_contents);
		m_match_contents = nullptr;
	}
	if (m_match_attributes != nullptr) {
		g_array_free(m_match_attributes, TRUE);
		m_match_attributes = nullptr;
	}
}

void
Terminal::match_contents_refresh()

{
	match_contents_clear();
	GArray *array = g_array_new(FALSE, TRUE, sizeof(struct _BteCharAttributes));
        auto match_contents = get_text_displayed(true /* wrap */,
                                                 array);
        m_match_contents = g_string_free(match_contents, FALSE);
	m_match_attributes = array;
}

void
Terminal::regex_match_remove_all() noexcept
{
        auto& match_regexes = match_regexes_writable();
        match_regexes.clear();
        match_regexes.shrink_to_fit();

	match_hilite_clear();
}

void
Terminal::regex_match_remove(int tag) noexcept
{
        auto i = regex_match_get_iter(tag);
        if (i == std::end(m_match_regexes))
                return;

        match_regexes_writable().erase(i);
}

/*
 * match_rowcol_to_offset:
 * @terminal:
 * @column:
 * @row:
 * @offset_ptr: (out):
 * @sattr_ptr: (out):
 * @ettr_ptr: (out):
 *
 * Maps (row, column) to an offset in m_match_attributes, and returns
 * that offset in @offset_ptr, and the start and end of the corresponding
 * line in @sattr_ptr and @eattr_ptr.
 */
bool
Terminal::match_rowcol_to_offset(bte::grid::column_t column,
                                           bte::grid::row_t row,
                                           gsize *offset_ptr,
                                           gsize *sattr_ptr,
                                           gsize *eattr_ptr)
{
        /* FIXME: use gsize, after making sure the code below doesn't underflow offset */
        gssize offset, sattr, eattr;
        struct _BteCharAttributes *attr = NULL;

	/* Map the pointer position to a portion of the string. */
        // FIXME do a bsearch here?
	eattr = m_match_attributes->len;
	for (offset = eattr; offset--; ) {
		attr = &g_array_index(m_match_attributes,
				      struct _BteCharAttributes,
				      offset);
		if (row < attr->row) {
			eattr = offset;
		}
		if (row == attr->row &&
		    column >= attr->column && column < attr->column + attr->columns) {
			break;
		}
	}

	_BTE_DEBUG_IF(BTE_DEBUG_REGEX) {
		if (offset < 0)
			g_printerr("Cursor is not on a character.\n");
		else {
                        gunichar c;
                        char utf[7];
                        c = g_utf8_get_char (m_match_contents + offset);
                        utf[g_unichar_to_utf8(g_unichar_isprint(c) ? c : 0xFFFD, utf)] = 0;

			g_printerr("Cursor is on character U+%04X '%s' at %" G_GSSIZE_FORMAT ".\n",
                                   c, utf, offset);
                }
	}

	/* If the pointer isn't on a matchable character, bug out. */
	if (offset < 0) {
		return false;
	}

	/* If the pointer is on a newline, bug out. */
	if (m_match_contents[offset] == '\0') {
		_bte_debug_print(BTE_DEBUG_EVENTS,
                                 "Cursor is on newline.\n");
		return false;
	}

	/* Snip off any final newlines. */
	while (m_match_contents[eattr] == '\n' ||
               m_match_contents[eattr] == '\0') {
		eattr--;
	}
	/* and scan forwards to find the end of this line */
	while (!(m_match_contents[eattr] == '\n' ||
                 m_match_contents[eattr] == '\0')) {
		eattr++;
	}

	/* find the start of row */
	if (row == 0) {
		sattr = 0;
	} else {
		for (sattr = offset; sattr > 0; sattr--) {
			attr = &g_array_index(m_match_attributes,
					      struct _BteCharAttributes,
					      sattr);
			if (row > attr->row) {
				break;
			}
		}
	}
	/* Scan backwards to find the start of this line */
	while (sattr > 0 &&
		! (m_match_contents[sattr] == '\n' ||
                   m_match_contents[sattr] == '\0')) {
		sattr--;
	}
	/* and skip any initial newlines. */
	while (m_match_contents[sattr] == '\n' ||
               m_match_contents[sattr] == '\0') {
		sattr++;
	}
	if (eattr <= sattr) { /* blank line */
		return false;
	}
	if (eattr <= offset || sattr > offset) {
		/* nothing to match on this line */
		return false;
	}

        *offset_ptr = offset;
        *sattr_ptr = sattr;
        *eattr_ptr = eattr;

        _BTE_DEBUG_IF(BTE_DEBUG_REGEX) {
                struct _BteCharAttributes *_sattr, *_eattr;
                _sattr = &g_array_index(m_match_attributes,
                                        struct _BteCharAttributes,
                                        sattr);
                _eattr = &g_array_index(m_match_attributes,
                                        struct _BteCharAttributes,
                                        eattr - 1);
                g_printerr("Cursor is in line from %" G_GSIZE_FORMAT "(%ld,%ld) to %" G_GSIZE_FORMAT "(%ld,%ld)\n",
                           sattr, _sattr->column, _sattr->row,
                           eattr - 1, _eattr->column, _eattr->row);
        }

        return true;
}

/* creates a pcre match context with appropriate limits */
pcre2_match_context_8 *
Terminal::create_match_context()
{
        pcre2_match_context_8 *match_context;

        match_context = pcre2_match_context_create_8(nullptr /* general context */);
        pcre2_set_match_limit_8(match_context, 65536); /* should be plenty */
        pcre2_set_recursion_limit_8(match_context, 64); /* should be plenty */

        return match_context;
}

bool
Terminal::match_check_pcre(pcre2_match_data_8 *match_data,
                           pcre2_match_context_8 *match_context,
                           bte::base::Regex const* regex,
                           uint32_t match_flags,
                           gsize sattr,
                           gsize eattr,
                           gsize offset,
                           char **result_ptr,
                           gsize *start,
                           gsize *end,
                           gsize *sblank_ptr,
                           gsize *eblank_ptr)
{
        int (* match_fn) (const pcre2_code_8 *,
                          PCRE2_SPTR8, PCRE2_SIZE, PCRE2_SIZE, uint32_t,
                          pcre2_match_data_8 *, pcre2_match_context_8 *);
        gsize sblank = 0, eblank = G_MAXSIZE;
        gsize position, line_length;
        const char *line;
        int r = 0;

        if (regex->jited())
                match_fn = pcre2_jit_match_8;
        else
                match_fn = pcre2_match_8;

        line = m_match_contents;
        /* FIXME: what we really want is to pass the whole data to pcre2_match, but
         * limit matching to between sattr and eattr, so that the extra data can
         * satisfy lookahead assertions. This needs new pcre2 API though.
         */
        line_length = eattr;

        /* Iterate throught the matches until we either find one which contains the
         * offset, or we get no more matches.
         */
        pcre2_set_offset_limit_8(match_context, eattr);
        position = sattr;
        while (position < eattr &&
               ((r = match_fn(regex->code(),
                              (PCRE2_SPTR8)line, line_length, /* subject, length */
                              position, /* start offset */
                              match_flags |
                              PCRE2_NO_UTF_CHECK | PCRE2_NOTEMPTY | PCRE2_PARTIAL_SOFT /* FIXME: HARD? */,
                              match_data,
                              match_context)) >= 0 || r == PCRE2_ERROR_PARTIAL)) {
                gsize ko = offset;
                gsize rm_so, rm_eo;
                gsize *ovector;

                ovector = pcre2_get_ovector_pointer_8(match_data);
                rm_so = ovector[0];
                rm_eo = ovector[1];
                if (G_UNLIKELY(rm_so == PCRE2_UNSET || rm_eo == PCRE2_UNSET))
                        break;

                /* The offsets should be "sane". We set NOTEMPTY, but check anyway */
                if (G_UNLIKELY(position == rm_eo)) {
                        /* rm_eo is before the end of subject string's length, so this is safe */
                        position = g_utf8_next_char(line + rm_eo) - line;
                        continue;
                }

                _BTE_DEBUG_IF(BTE_DEBUG_REGEX) {
                        gchar *result;
                        struct _BteCharAttributes *_sattr, *_eattr;
                        result = g_strndup(line + rm_so, rm_eo - rm_so);
                        _sattr = &g_array_index(m_match_attributes,
                                                struct _BteCharAttributes,
                                                rm_so);
                        _eattr = &g_array_index(m_match_attributes,
                                                struct _BteCharAttributes,
                                                rm_eo - 1);
                        g_printerr("%s match `%s' from %" G_GSIZE_FORMAT "(%ld,%ld) to %" G_GSIZE_FORMAT "(%ld,%ld) (%" G_GSSIZE_FORMAT ").\n",
                                   r == PCRE2_ERROR_PARTIAL ? "Partial":"Full",
                                   result,
                                   rm_so,
                                   _sattr->column,
                                   _sattr->row,
                                   rm_eo - 1,
                                   _eattr->column,
                                   _eattr->row,
                                   offset);
                        g_free(result);
                }

                /* advance position */
                position = rm_eo;

                /* FIXME: do handle newline / partial matches at end of line/start of next line */
                if (r == PCRE2_ERROR_PARTIAL)
                        continue;

                /* If the pointer is in this substring, then we're done. */
                if (ko >= rm_so && ko < rm_eo) {
                        *result_ptr = g_strndup(line + rm_so, rm_eo - rm_so);
                        *start = rm_so;
                        *end = rm_eo - 1;
                        return true;
                }

                if (ko >= rm_eo && rm_eo > sblank) {
                        sblank = rm_eo;
                }
                if (ko < rm_so && rm_so < eblank) {
                        eblank = rm_so;
                }
        }

        if (G_UNLIKELY(r < PCRE2_ERROR_PARTIAL))
                _bte_debug_print(BTE_DEBUG_REGEX, "Unexpected pcre2_match error code: %d\n", r);

        *sblank_ptr = sblank;
        *eblank_ptr = eblank;
        return false;
}

char *
Terminal::match_check_internal_pcre(bte::grid::column_t column,
                                    bte::grid::row_t row,
                                    MatchRegex const** match,
                                    size_t* start,
                                    size_t* end)
{
	gsize offset, sattr, eattr, start_blank, end_blank;
        pcre2_match_data_8 *match_data;
        pcre2_match_context_8 *match_context;

	_bte_debug_print(BTE_DEBUG_REGEX,
                         "Checking for pcre match at (%ld,%ld).\n", row, column);

        if (!match_rowcol_to_offset(column, row,
                                    &offset, &sattr, &eattr))
                return nullptr;

	start_blank = sattr;
	end_blank = eattr;

        match_context = create_match_context();
        match_data = pcre2_match_data_create_8(256 /* should be plenty */, NULL /* general context */);

	/* Now iterate over each regex we need to match against. */
        char* dingu_match{nullptr};
        for (auto const& rem : m_match_regexes) {
                gsize sblank, eblank;

                if (match_check_pcre(match_data, match_context,
                                     rem.regex(),
                                     rem.match_flags(),
                                     sattr, eattr, offset,
                                     &dingu_match,
                                     start, end,
                                     &sblank, &eblank)) {
                        _bte_debug_print(BTE_DEBUG_REGEX, "Matched dingu with tag %d\n", rem.tag());
                        *match = std::addressof(rem);
                        break;
                }

                if (sblank > start_blank) {
                        start_blank = sblank;
                }
                if (eblank < end_blank) {
                        end_blank = eblank;
                }
	}

        if (dingu_match == nullptr) {
                /* If we get here, there was no dingu match.
                 * Record smallest span where none of the dingus match.
                 */
                *start = start_blank;
                *end = end_blank - 1;
                *match = nullptr;

                _BTE_DEBUG_IF(BTE_DEBUG_REGEX) {
                        struct _BteCharAttributes *_sattr, *_eattr;
                        _sattr = &g_array_index(m_match_attributes,
                                                struct _BteCharAttributes,
                                                start_blank);
                        _eattr = &g_array_index(m_match_attributes,
                                                struct _BteCharAttributes,
                                                end_blank - 1);
                        g_printerr("No-match region from %" G_GSIZE_FORMAT "(%ld,%ld) to %" G_GSIZE_FORMAT "(%ld,%ld)\n",
                                   start_blank, _sattr->column, _sattr->row,
                                   end_blank - 1, _eattr->column, _eattr->row);
                }
        }

        pcre2_match_data_free_8(match_data);
        pcre2_match_context_free_8(match_context);

	return dingu_match;
}

/*
 * bte_terminal_match_check_internal:
 * @terminal:
 * @column:
 * @row:
 * @match: (out):
 * @start: (out):
 * @end: (out):
 *
 * Checks m_match_contents for dingu matches, and returns the start, and
 * end of the match in @start, @end, and the matched regex in @match.
 * If no match occurs, @match will be set to %nullptr,
 * and if they are nonzero, @start and @end mark the smallest span in the @row
 * in which none of the dingus match.
 *
 * Returns: (transfer full): the matched string, or %nullptr
 */
char *
Terminal::match_check_internal(bte::grid::column_t column,
                               bte::grid::row_t row,
                               MatchRegex const** match,
                               size_t* start,
                               size_t* end)
{
	if (m_match_contents == nullptr) {
		match_contents_refresh();
	}

        assert(match != nullptr);
        assert(start != nullptr);
        assert(end != nullptr);

        *match = nullptr;
        *start = 0;
        *end = 0;

        return match_check_internal_pcre(column, row, match, start, end);
}

char*
Terminal::regex_match_check(bte::grid::column_t column,
                            bte::grid::row_t row,
                            int* tag)
{
	long delta = m_screen->scroll_delta;
	_bte_debug_print(BTE_DEBUG_EVENTS | BTE_DEBUG_REGEX,
			"Checking for match at (%ld,%ld).\n",
			row, column);

        char* ret{nullptr};
        Terminal::MatchRegex const* match{nullptr};

        if (m_match_span.contains(row + delta, column)) {
                match = regex_match_current(); /* may be nullptr */
                ret = g_strdup(m_match);
	} else {
                gsize start, end;

                ret = match_check_internal(column, row + delta,
                                           &match,
                                           &start, &end);
	}
	_BTE_DEBUG_IF(BTE_DEBUG_EVENTS | BTE_DEBUG_REGEX) {
		if (ret != NULL) g_printerr("Matched `%s'.\n", ret);
	}
        if (tag != nullptr)
                *tag = (match != nullptr) ? match->tag() : -1;

	return ret;
}

/*
 * Terminal::view_coords_from_event:
 * @event: a mouse event
 *
 * Translates the event coordinates to view coordinates, by
 * subtracting the padding and window offset.
 * Coordinates < 0 or >= m_usable_view_extents.width() or .height()
 * mean that the event coordinates are outside the usable area
 * at that side; use view_coords_visible() to check for that.
 */
bte::view::coords
Terminal::view_coords_from_event(MouseEvent const& event) const
{
        return bte::view::coords(event.x() - m_padding.left, event.y() - m_padding.top);
}

bool
Terminal::widget_realized() const noexcept
{
        return m_real_widget ? m_real_widget->realized() : false;
}

/*
 * Terminal::grid_coords_from_event:
 * @event: a mouse event
 *
 * Translates the event coordinates to view coordinates, by
 * subtracting the padding and window offset.
 * Coordinates < 0 or >= m_usable_view_extents.width() or .height()
 * mean that the event coordinates are outside the usable area
 * at that side; use grid_coords_visible() to check for that.
 */
bte::grid::coords
Terminal::grid_coords_from_event(MouseEvent const& event) const
{
        return grid_coords_from_view_coords(view_coords_from_event(event));
}

/*
 * Terminal::confined_grid_coords_from_event:
 * @event: a mouse event
 *
 * Like grid_coords_from_event(), but also confines the coordinates
 * to an actual cell in the visible area.
 */
bte::grid::coords
Terminal::confined_grid_coords_from_event(MouseEvent const& event) const
{
        auto pos = view_coords_from_event(event);
        return confined_grid_coords_from_view_coords(pos);
}

/*
 * Terminal::grid_coords_from_view_coords:
 * @pos: the view coordinates
 *
 * Translates view coordinates to grid coordinates. If the view coordinates point to
 * cells that are not visible, may return any value < 0 or >= m_column_count, and
 * < first_displayed_row() or > last_displayed_row(), resp.
 */
bte::grid::coords
Terminal::grid_coords_from_view_coords(bte::view::coords const& pos) const
{
        /* Our caller had to update the ringview (we can't do because we're const). */
        g_assert(m_ringview.is_updated());

        bte::grid::column_t col;
        if (pos.x >= 0 && pos.x < m_view_usable_extents.width())
                col = pos.x / m_cell_width;
        else if (pos.x < 0)
                col = -1;
        else
                col = m_column_count;

        bte::grid::row_t row = pixel_to_row(pos.y);

        /* BiDi: convert to logical column. */
        bte::base::BidiRow const* bidirow = m_ringview.get_bidirow(confine_grid_row(row));
        col = bidirow->vis2log(col);

        return bte::grid::coords(row, col);
}

bte::grid::row_t
Terminal::confine_grid_row(bte::grid::row_t const& row) const
{
        auto first_row = first_displayed_row();
        auto last_row = last_displayed_row();

        return bte::clamp(row, first_row, last_row);
}

/*
 * Terminal::confined_grid_coords_from_view_coords:
 * @pos: the view coordinates
 *
 * Like grid_coords_from_view_coords(), but also confines the coordinates
 * to an actual cell in the visible area.
 */
bte::grid::coords
Terminal::confined_grid_coords_from_view_coords(bte::view::coords const& pos) const
{
        auto rowcol = grid_coords_from_view_coords(pos);
        return confine_grid_coords(rowcol);
}

/*
 * Terminal::view_coords_from_grid_coords:
 * @rowcol: the grid coordinates
 *
 * Translates grid coordinates to view coordinates. If the view coordinates are
 * outside the usable area, may return any value < 0 or >= m_usable_view_extents.
 *
 * Returns: %true if the coordinates are inside the usable area
 */
bte::view::coords
Terminal::view_coords_from_grid_coords(bte::grid::coords const& rowcol) const
{
        return bte::view::coords(rowcol.column() * m_cell_width,
                                 row_to_pixel(rowcol.row()));
}

bool
Terminal::view_coords_visible(bte::view::coords const& pos) const
{
        return pos.x >= 0 && pos.x < m_view_usable_extents.width() &&
               pos.y >= 0 && pos.y < m_view_usable_extents.height();
}

bool
Terminal::grid_coords_visible(bte::grid::coords const& rowcol) const
{
        return rowcol.column() >= 0 &&
               rowcol.column() < m_column_count &&
               rowcol.row() >= first_displayed_row() &&
               rowcol.row() <= last_displayed_row();
}

bte::grid::coords
Terminal::confine_grid_coords(bte::grid::coords const& rowcol) const
{
        /* Confine clicks to the nearest actual cell. This is especially useful for
         * fullscreen bte so that you can click on the very edge of the screen.
         */
        auto first_row = first_displayed_row();
        auto last_row = last_displayed_row();

        return bte::grid::coords(CLAMP(rowcol.row(), first_row, last_row),
                                 CLAMP(rowcol.column(), 0, m_column_count - 1));
}

/*
 * Track mouse click and drag positions (the "origin" and "last" coordinates) with half cell accuracy,
 * that is, know whether the event occurred over the left/start or right/end half of the cell.
 * This is required because some selection modes care about the cell over which the event occurred,
 * while some care about the closest boundary between cells.
 *
 * Storing the actual view coordinates would become problematic when the font size changes (bug 756058),
 * and would cause too much work when the mouse moves within the half cell.
 *
 * Left/start margin or anything further to the left/start is denoted by column -1's right half,
 * right/end margin or anything further to the right/end is denoted by column m_column_count's left half.
 *
 * BiDi: returns logical position (start or end) for normal selection modes, visual position (left or
 * right) for block mode.
 */
bte::grid::halfcoords
Terminal::selection_grid_halfcoords_from_view_coords(bte::view::coords const& pos) const
{
        /* Our caller had to update the ringview (we can't do because we're const). */
        g_assert(m_ringview.is_updated());

        bte::grid::row_t row = pixel_to_row(pos.y);
        bte::grid::column_t col;
        bte::grid::half_t half;

        if (pos.x < 0) {
                col = -1;
                half = 1;
        } else if (pos.x >= m_column_count * m_cell_width) {
                col = m_column_count;
                half = 0;
        } else {
                col = pos.x / m_cell_width;
                half = (pos.x * 2 / m_cell_width) % 2;
        }

        if (!m_selection_block_mode) {
                /* BiDi: convert from visual to logical half column. */
                bte::base::BidiRow const* bidirow = m_ringview.get_bidirow(confine_grid_row(row));

                if (bidirow->vis_is_rtl(col))
                        half = 1 - half;
                col = bidirow->vis2log(col);
        }

        return { row, bte::grid::halfcolumn_t(col, half) };
}

/*
 * Called on Shift+Click to continue (extend or shrink) the previous selection.
 * Swaps the two endpoints of the selection if needed, so that m_selection_origin
 * contains the new fixed point and m_selection_last is the newly dragged end.
 * In block mode it might even switch to the other two corners.
 * As per CTK+'s generic selection behavior, retains the origin and last
 * endpoints if the Shift+click happened inside the selection.
 */
void
Terminal::selection_maybe_swap_endpoints(bte::view::coords const& pos)
{
        if (m_selection_resolved.empty())
                return;

        /* Need to ensure the ringview is updated. */
        ringview_update();

        auto current = selection_grid_halfcoords_from_view_coords (pos);

        if (m_selection_block_mode) {
                if ((current.row() <= m_selection_origin.row() && m_selection_origin.row() < m_selection_last.row()) ||
                    (current.row() >= m_selection_origin.row() && m_selection_origin.row() > m_selection_last.row())) {
                        // FIXME see if we can use std::swap()
                        auto tmp = m_selection_origin.row();
                        m_selection_origin.set_row(m_selection_last.row());
                        m_selection_last.set_row(tmp);
                }
                if ((current.halfcolumn() <= m_selection_origin.halfcolumn() && m_selection_origin.halfcolumn() < m_selection_last.halfcolumn()) ||
                    (current.halfcolumn() >= m_selection_origin.halfcolumn() && m_selection_origin.halfcolumn() > m_selection_last.halfcolumn())) {
                        // FIXME see if we can use std::swap()
                        auto tmp = m_selection_origin.halfcolumn();
                        m_selection_origin.set_halfcolumn(m_selection_last.halfcolumn());
                        m_selection_last.set_halfcolumn(tmp);
                }
        } else {
                if ((current <= m_selection_origin && m_selection_origin < m_selection_last) ||
                    (current >= m_selection_origin && m_selection_origin > m_selection_last)) {
                        std::swap (m_selection_origin, m_selection_last);
                }
        }

        _bte_debug_print(BTE_DEBUG_SELECTION,
                         "Selection maybe swap endpoints: origin=%s last=%s\n",
                         m_selection_origin.to_string(),
                         m_selection_last.to_string());
}

bool
Terminal::rowcol_from_event(MouseEvent const& event,
                            long *column,
                            long *row)
{
        auto rowcol = grid_coords_from_event(event);
        if (!grid_coords_visible(rowcol))
                return false;

        *column = rowcol.column();
        *row = rowcol.row();
        return true;
}

char *
Terminal::hyperlink_check(MouseEvent const& event)
{
        long col, row;
        const char *hyperlink;
        const char *separator;

        if (!m_allow_hyperlink)
                return NULL;

        /* Need to ensure the ringview is updated. */
        ringview_update();

        if (!rowcol_from_event(event, &col, &row))
                return NULL;

        _bte_ring_get_hyperlink_at_position(m_screen->row_data, row, col, false, &hyperlink);

        if (hyperlink != NULL) {
                /* URI is after the first semicolon */
                separator = strchr(hyperlink, ';');
                g_assert(separator != NULL);
                hyperlink = separator + 1;
        }

        _bte_debug_print (BTE_DEBUG_HYPERLINK,
                          "hyperlink_check: \"%s\"\n",
                          hyperlink);

        return g_strdup(hyperlink);
}

char *
Terminal::regex_match_check(MouseEvent const& event,
                            int *tag)
{
        long col, row;

        /* Need to ensure the ringview is updated. */
        ringview_update();

        if (!rowcol_from_event(event, &col, &row))
                return FALSE;

        /* FIXME Shouldn't rely on a deprecated, not sub-row aware method. */
        // FIXMEchpe fix this scroll_delta substraction!
        return regex_match_check(col, row - (long)m_screen->scroll_delta, tag);
}

bool
Terminal::regex_match_check_extra(MouseEvent const& event,
                                  bte::base::Regex const** regexes,
                                  size_t n_regexes,
                                  uint32_t match_flags,
                                  char** matches)
{
	gsize offset, sattr, eattr;
        pcre2_match_data_8 *match_data;
        pcre2_match_context_8 *match_context;
        bool any_matches = false;
        long col, row;
        guint i;

        assert(regexes != nullptr || n_regexes == 0);
        assert(matches != nullptr);

        /* Need to ensure the ringview is updated. */
        ringview_update();

        if (!rowcol_from_event(event, &col, &row))
                return false;

	if (m_match_contents == nullptr) {
		match_contents_refresh();
	}

        if (!match_rowcol_to_offset(col, row,
                                    &offset, &sattr, &eattr))
                return false;

        match_context = create_match_context();
        match_data = pcre2_match_data_create_8(256 /* should be plenty */, nullptr /* general context */);

        for (i = 0; i < n_regexes; i++) {
                gsize start, end, sblank, eblank;
                char *match_string;

                g_return_val_if_fail(regexes[i] != nullptr, false);

                if (match_check_pcre(match_data, match_context,
                                     regexes[i], match_flags,
                                     sattr, eattr, offset,
                                     &match_string,
                                     &start, &end,
                                     &sblank, &eblank)) {
                        _bte_debug_print(BTE_DEBUG_REGEX, "Matched regex with text: %s\n", match_string);
                        matches[i] = match_string;
                        any_matches = true;
                } else
                        matches[i] = nullptr;
        }

        pcre2_match_data_free_8(match_data);
        pcre2_match_context_free_8(match_context);

        return any_matches;
}

/* Emit an adjustment changed signal on our adjustment object. */
void
Terminal::emit_adjustment_changed()
{
	if (m_adjustment_changed_pending) {
		bool changed = false;
		gdouble current, v;

                auto vadjustment = m_vadjustment.get();

                auto const freezer = bte::glib::FreezeObjectNotify{vadjustment};

		v = _bte_ring_delta (m_screen->row_data);
                current = ctk_adjustment_get_lower(vadjustment);
		if (!_bte_double_equal(current, v)) {
			_bte_debug_print(BTE_DEBUG_ADJ,
					"Changing lower bound from %.0f to %f\n",
					 current, v);
                        ctk_adjustment_set_lower(vadjustment, v);
			changed = true;
		}

		v = m_screen->insert_delta + m_row_count;
                current = ctk_adjustment_get_upper(vadjustment);
		if (!_bte_double_equal(current, v)) {
			_bte_debug_print(BTE_DEBUG_ADJ,
					"Changing upper bound from %.0f to %f\n",
					 current, v);
                        ctk_adjustment_set_upper(vadjustment, v);
			changed = true;
		}

		/* The step increment should always be one. */
                v = ctk_adjustment_get_step_increment(vadjustment);
		if (!_bte_double_equal(v, 1)) {
			_bte_debug_print(BTE_DEBUG_ADJ,
					"Changing step increment from %.0lf to 1\n", v);
                        ctk_adjustment_set_step_increment(vadjustment, 1);
			changed = true;
		}

		/* Set the number of rows the user sees to the number of rows the
		 * user sees. */
                v = ctk_adjustment_get_page_size(vadjustment);
		if (!_bte_double_equal(v, m_row_count)) {
			_bte_debug_print(BTE_DEBUG_ADJ,
					"Changing page size from %.0f to %ld\n",
					 v, m_row_count);
                        ctk_adjustment_set_page_size(vadjustment,
						     m_row_count);
			changed = true;
		}

		/* Clicking in the empty area should scroll one screen, so set the
		 * page size to the number of visible rows. */
                v = ctk_adjustment_get_page_increment(vadjustment);
		if (!_bte_double_equal(v, m_row_count)) {
			_bte_debug_print(BTE_DEBUG_ADJ,
					"Changing page increment from "
					"%.0f to %ld\n",
					v, m_row_count);
                        ctk_adjustment_set_page_increment(vadjustment,
							  m_row_count);
			changed = true;
		}

		if (changed)
			_bte_debug_print(BTE_DEBUG_SIGNALS,
					"Emitting adjustment_changed.\n");
		m_adjustment_changed_pending = FALSE;
	}
	if (m_adjustment_value_changed_pending) {
		double v, delta;
		_bte_debug_print(BTE_DEBUG_SIGNALS,
				"Emitting adjustment_value_changed.\n");
		m_adjustment_value_changed_pending = FALSE;

                auto vadjustment = m_vadjustment.get();
                v = ctk_adjustment_get_value(vadjustment);
		if (!_bte_double_equal(v, m_screen->scroll_delta)) {
			/* this little dance is so that the scroll_delta is
			 * updated immediately, but we still handled scrolling
			 * via the adjustment - e.g. user interaction with the
			 * scrollbar
			 */
			delta = m_screen->scroll_delta;
			m_screen->scroll_delta = v;
                        ctk_adjustment_set_value(vadjustment, delta);
		}
	}
}

/* Queue an adjustment-changed signal to be delivered when convenient. */
// FIXMEchpe this has just one caller, fold it into the call site
void
Terminal::queue_adjustment_changed()
{
	m_adjustment_changed_pending = true;
	add_update_timeout(this);
}

void
Terminal::queue_adjustment_value_changed(double v)
{
	if (!_bte_double_equal(v, m_screen->scroll_delta)) {
                _bte_debug_print(BTE_DEBUG_ADJ,
                                 "Adjustment value changed to %f\n",
                                 v);
		m_screen->scroll_delta = v;
		m_adjustment_value_changed_pending = true;
		add_update_timeout(this);
	}
}

void
Terminal::queue_adjustment_value_changed_clamped(double v)
{
        auto vadjustment = m_vadjustment.get();
        auto const lower = ctk_adjustment_get_lower(vadjustment);
        auto const upper = ctk_adjustment_get_upper(vadjustment);

	v = CLAMP(v, lower, MAX (lower, upper - m_row_count));

	queue_adjustment_value_changed(v);
}

void
Terminal::adjust_adjustments()
{
	g_assert(m_screen != nullptr);
	g_assert(m_screen->row_data != nullptr);

	queue_adjustment_changed();

	/* The lower value should be the first row in the buffer. */
	long delta = _bte_ring_delta(m_screen->row_data);
	/* Snap the insert delta and the cursor position to be in the visible
	 * area.  Leave the scrolling delta alone because it will be updated
	 * when the adjustment changes. */
	m_screen->insert_delta = MAX(m_screen->insert_delta, delta);
        m_screen->cursor.row = MAX(m_screen->cursor.row,
                                   m_screen->insert_delta);

	if (m_screen->scroll_delta > m_screen->insert_delta) {
		queue_adjustment_value_changed(m_screen->insert_delta);
	}
}

/* Update the adjustment field of the widget.  This function should be called
 * whenever we add rows to or remove rows from the history or switch screens. */
void
Terminal::adjust_adjustments_full()
{
	g_assert(m_screen != NULL);
	g_assert(m_screen->row_data != NULL);

	adjust_adjustments();
	queue_adjustment_changed();
}

/* Scroll a fixed number of lines up or down in the current screen. */
void
Terminal::scroll_lines(long lines)
{
	double destination;
	_bte_debug_print(BTE_DEBUG_ADJ, "Scrolling %ld lines.\n", lines);
	/* Calculate the ideal position where we want to be before clamping. */
	destination = m_screen->scroll_delta;
        /* Snap to whole cell offset. */
        if (lines > 0)
                destination = floor(destination);
        else if (lines < 0)
                destination = ceil(destination);
	destination += lines;
	/* Tell the scrollbar to adjust itself. */
	queue_adjustment_value_changed_clamped(destination);
}

/* Scroll so that the scroll delta is the minimum value. */
void
Terminal::maybe_scroll_to_top()
{
	queue_adjustment_value_changed(_bte_ring_delta(m_screen->row_data));
}

void
Terminal::maybe_scroll_to_bottom()
{
	queue_adjustment_value_changed(m_screen->insert_delta);
	_bte_debug_print(BTE_DEBUG_ADJ,
			"Snapping to bottom of screen\n");
}

/*
 * Terminal::set_encoding:
 * @charset: (allow-none): target charset, or %NULL to use UTF-8
 *
 * Changes the encoding the terminal will expect data from the child to
 * be encoded with.  If @charset is %NULL, it uses "UTF-8".
 *
 * Returns: %true if the encoding could be changed to the specified one
 */
bool
Terminal::set_encoding(char const* charset,
                       GError** error)
{
#ifdef WITH_ICU
        auto const to_utf8 = bool{charset == nullptr || g_ascii_strcasecmp(charset, "UTF-8") == 0};

        if (to_utf8) {
                if (data_syntax() == DataSyntax::eECMA48_UTF8)
                        return true;

                m_converter.reset();
                m_data_syntax = DataSyntax::eECMA48_UTF8;
        } else {
                if (data_syntax() == DataSyntax::eECMA48_PCTERM &&
                    m_converter->charset() == charset)
                        return true;

                auto converter = bte::base::ICUConverter::make(charset, error);
                if (!converter)
                        return false;

                m_converter = std::move(converter);
                m_data_syntax = DataSyntax::eECMA48_PCTERM;
        }

        /* Note: we DON'T convert any pending output from the previous charset to
         * the new charset, since that is in general not possible without loss, and
         * also the output may include binary data (Terminal::feed_child_binary()).
         * So we just clear the outgoing queue. (FIXMEchpe: instead, we could flush
         * the outgooing and only change charsets once it's empty.)
         * Do not clear the incoming queue.
         */
        _bte_byte_array_clear(m_outgoing);

        reset_decoder();

        if (pty())
                pty()->set_utf8(data_syntax() == DataSyntax::eECMA48_UTF8);

	_bte_debug_print(BTE_DEBUG_IO,
                         "Set terminal encoding to `%s'.\n",
                         encoding());

        return true;
#else
        g_set_error_literal(error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
                            "ICU support not available");
        return false;
#endif
}

bool
Terminal::set_cjk_ambiguous_width(int width)
{
        g_assert(width == 1 || width == 2);

        if (m_utf8_ambiguous_width == width)
                return false;

        m_utf8_ambiguous_width = width;
        return true;
}

// FIXMEchpe replace this with a method on BteRing
BteRowData *
Terminal::insert_rows (guint cnt)
{
	BteRowData *row;
	do {
		row = ring_append(false);
	} while(--cnt);
	return row;
}

/* Make sure we have enough rows and columns to hold data at the current
 * cursor position. */
BteRowData *
Terminal::ensure_row()
{
	BteRowData *row;

	/* Figure out how many rows we need to add. */
	auto const delta = m_screen->cursor.row - _bte_ring_next(m_screen->row_data) + 1;
	if (delta > 0) {
		row = insert_rows(delta);
		adjust_adjustments();
	} else {
		/* Find the row the cursor is in. */
		row = _bte_ring_index_writable(m_screen->row_data, m_screen->cursor.row);
	}
	g_assert(row != NULL);

	return row;
}

BteRowData *
Terminal::ensure_cursor()
{
	BteRowData *row = ensure_row();
        _bte_row_data_fill(row, &basic_cell, m_screen->cursor.col);

	return row;
}

/* Update the insert delta so that the screen which includes it also
 * includes the end of the buffer. */
void
Terminal::update_insert_delta()
{
	/* The total number of lines.  Add one to the cursor offset
	 * because it's zero-based. */
	auto rows = _bte_ring_next(m_screen->row_data);
        auto delta = m_screen->cursor.row - rows + 1;
	if (G_UNLIKELY (delta > 0)) {
		insert_rows(delta);
		rows = _bte_ring_next(m_screen->row_data);
	}

	/* Make sure that the bottom row is visible, and that it's in
	 * the buffer (even if it's empty).  This usually causes the
	 * top row to become a history-only row. */
	delta = m_screen->insert_delta;
	delta = MIN(delta, rows - m_row_count);
	delta = MAX(delta,
                    m_screen->cursor.row - (m_row_count - 1));
	delta = MAX(delta, _bte_ring_delta(m_screen->row_data));

	/* Adjust the insert delta and scroll if needed. */
	if (delta != m_screen->insert_delta) {
		m_screen->insert_delta = delta;
		adjust_adjustments();
	}
}

/* Apply the desired mouse pointer, based on certain member variables. */
void
Terminal::apply_mouse_cursor()
{
        if (!widget_realized())
                return;

        /* Show the cursor if over the widget and not autohidden, this is obvious.
         * Also show the cursor if outside the widget regardless of the autohidden state, so that if a popover is opened
         * and then the cursor returns (which doesn't trigger enter/motion events), it is visible.
         * That is, only hide the cursor if it's over the widget and is autohidden.
         * See bug 789390 and bug 789536 comment 6 for details. */
        if (!(m_mouse_autohide && m_mouse_cursor_autohidden && m_mouse_cursor_over_widget)) {
                if (m_hyperlink_hover_idx != 0) {
                        _bte_debug_print(BTE_DEBUG_CURSOR,
                                        "Setting hyperlink mouse cursor.\n");
                        m_real_widget->set_cursor(bte::platform::Widget::CursorType::eHyperlink);
                } else if (regex_match_has_current()) {
                        m_real_widget->set_cursor(regex_match_current()->cursor());
                } else if (m_mouse_tracking_mode != MouseTrackingMode::eNONE) {
			_bte_debug_print(BTE_DEBUG_CURSOR,
					"Setting mousing cursor.\n");
                        m_real_widget->set_cursor(bte::platform::Widget::CursorType::eMousing);
		} else {
			_bte_debug_print(BTE_DEBUG_CURSOR,
					"Setting default mouse cursor.\n");
                        m_real_widget->set_cursor(bte::platform::Widget::CursorType::eDefault);
		}
	} else {
		_bte_debug_print(BTE_DEBUG_CURSOR,
				"Setting to invisible cursor.\n");
                m_real_widget->set_cursor(bte::platform::Widget::CursorType::eInvisible);
	}
}

/* Show or hide the pointer if autohiding is enabled. */
void
Terminal::set_pointer_autohidden(bool autohidden)
{
        if (autohidden == m_mouse_cursor_autohidden)
                return;

        m_mouse_cursor_autohidden = autohidden;

        if (m_mouse_autohide) {
                hyperlink_hilite_update();
                match_hilite_update();
                apply_mouse_cursor();
        }
}

/*
 * Get the actually used color from the palette.
 * The return value can be NULL only if entry is one of BTE_CURSOR_BG,
 * BTE_CURSOR_FG, BTE_HIGHLIGHT_BG or BTE_HIGHLIGHT_FG.
 */
bte::color::rgb const*
Terminal::get_color(int entry) const
{
	BtePaletteColor const* palette_color = &m_palette[entry];
	guint source;
	for (source = 0; source < G_N_ELEMENTS(palette_color->sources); source++)
		if (palette_color->sources[source].is_set)
			return &palette_color->sources[source].color;
	return nullptr;
}

/* Set up a palette entry with a more-or-less match for the requested color. */
void
Terminal::set_color(int entry,
                              int source,
                              bte::color::rgb const& proposed)
{
        g_assert(entry >= 0 && entry < BTE_PALETTE_SIZE);

	BtePaletteColor *palette_color = &m_palette[entry];

        _bte_debug_print(BTE_DEBUG_MISC,
                         "Set %s color[%d] to (%04x,%04x,%04x).\n",
                         source == BTE_COLOR_SOURCE_ESCAPE ? "escape" : "API",
                         entry, proposed.red, proposed.green, proposed.blue);

        if (palette_color->sources[source].is_set &&
            palette_color->sources[source].color == proposed) {
                return;
        }
        palette_color->sources[source].is_set = TRUE;
        palette_color->sources[source].color = proposed;

	/* If we're not realized yet, there's nothing else to do. */
	if (!widget_realized())
		return;

	/* and redraw */
	if (entry == BTE_CURSOR_BG || entry == BTE_CURSOR_FG)
		invalidate_cursor_once();
	else
		invalidate_all();
}

void
Terminal::reset_color(int entry,
                                int source)
{
        g_assert(entry >= 0 && entry < BTE_PALETTE_SIZE);

	BtePaletteColor *palette_color = &m_palette[entry];

        _bte_debug_print(BTE_DEBUG_MISC,
                         "Reset %s color[%d].\n",
                         source == BTE_COLOR_SOURCE_ESCAPE ? "escape" : "API",
                         entry);

        if (!palette_color->sources[source].is_set) {
                return;
        }
        palette_color->sources[source].is_set = FALSE;

	/* If we're not realized yet, there's nothing else to do. */
	if (!widget_realized())
		return;

	/* and redraw */
	if (entry == BTE_CURSOR_BG || entry == BTE_CURSOR_FG)
		invalidate_cursor_once();
	else
		invalidate_all();
}

bool
Terminal::set_background_alpha(double alpha)
{
        g_assert(alpha >= 0. && alpha <= 1.);

        if (_bte_double_equal(alpha, m_background_alpha))
                return false;

        _bte_debug_print(BTE_DEBUG_MISC,
                         "Setting background alpha to %.3f\n", alpha);
        m_background_alpha = alpha;

        invalidate_all();

        return true;
}

void
Terminal::set_colors_default()
{
        set_colors(nullptr, nullptr, nullptr, 0);
}

/*
 * Terminal::set_colors:
 * @terminal: a #BteTerminal
 * @foreground: (allow-none): the new foreground color, or %NULL
 * @background: (allow-none): the new background color, or %NULL
 * @palette: (array length=palette_size zero-terminated=0): the color palette
 * @palette_size: the number of entries in @palette
 *
 * @palette specifies the new values for the 256 palette colors: 8 standard colors,
 * their 8 bright counterparts, 6x6x6 color cube, and 24 grayscale colors.
 * Omitted entries will default to a hardcoded value.
 *
 * @palette_size must be 0, 8, 16, 232 or 256.
 *
 * If @foreground is %NULL and @palette_size is greater than 0, the new foreground
 * color is taken from @palette[7].  If @background is %NULL and @palette_size is
 * greater than 0, the new background color is taken from @palette[0].
 */
void
Terminal::set_colors(bte::color::rgb const* foreground,
                               bte::color::rgb const* background,
                               bte::color::rgb const* new_palette,
                               gsize palette_size)
{
	_bte_debug_print(BTE_DEBUG_MISC,
			"Set color palette [%" G_GSIZE_FORMAT " elements].\n",
			palette_size);

	/* Accept NULL as the default foreground and background colors if we
	 * got a palette. */
	if ((foreground == NULL) && (palette_size >= 8)) {
		foreground = &new_palette[7];
	}
	if ((background == NULL) && (palette_size >= 8)) {
		background = &new_palette[0];
	}

	/* Initialize each item in the palette if we got any entries to work
	 * with. */
	for (gsize i = 0; i < G_N_ELEMENTS(m_palette); i++) {
                bte::color::rgb color;
		bool unset = false;

		if (i < 16) {
			color.blue = (i & 4) ? 0xc000 : 0;
			color.green = (i & 2) ? 0xc000 : 0;
			color.red = (i & 1) ? 0xc000 : 0;
			if (i > 7) {
				color.blue += 0x3fff;
				color.green += 0x3fff;
				color.red += 0x3fff;
			}
		}
		else if (i < 232) {
			int j = i - 16;
			int r = j / 36, g = (j / 6) % 6, b = j % 6;
			int red =   (r == 0) ? 0 : r * 40 + 55;
			int green = (g == 0) ? 0 : g * 40 + 55;
			int blue =  (b == 0) ? 0 : b * 40 + 55;
			color.red   = red | red << 8  ;
			color.green = green | green << 8;
			color.blue  = blue | blue << 8;
		} else if (i < 256) {
			int shade = 8 + (i - 232) * 10;
			color.red = color.green = color.blue = shade | shade << 8;
		}
		else switch (i) {
			case BTE_DEFAULT_BG:
				if (background) {
					color = *background;
				} else {
					color.red = 0;
					color.blue = 0;
					color.green = 0;
				}
				break;
			case BTE_DEFAULT_FG:
				if (foreground) {
					color = *foreground;
				} else {
					color.red = 0xc000;
					color.blue = 0xc000;
					color.green = 0xc000;
				}
				break;
			case BTE_BOLD_FG:
                                unset = true;
                                break;
			case BTE_HIGHLIGHT_BG:
				unset = true;
				break;
			case BTE_HIGHLIGHT_FG:
				unset = true;
				break;
			case BTE_CURSOR_BG:
				unset = true;
				break;
			case BTE_CURSOR_FG:
				unset = true;
				break;
			}

		/* Override from the supplied palette if there is one. */
		if (i < palette_size) {
			color = new_palette[i];
		}

		/* Set up the color entry. */
                if (unset)
                        reset_color(i, BTE_COLOR_SOURCE_API);
                else
                        set_color(i, BTE_COLOR_SOURCE_API, color);
	}
}

/*
 * Terminal::set_color_bold:
 * @bold: (allow-none): the new bold color or %NULL
 *
 * Sets the color used to draw bold text in the default foreground color.
 * If @bold is %NULL then the default color is used.
 */
void
Terminal::set_color_bold(bte::color::rgb const& color)
{
        _bte_debug_print(BTE_DEBUG_MISC,
                         "Set %s color to (%04x,%04x,%04x).\n", "bold",
                         color.red, color.green, color.blue);
        set_color(BTE_BOLD_FG, BTE_COLOR_SOURCE_API, color);
}

void
Terminal::reset_color_bold()
{
        _bte_debug_print(BTE_DEBUG_MISC,
                         "Reset %s color.\n", "bold");
        reset_color(BTE_BOLD_FG, BTE_COLOR_SOURCE_API);
}

/*
 * Terminal::set_color_foreground:
 * @foreground: the new foreground color
 *
 * Sets the foreground color used to draw normal text.
 */
void
Terminal::set_color_foreground(bte::color::rgb const& color)
{
        _bte_debug_print(BTE_DEBUG_MISC,
                         "Set %s color to (%04x,%04x,%04x).\n", "foreground",
                         color.red, color.green, color.blue);
	set_color(BTE_DEFAULT_FG, BTE_COLOR_SOURCE_API, color);
}

/*
 * Terminal::set_color_background:
 * @background: the new background color
 *
 * Sets the background color for text which does not have a specific background
 * color assigned.  Only has effect when no background image is set and when
 * the terminal is not transparent.
 */
void
Terminal::set_color_background(bte::color::rgb const& color)
{
        _bte_debug_print(BTE_DEBUG_MISC,
                         "Set %s color to (%04x,%04x,%04x).\n", "background",
                         color.red, color.green, color.blue);
	set_color(BTE_DEFAULT_BG, BTE_COLOR_SOURCE_API, color);
}

/*
 * Terminal::set_color_cursor_background:
 * @cursor_background: (allow-none): the new color to use for the text cursor, or %NULL
 *
 * Sets the background color for text which is under the cursor.  If %NULL, text
 * under the cursor will be drawn with foreground and background colors
 * reversed.
 */
void
Terminal::set_color_cursor_background(bte::color::rgb const& color)
{
        _bte_debug_print(BTE_DEBUG_MISC,
                         "Set %s color to (%04x,%04x,%04x).\n", "cursor background",
                         color.red, color.green, color.blue);
	set_color(BTE_CURSOR_BG, BTE_COLOR_SOURCE_API, color);
}

void
Terminal::reset_color_cursor_background()
{
        _bte_debug_print(BTE_DEBUG_MISC,
                         "Reset %s color.\n", "cursor background");
        reset_color(BTE_CURSOR_BG, BTE_COLOR_SOURCE_API);
}

/*
 * Terminal::set_color_cursor_foreground:
 * @cursor_foreground: (allow-none): the new color to use for the text cursor, or %NULL
 *
 * Sets the foreground color for text which is under the cursor.  If %NULL, text
 * under the cursor will be drawn with foreground and background colors
 * reversed.
 */
void
Terminal::set_color_cursor_foreground(bte::color::rgb const& color)
{
        _bte_debug_print(BTE_DEBUG_MISC,
                         "Set %s color to (%04x,%04x,%04x).\n", "cursor foreground",
                         color.red, color.green, color.blue);
	set_color(BTE_CURSOR_FG, BTE_COLOR_SOURCE_API, color);
}

void
Terminal::reset_color_cursor_foreground()
{
        _bte_debug_print(BTE_DEBUG_MISC,
                         "Reset %s color.\n", "cursor foreground");
        reset_color(BTE_CURSOR_FG, BTE_COLOR_SOURCE_API);
}

/*
 * Terminal::set_color_highlight_background:
 * @highlight_background: (allow-none): the new color to use for highlighted text, or %NULL
 *
 * Sets the background color for text which is highlighted.  If %NULL,
 * it is unset.  If neither highlight background nor highlight foreground are set,
 * highlighted text (which is usually highlighted because it is selected) will
 * be drawn with foreground and background colors reversed.
 */
void
Terminal::set_color_highlight_background(bte::color::rgb const& color)
{
        _bte_debug_print(BTE_DEBUG_MISC,
                         "Set %s color to (%04x,%04x,%04x).\n", "highlight background",
                         color.red, color.green, color.blue);
	set_color(BTE_HIGHLIGHT_BG, BTE_COLOR_SOURCE_API, color);
}

void
Terminal::reset_color_highlight_background()
{
        _bte_debug_print(BTE_DEBUG_MISC,
                         "Reset %s color.\n", "highlight background");
        reset_color(BTE_HIGHLIGHT_BG, BTE_COLOR_SOURCE_API);
}

/*
 * Terminal::set_color_highlight_foreground:
 * @highlight_foreground: (allow-none): the new color to use for highlighted text, or %NULL
 *
 * Sets the foreground color for text which is highlighted.  If %NULL,
 * it is unset.  If neither highlight background nor highlight foreground are set,
 * highlighted text (which is usually highlighted because it is selected) will
 * be drawn with foreground and background colors reversed.
 */
void
Terminal::set_color_highlight_foreground(bte::color::rgb const& color)
{
        _bte_debug_print(BTE_DEBUG_MISC,
                         "Set %s color to (%04x,%04x,%04x).\n", "highlight foreground",
                         color.red, color.green, color.blue);
	set_color(BTE_HIGHLIGHT_FG, BTE_COLOR_SOURCE_API, color);
}

void
Terminal::reset_color_highlight_foreground()
{
        _bte_debug_print(BTE_DEBUG_MISC,
                         "Reset %s color.\n", "highlight foreground");
        reset_color(BTE_HIGHLIGHT_FG, BTE_COLOR_SOURCE_API);
}

/*
 * Terminal::cleanup_fragments:
 * @start: the starting column, inclusive
 * @end: the end column, exclusive
 *
 * Needs to be called before modifying the contents in the cursor's row,
 * between the two given columns.  Cleans up TAB and CJK fragments to the
 * left of @start and to the right of @end.  If a CJK is split in half,
 * the remaining half is replaced by a space.  If a TAB at @start is split,
 * it is replaced by spaces.  If a TAB at @end is split, it is replaced by
 * a shorter TAB.  @start and @end can be equal if characters will be
 * inserted at the location rather than overwritten.
 *
 * The area between @start and @end is not cleaned up, hence the whole row
 * can be left in an inconsistent state.  It is expected that the caller
 * will fill up that range afterwards, resulting in a consistent row again.
 *
 * Invalidates the cells that visually change outside of the range,
 * because the caller can't reasonably be expected to take care of this.
 */
void
Terminal::cleanup_fragments(long start,
                                      long end)
{
        BteRowData *row = ensure_row();
        const BteCell *cell_start;
        BteCell *cell_end, *cell_col;
        gboolean cell_start_is_fragment;
        long col;

        g_assert(end >= start);

        /* Remember whether the cell at start is a fragment.  We'll need to know it when
         * handling the left hand side, but handling the right hand side first might
         * overwrite it if start == end (inserting to the middle of a character). */
        cell_start = _bte_row_data_get (row, start);
        cell_start_is_fragment = cell_start != NULL && cell_start->attr.fragment();

        /* On the right hand side, try to replace a TAB by a shorter TAB if we can.
         * This requires that the TAB on the left (which might be the same TAB) is
         * not yet converted to spaces, so start on the right hand side. */
        cell_end = _bte_row_data_get_writable (row, end);
        if (G_UNLIKELY (cell_end != NULL && cell_end->attr.fragment())) {
                col = end;
                do {
                        col--;
                        g_assert(col >= 0);  /* The first cell can't be a fragment. */
                        cell_col = _bte_row_data_get_writable (row, col);
                } while (cell_col->attr.fragment());
                if (cell_col->c == '\t') {
                        _bte_debug_print(BTE_DEBUG_MISC,
                                         "Replacing right part of TAB with a shorter one at %ld (%ld cells) => %ld (%ld cells)\n",
                                         col, (long) cell_col->attr.columns(), end, (long) cell_col->attr.columns() - (end - col));
                        cell_end->c = '\t';
                        cell_end->attr.set_fragment(false);
                        g_assert(cell_col->attr.columns() > end - col);
                        cell_end->attr.set_columns(cell_col->attr.columns() - (end - col));
                } else {
                        _bte_debug_print(BTE_DEBUG_MISC,
                                         "Cleaning CJK right half at %ld\n",
                                         end);
                        g_assert(end - col == 1 && cell_col->attr.columns() == 2);
                        cell_end->c = ' ';
                        cell_end->attr.set_fragment(false);
                        cell_end->attr.set_columns(1);
                        invalidate_row_and_context(m_screen->cursor.row);  /* FIXME can we do cheaper? */
                }
        }

        /* Handle the left hand side.  Converting longer TABs to shorter ones probably
         * wouldn't make that much sense here, so instead convert to spaces. */
        if (G_UNLIKELY (cell_start_is_fragment)) {
                gboolean keep_going = TRUE;
                col = start;
                do {
                        col--;
                        g_assert(col >= 0);  /* The first cell can't be a fragment. */
                        cell_col = _bte_row_data_get_writable (row, col);
                        if (!cell_col->attr.fragment()) {
                                if (cell_col->c == '\t') {
                                        _bte_debug_print(BTE_DEBUG_MISC,
                                                         "Replacing left part of TAB with spaces at %ld (%ld => %ld cells)\n",
                                                         col, (long)cell_col->attr.columns(), start - col);
                                        /* nothing to do here */
                                } else {
                                        _bte_debug_print(BTE_DEBUG_MISC,
                                                         "Cleaning CJK left half at %ld\n",
                                                         col);
                                        g_assert(start - col == 1);
                                        invalidate_row_and_context(m_screen->cursor.row);  /* FIXME can we do cheaper? */
                                }
                                keep_going = FALSE;
                        }
                        cell_col->c = ' ';
                        cell_col->attr.set_fragment(false);
                        cell_col->attr.set_columns(1);
                } while (keep_going);
        }
}

/* Cursor down, with scrolling. */
void
Terminal::cursor_down(bool explicit_sequence)
{
	long start, end;

        if (m_scrolling_restricted) {
                start = m_screen->insert_delta + m_scrolling_region.start;
                end = m_screen->insert_delta + m_scrolling_region.end;
	} else {
		start = m_screen->insert_delta;
		end = start + m_row_count - 1;
	}
        if (m_screen->cursor.row == end) {
                if (m_scrolling_restricted) {
			if (start == m_screen->insert_delta) {
                                /* Set the boundary to hard wrapped where
                                 * we're about to tear apart the contents. */
                                set_hard_wrapped(m_screen->cursor.row);
				/* Scroll this line into the scrollback
				 * buffer by inserting a line at the next
				 * line and scrolling the area up. */
				m_screen->insert_delta++;
                                m_screen->cursor.row++;
                                /* Update start and end, too. */
				start++;
				end++;
                                ring_insert(m_screen->cursor.row, false);
                                /* Repaint the affected lines, which is _below_
                                 * the region (bug 131). No need to extend,
                                 * set_hard_wrapped() took care of invalidating
                                 * the context lines if necessary. */
                                invalidate_rows(m_screen->cursor.row,
                                                m_screen->insert_delta + m_row_count - 1);
				/* Force scroll. */
				adjust_adjustments();
			} else {
                                /* Set the boundaries to hard wrapped where
                                 * we're about to tear apart the contents. */
                                set_hard_wrapped(start - 1);
                                set_hard_wrapped(end);
                                /* Scroll by removing a line and inserting a new one. */
				ring_remove(start);
				ring_insert(end, true);
                                /* Repaint the affected lines. No need to extend,
                                 * set_hard_wrapped() took care of invalidating
                                 * the context lines if necessary. */
                                invalidate_rows(start, end);
			}
		} else {
			/* Scroll up with history. */
                        m_screen->cursor.row++;
			update_insert_delta();
		}

                /* Handle bce (background color erase), however, diverge from xterm:
                 * only fill the new row with the background color if scrolling
                 * happens due to an explicit escape sequence, not due to autowrapping.
                 * See bug 754596 for details. */
                bool const not_default_bg = (m_color_defaults.attr.back() != BTE_DEFAULT_BG);

                if (explicit_sequence && not_default_bg) {
			BteRowData *rowdata = ensure_row();
                        _bte_row_data_fill (rowdata, &m_color_defaults, m_column_count);
		}
        } else if (m_screen->cursor.row < m_screen->insert_delta + m_row_count - 1) {
                /* Otherwise, just move the cursor down; unless it's already in the last
                 * physical row (which is possible with scrolling region, see #176). */
                m_screen->cursor.row++;
	}
}

/* Drop the scrollback. */
void
Terminal::drop_scrollback()
{
        /* Only for normal screen; alternate screen doesn't have a scrollback. */
        _bte_ring_drop_scrollback (m_normal_screen.row_data,
                                   m_normal_screen.insert_delta);

        if (m_screen == &m_normal_screen) {
                queue_adjustment_value_changed(m_normal_screen.insert_delta);
                adjust_adjustments_full();
        }
}

/* Restore cursor on a screen. */
void
Terminal::restore_cursor(BteScreen *screen__)
{
        screen__->cursor.col = screen__->saved.cursor.col;
        screen__->cursor.row = screen__->insert_delta + CLAMP(screen__->saved.cursor.row,
                                                              0, m_row_count - 1);

        m_modes_ecma.set_modes(screen__->saved.modes_ecma);

        m_modes_private.set_DEC_REVERSE_IMAGE(screen__->saved.reverse_mode);
        m_modes_private.set_DEC_ORIGIN(screen__->saved.origin_mode);

        m_defaults = screen__->saved.defaults;
        m_color_defaults = screen__->saved.color_defaults;
        m_character_replacements[0] = screen__->saved.character_replacements[0];
        m_character_replacements[1] = screen__->saved.character_replacements[1];
        m_character_replacement = screen__->saved.character_replacement;
}

/* Save cursor on a screen__. */
void
Terminal::save_cursor(BteScreen *screen__)
{
        screen__->saved.cursor.col = screen__->cursor.col;
        screen__->saved.cursor.row = screen__->cursor.row - screen__->insert_delta;

        screen__->saved.modes_ecma = m_modes_ecma.get_modes();

        screen__->saved.reverse_mode = m_modes_private.DEC_REVERSE_IMAGE();
        screen__->saved.origin_mode = m_modes_private.DEC_ORIGIN();

        screen__->saved.defaults = m_defaults;
        screen__->saved.color_defaults = m_color_defaults;
        screen__->saved.character_replacements[0] = m_character_replacements[0];
        screen__->saved.character_replacements[1] = m_character_replacements[1];
        screen__->saved.character_replacement = m_character_replacement;
}

/* Insert a single character into the stored data array. */
void
Terminal::insert_char(gunichar c,
                                bool insert,
                                bool invalidate_now)
{
	BteCellAttr attr;
	BteRowData *row;
	long col;
	int columns, i;
	bool line_wrapped = false; /* cursor moved before char inserted */
        gunichar c_unmapped = c;

        /* DEC Special Character and Line Drawing Set.  VT100 and higher (per XTerm docs). */
        static const gunichar line_drawing_map[32] = {
                0x0020,  /* _ => blank (space) */
                0x25c6,  /* ` => diamond */
                0x2592,  /* a => checkerboard */
                0x2409,  /* b => HT symbol */
                0x240c,  /* c => FF symbol */
                0x240d,  /* d => CR symbol */
                0x240a,  /* e => LF symbol */
                0x00b0,  /* f => degree */
                0x00b1,  /* g => plus/minus */
                0x2424,  /* h => NL symbol */
                0x240b,  /* i => VT symbol */
                0x2518,  /* j => downright corner */
                0x2510,  /* k => upright corner */
                0x250c,  /* l => upleft corner */
                0x2514,  /* m => downleft corner */
                0x253c,  /* n => cross */
                0x23ba,  /* o => scan line 1/9 */
                0x23bb,  /* p => scan line 3/9 */
                0x2500,  /* q => horizontal line (also scan line 5/9) */
                0x23bc,  /* r => scan line 7/9 */
                0x23bd,  /* s => scan line 9/9 */
                0x251c,  /* t => left t */
                0x2524,  /* u => right t */
                0x2534,  /* v => bottom t */
                0x252c,  /* w => top t */
                0x2502,  /* x => vertical line */
                0x2264,  /* y => <= */
                0x2265,  /* z => >= */
                0x03c0,  /* { => pi */
                0x2260,  /* | => not equal */
                0x00a3,  /* } => pound currency sign */
                0x00b7,  /* ~ => bullet */
        };

        insert |= m_modes_ecma.IRM();

	/* If we've enabled the special drawing set, map the characters to
	 * Unicode. */
        if (G_UNLIKELY (*m_character_replacement == BTE_CHARACTER_REPLACEMENT_LINE_DRAWING)) {
                if (c >= 95 && c <= 126)
                        c = line_drawing_map[c - 95];
        }

	/* Figure out how many columns this character should occupy. */
        columns = _bte_unichar_width(c, m_utf8_ambiguous_width);

	/* If we're autowrapping here, do it. */
        col = m_screen->cursor.col;
	if (G_UNLIKELY (columns && col + columns > m_column_count)) {
		if (m_modes_private.DEC_AUTOWRAP()) {
			_bte_debug_print(BTE_DEBUG_ADJ,
					"Autowrapping before character\n");
			/* Wrap. */
			/* XXX clear to the end of line */
                        col = m_screen->cursor.col = 0;
			/* Mark this line as soft-wrapped. */
			row = ensure_row();
                        set_soft_wrapped(m_screen->cursor.row);
                        cursor_down(false);
                        ensure_row();
                        apply_bidi_attributes(m_screen->cursor.row, row->attr.bidi_flags, BTE_BIDI_FLAG_ALL);
		} else {
			/* Don't wrap, stay at the rightmost column. */
                        col = m_screen->cursor.col =
				m_column_count - columns;
		}
		line_wrapped = true;
	}

	_bte_debug_print(BTE_DEBUG_PARSER,
			"Inserting U+%04X '%lc' (colors %" G_GUINT64_FORMAT ") (%ld+%d, %ld), delta = %ld; ",
                         (unsigned int)c, g_unichar_isprint(c) ? c : 0xfffd,
                         m_color_defaults.attr.colors(),
                        col, columns, (long)m_screen->cursor.row,
			(long)m_screen->insert_delta);

        //FIXMEchpe
        if (G_UNLIKELY(c == 0))
                goto not_inserted;

	if (G_UNLIKELY (columns == 0)) {

		/* It's a combining mark */

		long row_num;
		BteCell *cell;

		_bte_debug_print(BTE_DEBUG_PARSER, "combining U+%04X", c);

                row_num = m_screen->cursor.row;
		row = NULL;
		if (G_UNLIKELY (col == 0)) {
			/* We are at first column.  See if the previous line softwrapped.
			 * If it did, move there.  Otherwise skip inserting. */

			if (G_LIKELY (row_num > 0)) {
				row_num--;
				row = find_row_data_writable(row_num);

				if (row) {
					if (!row->attr.soft_wrapped)
						row = NULL;
					else
						col = _bte_row_data_length (row);
				}
			}
		} else {
			row = find_row_data_writable(row_num);
		}

		if (G_UNLIKELY (!row || !col))
			goto not_inserted;

		/* Combine it on the previous cell */

		col--;
		cell = _bte_row_data_get_writable (row, col);

		if (G_UNLIKELY (!cell))
			goto not_inserted;

		/* Find the previous cell */
		while (cell && cell->attr.fragment() && col > 0)
			cell = _bte_row_data_get_writable (row, --col);
		if (G_UNLIKELY (!cell || cell->c == '\t'))
			goto not_inserted;

		/* Combine the new character on top of the cell string */
		c = _bte_unistr_append_unichar (cell->c, c);

		/* And set it */
		columns = cell->attr.columns();
		for (i = 0; i < columns; i++) {
			cell = _bte_row_data_get_writable (row, col++);
			cell->c = c;
		}

		goto done;
        } else {
                m_last_graphic_character = c_unmapped;
	}

	/* Make sure we have enough rows to hold this data. */
	row = ensure_cursor();
	g_assert(row != NULL);

	if (insert) {
                cleanup_fragments(col, col);
		for (i = 0; i < columns; i++)
                        _bte_row_data_insert (row, col + i, &basic_cell);
	} else {
                cleanup_fragments(col, col + columns);
		_bte_row_data_fill (row, &basic_cell, col + columns);
	}

        attr = m_defaults.attr;
	attr.set_columns(columns);

	{
		BteCell *pcell = _bte_row_data_get_writable (row, col);
		pcell->c = c;
		pcell->attr = attr;
		col++;
	}

	/* insert wide-char fragments */
	attr.set_fragment(true);
	for (i = 1; i < columns; i++) {
		BteCell *pcell = _bte_row_data_get_writable (row, col);
		pcell->c = c;
		pcell->attr = attr;
		col++;
	}
	if (_bte_row_data_length (row) > m_column_count)
		cleanup_fragments(m_column_count, _bte_row_data_length (row));
	_bte_row_data_shrink (row, m_column_count);

        m_screen->cursor.col = col;

done:
        /* Signal that this part of the window needs drawing. */
        if (G_UNLIKELY (invalidate_now)) {
                invalidate_row_and_context(m_screen->cursor.row);
        }

	/* We added text, so make a note of it. */
	m_text_inserted_flag = TRUE;

not_inserted:
	_bte_debug_print(BTE_DEBUG_ADJ|BTE_DEBUG_PARSER,
			"insertion delta => %ld.\n",
			(long)m_screen->insert_delta);

        m_line_wrapped = line_wrapped;
}

guint8
Terminal::get_bidi_flags() const noexcept
{
        return (m_modes_ecma.BDSM() ? BTE_BIDI_FLAG_IMPLICIT : 0) |
               (m_bidi_rtl ? BTE_BIDI_FLAG_RTL : 0) |
               (m_modes_private.BTE_BIDI_AUTO() ? BTE_BIDI_FLAG_AUTO : 0) |
               (m_modes_private.BTE_BIDI_BOX_MIRROR() ? BTE_BIDI_FLAG_BOX_MIRROR : 0);
}

/* Apply the specified BiDi parameters on the paragraph beginning at the specified line. */
void
Terminal::apply_bidi_attributes(bte::grid::row_t start, guint8 bidi_flags, guint8 bidi_flags_mask)
{
        bte::grid::row_t row = start;
        BteRowData *rowdata;

        bidi_flags &= bidi_flags_mask;

        _bte_debug_print(BTE_DEBUG_BIDI,
                         "Applying BiDi parameters from row %ld.\n", row);

        rowdata = _bte_ring_index_writable (m_screen->row_data, row);
        if (rowdata == nullptr || (rowdata->attr.bidi_flags & bidi_flags_mask) == bidi_flags) {
                _bte_debug_print(BTE_DEBUG_BIDI,
                                 "BiDi parameters didn't change for this paragraph.\n");
                return;
        }

        while (true) {
                rowdata->attr.bidi_flags &= ~bidi_flags_mask;
                rowdata->attr.bidi_flags |= bidi_flags;

                if (!rowdata->attr.soft_wrapped)
                        break;

                rowdata = _bte_ring_index_writable (m_screen->row_data, row + 1);
                if (rowdata == nullptr)
                        break;
                row++;
        }

        _bte_debug_print(BTE_DEBUG_BIDI,
                         "Applied BiDi parameters to rows %ld..%ld.\n", start, row);

        m_ringview.invalidate();
        invalidate_rows(start, row);
}

/* Apply the current BiDi parameters covered by bidi_flags_mask on the current paragraph
 * if the cursor is at the first position of this paragraph. */
void
Terminal::maybe_apply_bidi_attributes(guint8 bidi_flags_mask)
{
        _bte_debug_print(BTE_DEBUG_BIDI,
                         "Maybe applying BiDi parameters on current paragraph.\n");

        if (m_screen->cursor.col != 0) {
                _bte_debug_print(BTE_DEBUG_BIDI,
                                 "No, cursor not in first column.\n");
                return;
        }

        auto row = m_screen->cursor.row;

        if (row > _bte_ring_delta (m_screen->row_data)) {
                const BteRowData *rowdata = _bte_ring_index (m_screen->row_data, row - 1);
                if (rowdata != nullptr && rowdata->attr.soft_wrapped) {
                        _bte_debug_print(BTE_DEBUG_BIDI,
                                         "No, we're not after a hard wrap.\n");
                        return;
                }
        }

        _bte_debug_print(BTE_DEBUG_BIDI,
                         "Yes, applying.\n");

        apply_bidi_attributes (row, get_bidi_flags(), bidi_flags_mask);
}

static void
reaper_child_exited_cb(BteReaper *reaper,
                       int ipid,
                       int status,
                       bte::terminal::Terminal* that) noexcept
try
{
        that->child_watch_done(pid_t{ipid}, status);
        // @that might be destroyed at this point
}
catch (...)
{
        bte::log_exception();
}

void
Terminal::child_watch_done(pid_t pid,
                           int status)
{
	if (pid != m_pty_pid)
                return;

        _BTE_DEBUG_IF (BTE_DEBUG_LIFECYCLE) {
                g_printerr ("Child[%d] exited with status %d\n",
                            pid, status);
#ifdef HAVE_SYS_WAIT_H
                if (WIFEXITED (status)) {
                        g_printerr ("Child[%d] exit code %d.\n",
                                    pid, WEXITSTATUS (status));
                } else if (WIFSIGNALED (status)) {
                        g_printerr ("Child[%d] dies with signal %d.\n",
                                    pid, WTERMSIG (status));
                }
#endif
        }

        /* Disconnect from the reaper */
        if (m_reaper) {
                g_signal_handlers_disconnect_by_func(m_reaper,
                                                     (gpointer)reaper_child_exited_cb,
                                                     this);
                g_object_unref(m_reaper);
                m_reaper = nullptr;
        }

        m_pty_pid = -1;

        /* If we still have a PTY, or data to process, defer emitting the signals
         * until we have EOF on the PTY, so that we can process all pending data.
         */
        if (pty() || !m_incoming_queue.empty()) {
                m_child_exit_status = status;
                m_child_exited_after_eos_pending = true;

                m_child_exited_eos_wait_timer.schedule_seconds(2); // FIXME: better value?
        } else {
                m_child_exited_after_eos_pending = false;

                if (widget())
                        widget()->emit_child_exited(status);
        }
}

static void
mark_input_source_invalid_cb(bte::terminal::Terminal* that)
{
	_bte_debug_print (BTE_DEBUG_IO, "Removed PTY input source\n");
	that->m_pty_input_source = 0;
}

/* Read and handle data from the child. */
static gboolean
io_read_cb(int fd,
           GIOCondition condition,
           bte::terminal::Terminal* that)
{
        return that->pty_io_read(fd, condition);
}

void
Terminal::connect_pty_read()
{
	if (m_pty_input_source != 0 || !pty())
		return;

        _bte_debug_print (BTE_DEBUG_IO, "Adding PTY input source\n");

        m_pty_input_source = g_unix_fd_add_full(BTE_CHILD_INPUT_PRIORITY,
                                                pty()->fd(),
                                                (GIOCondition)(G_IO_IN | G_IO_PRI | G_IO_HUP | G_IO_ERR),
                                                (GUnixFDSourceFunc)io_read_cb,
                                                this,
                                                (GDestroyNotify)mark_input_source_invalid_cb);
}

static void
mark_output_source_invalid_cb(bte::terminal::Terminal* that)
{
	_bte_debug_print (BTE_DEBUG_IO, "Removed PTY output source\n");
	that->m_pty_output_source = 0;
}

/* Send locally-encoded characters to the child. */
static gboolean
io_write_cb(int fd,
            GIOCondition condition,
            bte::terminal::Terminal* that)
{
        return that->pty_io_write(fd, condition);
}

void
Terminal::connect_pty_write()
{
        if (m_pty_output_source != 0 || !pty())
                return;

        g_warn_if_fail(m_input_enabled);

        /* Anything to write? */
        if (_bte_byte_array_length(m_outgoing) == 0)
                return;

        /* Do one write. FIXMEchpe why? */
        if (!pty_io_write (pty()->fd(), G_IO_OUT))
                return;

        _bte_debug_print (BTE_DEBUG_IO, "Adding PTY output source\n");

        m_pty_output_source = g_unix_fd_add_full(BTE_CHILD_OUTPUT_PRIORITY,
                                                 pty()->fd(),
                                                 G_IO_OUT,
                                                 (GUnixFDSourceFunc)io_write_cb,
                                                 this,
                                                 (GDestroyNotify)mark_output_source_invalid_cb);
}

void
Terminal::disconnect_pty_read()
{
	if (m_pty_input_source != 0) {
		_bte_debug_print (BTE_DEBUG_IO, "Removing PTY input source\n");
		g_source_remove(m_pty_input_source);
                // FIXMEchpe the destroy notify should already have done this!
		m_pty_input_source = 0;
	}
}

void
Terminal::disconnect_pty_write()
{
	if (m_pty_output_source != 0) {
		_bte_debug_print (BTE_DEBUG_IO, "Removing PTY output source\n");
		g_source_remove(m_pty_output_source);
                // FIXMEchpe the destroy notify should already have done this!
		m_pty_output_source = 0;
	}
}

void
Terminal::pty_termios_changed()
{
        _bte_debug_print(BTE_DEBUG_IO, "Termios changed\n");
}

void
Terminal::pty_scroll_lock_changed(bool locked)
{
        _bte_debug_print(BTE_DEBUG_IO, "Output %s (^%c)\n",
                         locked ? "stopped" : "started",
                         locked ? 'Q' : 'S');
}

/*
 * Terminal::watch_child:
 * @child_pid: a #pid_t
 *
 * Watches @child_pid. When the process exists, the #BteTerminal::child-exited
 * signal will be called with the child's exit status.
 *
 * Prior to calling this function, a #BtePty must have been set in @terminal
 * using bte_terminal_set_pty().
 * When the child exits, the terminal's #BtePty will be set to %NULL.
 *
 * Note: g_child_watch_add() or g_child_watch_add_full() must not have
 * been called for @child_pid, nor a #GSource for it been created with
 * g_child_watch_source_new().
 *
 * Note: when using the g_spawn_async() family of functions,
 * the %G_SPAWN_DO_NOT_REAP_CHILD flag MUST have been passed.
 */
void
Terminal::watch_child (pid_t child_pid)
{
        // FIXMEchpe: support passing child_pid = -1 to remove the wathch
        g_assert(child_pid != -1);
        if (!pty())
                return;

        auto const freezer = bte::glib::FreezeObjectNotify{m_terminal};

        /* Set this as the child's pid. */
        m_pty_pid = child_pid;

        /* Catch a child-exited signal from the child pid. */
        auto reaper = bte_reaper_ref();
        bte_reaper_add_child(child_pid);
        if (reaper != m_reaper) {
                if (m_reaper) {
                        g_signal_handlers_disconnect_by_func(m_reaper,
                                                             (gpointer)reaper_child_exited_cb,
                                                             this);
                        g_object_unref(m_reaper);
                }
                m_reaper = reaper; /* adopts */
                g_signal_connect(m_reaper, "child-exited",
                                 G_CALLBACK(reaper_child_exited_cb),
                                 this);
        } else {
                g_object_unref(reaper);
        }

        /* FIXMEchpe: call set_size() here? */
}

/* Reset the input method context. */
void
Terminal::im_reset()
{
        if (widget())
                widget()->im_reset();

        im_preedit_reset();
}

void
Terminal::process_incoming()
{
        switch (data_syntax()) {
        case DataSyntax::eECMA48_UTF8:   process_incoming_utf8();    break;
#ifdef WITH_ICU
        case DataSyntax::eECMA48_PCTERM: process_incoming_pcterm(); break;
#endif
        default: g_assert_not_reached(); break;
        }
}


/* Note that this code is mostly copied to process_incoming_pcterm() below; any non-charset-decoding
 * related changes made here need to be made there, too.
 * FIXMEchpe: refactor this to share more code with process_incoming_pcterm().
 */
void
Terminal::process_incoming_utf8()
{
	BteVisualPosition saved_cursor;
	gboolean saved_cursor_visible;
        CursorStyle saved_cursor_style;
        bte::grid::row_t bbox_top, bbox_bottom;
	gboolean modified, bottom;
	gboolean invalidated_text;
	gboolean in_scroll_region;

	_bte_debug_print(BTE_DEBUG_IO,
                         "Handler processing %" G_GSIZE_FORMAT " bytes over %" G_GSIZE_FORMAT " chunks.\n",
                         m_input_bytes,
                         m_incoming_queue.size());
	_bte_debug_print (BTE_DEBUG_WORK, "(");

        auto previous_screen = m_screen;

        bottom = m_screen->insert_delta == (long)m_screen->scroll_delta;

	/* Save the current cursor position. */
        saved_cursor = m_screen->cursor;
	saved_cursor_visible = m_modes_private.DEC_TEXT_CURSOR();
        saved_cursor_style = m_cursor_style;

        in_scroll_region = m_scrolling_restricted
            && (m_screen->cursor.row >= (m_screen->insert_delta + m_scrolling_region.start))
            && (m_screen->cursor.row <= (m_screen->insert_delta + m_scrolling_region.end));

	/* We should only be called when there's data to process. */
	g_assert(!m_incoming_queue.empty());

	modified = FALSE;
	invalidated_text = FALSE;

        bbox_bottom = -G_MAXINT;
        bbox_top = G_MAXINT;

        bte::parser::Sequence seq{m_parser};

        m_line_wrapped = false;

        size_t bytes_processed = 0;

        while (!m_incoming_queue.empty()) {
                auto chunk = std::move(m_incoming_queue.front());
                m_incoming_queue.pop();

                g_assert_nonnull(chunk.get());

                _BTE_DEBUG_IF(BTE_DEBUG_IO) {
                        _bte_debug_hexdump("Incoming buffer", chunk->data, chunk->len);
                }

                bytes_processed += chunk->len;

                auto const* ip = chunk->data;
                auto const* iend = chunk->data + chunk->len;

                for ( ; ip < iend; ++ip) {

                        switch (m_utf8_decoder.decode(*ip)) {
                        case bte::base::UTF8Decoder::REJECT_REWIND:
                                /* Rewind the stream.
                                 * Note that this will never lead to a loop, since in the
                                 * next round this byte *will* be consumed.
                                 */
                                --ip;
                                [[fallthrough]];
                        case bte::base::UTF8Decoder::REJECT:
                                m_utf8_decoder.reset();
                                /* Fall through to insert the U+FFFD replacement character. */
                                [[fallthrough]];
                        case bte::base::UTF8Decoder::ACCEPT: {
                                auto rv = m_parser.feed(m_utf8_decoder.codepoint());
                                if (G_UNLIKELY(rv < 0)) {
#ifdef DEBUG
                                        uint32_t c = m_utf8_decoder.codepoint();
                                        char c_buf[7];
                                        g_snprintf(c_buf, sizeof(c_buf), "%lc", c);
                                        char const* wp_str = g_unichar_isprint(c) ? c_buf : _bte_debug_sequence_to_string(c_buf, -1);
                                        _bte_debug_print(BTE_DEBUG_PARSER, "Parser error on U+%04X [%s]!\n",
                                                         c, wp_str);
#endif
                                        break;
                                }

#ifdef BTE_DEBUG
                                if (rv != BTE_SEQ_NONE)
                                        g_assert((bool)seq);
#endif

                                _BTE_DEBUG_IF(BTE_DEBUG_PARSER) {
                                        if (rv != BTE_SEQ_NONE) {
                                                seq.print();
                                        }
                                }

                                // FIXMEchpe this assumes that the only handler inserting
                                // a character is GRAPHIC, which isn't true (at least ICH, REP, SUB
                                // also do, and invalidate directly for now)...

                                switch (rv) {
                                case BTE_SEQ_GRAPHIC: {

                                        bbox_top = std::min(bbox_top,
                                                            m_screen->cursor.row);

                                        // does insert_char(c, false, false)
                                        GRAPHIC(seq);
                                        _bte_debug_print(BTE_DEBUG_PARSER,
                                                         "Last graphic is now U+%04X %lc\n",
                                                         m_last_graphic_character,
                                                         g_unichar_isprint(m_last_graphic_character) ? m_last_graphic_character : 0xfffd);

                                        if (m_line_wrapped) {
                                                m_line_wrapped = false;
                                                /* line wrapped, correct bbox */
                                                if (invalidated_text &&
                                                    (m_screen->cursor.row > bbox_bottom + BTE_CELL_BBOX_SLACK ||
                                                     m_screen->cursor.row < bbox_top - BTE_CELL_BBOX_SLACK)) {
                                                        invalidate_rows_and_context(bbox_top, bbox_bottom);
                                                        bbox_bottom = -G_MAXINT;
                                                        bbox_top = G_MAXINT;
                                                }
                                                bbox_top = std::min(bbox_top,
                                                                    m_screen->cursor.row);
                                        }
                                        /* Add the cells over which we have moved to the region
                                         * which we need to refresh for the user. */
                                        bbox_bottom = std::max(bbox_bottom,
                                                               m_screen->cursor.row);
                                        invalidated_text = TRUE;

                                        /* We *don't* emit flush pending signals here. */
                                        modified = TRUE;

                                        break;
                                }

                                case BTE_SEQ_NONE:
                                case BTE_SEQ_IGNORE:
                                        break;

                                default: {
                                        switch (seq.command()) {
#define _BTE_CMD(cmd)   case BTE_CMD_##cmd: cmd(seq); break;
#define _BTE_NOP(cmd)
#include "parser-cmd.hh"
#undef _BTE_CMD
#undef _BTE_NOP
                                        default:
                                                _bte_debug_print(BTE_DEBUG_PARSER,
                                                                 "Unknown parser command %d\n", seq.command());
                                                break;
                                        }

                                        m_last_graphic_character = 0;

                                        modified = TRUE;

                                        // FIXME m_screen may be != previous_screen, check for that!

                                        gboolean new_in_scroll_region = m_scrolling_restricted
                                                && (m_screen->cursor.row >= (m_screen->insert_delta + m_scrolling_region.start))
                                                && (m_screen->cursor.row <= (m_screen->insert_delta + m_scrolling_region.end));

                                        /* if we have moved greatly during the sequence handler, or moved
                                         * into a scroll_region from outside it, restart the bbox.
                                         */
                                        if (invalidated_text &&
                                            ((new_in_scroll_region && !in_scroll_region) ||
                                             (m_screen->cursor.row > bbox_bottom + BTE_CELL_BBOX_SLACK ||
                                              m_screen->cursor.row < bbox_top - BTE_CELL_BBOX_SLACK))) {
                                                invalidate_rows_and_context(bbox_top, bbox_bottom);
                                                invalidated_text = FALSE;
                                                bbox_bottom = -G_MAXINT;
                                                bbox_top = G_MAXINT;
                                        }

                                        in_scroll_region = new_in_scroll_region;

                                        break;
                                }
                                }
                                break;
                        }
                        }
                }

                if (chunk->eos()) {
                        m_eos_pending = true;
                        /* If there's an unfinished character in the queue, insert a replacement character */
                        if (m_utf8_decoder.flush()) {
                                insert_char(m_utf8_decoder.codepoint(), false, true);
                        }

                        break;
                }
        }

#ifdef BTE_DEBUG
		/* Some safety checks: ensure the visible parts of the buffer
		 * are all in the buffer. */
		g_assert_cmpint(m_screen->insert_delta, >=, _bte_ring_delta(m_screen->row_data));

		/* The cursor shouldn't be above or below the addressable
		 * part of the display buffer. */
                g_assert_cmpint(m_screen->cursor.row, >=, m_screen->insert_delta);
#endif

	if (modified) {
		/* Keep the cursor on-screen if we scroll on output, or if
		 * we're currently at the bottom of the buffer. */
		update_insert_delta();
		if (m_scroll_on_output || bottom) {
			maybe_scroll_to_bottom();
		}
		/* Deselect the current selection if its contents are changed
		 * by this insertion. */
                if (!m_selection_resolved.empty()) {
                        //FIXMEchpe: this is atrocious
			auto selection = get_selected_text();
			if ((selection == nullptr) ||
			    (m_selection[BTE_SELECTION_PRIMARY] == nullptr) ||
			    (strcmp(selection->str, m_selection[BTE_SELECTION_PRIMARY]->str) != 0)) {
				deselect_all();
			}
                        if (selection)
                                g_string_free(selection, TRUE);
		}
	}

	if (modified || (m_screen != previous_screen)) {
                m_ringview.invalidate();
		/* Signal that the visible contents changed. */
		queue_contents_changed();
	}

	emit_pending_signals();

	if (invalidated_text) {
                invalidate_rows_and_context(bbox_top, bbox_bottom);
	}

        if ((saved_cursor.col != m_screen->cursor.col) ||
            (saved_cursor.row != m_screen->cursor.row)) {
		/* invalidate the old and new cursor positions */
		if (saved_cursor_visible)
                        invalidate_row(saved_cursor.row);
		invalidate_cursor_once();
		check_cursor_blink();
		/* Signal that the cursor moved. */
		queue_cursor_moved();
        } else if ((saved_cursor_visible != m_modes_private.DEC_TEXT_CURSOR()) ||
                   (saved_cursor_style != m_cursor_style)) {
                invalidate_row(saved_cursor.row);
		check_cursor_blink();
	}

	/* Tell the input method where the cursor is. */
        im_update_cursor();

        /* After processing some data, do a hyperlink GC. The multiplier is totally arbitrary, feel free to fine tune. */
        _bte_ring_hyperlink_maybe_gc(m_screen->row_data, bytes_processed * 8);

	_bte_debug_print (BTE_DEBUG_WORK, ")");
	_bte_debug_print (BTE_DEBUG_IO,
                          "%" G_GSIZE_FORMAT " bytes in %" G_GSIZE_FORMAT " chunks left to process.\n",
                          m_input_bytes,
                          m_incoming_queue.size());
}

#ifdef WITH_ICU

/* Note that this is mostly a copy of process_incoming_utf8() above; any non-charset-decoding
 * related changes made here need to be made there, too.
 * FIXMEchpe: refactor this to share more code with process_incoming_utf8().
 */
void
Terminal::process_incoming_pcterm()
{
	BteVisualPosition saved_cursor;
	gboolean saved_cursor_visible;
        CursorStyle saved_cursor_style;
        bte::grid::row_t bbox_top, bbox_bottom;
	gboolean modified, bottom;
	gboolean invalidated_text;
	gboolean in_scroll_region;

	_bte_debug_print(BTE_DEBUG_IO,
                         "Handler processing %" G_GSIZE_FORMAT " bytes over %" G_GSIZE_FORMAT " chunks.\n",
                         m_input_bytes,
                         m_incoming_queue.size());
	_bte_debug_print (BTE_DEBUG_WORK, "(");

        auto previous_screen = m_screen;

        bottom = m_screen->insert_delta == (long)m_screen->scroll_delta;

	/* Save the current cursor position. */
        saved_cursor = m_screen->cursor;
	saved_cursor_visible = m_modes_private.DEC_TEXT_CURSOR();
        saved_cursor_style = m_cursor_style;

        in_scroll_region = m_scrolling_restricted
            && (m_screen->cursor.row >= (m_screen->insert_delta + m_scrolling_region.start))
            && (m_screen->cursor.row <= (m_screen->insert_delta + m_scrolling_region.end));

	/* We should only be called when there's data to process. */
	g_assert(!m_incoming_queue.empty());

	modified = FALSE;
	invalidated_text = FALSE;

        bbox_bottom = -G_MAXINT;
        bbox_top = G_MAXINT;

        bte::parser::Sequence seq{m_parser};

        m_line_wrapped = false;

        size_t bytes_processed = 0;

        auto& decoder = m_converter->decoder();

        while (!m_incoming_queue.empty()) {
                auto chunk = std::move(m_incoming_queue.front());
                m_incoming_queue.pop();

                g_assert_nonnull(chunk.get());

                _BTE_DEBUG_IF(BTE_DEBUG_IO) {
                        _bte_debug_hexdump("Incoming buffer", chunk->data, chunk->len);
                }

                bytes_processed += chunk->len;

                auto const* ip = chunk->data;
                auto const* iend = chunk->data + chunk->len;

                auto eos = bool{false};
                auto flush = bool{false};

        start:
                while (ip < iend || flush) {
                        switch (decoder.decode(&ip, flush)) {
                        case bte::base::ICUDecoder::Result::eSomething: {
                                auto rv = m_parser.feed(decoder.codepoint());
                                if (G_UNLIKELY(rv < 0)) {
#ifdef BTE_DEBUG
                                        uint32_t c = decoder.codepoint();
                                        char c_buf[7];
                                        g_snprintf(c_buf, sizeof(c_buf), "%lc", c);
                                        char const* wp_str = g_unichar_isprint(c) ? c_buf : _bte_debug_sequence_to_string(c_buf, -1);
                                        _bte_debug_print(BTE_DEBUG_PARSER, "Parser error on U+%04X [%s]!\n",
                                                         c, wp_str);
#endif
                                        break;
                                }

#ifdef BTE_DEBUG
                                if (rv != BTE_SEQ_NONE)
                                        g_assert((bool)seq);
#endif

                                _BTE_DEBUG_IF(BTE_DEBUG_PARSER) {
                                        if (rv != BTE_SEQ_NONE) {
                                                seq.print();
                                        }
                                }

                                // FIXMEchpe this assumes that the only handler inserting
                                // a character is GRAPHIC, which isn't true (at least ICH, REP, SUB
                                // also do, and invalidate directly for now)...

                                switch (rv) {
                                case BTE_SEQ_GRAPHIC: {

                                        bbox_top = std::min(bbox_top,
                                                            m_screen->cursor.row);

                                        // does insert_char(c, false, false)
                                        GRAPHIC(seq);
                                        _bte_debug_print(BTE_DEBUG_PARSER,
                                                         "Last graphic is now U+%04X %lc\n",
                                                         m_last_graphic_character,
                                                         g_unichar_isprint(m_last_graphic_character) ? m_last_graphic_character : 0xfffd);

                                        if (m_line_wrapped) {
                                                m_line_wrapped = false;
                                                /* line wrapped, correct bbox */
                                                if (invalidated_text &&
                                                    (m_screen->cursor.row > bbox_bottom + BTE_CELL_BBOX_SLACK ||
                                                     m_screen->cursor.row < bbox_top - BTE_CELL_BBOX_SLACK)) {
                                                        invalidate_rows_and_context(bbox_top, bbox_bottom);
                                                        bbox_bottom = -G_MAXINT;
                                                        bbox_top = G_MAXINT;
                                                }
                                                bbox_top = std::min(bbox_top,
                                                                    m_screen->cursor.row);
                                        }
                                        /* Add the cells over which we have moved to the region
                                         * which we need to refresh for the user. */
                                        bbox_bottom = std::max(bbox_bottom,
                                                               m_screen->cursor.row);
                                        invalidated_text = TRUE;

                                        /* We *don't* emit flush pending signals here. */
                                        modified = TRUE;

                                        break;
                                }

                                case BTE_SEQ_NONE:
                                case BTE_SEQ_IGNORE:
                                        break;

                                default: {
                                        switch (seq.command()) {
#define _BTE_CMD(cmd)   case BTE_CMD_##cmd: cmd(seq); break;
#define _BTE_NOP(cmd)
#include "parser-cmd.hh"
#undef _BTE_CMD
#undef _BTE_NOP
                                        default:
                                                _bte_debug_print(BTE_DEBUG_PARSER,
                                                                 "Unknown parser command %d\n", seq.command());
                                                break;
                                        }

                                        m_last_graphic_character = 0;

                                        modified = TRUE;

                                        // FIXME m_screen may be != previous_screen, check for that!

                                        gboolean new_in_scroll_region = m_scrolling_restricted
                                                && (m_screen->cursor.row >= (m_screen->insert_delta + m_scrolling_region.start))
                                                && (m_screen->cursor.row <= (m_screen->insert_delta + m_scrolling_region.end));

                                        /* if we have moved greatly during the sequence handler, or moved
                                         * into a scroll_region from outside it, restart the bbox.
                                         */
                                        if (invalidated_text &&
                                            ((new_in_scroll_region && !in_scroll_region) ||
                                             (m_screen->cursor.row > bbox_bottom + BTE_CELL_BBOX_SLACK ||
                                              m_screen->cursor.row < bbox_top - BTE_CELL_BBOX_SLACK))) {
                                                invalidate_rows_and_context(bbox_top, bbox_bottom);
                                                invalidated_text = FALSE;
                                                bbox_bottom = -G_MAXINT;
                                                bbox_top = G_MAXINT;
                                        }

                                        in_scroll_region = new_in_scroll_region;

                                        break;
                                }
                                }
                                break;
                        }
                        case bte::base::ICUDecoder::Result::eNothing:
                                flush = false;
                                break;

                        case bte::base::ICUDecoder::Result::eError:
                                // FIXMEchpe do we need ++ip here?
                                decoder.reset();
                                break;

                        }
                }

                if (eos) {
                        /* Done processing the last chunk */
                        m_eos_pending = true;
                        break;
                }

                if (chunk->eos()) {
                        /* On EOS, we still need to flush the decoder before we can finish */
                        eos = flush = true;
                        goto start;
                }
        }

#ifdef BTE_DEBUG
		/* Some safety checks: ensure the visible parts of the buffer
		 * are all in the buffer. */
		g_assert_cmpint(m_screen->insert_delta, >=, _bte_ring_delta(m_screen->row_data));

		/* The cursor shouldn't be above or below the addressable
		 * part of the display buffer. */
                g_assert_cmpint(m_screen->cursor.row, >=, m_screen->insert_delta);
#endif

	if (modified) {
		/* Keep the cursor on-screen if we scroll on output, or if
		 * we're currently at the bottom of the buffer. */
		update_insert_delta();
		if (m_scroll_on_output || bottom) {
			maybe_scroll_to_bottom();
		}
		/* Deselect the current selection if its contents are changed
		 * by this insertion. */
                if (!m_selection_resolved.empty()) {
                        //FIXMEchpe: this is atrocious
			auto selection = get_selected_text();
			if ((selection == nullptr) ||
			    (m_selection[BTE_SELECTION_PRIMARY] == nullptr) ||
			    (strcmp(selection->str, m_selection[BTE_SELECTION_PRIMARY]->str) != 0)) {
				deselect_all();
			}
                        if (selection)
                                g_string_free(selection, TRUE);
		}
	}

	if (modified || (m_screen != previous_screen)) {
                m_ringview.invalidate();
		/* Signal that the visible contents changed. */
		queue_contents_changed();
	}

	emit_pending_signals();

	if (invalidated_text) {
                invalidate_rows_and_context(bbox_top, bbox_bottom);
	}

        if ((saved_cursor.col != m_screen->cursor.col) ||
            (saved_cursor.row != m_screen->cursor.row)) {
		/* invalidate the old and new cursor positions */
		if (saved_cursor_visible)
                        invalidate_row(saved_cursor.row);
		invalidate_cursor_once();
		check_cursor_blink();
		/* Signal that the cursor moved. */
		queue_cursor_moved();
        } else if ((saved_cursor_visible != m_modes_private.DEC_TEXT_CURSOR()) ||
                   (saved_cursor_style != m_cursor_style)) {
                invalidate_row(saved_cursor.row);
		check_cursor_blink();
	}

	/* Tell the input method where the cursor is. */
        im_update_cursor();

        /* After processing some data, do a hyperlink GC. The multiplier is totally arbitrary, feel free to fine tune. */
        _bte_ring_hyperlink_maybe_gc(m_screen->row_data, bytes_processed * 8);

	_bte_debug_print (BTE_DEBUG_WORK, ")");
	_bte_debug_print (BTE_DEBUG_IO,
                          "%" G_GSIZE_FORMAT " bytes in %" G_GSIZE_FORMAT " chunks left to process.\n",
                          m_input_bytes,
                          m_incoming_queue.size());
}

#endif /* WITH_ICU */

bool
Terminal::pty_io_read(int const fd,
                      GIOCondition const condition)
{
	_bte_debug_print (BTE_DEBUG_WORK, ".");
        _bte_debug_print(BTE_DEBUG_IO, "::pty_io_read condition %02x\n", condition);

        /* We need to check for EOS so that we can shut down the PTY.
         * When we get G_IO_HUP without G_IO_IN, we can process the EOF now.
         * However when we get G_IO_IN | G_IO_HUP, there is still data to be
         * read in this round, and in potentially more rounds; read the data
         * now, do *not* process the EOS (unless the read returns EIO, which
         * does happen and appears to mean that despite G_IO_IN no data was
         * actually available to be read, not even the cpkt header), and
         * otherwise wait for further calls which will have G_IO_HUP (and
         * possibly G_IO_IN again).
         */
        auto eos = bool{condition == G_IO_HUP};

        /* There is data to read */
	auto err = int{0};
        auto again = bool{true};
        bte::base::Chunk* chunk{nullptr};
	if (condition & (G_IO_IN | G_IO_PRI)) {
		guchar *bp;
		int rem, len;
		guint bytes, max_bytes;

		/* Limit the amount read between updates, so as to
		 * 1. maintain fairness between multiple terminals;
		 * 2. prevent reading the entire output of a command in one
		 *    pass, i.e. we always try to refresh the terminal ~40Hz.
		 *    See time_process_incoming() where we estimate the
		 *    maximum number of bytes we can read/process in between
		 *    updates.
		 */
		max_bytes = m_active_terminals_link != nullptr ?
		            g_list_length(g_active_terminals) - 1 : 0;
		if (max_bytes) {
			max_bytes = m_max_input_bytes / max_bytes;
		} else {
			max_bytes = m_max_input_bytes;
		}
		bytes = m_input_bytes;

                /* If possible, try adding more data to the chunk at the back of the queue */
                if (!m_incoming_queue.empty())
                        chunk = m_incoming_queue.back().get();

		do {
                        /* No chunk, chunk sealed or at least ¾ full? Get a new chunk */
			if (!chunk ||
                            chunk->sealed() ||
                            chunk->len >= 3 * chunk->capacity() / 4) {
                                m_incoming_queue.push(bte::base::Chunk::get());

                                chunk = m_incoming_queue.back().get();
			}

			rem = chunk->remaining_capacity();
			bp = chunk->data + chunk->len;
			len = 0;
			do {
                                /* We'd like to read (fd, bp, rem); but due to TIOCPKT mode
                                 * there's an extra input byte returned at the beginning.
                                 * We need to see what that byte is, but otherwise drop it
                                 * and write continuously to chunk->data.
                                 */
                                char pkt_header;
                                char save = bp[-1];
                                errno = 0;
                                int ret = read (fd, bp - 1, rem + 1);
                                pkt_header = bp[-1];
                                bp[-1] = save;
				switch (ret){
					case -1:
						err = errno;
						goto out;
					case 0:
						eos = true;
						goto out;
					default:
                                                ret--;

                                                if (pkt_header == TIOCPKT_DATA) {
                                                        bp += ret;
                                                        rem -= ret;
                                                        len += ret;
                                                } else {
                                                        if (pkt_header & TIOCPKT_IOCTL) {
                                                                /* We'd like to always be informed when the termios change,
                                                                 * so we can e.g. detect when no-echo is en/disabled and
                                                                 * change the cursor/input method/etc., but unfortunately
                                                                 * the kernel only sends this flag when (old or new) 'local flags'
                                                                 * include EXTPROC, which is not used often, and due to its side
                                                                 * effects, cannot be enabled by bte by default.
                                                                 *
                                                                 * FIXME: improve the kernel! see discussion in bug 755371
                                                                 * starting at comment 12
                                                                 */
                                                                pty_termios_changed();
                                                        }
                                                        if (pkt_header & TIOCPKT_STOP) {
                                                                pty_scroll_lock_changed(true);
                                                        }
                                                        if (pkt_header & TIOCPKT_START) {
                                                                pty_scroll_lock_changed(false);
                                                        }
                                                }
						break;
				}
			} while (rem);
out:
			chunk->len += len;
			bytes += len;
		} while (bytes < max_bytes &&
		         chunk->len == chunk->capacity());

                /* We may have an empty chunk at the back of the queue, but
                 * that doesn't matter, we'll fill it next time.
                 */

		if (!is_processing()) {
			add_process_timeout(this);
		}
		m_pty_input_active = len != 0;
		m_input_bytes = bytes;
		again = bytes < max_bytes;

		_bte_debug_print (BTE_DEBUG_IO, "read %d/%d bytes, again? %s, active? %s\n",
				bytes, max_bytes,
				again ? "yes" : "no",
				m_pty_input_active ? "yes" : "no");
	}

        if (condition & G_IO_ERR)
                err = EIO;

	/* Error? */
	switch (err) {
        case 0: /* no error */
                break;
        case EIO: /* EOS */
                eos = true;
                break;
        case EAGAIN:
        case EBUSY: /* do nothing */
                break;
        default:
                auto errsv = bte::libc::ErrnoSaver{};
                _bte_debug_print (BTE_DEBUG_IO, "Error reading from child: %s",
                                  g_strerror(errsv));
                break;
	}

        if (eos) {
		_bte_debug_print(BTE_DEBUG_IO, "got PTY EOF\n");

                /* Make a note of the EOS; but do not process it since there may be data
                 * to be processed first in the incomding queue.
                 */
                if (!chunk || chunk->sealed()) {
                        m_incoming_queue.push(bte::base::Chunk::get());
                        chunk = m_incoming_queue.back().get();
                }

                chunk->set_sealed();
                chunk->set_eos();

                /* Cancel wait timer */
                m_child_exited_eos_wait_timer.abort();

                /* Need to process the EOS */
		if (!is_processing()) {
			add_process_timeout(this);
		}

                again = false;
        }

	return again;
}

/*
 * Terminal::feed:
 * @data: data
 *
 * Interprets @data as if it were data received from a child process.
 */
void
Terminal::feed(std::string_view const& data,
               bool start_processing_)
{
        auto length = data.size();
        auto ptr = data.data();

        bte::base::Chunk* chunk = nullptr;
        if (!m_incoming_queue.empty()) {
                auto& achunk = m_incoming_queue.back();
                if (length < achunk->remaining_capacity() && !achunk->sealed())
                        chunk = achunk.get();
        }
        if (chunk == nullptr) {
                m_incoming_queue.push(bte::base::Chunk::get());
                chunk = m_incoming_queue.back().get();
        }

        /* Break the incoming data into chunks. */
        do {
                auto rem = chunk->remaining_capacity();
                auto len = std::min(length, rem);
                memcpy (chunk->data + chunk->len, ptr, len);
                chunk->len += len;
                length -= len;
                if (length == 0)
                        break;

                ptr += len;

                /* Get another chunk for the remaining data */
                m_incoming_queue.push(bte::base::Chunk::get());
                chunk = m_incoming_queue.back().get();
        } while (true);

        if (start_processing_)
                start_processing();
}

bool
Terminal::pty_io_write(int const fd,
                       GIOCondition const condition)
{
        auto const count = write(fd,
                                 m_outgoing->data,
                                 _bte_byte_array_length(m_outgoing));
	if (count != -1) {
		_BTE_DEBUG_IF (BTE_DEBUG_IO) {
                        _bte_debug_hexdump("Outgoing buffer written",
                                           (uint8_t const*)m_outgoing->data,
                                           count);
		}
		_bte_byte_array_consume(m_outgoing, count);
	}

        /* Run again if there are more bytes to write */
        return _bte_byte_array_length(m_outgoing) != 0;
}

/* Send some UTF-8 data to the child. */
void
Terminal::send_child(std::string_view const& data)
{
        // FIXMEchpe remove
        if (!m_input_enabled)
                return;

        /* Note that for backward compatibility, we need to emit the
         * ::commit signal even if there is no PTY. See issue bte#222.
         */

        switch (data_syntax()) {
        case DataSyntax::eECMA48_UTF8:
                emit_commit(data);
                if (pty())
                        _bte_byte_array_append(m_outgoing, data.data(), data.size());
                break;

#ifdef WITH_ICU
        case DataSyntax::eECMA48_PCTERM: {
                auto converted = m_converter->convert(data);

                emit_commit(converted);
                if (pty())
                        _bte_byte_array_append(m_outgoing, converted.data(), converted.size());
                break;
        }
#endif

        default:
                g_assert_not_reached();
                return;
        }

        /* If we need to start waiting for the child pty to
         * become available for writing, set that up here. */
        connect_pty_write();
}

/*
 * BteTerminal::feed_child:
 * @str: data to send to the child
 *
 * Sends UTF-8 text to the child as if it were entered by the user
 * at the keyboard.
 *
 * Does nothing if input is disabled.
 */
void
Terminal::feed_child(std::string_view const& str)
{
        if (!m_input_enabled)
                return;

        send_child(str);
}

/*
 * Terminal::feed_child_binary:
 * @data: data to send to the child
 *
 * Sends a block of binary data to the child.
 *
 * Does nothing if input is disabled.
 */
void
Terminal::feed_child_binary(std::string_view const& data)
{
        if (!m_input_enabled)
                return;

        /* If there's a place for it to go, add the data to the
         * outgoing buffer. */
        if (!pty())
                return;

        emit_commit(data);
        _bte_byte_array_append(m_outgoing, data.data(), data.size());

        /* If we need to start waiting for the child pty to
         * become available for writing, set that up here. */
        connect_pty_write();
}

void
Terminal::send(bte::parser::u8SequenceBuilder const& builder,
                         bool c1,
                         bte::parser::u8SequenceBuilder::Introducer introducer,
                         bte::parser::u8SequenceBuilder::ST st) noexcept
{
        std::string str;
        builder.to_string(str, c1, -1, introducer, st);
        feed_child(str);
}

void
Terminal::send(bte::parser::Sequence const& seq,
               bte::parser::u8SequenceBuilder const& builder) noexcept
{
        // FIXMEchpe always take c1 & ST from @seq?
        if (seq.type() == BTE_SEQ_OSC &&
            builder.type() == BTE_SEQ_OSC) {
                /* If we reply to a BEL-terminated OSC, reply with BEL-terminated OSC
                 * as well, see https://bugzilla.gnome.org/show_bug.cgi?id=722446 and
                 * https://gitlab.gnome.org/GNOME/bte/issues/65 .
                 */
                send(builder, false,
                     bte::parser::u8SequenceBuilder::Introducer::DEFAULT,
                     seq.terminator() == 0x7 ? bte::parser::u8SequenceBuilder::ST::BEL
                     : bte::parser::u8SequenceBuilder::ST::DEFAULT);
        } else {
                send(builder, false);
        }
}

void
Terminal::send(unsigned int type,
                         std::initializer_list<int> params) noexcept
{
        // FIXMEchpe take c1 & ST from @seq
        send(bte::parser::ReplyBuilder{type, params}, false);
}

void
Terminal::reply(bte::parser::Sequence const& seq,
                          unsigned int type,
                          std::initializer_list<int> params) noexcept
{
        send(seq, bte::parser::ReplyBuilder{type, params});
}

#if 0
void
Terminal::reply(bte::parser::Sequence const& seq,
                          unsigned int type,
                          std::initializer_list<int> params,
                          std::string const& str) noexcept
{
        bte::parser::ReplyBuilder reply_builder{type, params};
        reply_builder.set_string(str);
        send(seq, reply_builder);
}
#endif

void
Terminal::reply(bte::parser::Sequence const& seq,
                          unsigned int type,
                          std::initializer_list<int> params,
                          bte::parser::ReplyBuilder const& builder) noexcept
{
        std::string str;
        builder.to_string(str, true, -1,
                          bte::parser::ReplyBuilder::Introducer::NONE,
                          bte::parser::ReplyBuilder::ST::NONE);

        bte::parser::ReplyBuilder reply_builder{type, params};
        reply_builder.set_string(std::move(str));
        send(seq, reply_builder);
}

void
Terminal::reply(bte::parser::Sequence const& seq,
                          unsigned int type,
                          std::initializer_list<int> params,
                          char const* format,
                          ...) noexcept
{
        char buf[128];
        va_list vargs;
        va_start(vargs, format);
        auto len = g_vsnprintf(buf, sizeof(buf), format, vargs);
        va_end(vargs);
        g_assert_cmpint(len, <, sizeof(buf));

        bte::parser::ReplyBuilder builder{type, params};
        builder.set_string(std::string{buf});

        send(seq, builder);
}

void
Terminal::im_commit(std::string_view const& str)
{
        if (!m_input_enabled)
                return;

        _bte_debug_print(BTE_DEBUG_EVENTS,
                         "Input method committed `%s'.\n", std::string{str}.c_str());
        send_child(str);

	/* Committed text was committed because the user pressed a key, so
	 * we need to obey the scroll-on-keystroke setting. */
        if (m_scroll_on_keystroke && m_input_enabled) {
		maybe_scroll_to_bottom();
	}
}

void
Terminal::im_preedit_set_active(bool active) noexcept
{
	m_im_preedit_active = active;
}

void
Terminal::im_preedit_reset() noexcept
{
        m_im_preedit.clear();
        m_im_preedit.shrink_to_fit();
        m_im_preedit_cursor = 0;
        m_im_preedit_attrs.reset();
}

void
Terminal::im_preedit_changed(std::string_view const& str,
                             int cursorpos,
                             pango_attr_list_unique_type&& attrs) noexcept
{
	/* Queue the area where the current preedit string is being displayed
	 * for repainting. */
	invalidate_cursor_once();

        im_preedit_reset();
	m_im_preedit = str;
        m_im_preedit_attrs = std::move(attrs);
        m_im_preedit_cursor = cursorpos;

        /* Invalidate again with the new cursor position */
	invalidate_cursor_once();

        /* And tell the input method where the cursor is on the screen */
        im_update_cursor();
}

bool
Terminal::im_retrieve_surrounding()
{
        /* FIXME: implement this! Bug #726191 */
        return false;
}

bool
Terminal::im_delete_surrounding(int offset,
                                int n_chars)
{
        /* FIXME: implement this! Bug #726191 */
        return false;
}

void
Terminal::im_update_cursor()
{
	if (!widget_realized())
                return;

        cairo_rectangle_int_t rect;
        rect.x = m_screen->cursor.col * m_cell_width + m_padding.left +
                 get_preedit_width(false) * m_cell_width;
        rect.width = m_cell_width; // FIXMEchpe: if columns > 1 ?
        rect.y = row_to_pixel(m_screen->cursor.row) + m_padding.top;
        rect.height = m_cell_height;
        m_real_widget->im_set_cursor_location(&rect);
}

void
Terminal::set_border_padding(CtkBorder const* padding)
{
        if (memcmp(padding, &m_padding, sizeof(*padding)) != 0) {
                _bte_debug_print(BTE_DEBUG_MISC | BTE_DEBUG_WIDGET_SIZE,
                                 "Setting padding to (%d,%d,%d,%d)\n",
                                 padding->left, padding->right,
                                 padding->top, padding->bottom);

                m_padding = *padding;
                update_view_extents();
                ctk_widget_queue_resize(m_widget);
        } else {
                _bte_debug_print(BTE_DEBUG_MISC | BTE_DEBUG_WIDGET_SIZE,
                                 "Keeping padding the same at (%d,%d,%d,%d)\n",
                                 padding->left, padding->right,
                                 padding->top, padding->bottom);

        }
}

void
Terminal::set_cursor_aspect(float aspect)
{
        if (_bte_double_equal(aspect, m_cursor_aspect_ratio))
                return;

        m_cursor_aspect_ratio = aspect;
        invalidate_cursor_once();
}

void
Terminal::widget_style_updated()
{
        // FIXMEchpe: remove taking font info from the widget style
        set_font_desc(m_unscaled_font_desc.get());
}

void
Terminal::add_cursor_timeout()
{
	if (m_cursor_blink_timer)
		return; /* already added */

	m_cursor_blink_time = 0;
        m_cursor_blink_timer.schedule(m_cursor_blink_cycle, bte::glib::Timer::Priority::eLOW);
}

void
Terminal::remove_cursor_timeout()
{
	if (!m_cursor_blink_timer)
		return; /* already removed */

        m_cursor_blink_timer.abort();
        if (!m_cursor_blink_state) {
                invalidate_cursor_once();
                m_cursor_blink_state = true;
        }
}

/* Activates / disactivates the cursor blink timer to reduce wakeups */
void
Terminal::check_cursor_blink()
{
	if (m_has_focus &&
	    m_cursor_blinks &&
	    m_modes_private.DEC_TEXT_CURSOR())
		add_cursor_timeout();
	else
		remove_cursor_timeout();
}

void
Terminal::beep()
{
	if (m_audible_bell)
                m_real_widget->beep();
}

bool
Terminal::widget_key_press(KeyEvent const& event)
{
	char *normal = NULL;
	gsize normal_length = 0;
	struct termios tio;
	gboolean scrolled = FALSE, steal = FALSE, modifier = FALSE, handled,
		 suppress_alt_esc = FALSE, add_modifiers = FALSE;
	guint keyval = 0;
	gunichar keychar = 0;
	char keybuf[BTE_UTF8_BPC];

	/* If it's a keypress, record that we got the event, in case the
	 * input method takes the event from us. */
        // FIXMEchpe this is ::widget_key_press; what other event type could it even be!?
	if (event.is_key_press()) {
		/* Store a copy of the key. */
                keyval = event.keyval();
                m_modifiers = event.modifiers();

                // FIXMEchpe?
		if (m_cursor_blink_timer) {
			remove_cursor_timeout();
			add_cursor_timeout();
		}

		/* Determine if this is just a modifier key. */
		modifier = _bte_keymap_key_is_modifier(keyval);

		/* Unless it's a modifier key, hide the pointer. */
		if (!modifier) {
                        set_pointer_autohidden(true);
		}

		_bte_debug_print(BTE_DEBUG_EVENTS,
				"Keypress, modifiers=0x%x, "
				"keyval=0x%x, raw string=`%s'.\n",
				m_modifiers,
                                 keyval, event.string());

		/* We steal many keypad keys here. */
		if (!m_im_preedit_active) {
			switch (keyval) {
			case CDK_KEY_KP_Add:
			case CDK_KEY_KP_Subtract:
			case CDK_KEY_KP_Multiply:
			case CDK_KEY_KP_Divide:
			case CDK_KEY_KP_Enter:
				steal = TRUE;
				break;
			default:
				break;
			}
			if (m_modifiers & BTE_ALT_MASK) {
				steal = TRUE;
			}
			switch (keyval) {
                        case CDK_KEY_ISO_Lock:
                        case CDK_KEY_ISO_Level2_Latch:
                        case CDK_KEY_ISO_Level3_Shift:
                        case CDK_KEY_ISO_Level3_Latch:
                        case CDK_KEY_ISO_Level3_Lock:
                        case CDK_KEY_ISO_Level5_Shift:
                        case CDK_KEY_ISO_Level5_Latch:
                        case CDK_KEY_ISO_Level5_Lock:
                        case CDK_KEY_ISO_Group_Shift:
                        case CDK_KEY_ISO_Group_Latch:
                        case CDK_KEY_ISO_Group_Lock:
                        case CDK_KEY_ISO_Next_Group:
                        case CDK_KEY_ISO_Next_Group_Lock:
                        case CDK_KEY_ISO_Prev_Group:
                        case CDK_KEY_ISO_Prev_Group_Lock:
                        case CDK_KEY_ISO_First_Group:
                        case CDK_KEY_ISO_First_Group_Lock:
                        case CDK_KEY_ISO_Last_Group:
                        case CDK_KEY_ISO_Last_Group_Lock:
			case CDK_KEY_Multi_key:
			case CDK_KEY_Codeinput:
			case CDK_KEY_SingleCandidate:
			case CDK_KEY_MultipleCandidate:
			case CDK_KEY_PreviousCandidate:
			case CDK_KEY_Kanji:
			case CDK_KEY_Muhenkan:
                        case CDK_KEY_Henkan_Mode:
                        /* case CDK_KEY_Henkan: is CDK_KEY_Henkan_Mode */
			case CDK_KEY_Romaji:
			case CDK_KEY_Hiragana:
			case CDK_KEY_Katakana:
			case CDK_KEY_Hiragana_Katakana:
			case CDK_KEY_Zenkaku:
			case CDK_KEY_Hankaku:
			case CDK_KEY_Zenkaku_Hankaku:
			case CDK_KEY_Touroku:
			case CDK_KEY_Massyo:
			case CDK_KEY_Kana_Lock:
			case CDK_KEY_Kana_Shift:
			case CDK_KEY_Eisu_Shift:
			case CDK_KEY_Eisu_toggle:
                        /* case CDK_KEY_Kanji_Bangou: is CDK_KEY_Codeinput */
                        /* case CDK_KEY_Zen_Koho: is CDK_KEY_MultipleCandidate */
                        /* case CDK_KEY_Mae_Koho: is CDK_KEY_PreviousCandidate */
                        /* case CDK_KEY_kana_switch: is CDK_KEY_ISO_Group_Shift */
                        case CDK_KEY_Hangul:
                        case CDK_KEY_Hangul_Start:
                        case CDK_KEY_Hangul_End:
                        case CDK_KEY_Hangul_Hanja:
                        case CDK_KEY_Hangul_Jamo:
                        case CDK_KEY_Hangul_Romaja:
                        /* case CDK_KEY_Hangul_Codeinput: is CDK_KEY_Codeinput */
                        case CDK_KEY_Hangul_Jeonja:
                        case CDK_KEY_Hangul_Banja:
                        case CDK_KEY_Hangul_PreHanja:
                        case CDK_KEY_Hangul_PostHanja:
                        /* case CDK_KEY_Hangul_SingleCandidate: is CDK_KEY_SingleCandidate */
                        /* case CDK_KEY_Hangul_MultipleCandidate: is CDK_KEY_MultipleCandidate */
                        /* case CDK_KEY_Hangul_PreviousCandidate: is CDK_KEY_PreviousCandidate */
                        case CDK_KEY_Hangul_Special:
                        /* case CDK_KEY_Hangul_switch: is CDK_KEY_ISO_Group_Shift */

				steal = FALSE;
				break;
			default:
				break;
			}
		}
	}

	/* Let the input method at this one first. */
	if (!steal && m_input_enabled) {
                if (m_real_widget->im_filter_keypress(event)) {
			_bte_debug_print(BTE_DEBUG_EVENTS,
					"Keypress taken by IM.\n");
			return true;
		}
	}

	/* Now figure out what to send to the child. */
	if (event.is_key_press() && !modifier) {
		handled = FALSE;
		/* Map the key to a sequence name if we can. */
		switch (event.keyval()) {
		case CDK_KEY_BackSpace:
			switch (m_backspace_binding) {
			case EraseMode::eASCII_BACKSPACE:
				normal = g_strdup("");
				normal_length = 1;
				suppress_alt_esc = FALSE;
				break;
			case EraseMode::eASCII_DELETE:
				normal = g_strdup("");
				normal_length = 1;
				suppress_alt_esc = FALSE;
				break;
			case EraseMode::eDELETE_SEQUENCE:
                                normal = g_strdup("\e[3~");
                                normal_length = 4;
                                add_modifiers = TRUE;
				suppress_alt_esc = TRUE;
				break;
			case EraseMode::eTTY:
				if (pty() &&
				    tcgetattr(pty()->fd(), &tio) != -1)
				{
					normal = g_strdup_printf("%c", tio.c_cc[VERASE]);
					normal_length = 1;
				}
				suppress_alt_esc = FALSE;
				break;
			case EraseMode::eAUTO:
			default:
#ifndef _POSIX_VDISABLE
#define _POSIX_VDISABLE '\0'
#endif
				if (pty() &&
				    tcgetattr(pty()->fd(), &tio) != -1 &&
				    tio.c_cc[VERASE] != _POSIX_VDISABLE)
				{
					normal = g_strdup_printf("%c", tio.c_cc[VERASE]);
					normal_length = 1;
				}
				else
				{
					normal = g_strdup("");
					normal_length = 1;
					suppress_alt_esc = FALSE;
				}
				suppress_alt_esc = FALSE;
				break;
			}
                        /* Toggle ^H vs ^? if Ctrl is pressed */
                        if (normal_length == 1 && m_modifiers & CDK_CONTROL_MASK) {
                                if (normal[0] == '\010')
                                        normal[0] = '\177';
                                else if (normal[0] == '\177')
                                        normal[0] = '\010';
                        }
			handled = TRUE;
			break;
		case CDK_KEY_KP_Delete:
		case CDK_KEY_Delete:
			switch (m_delete_binding) {
			case EraseMode::eASCII_BACKSPACE:
				normal = g_strdup("\010");
				normal_length = 1;
				break;
			case EraseMode::eASCII_DELETE:
				normal = g_strdup("\177");
				normal_length = 1;
				break;
			case EraseMode::eTTY:
				if (pty() &&
				    tcgetattr(pty()->fd(), &tio) != -1)
				{
					normal = g_strdup_printf("%c", tio.c_cc[VERASE]);
					normal_length = 1;
				}
				suppress_alt_esc = FALSE;
				break;
			case EraseMode::eDELETE_SEQUENCE:
			case EraseMode::eAUTO:
			default:
                                normal = g_strdup("\e[3~");
                                normal_length = 4;
                                add_modifiers = TRUE;
				break;
			}
			handled = TRUE;
                        /* FIXMEchpe: why? this overrides the FALSE set above? */
			suppress_alt_esc = TRUE;
			break;
		case CDK_KEY_KP_Insert:
		case CDK_KEY_Insert:
			if (m_modifiers & CDK_SHIFT_MASK) {
				if (m_modifiers & CDK_CONTROL_MASK) {
                                        emit_paste_clipboard();
					handled = TRUE;
					suppress_alt_esc = TRUE;
				} else {
                                        widget_paste(CDK_SELECTION_PRIMARY);
					handled = TRUE;
					suppress_alt_esc = TRUE;
				}
			} else if (m_modifiers & CDK_CONTROL_MASK) {
                                emit_copy_clipboard();
				handled = TRUE;
				suppress_alt_esc = TRUE;
			}
			break;
		/* Keypad/motion keys. */
		case CDK_KEY_KP_Up:
		case CDK_KEY_Up:
			if (m_screen == &m_normal_screen &&
			    m_modifiers & CDK_CONTROL_MASK &&
                            m_modifiers & CDK_SHIFT_MASK) {
				scroll_lines(-1);
				scrolled = TRUE;
				handled = TRUE;
				suppress_alt_esc = TRUE;
			}
			break;
		case CDK_KEY_KP_Down:
		case CDK_KEY_Down:
			if (m_screen == &m_normal_screen &&
			    m_modifiers & CDK_CONTROL_MASK &&
                            m_modifiers & CDK_SHIFT_MASK) {
				scroll_lines(1);
				scrolled = TRUE;
				handled = TRUE;
				suppress_alt_esc = TRUE;
			}
			break;
		case CDK_KEY_KP_Page_Up:
		case CDK_KEY_Page_Up:
			if (m_screen == &m_normal_screen &&
			    m_modifiers & CDK_SHIFT_MASK) {
				scroll_pages(-1);
				scrolled = TRUE;
				handled = TRUE;
				suppress_alt_esc = TRUE;
			}
			break;
		case CDK_KEY_KP_Page_Down:
		case CDK_KEY_Page_Down:
			if (m_screen == &m_normal_screen &&
			    m_modifiers & CDK_SHIFT_MASK) {
				scroll_pages(1);
				scrolled = TRUE;
				handled = TRUE;
				suppress_alt_esc = TRUE;
			}
			break;
		case CDK_KEY_KP_Home:
		case CDK_KEY_Home:
			if (m_screen == &m_normal_screen &&
			    m_modifiers & CDK_SHIFT_MASK) {
				maybe_scroll_to_top();
				scrolled = TRUE;
				handled = TRUE;
			}
			break;
		case CDK_KEY_KP_End:
		case CDK_KEY_End:
			if (m_screen == &m_normal_screen &&
			    m_modifiers & CDK_SHIFT_MASK) {
				maybe_scroll_to_bottom();
				scrolled = TRUE;
				handled = TRUE;
			}
			break;
		/* Let Shift +/- tweak the font, like XTerm does. */
		case CDK_KEY_KP_Add:
		case CDK_KEY_KP_Subtract:
			if (m_modifiers & (CDK_SHIFT_MASK | CDK_CONTROL_MASK)) {
				switch (keyval) {
				case CDK_KEY_KP_Add:
					emit_increase_font_size();
					handled = TRUE;
					suppress_alt_esc = TRUE;
					break;
				case CDK_KEY_KP_Subtract:
					emit_decrease_font_size();
					handled = TRUE;
					suppress_alt_esc = TRUE;
					break;
				}
			}
			break;
		default:
			break;
		}
		/* If the above switch statement didn't do the job, try mapping
		 * it to a literal or capability name. */
                if (handled == FALSE) {
                        if (G_UNLIKELY (m_enable_bidi &&
                                        m_modes_private.BTE_BIDI_SWAP_ARROW_KEYS() &&
                                        (keyval == CDK_KEY_Left ||
                                         keyval == CDK_KEY_Right ||
                                         keyval == CDK_KEY_KP_Left ||
                                         keyval == CDK_KEY_KP_Right))) {
                                /* In keyboard arrow swapping mode, the left and right arrows need swapping
                                 * if the cursor stands inside a (possibly autodetected) RTL paragraph. */
                                ensure_row();
                                BteRowData const *row_data = find_row_data(m_screen->cursor.row);
                                bool rtl;
                                if ((row_data->attr.bidi_flags & (BTE_BIDI_FLAG_IMPLICIT | BTE_BIDI_FLAG_AUTO))
                                                              == (BTE_BIDI_FLAG_IMPLICIT | BTE_BIDI_FLAG_AUTO)) {
                                        /* Implicit paragraph with autodetection. Need to run the BiDi algorithm
                                         * to get the autodetected direction.
                                         * m_ringview is for the onscreen contents and the cursor may be offscreen.
                                         * Better leave that alone and use a temporary ringview for the cursor's row. */
                                        bte::base::RingView ringview;
                                        ringview.set_ring(m_screen->row_data);
                                        ringview.set_rows(m_screen->cursor.row, 1);
                                        ringview.set_width(m_column_count);
                                        ringview.update();
                                        rtl = ringview.get_bidirow(m_screen->cursor.row)->base_is_rtl();
                                } else {
                                        /* Not an implicit paragraph with autodetection, no autodetection
                                         * is required. Take the direction straight from the stored data. */
                                        rtl = !!(row_data->attr.bidi_flags & BTE_BIDI_FLAG_RTL);
                                }
                                if (rtl) {
                                        switch (keyval) {
                                        case CDK_KEY_Left:
                                                keyval = CDK_KEY_Right;
                                                break;
                                        case CDK_KEY_Right:
                                                keyval = CDK_KEY_Left;
                                                break;
                                        case CDK_KEY_KP_Left:
                                                keyval = CDK_KEY_KP_Right;
                                                break;
                                        case CDK_KEY_KP_Right:
                                                keyval = CDK_KEY_KP_Left;
                                                break;
                                        }
                                }
                        }

			_bte_keymap_map(keyval, m_modifiers,
                                        m_modes_private.DEC_APPLICATION_CURSOR_KEYS(),
                                        m_modes_private.DEC_APPLICATION_KEYPAD(),
					&normal,
					&normal_length);
			/* If we found something this way, suppress
			 * escape-on-alt. */
                        if (normal != NULL && normal_length > 0) {
				suppress_alt_esc = TRUE;
			}
		}

		/* Shall we do this here or earlier?  See bug 375112 and bug 589557 */
		if (m_modifiers & CDK_CONTROL_MASK && widget())
                        keyval = widget()->key_event_translate_ctrlkey(event);

		/* If we didn't manage to do anything, try to salvage a
		 * printable string. */
		if (handled == FALSE && normal == NULL) {

			/* Convert the keyval to a gunichar. */
			keychar = cdk_keyval_to_unicode(keyval);
			normal_length = 0;
			if (keychar != 0) {
				/* Convert the gunichar to a string. */
				normal_length = g_unichar_to_utf8(keychar,
								  keybuf);
				if (normal_length != 0) {
					normal = (char *)g_malloc(normal_length + 1);
					memcpy(normal, keybuf, normal_length);
					normal[normal_length] = '\0';
				} else {
					normal = NULL;
				}
			}
			if ((normal != NULL) &&
			    (m_modifiers & CDK_CONTROL_MASK)) {
				/* Replace characters which have "control"
				 * counterparts with those counterparts. */
				for (size_t i = 0; i < normal_length; i++) {
					if ((((guint8)normal[i]) >= 0x40) &&
					    (((guint8)normal[i]) <  0x80)) {
						normal[i] &= (~(0x60));
					}
				}
			}
			_BTE_DEBUG_IF (BTE_DEBUG_EVENTS) {
				if (normal) g_printerr(
						"Keypress, modifiers=0x%x, "
						"keyval=0x%x, cooked string=`%s'.\n",
						m_modifiers,
						keyval, normal);
			}
		}
		/* If we got normal characters, send them to the child. */
		if (normal != NULL) {
                        if (add_modifiers) {
                                _bte_keymap_key_add_key_modifiers(keyval,
                                                                  m_modifiers,
                                                                  m_modes_private.DEC_APPLICATION_CURSOR_KEYS(),
                                                                  &normal,
                                                                  &normal_length);
                        }
			if (m_modes_private.XTERM_META_SENDS_ESCAPE() &&
			    !suppress_alt_esc &&
			    (normal_length > 0) &&
			    (m_modifiers & BTE_ALT_MASK)) {
				feed_child(_BTE_CAP_ESC, 1);
			}
			if (normal_length > 0) {
				send_child({normal, normal_length});
			}
			g_free(normal);
		}
		/* Keep the cursor on-screen. */
		if (!scrolled && !modifier &&
                    m_scroll_on_keystroke && m_input_enabled) {
			maybe_scroll_to_bottom();
		}
		return true;
	}
	return false;
}

bool
Terminal::widget_key_release(KeyEvent const& event)
{
        m_modifiers = event.modifiers();

	if (m_input_enabled &&
            m_real_widget->im_filter_keypress(event))
                return true;

        return false;
}

static const guint8 word_char_by_category[] = {
        [G_UNICODE_CONTROL]             = 2,
        [G_UNICODE_FORMAT]              = 2,
        [G_UNICODE_UNASSIGNED]          = 2,
        [G_UNICODE_PRIVATE_USE]         = 0,
        [G_UNICODE_SURROGATE]           = 2,
        [G_UNICODE_LOWERCASE_LETTER]    = 1,
        [G_UNICODE_MODIFIER_LETTER]     = 1,
        [G_UNICODE_OTHER_LETTER]        = 1,
        [G_UNICODE_TITLECASE_LETTER]    = 1,
        [G_UNICODE_UPPERCASE_LETTER]    = 1,
        [G_UNICODE_SPACING_MARK]        = 0,
        [G_UNICODE_ENCLOSING_MARK]      = 0,
        [G_UNICODE_NON_SPACING_MARK]    = 0,
        [G_UNICODE_DECIMAL_NUMBER]      = 1,
        [G_UNICODE_LETTER_NUMBER]       = 1,
        [G_UNICODE_OTHER_NUMBER]        = 1,
        [G_UNICODE_CONNECT_PUNCTUATION] = 0,
        [G_UNICODE_DASH_PUNCTUATION]    = 0,
        [G_UNICODE_CLOSE_PUNCTUATION]   = 0,
        [G_UNICODE_FINAL_PUNCTUATION]   = 0,
        [G_UNICODE_INITIAL_PUNCTUATION] = 0,
        [G_UNICODE_OTHER_PUNCTUATION]   = 0,
        [G_UNICODE_OPEN_PUNCTUATION]    = 0,
        [G_UNICODE_CURRENCY_SYMBOL]     = 0,
        [G_UNICODE_MODIFIER_SYMBOL]     = 0,
        [G_UNICODE_MATH_SYMBOL]         = 0,
        [G_UNICODE_OTHER_SYMBOL]        = 0,
        [G_UNICODE_LINE_SEPARATOR]      = 2,
        [G_UNICODE_PARAGRAPH_SEPARATOR] = 2,
        [G_UNICODE_SPACE_SEPARATOR]     = 2,
};

/*
 * Terminal::is_word_char:
 * @c: a candidate Unicode code point
 *
 * Checks if a particular character is considered to be part of a word or not.
 *
 * Returns: %TRUE if the character is considered to be part of a word
 */
bool
Terminal::is_word_char(gunichar c) const
{
        const guint8 v = word_char_by_category[g_unichar_type(c)];

        if (v)
                return v == 1;

        /* Do we have an exception? */
        return std::find(std::begin(m_word_char_exceptions), std::end(m_word_char_exceptions), char32_t(c)) != std::end(m_word_char_exceptions);
}

/* Check if the characters in the two given locations are in the same class
 * (word vs. non-word characters).
 * Note that calling this method may invalidate the return value of
 * a previous find_row_data() call. */
bool
Terminal::is_same_class(bte::grid::column_t acol,
                                  bte::grid::row_t arow,
                                  bte::grid::column_t bcol,
                                  bte::grid::row_t brow) const
{
	BteCell const* pcell = nullptr;
	bool word_char;
	if ((pcell = find_charcell(acol, arow)) != nullptr && pcell->c != 0) {
                /* Group together if they're fragments of the very same character (not just character value) */
                if (arow == brow) {
                        auto a2 = acol, b2 = bcol;
                        while (a2 > 0 && find_charcell(a2, arow)->attr.fragment()) a2--;
                        while (b2 > 0 && find_charcell(b2, brow)->attr.fragment()) b2--;
                        if (a2 == b2)
                                return true;
                }

		word_char = is_word_char(_bte_unistr_get_base(pcell->c));

		/* Lets not group non-wordchars together (bug #25290) */
		if (!word_char)
			return false;

		pcell = find_charcell(bcol, brow);
		if (pcell == NULL || pcell->c == 0) {
			return false;
		}
		if (word_char != is_word_char(_bte_unistr_get_base(pcell->c))) {
			return false;
		}
		return true;
	}
	return false;
}

/*
 * Convert the mouse click or drag location (left or right half of a cell) into a selection endpoint
 * (a boundary between characters), extending the selection according to the current mode, in the
 * direction given in the @after parameter.
 *
 * All four selection modes require different strategies.
 *
 * In char mode, what matters is which vertical character boundary is closer, taking multi-cell characters
 * (CJKs, TABs) into account. Given the string "abcdef", if the user clicks on the boundary between "a"
 * and "b" (perhaps on the right half of "a", perhaps on the left half of "b"), and moves the mouse to the
 * boundary between "e" and "f" (perhaps a bit over "e", perhaps a bit over "f"), the selection should be
 * "bcde". By dragging the mouse back to approximately the click location, it is possible to select the
 * empty string. This is the common sense behavior impemented by basically every graphical toolkit
 * (unfortunately not by many terminal emulators), and also the one we go for.
 *
 * Word mode is the trickiest one. Many implementations have weird corner case bugs (e.g. don't highlight
 * a word if you double click on the second half of its last letter, or even highlight it if you click on
 * the first half of the following space). I think it is expected that double-clicking anywhere over a
 * word (including the first half of its first letter, or the last half of its last letter), but over no
 * other character, selects this entire word. By dragging the mouse it's not possible to select nothing,
 * the word (or non-word character) initially clicked on is always part of the selection. (An exception
 * is when clicking occurred over the margin, or an unused cell in a soft-wrapped row (due to CJK
 * wrapping).) Also, for symmetry reasons, the word (or non-word character) under the current mouse
 * location is also always selected.
 *
 * Line (paragraph) mode is conceptually quite similar to word mode (the cell, thus the entire row under
 * the click's location is always included), but is much easier to implement.
 *
 * In block mode, similarly to char mode, we care about vertical character boundary. (This is somewhat
 * debatable, as results in asymmetrical behavior along the two axes: a rectangle can disappear by
 * becoming zero wide, but not zero high.) We cannot take care of CJKs at the endpoints now because CJKs
 * can cross the boundary in any included row. Taking care of them needs to go to cell_is_selected_*().
 * We don't care about used vs. unused cells either. The event coordinate is simply rounded to the
 * nearest vertical cell boundary.
 */
bte::grid::coords
Terminal::resolve_selection_endpoint(bte::grid::halfcoords const& rowcolhalf, bool after) const
{
        auto row = rowcolhalf.row();
        auto col = rowcolhalf.halfcolumn().column();  /* Points to an actual cell now. At the end of this
                                                         method it'll point to a boundary. */
        auto half = rowcolhalf.halfcolumn().half();  /* 0 for left half, 1 for right half of the cell. */
        BteRowData const* rowdata;
        BteCell const* cell;
        int len;

        if (m_selection_block_mode) {
                /* Just find the nearest cell boundary within the line, not caring about CJKs, unused
                 * cells, or wrapping at EOL. The @after parameter is unused in this mode. */
                col += half;
                col = std::clamp (col, 0L, m_column_count);
        } else {
                switch (m_selection_type) {
                case SelectionType::eCHAR:
                        /* Find the nearest actual character boundary, taking CJKs and TABs into account.
                         * If at least halfway through the first unused cell, or over the right margin
                         * then wrap to the beginning of the next line.
                         * The @after parameter is unused in this mode. */
                        if (col < 0) {
                                col = 0;
                        } else if (col >= m_column_count) {
                                /* If on the right padding, select the entire line including a possible
                                 * newline character. This way if a line is fully filled and ends in a
                                 * newline, there's only a half cell width for which the line is selected
                                 * without the newline, but at least there's a way to include the newline
                                 * by moving the mouse to the right (bug 724253). */
                                col = 0;
                                row++;
                        } else {
                                bte::grid::column_t char_begin, char_end;  /* cell boundaries */
                                rowdata = find_row_data(row);
                                if (rowdata && col < _bte_row_data_nonempty_length(rowdata)) {
                                        /* Clicked over a used cell. Check for multi-cell characters. */
                                        char_begin = col;
                                        while (char_begin > 0) {
                                                cell = _bte_row_data_get (rowdata, char_begin);
                                                if (!cell->attr.fragment())
                                                        break;
                                                char_begin--;
                                        }
                                        cell = _bte_row_data_get (rowdata, char_begin);
                                        char_end = char_begin + cell->attr.columns();
                                } else {
                                        /* Clicked over unused area. Just go with cell boundaries. */
                                        char_begin = col;
                                        char_end = char_begin + 1;
                                }
                                /* Which boundary is closer? */
                                if (col * 2 + half < char_begin + char_end)
                                        col = char_begin;
                                else
                                        col = char_end;

                                /* Maybe wrap to the beginning of the next line. */
                                if (col > (rowdata ? _bte_row_data_nonempty_length(rowdata) : 0)) {
                                        col = 0;
                                        row++;
                                }
                        }
                        break;

                case SelectionType::eWORD:
                        /* Initialization for the cumbersome cases where the click didn't occur over an actual used cell. */
                        rowdata = find_row_data(row);
                        if (col < 0) {
                                /* Clicked over the left margin.
                                 * - If within a word (that is, the first letter in this row, and the last
                                 *   letter of the previous row belong to the same word) then select the
                                 *   letter according to the direction and continue expanding.
                                 * - Otherwise stop, the boundary is here before the first letter. */
                                if (row > 0 &&
                                    (rowdata = find_row_data(row - 1)) != nullptr &&
                                    rowdata->attr.soft_wrapped &&
                                    (len = _bte_row_data_nonempty_length(rowdata)) > 0 &&
                                    is_same_class(len - 1, row - 1, 0, row) /* invalidates rowdata! */) {
                                        if (!after) {
                                                col = len - 1;
                                                row--;
                                        } else {
                                                col = 0;
                                        }
                                        /* go on with expanding */
                                } else {
                                        col = 0;  /* end-exclusive */
                                        break;  /* done, don't expand any more */
                                }
                        } else if (col >= (rowdata ? _bte_row_data_nonempty_length(rowdata) : 0)) {
                                /* Clicked over the right margin, or right unused area.
                                 * - If within a word (that is, the last letter in this row, and the first
                                 *   letter of the next row belong to the same word) then select the letter
                                 *   according to the direction and continue expanding.
                                 * - Otherwise, if the row is soft-wrapped and we're over the unused area
                                 *   (which can happen if a CJK wrapped) or over the right margin, then
                                 *   stop, the boundary is wrapped to the beginning of the next row.
                                 * - Otherwise select the newline only and stop. */
                                if (rowdata != nullptr &&
                                    rowdata->attr.soft_wrapped) {
                                        if ((len = _bte_row_data_nonempty_length(rowdata)) > 0 &&
                                            is_same_class(len - 1, row, 0, row + 1) /* invalidates rowdata! */) {
                                                if (!after) {
                                                        col = len - 1;
                                                } else {
                                                        col = 0;
                                                        row++;
                                                }
                                                /* go on with expanding */
                                        } else {
                                                col = 0;  /* end-exclusive */
                                                row++;
                                                break;  /* done, don't expand any more */
                                        }
                                } else {
                                        if (!after) {
                                                col = rowdata ? _bte_row_data_nonempty_length(rowdata) : 0;  /* end-exclusive */
                                        } else {
                                                col = 0;  /* end-exclusive */
                                                row++;
                                        }
                                        break;  /* done, don't expand any more */
                                }
                        }

                        /* Expand in the given direction. */
                        if (!after) {
                                /* Keep selecting to the left (and then up) as long as the next character
                                 * we look at is of the same class as the current start point. */
                                while (true) {
                                        /* Back up within the row. */
                                        for (; col > 0; col--) {
                                                if (!is_same_class(col - 1, row, col, row)) {
                                                        break;
                                                }
                                        }
                                        if (col > 0) {
                                                /* We hit a stopping point, so stop. */
                                                break;
                                        }
                                        if (row == 0) {
                                                /* At the very beginning. */
                                                break;
                                        }
                                        rowdata = find_row_data(row - 1);
                                        if (!rowdata || !rowdata->attr.soft_wrapped) {
                                                /* Reached a hard newline. */
                                                break;
                                        }
                                        len = _bte_row_data_nonempty_length(rowdata);
                                        /* len might be smaller than m_column_count if a CJK wrapped */
                                        if (!is_same_class(len - 1, row - 1, col, row) /* invalidates rowdata! */) {
                                                break;
                                        }
                                        /* Move on to the previous line. */
                                        col = len - 1;
                                        row--;
                                }
                        } else {
                                /* Keep selecting to the right (and then down) as long as the next character
                                 * we look at is of the same class as the current end point. */
                                while (true) {
                                        rowdata = find_row_data(row);
                                        if (!rowdata) {
                                                break;
                                        }
                                        len = _bte_row_data_nonempty_length(rowdata);
                                        bool soft_wrapped = rowdata->attr.soft_wrapped;
                                        /* Move forward within the row. */
                                        for (; col < len - 1; col++) {
                                                if (!is_same_class(col, row, col + 1, row) /* invalidates rowdata! */) {
                                                        break;
                                                }
                                        }
                                        if (col < len - 1) {
                                                /* We hit a stopping point, so stop. */
                                                break;
                                        }
                                        if (!soft_wrapped) {
                                                /* Reached a hard newline. */
                                                break;
                                        }
                                        if (!is_same_class(col, row, 0, row + 1)) {
                                                break;
                                        }
                                        /* Move on to the next line. */
                                        col = 0;
                                        row++;
                                }
                                col++;  /* col points to an actual cell, we need end-exclusive instead. */
                        }
                        break;

                case SelectionType::eLINE:
                        if (!after) {
                                /* Back up as far as we can go. */
                                while (row > 0 &&
                                       _bte_ring_contains (m_screen->row_data, row - 1) &&
                                       m_screen->row_data->is_soft_wrapped(row - 1)) {
                                        row--;
                                }
                        } else {
                                /* Move forward as far as we can go. */
                                while (_bte_ring_contains (m_screen->row_data, row) &&
                                       m_screen->row_data->is_soft_wrapped(row)) {
                                        row++;
                                }
                                row++;  /* One more row, since the column is 0. */
                        }
                        col = 0;
                        break;
                }
        }

        return { row, col };
}

/*
 * Creates the selection's span from the origin and last coordinates.
 *
 * The origin and last points might be in reverse order; in block mode they might even point to the
 * two other corners of the rectangle than the ones we're interested in.
 * The resolved span will contain the endpoints in the proper order.
 *
 * In word & line (paragraph) modes it extends the selection accordingly.
 *
 * Also makes sure to invalidate the regions that changed, and update m_selecting_had_delta.
 *
 * FIXMEegmont it always resolves both endpoints. With a bit of extra bookkeeping it could usually
 * just resolve the moving one.
 */
void
Terminal::resolve_selection()
{
        if (m_selection_origin.row() < 0 || m_selection_last.row() < 0) {
                invalidate (m_selection_resolved);
                m_selection_resolved.clear();
                _bte_debug_print(BTE_DEBUG_SELECTION, "Selection resolved to %s.\n", m_selection_resolved.to_string());
                return;
        }

        auto m_selection_resolved_old = m_selection_resolved;

        if (m_selection_block_mode) {
                auto top    = std::min (m_selection_origin.row(), m_selection_last.row());
                auto bottom = std::max (m_selection_origin.row(), m_selection_last.row());
                auto left   = std::min (m_selection_origin.halfcolumn(), m_selection_last.halfcolumn());
                auto right  = std::max (m_selection_origin.halfcolumn(), m_selection_last.halfcolumn());

                auto topleft     = resolve_selection_endpoint ({ top,    left  }, false);
                auto bottomright = resolve_selection_endpoint ({ bottom, right }, true);

                if (topleft.column() == bottomright.column()) {
                        m_selection_resolved.clear();
                } else {
                        m_selection_resolved.set (topleft, bottomright);
                }
        } else {
                auto start = std::min (m_selection_origin, m_selection_last);
                auto end   = std::max (m_selection_origin, m_selection_last);

                m_selection_resolved.set (resolve_selection_endpoint (start, false),
                                          resolve_selection_endpoint (end,   true));
        }

        if (!m_selection_resolved.empty())
                m_selecting_had_delta = true;

        _bte_debug_print(BTE_DEBUG_SELECTION, "Selection resolved to %s.\n", m_selection_resolved.to_string());

        invalidate_symmetrical_difference (m_selection_resolved_old, m_selection_resolved, m_selection_block_mode);
}

void
Terminal::modify_selection (bte::view::coords const& pos)
{
        g_assert (m_selecting);

        /* Need to ensure the ringview is updated. */
        ringview_update();

        auto current = selection_grid_halfcoords_from_view_coords (pos);

        if (current == m_selection_last)
                return;

        _bte_debug_print(BTE_DEBUG_SELECTION,
                         "Selection dragged to %s.\n",
                         current.to_string());

        m_selection_last = current;
        resolve_selection();
}

/* Check if a cell is selected or not. BiDi: the coordinate is logical. */
bool
Terminal::cell_is_selected_log(bte::grid::column_t lcol,
                               bte::grid::row_t row) const
{
        /* Our caller had to update the ringview (we can't do because we're const). */
        g_assert(m_ringview.is_updated());

        if (m_selection_block_mode) {
                /* In block mode, make sure CJKs and TABs aren't cut in half. */
                while (lcol > 0) {
                        BteCell const* cell = find_charcell(lcol, row);
                        if (!cell || !cell->attr.fragment())
                                break;
                        lcol--;
                }
                /* Convert to visual. */
                bte::base::BidiRow const* bidirow = m_ringview.get_bidirow(row);
                bte::grid::column_t vcol = bidirow->log2vis(lcol);
                return m_selection_resolved.box_contains ({ row, vcol });
        } else {
                /* In normal modes, resolve_selection() made sure to generate such boundaries for m_selection_resolved. */
                return m_selection_resolved.contains ({ row, lcol });
        }
}

/* Check if a cell is selected or not. BiDi: the coordinate is visual. */
bool
Terminal::cell_is_selected_vis(bte::grid::column_t vcol,
                               bte::grid::row_t row) const
{
        /* Our caller had to update the ringview (we can't do because we're const). */
        g_assert(m_ringview.is_updated());

        /* Convert to logical column. */
        bte::base::BidiRow const* bidirow = m_ringview.get_bidirow(row);
        bte::grid::column_t lcol = bidirow->vis2log(vcol);

        return cell_is_selected_log(lcol, row);
}

void
Terminal::widget_paste_received(char const* text)
{
	gchar *paste, *p;
        gsize run;
        unsigned char c;

	if (text == nullptr)
                return;

        gsize len = strlen(text);
        _bte_debug_print(BTE_DEBUG_SELECTION,
                         "Pasting %" G_GSIZE_FORMAT " UTF-8 bytes.\n", len);
        // FIXMEchpe this cannot happen ever
        if (!g_utf8_validate(text, len, NULL)) {
                g_warning("Paste not valid UTF-8, dropping.");
                return;
        }

        /* Convert newlines to carriage returns, which more software
         * is able to cope with (cough, pico, cough).
         * Filter out control chars except HT, CR (even stricter than xterm).
         * Also filter out C1 controls: U+0080 (0xC2 0x80) - U+009F (0xC2 0x9F). */
        p = paste = (gchar *) g_malloc(len + 1);
        while (p != nullptr && text[0] != '\0') {
                run = strcspn(text, "\x01\x02\x03\x04\x05\x06\x07"
                              "\x08\x0A\x0B\x0C\x0E\x0F"
                              "\x10\x11\x12\x13\x14\x15\x16\x17"
                              "\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"
                              "\x7F\xC2");
                memcpy(p, text, run);
                p += run;
                text += run;
                switch (text[0]) {
                case '\x00':
                        break;
                case '\x0A':
                        *p = '\x0D';
                        p++;
                        text++;
                        break;
                case '\xC2':
                        c = text[1];
                        if (c >= 0x80 && c <= 0x9F) {
                                /* Skip both bytes of a C1 */
                                text += 2;
                        } else {
                                /* Move along, nothing to see here */
                                *p = '\xC2';
                                p++;
                                text++;
                        }
                        break;
                default:
                        /* Swallow this byte */
                        text++;
                        break;
                }
        }

        bool const bracketed_paste = m_modes_private.XTERM_READLINE_BRACKETED_PASTE();
        // FIXMEchpe can we not hardcode C0 controls here?
        if (bracketed_paste)
                feed_child("\e[200~"sv);
        // FIXMEchpe add a way to avoid the extra string copy done here
        feed_child(paste, p - paste);
        if (bracketed_paste)
                feed_child("\e[201~"sv);
        g_free(paste);
}

bool
Terminal::feed_mouse_event(bte::grid::coords const& rowcol /* confined */,
                                     int button,
                                     bool is_drag,
                                     bool is_release)
{
	unsigned char cb = 0;

        /* Don't send events on scrollback contents: bug 755187. */
        if (grid_coords_in_scrollback(rowcol))
                return false;

	/* Make coordinates 1-based. */
	auto cx = rowcol.column() + 1;
	auto cy = rowcol.row() - m_screen->insert_delta + 1;

	/* Encode the button information in cb. */
	switch (button) {
        case 0:                 /* No button, just dragging. */
                cb = 3;
                break;
	case 1:			/* Left. */
		cb = 0;
		break;
	case 2:			/* Middle. */
		cb = 1;
		break;
	case 3:			/* Right. */
		cb = 2;
		break;
	case 4:
		cb = 64;	/* Scroll up. */
		break;
	case 5:
		cb = 65;	/* Scroll down. */
		break;
	}

	/* With the exception of the 1006 mode, button release is also encoded here. */
	/* Note that if multiple extensions are enabled, the 1006 is used, so it's okay to check for only that. */
	if (is_release && !m_modes_private.XTERM_MOUSE_EXT_SGR()) {
		cb = 3;
	}

	/* Encode the modifiers. */
        if (m_mouse_tracking_mode >= MouseTrackingMode::eSEND_XY_ON_BUTTON) {
                if (m_modifiers & CDK_SHIFT_MASK) {
                        cb |= 4;
                }
                if (m_modifiers & BTE_ALT_MASK) {
                        cb |= 8;
                }
                if (m_modifiers & CDK_CONTROL_MASK) {
                        cb |= 16;
                }
        }

	/* Encode a drag event. */
	if (is_drag) {
		cb |= 32;
	}

	/* Check the extensions in decreasing order of preference. Encoding the release event above assumes that 1006 comes first. */
	if (m_modes_private.XTERM_MOUSE_EXT_SGR()) {
		/* xterm's extended mode (1006) */
                send(is_release ? BTE_REPLY_XTERM_MOUSE_EXT_SGR_REPORT_BUTTON_RELEASE
                                : BTE_REPLY_XTERM_MOUSE_EXT_SGR_REPORT_BUTTON_PRESS,
                     {cb, (int)cx, (int)cy});
	} else if (cx <= 223 && cy <= 223) {
		/* legacy mode */
                char buf[8];
                size_t len = g_snprintf(buf, sizeof(buf), _BTE_CAP_CSI "M%c%c%c", 32 + cb, 32 + (guchar)cx, 32 + (guchar)cy);

                /* Send event direct to the child, this is binary not text data */
                feed_child_binary({buf, len});
	}

        return true;
}

void
Terminal::feed_focus_event(bool in)
{
        send(in ? BTE_REPLY_XTERM_FOCUS_IN : BTE_REPLY_XTERM_FOCUS_OUT, {});
}

void
Terminal::feed_focus_event_initial()
{
        /* We immediately send the terminal a focus event, since otherwise
         * it has no way to know the current status.
         */
        feed_focus_event(m_has_focus);
}

void
Terminal::maybe_feed_focus_event(bool in)
{
        if (m_modes_private.XTERM_FOCUS())
                feed_focus_event(in);
}

/*
 * Terminal::maybe_send_mouse_button:
 * @terminal:
 * @event:
 *
 * Sends a mouse button click or release notification to the application,
 * if the terminal is in mouse tracking mode.
 *
 * Returns: %TRUE iff the event was consumed
 */
bool
Terminal::maybe_send_mouse_button(bte::grid::coords const& unconfined_rowcol,
                                  MouseEvent const& event)
{
	switch (event.type()) {
        case EventBase::Type::eMOUSE_PRESS:
		if (m_mouse_tracking_mode < MouseTrackingMode::eSEND_XY_ON_CLICK) {
			return false;
		}
		break;
        case EventBase::Type::eMOUSE_RELEASE:
		if (m_mouse_tracking_mode < MouseTrackingMode::eSEND_XY_ON_BUTTON) {
			return false;
		}
		break;
        case EventBase::Type::eMOUSE_DOUBLE_PRESS:
        case EventBase::Type::eMOUSE_TRIPLE_PRESS:
	default:
		return false;
	}

        auto rowcol = confine_grid_coords(unconfined_rowcol);
        return feed_mouse_event(rowcol,
                                event.button_value(),
                                false /* not drag */,
                                event.is_mouse_release());
}

/*
 * Terminal::maybe_send_mouse_drag:
 * @terminal:
 * @event:
 *
 * Sends a mouse motion notification to the application,
 * if the terminal is in mouse tracking mode.
 *
 * Returns: %TRUE iff the event was consumed
 */
bool
Terminal::maybe_send_mouse_drag(bte::grid::coords const& unconfined_rowcol,
                                MouseEvent const& event)
{
        /* Need to ensure the ringview is updated. */
        ringview_update();

        auto rowcol = confine_grid_coords(unconfined_rowcol);

	/* First determine if we even want to send notification. */
        switch (event.type()) {
        case EventBase::Type::eMOUSE_MOTION:
		if (m_mouse_tracking_mode < MouseTrackingMode::eCELL_MOTION_TRACKING)
			return false;

		if (m_mouse_tracking_mode < MouseTrackingMode::eALL_MOTION_TRACKING) {

                        if (m_mouse_pressed_buttons == 0) {
				return false;
			}
			/* The xterm doc is not clear as to whether
			 * all-tracking also sends degenerate same-cell events;
                         * we don't.
                         */
                        if (rowcol == confined_grid_coords_from_view_coords(m_mouse_last_position))
				return false;
		}
		break;
	default:
		return false;
	}

        /* As per xterm, report the leftmost pressed button - if any. */
        int button;
        if (m_mouse_pressed_buttons & 1)
                button = 1;
        else if (m_mouse_pressed_buttons & 2)
                button = 2;
        else if (m_mouse_pressed_buttons & 4)
                button = 3;
        else
                button = 0;

        return feed_mouse_event(rowcol,
                                button,
                                true /* drag */,
                                false /* not release */);
}

/*
 * Terminal::hyperlink_invalidate_and_get_bbox
 *
 * Invalidates cells belonging to the non-zero hyperlink idx, in order to
 * stop highlighting the previously hovered hyperlink or start highlighting
 * the new one. Optionally stores the coordinates of the bounding box.
 */
void
Terminal::hyperlink_invalidate_and_get_bbox(bte::base::Ring::hyperlink_idx_t idx,
                                                      CdkRectangle *bbox)
{
        auto first_row = first_displayed_row();
        auto end_row = last_displayed_row() + 1;
        bte::grid::row_t row, top = LONG_MAX, bottom = -1;
        bte::grid::column_t col, left = LONG_MAX, right = -1;
        const BteRowData *rowdata;

        g_assert (idx != 0);

        for (row = first_row; row < end_row; row++) {
                rowdata = _bte_ring_index(m_screen->row_data, row);
                if (rowdata != NULL) {
                        bool do_invalidate_row = false;
                        for (col = 0; col < rowdata->len; col++) {
                                if (G_UNLIKELY (rowdata->cells[col].attr.hyperlink_idx == idx)) {
                                        do_invalidate_row = true;
                                        top = MIN(top, row);
                                        bottom = MAX(bottom, row);
                                        left = MIN(left, col);
                                        right = MAX(right, col);
                                }
                        }
                        if (G_UNLIKELY (do_invalidate_row)) {
                                invalidate_row(row);
                        }
                }
        }

        if (bbox == NULL)
                return;

        /* If bbox != NULL, we're looking for the new hovered hyperlink which always has onscreen bits. */
        g_assert (top != LONG_MAX && bottom != -1 && left != LONG_MAX && right != -1);

        auto allocation = get_allocated_rect();
        bbox->x = allocation.x + m_padding.left + left * m_cell_width;
        bbox->y = allocation.y + m_padding.top + row_to_pixel(top);
        bbox->width = (right - left + 1) * m_cell_width;
        bbox->height = (bottom - top + 1) * m_cell_height;
        _bte_debug_print (BTE_DEBUG_HYPERLINK,
                          "Hyperlink bounding box: x=%d y=%d w=%d h=%d\n",
                          bbox->x, bbox->y, bbox->width, bbox->height);
}

/*
 * Terminal::hyperlink_hilite_update:
 *
 * Checks the coordinates for hyperlink. Updates m_hyperlink_hover_idx
 * and m_hyperlink_hover_uri, and schedules to update the highlighting.
 */
void
Terminal::hyperlink_hilite_update()
{
        const BteRowData *rowdata;
        bool do_check_hilite;
        bte::grid::coords rowcol;
        bte::base::Ring::hyperlink_idx_t new_hyperlink_hover_idx = 0;
        CdkRectangle bbox;
        const char *separator;

        if (!m_allow_hyperlink)
                return;

        _bte_debug_print (BTE_DEBUG_HYPERLINK,
                         "hyperlink_hilite_update\n");

        /* Need to ensure the ringview is updated. */
        ringview_update();

        /* m_mouse_last_position contains the current position, see bug 789536 comment 24. */
        auto pos = m_mouse_last_position;

        /* Whether there's any chance we'd highlight something */
        do_check_hilite = view_coords_visible(pos) &&
                          m_mouse_cursor_over_widget &&
                          !(m_mouse_autohide && m_mouse_cursor_autohidden) &&
                          !m_selecting;
        if (do_check_hilite) {
                rowcol = grid_coords_from_view_coords(pos);
                rowdata = find_row_data(rowcol.row());
                if (rowdata && rowcol.column() < rowdata->len) {
                        new_hyperlink_hover_idx = rowdata->cells[rowcol.column()].attr.hyperlink_idx;
                }
        }

        if (new_hyperlink_hover_idx == m_hyperlink_hover_idx) {
                _bte_debug_print (BTE_DEBUG_HYPERLINK,
                                  "hyperlink did not change\n");
                return;
        }

        /* Invalidate cells of the old hyperlink. */
        if (m_hyperlink_hover_idx != 0) {
                hyperlink_invalidate_and_get_bbox(m_hyperlink_hover_idx, NULL);
        }

        /* This might be different from new_hyperlink_hover_idx. If in the stream, that one contains
         * the pseudo idx BTE_HYPERLINK_IDX_TARGET_IN_STREAM and now a real idx is allocated.
         * Plus, the ring's internal belief of the hovered hyperlink is also updated. */
        if (do_check_hilite) {
                m_hyperlink_hover_idx = _bte_ring_get_hyperlink_at_position(m_screen->row_data, rowcol.row(), rowcol.column(), true, &m_hyperlink_hover_uri);
        } else {
                m_hyperlink_hover_idx = 0;
                m_hyperlink_hover_uri = nullptr;
        }

        /* Invalidate cells of the new hyperlink. Get the bounding box. */
        if (m_hyperlink_hover_idx != 0) {
                /* URI is after the first semicolon */
                separator = strchr(m_hyperlink_hover_uri, ';');
                g_assert(separator != NULL);
                m_hyperlink_hover_uri = separator + 1;

                hyperlink_invalidate_and_get_bbox(m_hyperlink_hover_idx, &bbox);
                g_assert(bbox.width > 0 && bbox.height > 0);
        }
        _bte_debug_print(BTE_DEBUG_HYPERLINK,
                         "Hover idx: %d \"%s\"\n",
                         m_hyperlink_hover_idx,
                         m_hyperlink_hover_uri);

        /* Underlining hyperlinks has precedence over regex matches. So when the hovered hyperlink changes,
         * the regex match might need to become or stop being underlined. */
        if (regex_match_has_current())
                invalidate_match_span();

        apply_mouse_cursor();

        emit_hyperlink_hover_uri_changed(m_hyperlink_hover_idx != 0 ? &bbox : NULL);
}

/*
 * Terminal::match_hilite_clear:
 *
 * Reset match variables and invalidate the old match region if highlighted.
 */
void
Terminal::match_hilite_clear()
{
        if (regex_match_has_current())
                invalidate_match_span();

        m_match_span.clear();
        m_match_current = nullptr;

        g_free(m_match);
        m_match = nullptr;
}

/* This is only used by the dingu matching code, so no need to extend the area. */
void
Terminal::invalidate_match_span()
{
        _bte_debug_print(BTE_DEBUG_EVENTS,
                         "Invalidating match span %s\n", m_match_span.to_string());
        invalidate(m_match_span);
}

/*
 * Terminal::match_hilite_update:
 *
 * Checks the coordinates for dingu matches, setting m_match_span to
 * the match region or the no-matches region, and if there is a match,
 * sets it to display highlighted.
 */
void
Terminal::match_hilite_update()
{
        /* Need to ensure the ringview is updated. */
        ringview_update();

        /* m_mouse_last_position contains the current position, see bug 789536 comment 24. */
        auto pos = m_mouse_last_position;

        glong col = pos.x / m_cell_width;
        glong row = pixel_to_row(pos.y);

        /* BiDi: convert to logical column. */
        bte::base::BidiRow const* bidirow = m_ringview.get_bidirow(confine_grid_row(row));
        col = bidirow->vis2log(col);

	_bte_debug_print(BTE_DEBUG_EVENTS,
                         "Match hilite update (%ld, %ld) -> %ld, %ld\n",
                         pos.x, pos.y, col, row);

        /* Whether there's any chance we'd highlight something */
        bool do_check_hilite = view_coords_visible(pos) &&
                               m_mouse_cursor_over_widget &&
                               !(m_mouse_autohide && m_mouse_cursor_autohidden) &&
                               !m_selecting;
        if (!do_check_hilite) {
                if (regex_match_has_current())
                         match_hilite_clear();
                return;
        }

        if (m_match_span.contains(row, col)) {
                /* Already highlighted. */
                return;
        }

        /* Reset match variables and invalidate the old match region if highlighted */
        match_hilite_clear();

        /* Check for matches. */
	gsize start, end;
        auto new_match = match_check_internal(col,
                                              row,
                                              &m_match_current,
                                              &start,
                                              &end);

	/* Read the new locations. */
	if (start < m_match_attributes->len &&
            end < m_match_attributes->len) {
                struct _BteCharAttributes const *sa, *ea;
		sa = &g_array_index(m_match_attributes,
                                   struct _BteCharAttributes,
                                   start);
                ea = &g_array_index(m_match_attributes,
                                    struct _BteCharAttributes,
                                    end);

                /* convert from inclusive to exclusive (a.k.a. boundary) ending, taking a possible last CJK character into account */
                m_match_span = bte::grid::span(sa->row, sa->column, ea->row, ea->column + ea->columns);
	}

        g_assert(!m_match); /* from match_hilite_clear() above */
	m_match = new_match;

	if (m_match) {
		_bte_debug_print(BTE_DEBUG_EVENTS,
				"Matched %s.\n", m_match_span.to_string());
                invalidate_match_span();
        } else {
		_bte_debug_print(BTE_DEBUG_EVENTS,
                                 "No matches %s.\n", m_match_span.to_string());
	}

        apply_mouse_cursor();
}

/* Note that the clipboard has cleared. */
static void
clipboard_clear_cb(CtkClipboard *clipboard,
                   gpointer user_data)
{
	auto that = reinterpret_cast<bte::terminal::Terminal*>(user_data);
        that->widget_clipboard_cleared(clipboard);
}

void
Terminal::widget_clipboard_cleared(CtkClipboard *clipboard_)
{
        if (m_changing_selection)
                return;

	if (clipboard_ == m_clipboard[BTE_SELECTION_PRIMARY]) {
		if (m_selection_owned[BTE_SELECTION_PRIMARY] &&
                    !m_selection_resolved.empty()) {
			_bte_debug_print(BTE_DEBUG_SELECTION, "Lost selection.\n");
			deselect_all();
		}
                m_selection_owned[BTE_SELECTION_PRIMARY] = false;
	} else if (clipboard_ == m_clipboard[BTE_SELECTION_CLIPBOARD]) {
                m_selection_owned[BTE_SELECTION_CLIPBOARD] = false;
        }
}

/* Supply the selected text to the clipboard. */
static void
clipboard_copy_cb(CtkClipboard *clipboard,
                  CtkSelectionData *data,
                  guint info,
                  gpointer user_data)
{
	auto that = reinterpret_cast<bte::terminal::Terminal*>(user_data);
        that->widget_clipboard_requested(clipboard, data, info);
}

static char*
text_to_utf16_mozilla(GString* text,
                      gsize* len_ptr)
{
        /* Use g_convert() instead of g_utf8_to_utf16() since the former
         * adds a BOM which Mozilla requires for text/html format.
         */
        return g_convert(text->str, text->len,
                         "UTF-16", /* conver to UTF-16 */
                         "UTF-8", /* convert from UTF-8 */
                         nullptr /* out bytes_read */,
                         len_ptr,
                         nullptr);
}

void
Terminal::widget_clipboard_requested(CtkClipboard *target_clipboard,
                                               CtkSelectionData *data,
                                               guint info)
{
	for (auto sel = 0; sel < LAST_BTE_SELECTION; sel++) {
		if (target_clipboard == m_clipboard[sel] &&
                    m_selection[sel] != nullptr) {
			_BTE_DEBUG_IF(BTE_DEBUG_SELECTION) {
				int i;
				g_printerr("Setting selection %d (%" G_GSIZE_FORMAT " UTF-8 bytes.) for target %s\n",
                                           sel,
                                           m_selection[sel]->len,
                                           cdk_atom_name(ctk_selection_data_get_target(data)));
                                char const* selection_text = m_selection[sel]->str;
                                for (i = 0; selection_text[i] != '\0'; i++) {
                                        g_printerr("0x%04x ", selection_text[i]);
                                        if ((i & 0x7) == 0x7)
                                                g_printerr("\n");
				}
                                g_printerr("\n");
			}
			if (info == BTE_TARGET_TEXT) {
				ctk_selection_data_set_text(data,
                                                            m_selection[sel]->str,
                                                            m_selection[sel]->len);
			} else if (info == BTE_TARGET_HTML) {
				gsize len;
                                auto selection = text_to_utf16_mozilla(m_selection[sel], &len);
                                // FIXMEchpe this makes yet another copy of the data... :(
                                if (selection)
                                        ctk_selection_data_set(data,
                                                               cdk_atom_intern_static_string("text/html"),
                                                               16,
                                                               (const guchar *)selection,
                                                               len);
				g_free(selection);
			} else {
                                /* Not reached */
                        }
		}
	}
}

/* Convert the internal color code (either index or RGB) into RGB. */
template <unsigned int redbits,
          unsigned int greenbits,
          unsigned int bluebits>
void
Terminal::rgb_from_index(guint index,
                                   bte::color::rgb& color) const
{
        bool dim = false;
        if (!(index & BTE_RGB_COLOR_MASK(redbits, greenbits, bluebits)) && (index & BTE_DIM_COLOR)) {
                index &= ~BTE_DIM_COLOR;
                dim = true;
        }

	if (index >= BTE_LEGACY_COLORS_OFFSET && index < BTE_LEGACY_COLORS_OFFSET + BTE_LEGACY_FULL_COLOR_SET_SIZE)
		index -= BTE_LEGACY_COLORS_OFFSET;
	if (index < BTE_PALETTE_SIZE) {
                color = *get_color(index);
                if (dim) {
                        /* magic formula taken from xterm */
                        color.red = color.red * 2 / 3;
                        color.green = color.green * 2 / 3;
                        color.blue = color.blue * 2 / 3;
                }
	} else if (index & BTE_RGB_COLOR_MASK(redbits, greenbits, bluebits)) {
                color.red   = BTE_RGB_COLOR_GET_COMPONENT(index, greenbits + bluebits, redbits) * 0x101U;
                color.green = BTE_RGB_COLOR_GET_COMPONENT(index, bluebits, greenbits) * 0x101U;
                color.blue  = BTE_RGB_COLOR_GET_COMPONENT(index, 0, bluebits) * 0x101U;
	} else {
		g_assert_not_reached();
	}
}

GString*
Terminal::get_text(bte::grid::row_t start_row,
                             bte::grid::column_t start_col,
                             bte::grid::row_t end_row,
                             bte::grid::column_t end_col,
                             bool block,
                             bool wrap,
                             GArray *attributes)
{
	const BteCell *pcell = NULL;
	GString *string;
	struct _BteCharAttributes attr;
	bte::color::rgb fore, back;
        std::unique_ptr<bte::base::RingView> ringview;
        bte::base::BidiRow const *bidirow = nullptr;
        bte::grid::column_t vcol;

	if (attributes)
		g_array_set_size (attributes, 0);

	string = g_string_new(NULL);
	memset(&attr, 0, sizeof(attr));

        if (start_col < 0)
                start_col = 0;

        if (m_enable_bidi && block) {
                /* Rectangular selection operates on the visual contents, not the logical.
                 * m_ringview corresponds to the currently onscreen bits, therefore does not
                 * necessarily include the entire selection. Also we want m_ringview's size
                 * to be limited, even if the user selects a giant rectangle.
                 * So use a new ringview for the selection. */
                ringview = std::make_unique<bte::base::RingView>();
                ringview->set_ring(m_screen->row_data);
                ringview->set_rows(start_row, end_row - start_row + 1);
                ringview->set_width(m_column_count);
                ringview->update();
        }

        bte::grid::column_t lcol = block ? 0 : start_col;
        bte::grid::row_t row;
        for (row = start_row; row < end_row + 1; row++, lcol = 0) {
		BteRowData const* row_data = find_row_data(row);
                gsize last_empty, last_nonempty;
                bte::grid::column_t last_emptycol, last_nonemptycol;
                bte::grid::column_t line_last_column = (!block && row == end_row) ? end_col : m_column_count;

                last_empty = last_nonempty = string->len;
                last_emptycol = last_nonemptycol = -1;

		attr.row = row;
                attr.column = lcol;
		pcell = NULL;
		if (row_data != NULL) {
                        bidirow = ringview ? ringview->get_bidirow(row) : nullptr;
                        while (lcol < line_last_column &&
                               (pcell = _bte_row_data_get (row_data, lcol))) {

                                /* In block mode, we scan each row from its very beginning to its very end in logical order,
                                 * and here filter out the characters that are visually outside of the block. */
                                if (bidirow) {
                                        vcol = bidirow->log2vis(lcol);
                                        if (vcol < start_col || vcol >= end_col) {
                                                lcol++;
                                                continue;
                                        }
                                }

                                attr.column = lcol;

				/* If it's not part of a multi-column character,
				 * and passes the selection criterion, add it to
				 * the selection. */
				if (!pcell->attr.fragment()) {
					/* Store the attributes of this character. */
                                        // FIXMEchpe shouldn't this use determine_colors?
                                        uint32_t fg, bg, dc;
                                        bte_color_triple_get(pcell->attr.colors(), &fg, &bg, &dc);
                                        rgb_from_index<8, 8, 8>(fg, fore);
                                        rgb_from_index<8, 8, 8>(bg, back);
					attr.fore.red = fore.red;
					attr.fore.green = fore.green;
					attr.fore.blue = fore.blue;
					attr.back.red = back.red;
					attr.back.green = back.green;
					attr.back.blue = back.blue;
					attr.underline = (pcell->attr.underline() == 1);
					attr.strikethrough = pcell->attr.strikethrough();
                                        attr.columns = pcell->attr.columns();

					/* Store the cell string */
					if (pcell->c == 0) {
                                                /* Empty cells of nondefault background color are
                                                 * stored as NUL characters. Treat them as spaces,
                                                 * but make a note of the last occurrence. */
						g_string_append_c (string, ' ');
                                                last_empty = string->len;
                                                last_emptycol = lcol;
					} else {
						_bte_unistr_append_to_string (pcell->c, string);
                                                last_nonempty = string->len;
                                                last_nonemptycol = lcol;
					}

					/* If we added text to the string, record its
					 * attributes, one per byte. */
					if (attributes) {
						bte_g_array_fill(attributes,
								&attr, string->len);
					}
				}

                                lcol++;
			}
		}

                /* Empty cells of nondefault background color can appear anywhere in a line,
                 * not just at the end, e.g. between "foo" and "bar" here:
                 *   echo -e '\e[46mfoo\e[K\e[7Gbar\e[m'
                 * Strip off the trailing ones, preserve the middle ones. */
                if (last_empty > last_nonempty) {

                        lcol = last_emptycol + 1;

                        if (row_data != NULL) {
                                while ((pcell = _bte_row_data_get (row_data, lcol))) {
                                        lcol++;

                                        if (pcell->attr.fragment())
                                                continue;

                                        if (pcell->c != 0)
                                                break;
                                }
                        }
                        if (pcell == NULL) {
                                g_string_truncate(string, last_nonempty);
                                if (attributes)
                                        g_array_set_size(attributes, string->len);
                                attr.column = last_nonemptycol;
                        }
                }

		/* Adjust column, in case we want to append a newline */
                //FIXMEchpe MIN ?
		attr.column = MAX(m_column_count, attr.column + 1);

		/* Add a newline in block mode. */
		if (block) {
			string = g_string_append_c(string, '\n');
		}
		/* Else, if the last visible column on this line was in range and
		 * not soft-wrapped, append a newline. */
		else if (row < end_row) {
			/* If we didn't softwrap, add a newline. */
			/* XXX need to clear row->soft_wrap on deletion! */
                        if (!m_screen->row_data->is_soft_wrapped(row)) {
				string = g_string_append_c(string, '\n');
			}
		}

		/* Make sure that the attributes array is as long as the string. */
		if (attributes) {
			bte_g_array_fill (attributes, &attr, string->len);
		}
	}

	/* Sanity check. */
        if (attributes != nullptr)
                g_assert_cmpuint(string->len, ==, attributes->len);

        return string;
}

GString*
Terminal::get_text_displayed(bool wrap,
                                       GArray *attributes)
{
        return get_text(first_displayed_row(), 0,
                        last_displayed_row() + 1, 0,
                        false /* block */, wrap,
                        attributes);
}

/* This is distinct from just using first/last_displayed_row since a11y
 * doesn't know about sub-row displays.
 */
GString*
Terminal::get_text_displayed_a11y(bool wrap,
                                            GArray *attributes)
{
        return get_text(m_screen->scroll_delta, 0,
                        m_screen->scroll_delta + m_row_count - 1 + 1, 0,
                        false /* block */, wrap,
                        attributes);
}

GString*
Terminal::get_selected_text(GArray *attributes)
{
        return get_text(m_selection_resolved.start_row(),
                        m_selection_resolved.start_column(),
                        m_selection_resolved.end_row(),
                        m_selection_resolved.end_column(),
                        m_selection_block_mode,
                        true /* wrap */,
                        attributes);
}

#ifdef BTE_DEBUG
unsigned int
Terminal::checksum_area(bte::grid::row_t start_row,
                                  bte::grid::column_t start_col,
                                  bte::grid::row_t end_row,
                                  bte::grid::column_t end_col)
{
        unsigned int checksum = 0;

        auto text = get_text(start_row, start_col, end_row, end_col,
                             true /* block */, false /* wrap */,
                             nullptr /* not interested in attributes */);
        if (text == nullptr)
                return checksum;

        char const* end = (char const*)text->str + text->len;
        for (char const *p = text->str; p < end; p = g_utf8_next_char(p)) {
                auto const c = g_utf8_get_char(p);
                if (c == '\n')
                        continue;
                checksum += c;
        }
        g_string_free(text, true);

        return checksum & 0xffff;
}
#endif /* BTE_DEBUG */

/*
 * Compares the visual attributes of a BteCellAttr for equality, but ignores
 * attributes that tend to change from character to character or are otherwise
 * strange (in particular: fragment, columns).
 */
// FIXMEchpe: make BteCellAttr a class with operator==
static bool
bte_terminal_cellattr_equal(BteCellAttr const* attr1,
                            BteCellAttr const* attr2)
{
        //FIXMEchpe why exclude DIM here?
	return (((attr1->attr ^ attr2->attr) & BTE_ATTR_ALL_MASK) == 0 &&
                attr1->colors()       == attr2->colors()   &&
                attr1->hyperlink_idx  == attr2->hyperlink_idx);
}

/*
 * Wraps a given string according to the BteCellAttr in HTML tags. Used
 * old-style HTML (and not CSS) for better compatibility with, for example,
 * evolution's mail editor component.
 */
char *
Terminal::cellattr_to_html(BteCellAttr const* attr,
                                     char const* text) const
{
	GString *string;
        guint fore, back, deco;

	string = g_string_new(text);

        determine_colors(attr, false, false, &fore, &back, &deco);

	if (attr->bold()) {
		g_string_prepend(string, "<b>");
		g_string_append(string, "</b>");
	}
	if (attr->italic()) {
		g_string_prepend(string, "<i>");
		g_string_append(string, "</i>");
	}
        /* <u> should be inside <font> so that it inherits its color by default */
        if (attr->underline() != 0) {
                static const char styles[][7] = {"", "single", "double", "wavy"};
                char *tag, *colorattr;

                if (deco != BTE_DEFAULT_FG) {
                        bte::color::rgb color;

                        rgb_from_index<4, 5, 4>(deco, color);
                        colorattr = g_strdup_printf(";text-decoration-color:#%02X%02X%02X",
                                                    color.red >> 8,
                                                    color.green >> 8,
                                                    color.blue >> 8);
                } else {
                        colorattr = g_strdup("");
                }

                tag = g_strdup_printf("<u style=\"text-decoration-style:%s%s\">",
                                      styles[attr->underline()],
                                      colorattr);
                g_string_prepend(string, tag);
                g_free(tag);
                g_free(colorattr);
                g_string_append(string, "</u>");
        }
	if (fore != BTE_DEFAULT_FG || attr->reverse()) {
		bte::color::rgb color;
                char *tag;

                rgb_from_index<8, 8, 8>(fore, color);
		tag = g_strdup_printf("<font color=\"#%02X%02X%02X\">",
                                      color.red >> 8,
                                      color.green >> 8,
                                      color.blue >> 8);
		g_string_prepend(string, tag);
		g_free(tag);
		g_string_append(string, "</font>");
	}
	if (back != BTE_DEFAULT_BG || attr->reverse()) {
		bte::color::rgb color;
                char *tag;

                rgb_from_index<8, 8, 8>(back, color);
		tag = g_strdup_printf("<span style=\"background-color:#%02X%02X%02X\">",
                                      color.red >> 8,
                                      color.green >> 8,
                                      color.blue >> 8);
		g_string_prepend(string, tag);
		g_free(tag);
		g_string_append(string, "</span>");
	}
	if (attr->strikethrough()) {
		g_string_prepend(string, "<strike>");
		g_string_append(string, "</strike>");
	}
	if (attr->overline()) {
		g_string_prepend(string, "<span style=\"text-decoration-line:overline\">");
		g_string_append(string, "</span>");
	}
	if (attr->blink()) {
		g_string_prepend(string, "<blink>");
		g_string_append(string, "</blink>");
	}
	/* reverse and invisible are not supported */

	return g_string_free(string, FALSE);
}

/*
 * Similar to find_charcell(), but takes a BteCharAttribute for
 * indexing and returns the BteCellAttr.
 */
BteCellAttr const*
Terminal::char_to_cell_attr(BteCharAttributes const* attr) const
{
	BteCell const* cell = find_charcell(attr->column, attr->row);
	if (cell)
		return &cell->attr;
	return nullptr;
}

/*
 * Terminal::attributes_to_html:
 * @text: A string as returned by the bte_terminal_get_* family of functions.
 * @attrs: (array) (element-type Bte.CharAttributes): text attributes, as created by bte_terminal_get_*
 *
 * Marks the given text up according to the given attributes, using HTML <span>
 * commands, and wraps the string in a <pre> element. The attributes have to be
 * "fresh" in the sense that the terminal must not have changed since they were
 * obtained using the bte_terminal_get* function.
 *
 * Returns: (transfer full): a newly allocated text string, or %NULL.
 */
GString*
Terminal::attributes_to_html(GString* text_string,
                                       GArray* attrs)
{
	GString *string;
	guint from,to;
	const BteCellAttr *attr;
	char *escaped, *marked;

        char const* text = text_string->str;
        auto len = text_string->len;
        g_assert_cmpuint(len, ==, attrs->len);

	/* Initial size fits perfectly if the text has no attributes and no
	 * characters that need to be escaped
         */
	string = g_string_sized_new (len + 11);

	g_string_append(string, "<pre>");
	/* Find streches with equal attributes. Newlines are treated specially,
	 * so that the <span> do not cover multiple lines.
         */
	from = to = 0;
	while (text[from] != '\0') {
		g_assert(from == to);
		if (text[from] == '\n') {
			g_string_append_c(string, '\n');
			from = ++to;
		} else {
			attr = char_to_cell_attr(
				&g_array_index(attrs, BteCharAttributes, from));
			while (text[to] != '\0' && text[to] != '\n' &&
			       bte_terminal_cellattr_equal(attr,
                                                           char_to_cell_attr(
						&g_array_index(attrs, BteCharAttributes, to))))
			{
				to++;
			}
			escaped = g_markup_escape_text(text + from, to - from);
			marked = cellattr_to_html(attr, escaped);
			g_string_append(string, marked);
			g_free(escaped);
			g_free(marked);
			from = to;
		}
	}
	g_string_append(string, "</pre>");

	return string;
}

static CtkTargetEntry*
targets_for_format(BteFormat format,
                   int *n_targets)
{
        switch (format) {
        case BTE_FORMAT_TEXT: {
                static CtkTargetEntry *text_targets = nullptr;
                static int n_text_targets;

                if (text_targets == nullptr) {
			auto list = ctk_target_list_new (nullptr, 0);
			ctk_target_list_add_text_targets (list, BTE_TARGET_TEXT);

                        text_targets = ctk_target_table_new_from_list (list, &n_text_targets);
			ctk_target_list_unref (list);
                }

                *n_targets = n_text_targets;
                return text_targets;
        }

        case BTE_FORMAT_HTML: {
                static CtkTargetEntry *html_targets = nullptr;
                static int n_html_targets;

                if (html_targets == nullptr) {
			auto list = ctk_target_list_new (nullptr, 0);
			ctk_target_list_add_text_targets (list, BTE_TARGET_TEXT);
                        ctk_target_list_add (list,
                                             cdk_atom_intern_static_string("text/html"),
                                             0,
                                             BTE_TARGET_HTML);

                        html_targets = ctk_target_table_new_from_list (list, &n_html_targets);
			ctk_target_list_unref (list);
                }

                *n_targets = n_html_targets;
                return html_targets;
        }
        default:
                g_assert_not_reached();
        }
}

/* Place the selected text onto the clipboard.  Do this asynchronously so that
 * we get notified when the selection we placed on the clipboard is replaced. */
void
Terminal::widget_copy(BteSelection sel,
                                BteFormat format)
{
        /* Only put HTML on the CLIPBOARD, not PRIMARY */
        g_assert(sel == BTE_SELECTION_CLIPBOARD || format == BTE_FORMAT_TEXT);

	/* Chuck old selected text and retrieve the newly-selected text. */
        GArray *attributes = g_array_new(FALSE, TRUE, sizeof(struct _BteCharAttributes));
        auto selection = get_selected_text(attributes);

        if (m_selection[sel]) {
                g_string_free(m_selection[sel], TRUE);
                m_selection[sel] = nullptr;
        }

        if (selection == nullptr) {
                g_array_free(attributes, TRUE);
                m_selection_owned[sel] = false;
                return;
        }

        if (format == BTE_FORMAT_HTML) {
                m_selection[sel] = attributes_to_html(selection, attributes);
                g_string_free(selection, TRUE);
        } else {
                m_selection[sel] = selection;
        }

	g_array_free (attributes, TRUE);

	/* Place the text on the clipboard. */
        _bte_debug_print(BTE_DEBUG_SELECTION,
                         "Assuming ownership of selection.\n");

        int n_targets;
        auto targets = targets_for_format(format, &n_targets);

        m_changing_selection = true;
        ctk_clipboard_set_with_data(m_clipboard[sel],
                                    targets,
                                    n_targets,
                                    clipboard_copy_cb,
                                    clipboard_clear_cb,
                                    this);
        m_changing_selection = false;

        ctk_clipboard_set_can_store(m_clipboard[sel], nullptr, 0);
        m_selection_owned[sel] = true;
        m_selection_format[sel] = format;
}

/* Paste from the given clipboard. */
void
Terminal::widget_paste(CdkAtom board)
{
        if (!m_input_enabled)
                return;

	auto clip = ctk_clipboard_get_for_display(ctk_widget_get_display(m_widget), board);
	if (!clip)
                return;

        _bte_debug_print(BTE_DEBUG_SELECTION, "Requesting clipboard contents.\n");

        m_paste_request.request_text(clip, &Terminal::widget_paste_received, this);
}

/* Confine coordinates into the visible area. Padding is already subtracted. */
void
Terminal::confine_coordinates(long *xp,
                                        long *yp)
{
	long x = *xp;
	long y = *yp;
        long y_stop;

        /* Allow to use the bottom extra padding only if there's content there. */
        y_stop = MIN(m_view_usable_extents.height(),
                     row_to_pixel(m_screen->insert_delta + m_row_count));

	if (y < 0) {
		y = 0;
		if (!m_selection_block_mode)
			x = 0;
        } else if (y >= y_stop) {
                y = y_stop - 1;
		if (!m_selection_block_mode)
			x = m_column_count * m_cell_width - 1;
	}
	if (x < 0) {
		x = 0;
	} else if (x >= m_column_count * m_cell_width) {
		x = m_column_count * m_cell_width - 1;
	}

	*xp = x;
	*yp = y;
}

/* Start selection at the location of the event.
 * In case of regular selection, this is called with the original click's location
 * once the mouse has moved by the ctk drag threshold.
 */
void
Terminal::start_selection (bte::view::coords const& pos,
                           SelectionType type)
{
	if (m_selection_block_mode)
		type = SelectionType::eCHAR;

        /* Need to ensure the ringview is updated. */
        ringview_update();

        m_selection_origin = m_selection_last = selection_grid_halfcoords_from_view_coords(pos);

	/* Record the selection type. */
	m_selection_type = type;
	m_selecting = TRUE;
        m_selecting_had_delta = false;  /* resolve_selection() below will most likely flip it to true. */
        m_will_select_after_threshold = false;

	_bte_debug_print(BTE_DEBUG_SELECTION,
                         "Selection started at %s.\n",
                         m_selection_origin.to_string());

        /* Take care of updating the display. */
        resolve_selection();

	/* Temporarily stop caring about input from the child. */
	disconnect_pty_read();
}

bool
Terminal::maybe_end_selection()
{
	if (m_selecting) {
		/* Copy only if something was selected. */
                if (!m_selection_resolved.empty() &&
		    m_selecting_had_delta) {
                        widget_copy(BTE_SELECTION_PRIMARY, BTE_FORMAT_TEXT);
			emit_selection_changed();
		}
                stop_autoscroll();  /* Required before setting m_selecting to false, see #105. */
		m_selecting = false;

		/* Reconnect to input from the child if we paused it. */
		connect_pty_read();

		return true;
	}

        if (m_will_select_after_threshold)
                return true;

        return false;
}

/*
 * Terminal::select_all:
 *
 * Selects all text within the terminal (including the scrollback buffer).
 */
void
Terminal::select_all()
{
	deselect_all();

	m_selecting_had_delta = TRUE;

        m_selection_resolved.set ({ _bte_ring_delta (m_screen->row_data), 0 },
                                  { _bte_ring_next  (m_screen->row_data), 0 });

	_bte_debug_print(BTE_DEBUG_SELECTION, "Selecting *all* text.\n");

        widget_copy(BTE_SELECTION_PRIMARY, BTE_FORMAT_TEXT);
	emit_selection_changed();

	invalidate_all();
}

bool
Terminal::mouse_autoscroll_timer_callback()
{
	bool extend = false;
	long x, y, xmax, ymax;
	glong adj;

        auto again = bool{true};

	/* Provide an immediate effect for mouse wigglers. */
	if (m_mouse_last_position.y < 0) {
		if (m_vadjustment) {
			/* Try to scroll up by one line. */
			adj = m_screen->scroll_delta - 1;
			queue_adjustment_value_changed_clamped(adj);
			extend = true;
		}
		_bte_debug_print(BTE_DEBUG_EVENTS, "Autoscrolling down.\n");
	}
	if (m_mouse_last_position.y >= m_view_usable_extents.height()) {
		if (m_vadjustment) {
			/* Try to scroll up by one line. */
			adj = m_screen->scroll_delta + 1;
			queue_adjustment_value_changed_clamped(adj);
			extend = true;
		}
		_bte_debug_print(BTE_DEBUG_EVENTS, "Autoscrolling up.\n");
	}
	if (extend) {
                // FIXMEchpe use confine_view_coords here
		/* Don't select off-screen areas.  That just confuses people. */
		xmax = m_column_count * m_cell_width;
		ymax = m_row_count * m_cell_height;

		x = CLAMP(m_mouse_last_position.x, 0, xmax);
		y = CLAMP(m_mouse_last_position.y, 0, ymax);
		/* If we clamped the Y, mess with the X to get the entire
		 * lines. */
		if (m_mouse_last_position.y < 0 && !m_selection_block_mode) {
			x = 0;
		}
		if (m_mouse_last_position.y >= ymax && !m_selection_block_mode) {
			x = m_column_count * m_cell_width;
		}
		/* Extend selection to cover the newly-scrolled area. */
                modify_selection(bte::view::coords(x, y));
	} else {
		/* Stop autoscrolling. */
                again = false;
	}
	return again;
}

/* Start autoscroll. */
void
Terminal::start_autoscroll()
{
	if (m_mouse_autoscroll_timer)
                return;

        m_mouse_autoscroll_timer.schedule(666 / m_row_count, // FIXME WTF?
                                          bte::glib::Timer::Priority::eLOW);
}

bool
Terminal::widget_mouse_motion(MouseEvent const& event)
{
        /* Need to ensure the ringview is updated. */
        ringview_update();

        auto pos = view_coords_from_event(event);
        auto rowcol = grid_coords_from_view_coords(pos);

	_bte_debug_print(BTE_DEBUG_EVENTS,
                         "Motion notify %s %s\n",
                         pos.to_string(), rowcol.to_string());

        m_modifiers = event.modifiers();

        if (m_will_select_after_threshold) {
                if (!ctk_drag_check_threshold(m_widget,
                                              m_mouse_last_position.x,
                                              m_mouse_last_position.y,
                                              pos.x, pos.y))
                        return true;

                start_selection(bte::view::coords(m_mouse_last_position.x, m_mouse_last_position.y),
                                SelectionType::eCHAR);
        }

        auto handled = bool{false};
        if (m_selecting &&
            (m_mouse_handled_buttons & 1) != 0) {
                _bte_debug_print(BTE_DEBUG_EVENTS, "Mousing drag 1.\n");
                modify_selection(pos);

                /* Start scrolling if we need to. */
                if (pos.y < 0 || pos.y >= m_view_usable_extents.height()) {
                        /* Give mouse wigglers something. */
                        stop_autoscroll();
                        mouse_autoscroll_timer_callback();
                        start_autoscroll();
                }

                handled = true;
        }

        if (!handled && m_input_enabled)
                maybe_send_mouse_drag(rowcol, event);

        if (pos != m_mouse_last_position) {
                m_mouse_last_position = pos;

                set_pointer_autohidden(false);
                hyperlink_hilite_update();
                match_hilite_update();
        }

	return handled;
}

bool
Terminal::widget_mouse_press(MouseEvent const& event)
{
	bool handled = false;
	gboolean start_selecting = FALSE, extend_selecting = FALSE;

        /* Need to ensure the ringview is updated. */
        ringview_update();

        auto pos = view_coords_from_event(event);
        auto rowcol = grid_coords_from_view_coords(pos);

        m_modifiers = event.modifiers();

        switch (event.type()) {
        case EventBase::Type::eMOUSE_PRESS:
		_bte_debug_print(BTE_DEBUG_EVENTS,
                                 "Button %d single-click at %s\n",
                                 event.button_value(),
                                 rowcol.to_string());
		/* Handle this event ourselves. */
                switch (event.button()) {
                case MouseEvent::Button::eLEFT:
			_bte_debug_print(BTE_DEBUG_EVENTS,
					"Handling click ourselves.\n");
			/* Grab focus. */
			if (!m_has_focus)
                                widget()->grab_focus();

			/* If we're in event mode, and the user held down the
			 * shift key, we start selecting. */
			if (m_mouse_tracking_mode != MouseTrackingMode::eNONE) {
				if (m_modifiers & CDK_SHIFT_MASK) {
					start_selecting = TRUE;
				}
			} else {
				/* If the user hit shift, then extend the
				 * selection instead. */
				if ((m_modifiers & CDK_SHIFT_MASK) &&
                                    !m_selection_resolved.empty()) {
					extend_selecting = TRUE;
				} else {
					start_selecting = TRUE;
				}
			}
			if (start_selecting) {
				deselect_all();
                                m_will_select_after_threshold = true;
                                m_selection_block_mode = !!(m_modifiers & CDK_CONTROL_MASK);
				handled = true;
			}
			if (extend_selecting) {
				/* The whole selection code needs to be
				 * rewritten.  For now, put this here to
				 * fix bug 614658 */
				m_selecting = TRUE;
                                selection_maybe_swap_endpoints (pos);
                                modify_selection(pos);
				handled = true;
			}
			break;
		/* Paste if the user pressed shift or we're not sending events
		 * to the app. */
                case MouseEvent::Button::eMIDDLE:
			if ((m_modifiers & CDK_SHIFT_MASK) ||
			    m_mouse_tracking_mode == MouseTrackingMode::eNONE) {
                                if (widget()->primary_paste_enabled()) {
                                        widget_paste(CDK_SELECTION_PRIMARY);
                                        handled = true;
                                }
			}
			break;
                case MouseEvent::Button::eRIGHT:
		default:
			break;
		}
                if (event.button_value() >= 1 && event.button_value() <= 3) {
                        if (handled)
                                m_mouse_handled_buttons |= (1 << (event.button_value() - 1));
                        else
                                m_mouse_handled_buttons &= ~(1 << (event.button_value() - 1));
                }
		/* If we haven't done anything yet, try sending the mouse
		 * event to the app. */
		if (handled == FALSE) {
                        handled = maybe_send_mouse_button(rowcol, event);
		}
		break;
        case EventBase::Type::eMOUSE_DOUBLE_PRESS:
		_bte_debug_print(BTE_DEBUG_EVENTS,
                                 "Button %d double-click at %s\n",
                                 event.button_value(),
                                 rowcol.to_string());
                switch (event.button()) {
                case MouseEvent::Button::eLEFT:
                        if (m_will_select_after_threshold) {
                                start_selection(pos,
                                                SelectionType::eCHAR);
				handled = true;
			}
                        if ((m_mouse_handled_buttons & 1) != 0) {
                                start_selection(pos,
                                                SelectionType::eWORD);
				handled = true;
			}
			break;
                case MouseEvent::Button::eMIDDLE:
                case MouseEvent::Button::eRIGHT:
		default:
			break;
		}
		break;
        case EventBase::Type::eMOUSE_TRIPLE_PRESS:
		_bte_debug_print(BTE_DEBUG_EVENTS,
                                 "Button %d triple-click at %s\n",
                                 event.button_value(),
                                 rowcol.to_string());
                switch (event.button()) {
                case MouseEvent::Button::eLEFT:
                        if ((m_mouse_handled_buttons & 1) != 0) {
                                start_selection(pos,
                                                SelectionType::eLINE);
				handled = true;
			}
			break;
                case MouseEvent::Button::eMIDDLE:
                case MouseEvent::Button::eRIGHT:
		default:
			break;
		}
	default:
		break;
	}

	/* Save the pointer state for later use. */
        if (event.button_value() >= 1 && event.button_value() <= 3)
                m_mouse_pressed_buttons |= (1 << (event.button_value() - 1));

	m_mouse_last_position = pos;

        set_pointer_autohidden(false);
        hyperlink_hilite_update();
        match_hilite_update();

	return handled;
}

bool
Terminal::widget_mouse_release(MouseEvent const& event)
{
	bool handled = false;

        /* Need to ensure the ringview is updated. */
        ringview_update();

        auto pos = view_coords_from_event(event);
        auto rowcol = grid_coords_from_view_coords(pos);

	stop_autoscroll();

        m_modifiers = event.modifiers();

        switch (event.type()) {
        case EventBase::Type::eMOUSE_RELEASE:
		_bte_debug_print(BTE_DEBUG_EVENTS,
                                 "Button %d released at %s\n",
                                 event.button_value(), rowcol.to_string());
                switch (event.button()) {
                case MouseEvent::Button::eLEFT:
                        if ((m_mouse_handled_buttons & 1) != 0)
                                handled = maybe_end_selection();
			break;
                case MouseEvent::Button::eMIDDLE:
                        handled = (m_mouse_handled_buttons & 2) != 0;
                        m_mouse_handled_buttons &= ~2;
			break;
                case MouseEvent::Button::eRIGHT:
		default:
			break;
		}
		if (!handled && m_input_enabled) {
                        handled = maybe_send_mouse_button(rowcol, event);
		}
		break;
	default:
		break;
	}

	/* Save the pointer state for later use. */
        if (event.button_value() >= 1 && event.button_value() <= 3)
                m_mouse_pressed_buttons &= ~(1 << (event.button_value() - 1));

	m_mouse_last_position = pos;
        m_will_select_after_threshold = false;

        set_pointer_autohidden(false);
        hyperlink_hilite_update();
        match_hilite_update();

	return handled;
}

void
Terminal::widget_focus_in()
{
	_bte_debug_print(BTE_DEBUG_EVENTS, "Focus in.\n");

        m_has_focus = true;
        widget()->grab_focus();

	/* We only have an IM context when we're realized, and there's not much
	 * point to painting the cursor if we don't have a window. */
	if (widget_realized()) {
		m_cursor_blink_state = TRUE;

                /* If blinking gets enabled now, do a full repaint.
                 * If blinking gets disabled, only repaint if there's blinking stuff present
                 * (we could further optimize by checking its current phase). */
                if (m_text_blink_mode == TextBlinkMode::eFOCUSED ||
                    (m_text_blink_mode == TextBlinkMode::eUNFOCUSED && m_text_blink_timer)) {
                        invalidate_all();
                }

		check_cursor_blink();

                m_real_widget->im_focus_in();
		invalidate_cursor_once();
                maybe_feed_focus_event(true);
	}
}

void
Terminal::widget_focus_out()
{
	_bte_debug_print(BTE_DEBUG_EVENTS, "Focus out.\n");

	/* We only have an IM context when we're realized, and there's not much
	 * point to painting ourselves if we don't have a window. */
	if (widget_realized()) {
                maybe_feed_focus_event(false);

		maybe_end_selection();

                /* If blinking gets enabled now, do a full repaint.
                 * If blinking gets disabled, only repaint if there's blinking stuff present
                 * (we could further optimize by checking its current phase). */
                if (m_text_blink_mode == TextBlinkMode::eUNFOCUSED ||
                    (m_text_blink_mode == TextBlinkMode::eFOCUSED && m_text_blink_timer)) {
                        invalidate_all();
                }

                m_real_widget->im_focus_out();
		invalidate_cursor_once();

                m_mouse_pressed_buttons = 0;
                m_mouse_handled_buttons = 0;
	}

	m_has_focus = false;
	check_cursor_blink();
}

void
Terminal::widget_mouse_enter(MouseEvent const& event)
{
        auto pos = view_coords_from_event(event);

        // FIXMEchpe read event modifiers here

	_bte_debug_print(BTE_DEBUG_EVENTS, "Enter at %s\n", pos.to_string());

        m_mouse_cursor_over_widget = TRUE;
        m_mouse_last_position = pos;

        set_pointer_autohidden(false);
        hyperlink_hilite_update();
        match_hilite_update();
        apply_mouse_cursor();
}

void
Terminal::widget_mouse_leave(MouseEvent const& event)
{
        auto pos = view_coords_from_event(event);

        // FIXMEchpe read event modifiers here

	_bte_debug_print(BTE_DEBUG_EVENTS, "Leave at %s\n", pos.to_string());

        m_mouse_cursor_over_widget = FALSE;
        m_mouse_last_position = pos;

        hyperlink_hilite_update();
        match_hilite_update();
        apply_mouse_cursor();
}

/* Apply the changed metrics, and queue a resize if need be.
 *
 * The cell's height consists of 4 parts, from top to bottom:
 * - char_spacing.top: half of the extra line spacing,
 * - char_ascent: the font's ascent,
 * - char_descent: the font's descent,
 * - char_spacing.bottom: the other half of the extra line spacing.
 * Extra line spacing is typically 0, beef up cell_height_scale to get actual pixels
 * here. Similarly, increase cell_width_scale to get nonzero char_spacing.{left,right}.
 */
void
Terminal::apply_font_metrics(int cell_width,
                                       int cell_height,
                                       int char_ascent,
                                       int char_descent,
                                       CtkBorder char_spacing)
{
        int char_height;
	bool resize = false, cresize = false;

	/* Sanity check for broken font changes. */
        cell_width = MAX(cell_width, 1);
        cell_height = MAX(cell_height, 2);
        char_ascent = MAX(char_ascent, 1);
        char_descent = MAX(char_descent, 1);

        /* For convenience only. */
        char_height = char_ascent + char_descent;

	/* Change settings, and keep track of when we've changed anything. */
        if (cell_width != m_cell_width) {
		resize = cresize = true;
                m_cell_width = cell_width;
	}
        if (cell_height != m_cell_height) {
		resize = cresize = true;
                m_cell_height = cell_height;
	}
        if (char_ascent != m_char_ascent) {
		resize = true;
                m_char_ascent = char_ascent;
	}
        if (char_descent != m_char_descent) {
		resize = true;
                m_char_descent = char_descent;
	}
        if (memcmp(&char_spacing, &m_char_padding, sizeof(CtkBorder)) != 0) {
                resize = true;
                m_char_padding = char_spacing;
        }
        m_line_thickness = MAX (MIN (char_descent / 2, char_height / 14), 1);
        /* FIXME take these from pango_font_metrics_get_{underline,strikethrough}_{position,thickness} */
        m_underline_thickness = m_line_thickness;
        m_underline_position = MIN (char_spacing.top + char_ascent + m_line_thickness, cell_height - m_underline_thickness);
        m_double_underline_thickness = m_line_thickness;
        /* FIXME make sure this doesn't reach the baseline (switch to thinner lines, or one thicker line in that case) */
        m_double_underline_position = MIN (char_spacing.top + char_ascent + m_line_thickness, cell_height - 3 * m_double_underline_thickness);
        m_undercurl_thickness = m_line_thickness;
        m_undercurl_position = MIN (char_spacing.top + char_ascent + m_line_thickness, cell_height - _bte_draw_get_undercurl_height(cell_width, m_undercurl_thickness));
        m_strikethrough_thickness = m_line_thickness;
        m_strikethrough_position = char_spacing.top + char_ascent - char_height / 4;
        m_overline_thickness = m_line_thickness;
        m_overline_position = char_spacing.top;  /* FIXME */
        m_regex_underline_thickness = 1;  /* FIXME */
        m_regex_underline_position = char_spacing.top + char_height - m_regex_underline_thickness;  /* FIXME */

	/* Queue a resize if anything's changed. */
	if (resize) {
		if (widget_realized()) {
			ctk_widget_queue_resize_no_redraw(m_widget);
		}
	}
	/* Emit a signal that the font changed. */
	if (cresize) {
                if (pty()) {
                        /* Update pixel size of PTY. */
                        pty()->set_size(m_row_count,
                                        m_column_count,
                                        m_cell_height,
                                        m_cell_width);
                }
		emit_char_size_changed(m_cell_width, m_cell_height);
	}
	/* Repaint. */
	invalidate_all();
}

void
Terminal::ensure_font()
{
	{
		/* Load default fonts, if no fonts have been loaded. */
		if (!m_has_fonts) {
			set_font_desc(m_unscaled_font_desc.get());
		}
		if (m_fontdirty) {
                        int cell_width, cell_height;
                        int char_ascent, char_descent;
                        CtkBorder char_spacing;
			m_fontdirty = false;
			m_draw.set_text_font(
                                                 m_widget,
                                                 m_fontdesc.get(),
                                                 m_cell_width_scale,
                                                 m_cell_height_scale);
			m_draw.get_text_metrics(
                                                    &cell_width, &cell_height,
                                                    &char_ascent, &char_descent,
                                                    &char_spacing);
                        apply_font_metrics(cell_width, cell_height,
                                           char_ascent, char_descent,
                                           char_spacing);
		}
	}
}

void
Terminal::update_font()
{
        /* We'll get called again later */
        if (!m_unscaled_font_desc)
                return;

        auto desc = pango_font_description_copy(m_unscaled_font_desc.get());

        double size = pango_font_description_get_size(desc);
        if (pango_font_description_get_size_is_absolute(desc)) {
                pango_font_description_set_absolute_size(desc, m_font_scale * size);
        } else {
                pango_font_description_set_size(desc, m_font_scale * size);
        }

        m_fontdesc.reset(desc); /* adopts */
        m_fontdirty = true;
        m_has_fonts = true;

        /* Set the drawing font. */
        if (widget_realized()) {
                ensure_font();
        }
}

/*
 * Terminal::set_font_desc:
 * @font_desc: (allow-none): a #PangoFontDescription for the desired font, or %nullptr
 *
 * Sets the font used for rendering all text displayed by the terminal,
 * overriding any fonts set using ctk_widget_modify_font().  The terminal
 * will immediately attempt to load the desired font, retrieve its
 * metrics, and attempt to resize itself to keep the same number of rows
 * and columns.  The font scale is applied to the specified font.
 */
bool
Terminal::set_font_desc(PangoFontDescription const* font_desc)
{
	/* Create an owned font description. */
        PangoFontDescription *desc;

        auto context = ctk_widget_get_style_context(m_widget);
        ctk_style_context_save(context);
        ctk_style_context_set_state (context, CTK_STATE_FLAG_NORMAL);
        ctk_style_context_get(context, CTK_STATE_FLAG_NORMAL, "font", &desc, nullptr);
        ctk_style_context_restore(context);

	pango_font_description_set_family_static (desc, "monospace");
	if (font_desc != nullptr) {
		pango_font_description_merge (desc, font_desc, TRUE);
		_BTE_DEBUG_IF(BTE_DEBUG_MISC) {
			if (desc) {
				char *tmp;
				tmp = pango_font_description_to_string(desc);
				g_printerr("Using pango font \"%s\".\n", tmp);
				g_free (tmp);
			}
		}
	} else {
		_bte_debug_print(BTE_DEBUG_MISC,
				"Using default monospace font.\n");
	}

        bool const same_desc = m_unscaled_font_desc &&
                pango_font_description_equal(m_unscaled_font_desc.get(), desc);

	/* Note that we proceed to recreating the font even if the description
	 * are the same.  This is because maybe screen
	 * font options were changed, or new fonts installed.  Those will be
	 * detected at font creation time and respected.
	 */

        m_unscaled_font_desc.reset(desc); /* adopts */
        update_font();

        return !same_desc;
}

bool
Terminal::set_font_scale(gdouble scale)
{
        /* FIXME: compare old and new scale in pixel space */
        if (_bte_double_equal(scale, m_font_scale))
                return false;

        m_font_scale = scale;
        update_font();

        return true;
}

bool
Terminal::set_cell_width_scale(double scale)
{
        /* FIXME: compare old and new scale in pixel space */
        if (_bte_double_equal(scale, m_cell_width_scale))
                return false;

        m_cell_width_scale = scale;
        /* Set the drawing font. */
        m_fontdirty = true;
        if (widget_realized()) {
                ensure_font();
        }

        return true;
}

bool
Terminal::set_cell_height_scale(double scale)
{
        /* FIXME: compare old and new scale in pixel space */
        if (_bte_double_equal(scale, m_cell_height_scale))
                return false;

        m_cell_height_scale = scale;
        /* Set the drawing font. */
        m_fontdirty = true;
        if (widget_realized()) {
                ensure_font();
        }

        return true;
}

/* Read and refresh our perception of the size of the PTY. */
void
Terminal::refresh_size()
{
        if (!pty())
                return;

	int rows, columns;
        if (!pty()->get_size(&rows, &columns)) {
                /* Error reading PTY size, use defaults */
                rows = BTE_ROWS;
                columns = BTE_COLUMNS;
	}

        if (m_row_count == rows &&
            m_column_count == columns)
                return;

        m_row_count = rows;
        m_column_count = columns;
        m_tabstops.resize(columns);
}

/* Resize the given screen (normal or alternate) of the terminal. */
void
Terminal::screen_set_size(BteScreen *screen_,
                                    long old_columns,
                                    long old_rows,
                                    bool do_rewrap)
{
	BteRing *ring = screen_->row_data;
	BteVisualPosition cursor_saved_absolute;
	BteVisualPosition below_viewport;
	BteVisualPosition below_current_paragraph;
        BteVisualPosition selection_start, selection_end;
	BteVisualPosition *markers[7];
        gboolean was_scrolled_to_top = ((long) ceil(screen_->scroll_delta) == _bte_ring_delta(ring));
        gboolean was_scrolled_to_bottom = ((long) screen_->scroll_delta == screen_->insert_delta);
	glong old_top_lines;
	double new_scroll_delta;

        if (m_selection_block_mode && do_rewrap && old_columns != m_column_count)
                deselect_all();

	_bte_debug_print(BTE_DEBUG_RESIZE,
			"Resizing %s screen_\n"
			"Old  insert_delta=%ld  scroll_delta=%f\n"
                        "     cursor (absolute)  row=%ld  col=%ld\n"
			"     cursor_saved (relative to insert_delta)  row=%ld  col=%ld\n",
			screen_ == &m_normal_screen ? "normal" : "alternate",
			screen_->insert_delta, screen_->scroll_delta,
                        screen_->cursor.row, screen_->cursor.col,
                        screen_->saved.cursor.row, screen_->saved.cursor.col);

        cursor_saved_absolute.row = screen_->saved.cursor.row + screen_->insert_delta;
        cursor_saved_absolute.col = screen_->saved.cursor.col;
	below_viewport.row = screen_->scroll_delta + old_rows;
	below_viewport.col = 0;
        below_current_paragraph.row = screen_->cursor.row + 1;
	while (below_current_paragraph.row < _bte_ring_next(ring)
	    && _bte_ring_index(ring, below_current_paragraph.row - 1)->attr.soft_wrapped) {
		below_current_paragraph.row++;
	}
	below_current_paragraph.col = 0;
        memset(&markers, 0, sizeof(markers));
        markers[0] = &cursor_saved_absolute;
        markers[1] = &below_viewport;
        markers[2] = &below_current_paragraph;
        markers[3] = &screen_->cursor;
        if (!m_selection_resolved.empty()) {
                selection_start.row = m_selection_resolved.start_row();
                selection_start.col = m_selection_resolved.start_column();
                selection_end.row = m_selection_resolved.end_row();
                selection_end.col = m_selection_resolved.end_column();
                markers[4] = &selection_start;
                markers[5] = &selection_end;
	}

	old_top_lines = below_current_paragraph.row - screen_->insert_delta;

	if (do_rewrap && old_columns != m_column_count)
		_bte_ring_rewrap(ring, m_column_count, markers);

	if (_bte_ring_length(ring) > m_row_count) {
		/* The content won't fit without scrollbars. Before figuring out the position, we might need to
		   drop some lines from the ring if the cursor is not at the bottom, as XTerm does. See bug 708213.
		   This code is really tricky, see ../doc/rewrap.txt for details! */
		glong new_top_lines, drop1, drop2, drop3, drop;
		screen_->insert_delta = _bte_ring_next(ring) - m_row_count;
		new_top_lines = below_current_paragraph.row - screen_->insert_delta;
		drop1 = _bte_ring_length(ring) - m_row_count;
		drop2 = _bte_ring_next(ring) - below_current_paragraph.row;
		drop3 = old_top_lines - new_top_lines;
		drop = MIN(MIN(drop1, drop2), drop3);
		if (drop > 0) {
			int new_ring_next = screen_->insert_delta + m_row_count - drop;
			_bte_debug_print(BTE_DEBUG_RESIZE,
					"Dropping %ld [== MIN(%ld, %ld, %ld)] rows at the bottom\n",
					drop, drop1, drop2, drop3);
			_bte_ring_shrink(ring, new_ring_next - _bte_ring_delta(ring));
		}
	}

        if (!m_selection_resolved.empty()) {
                m_selection_resolved.set ({ selection_start.row, selection_start.col },
                                          { selection_end.row, selection_end.col });
	}

	/* Figure out new insert and scroll deltas */
	if (_bte_ring_length(ring) <= m_row_count) {
		/* Everything fits without scrollbars. Align at top. */
		screen_->insert_delta = _bte_ring_delta(ring);
		new_scroll_delta = screen_->insert_delta;
		_bte_debug_print(BTE_DEBUG_RESIZE,
				"Everything fits without scrollbars\n");
	} else {
		/* Scrollbar required. Can't afford unused lines at bottom. */
		screen_->insert_delta = _bte_ring_next(ring) - m_row_count;
		if (was_scrolled_to_bottom) {
			/* Was scrolled to bottom, keep this way. */
			new_scroll_delta = screen_->insert_delta;
			_bte_debug_print(BTE_DEBUG_RESIZE,
					"Scroll to bottom\n");
		} else if (was_scrolled_to_top) {
			/* Was scrolled to top, keep this way. Not sure if this special case is worth it. */
			new_scroll_delta = _bte_ring_delta(ring);
			_bte_debug_print(BTE_DEBUG_RESIZE,
					"Scroll to top\n");
		} else {
			/* Try to scroll so that the bottom visible row stays.
			   More precisely, the character below the bottom left corner stays in that
			   (invisible) row.
			   So if the bottom of the screen_ was at a hard line break then that hard
			   line break will stay there.
			   TODO: What would be the best behavior if the bottom of the screen_ is a
			   soft line break, i.e. only a partial line is visible at the bottom? */
			new_scroll_delta = below_viewport.row - m_row_count;
			/* Keep the old fractional part. */
			new_scroll_delta += screen_->scroll_delta - floor(screen_->scroll_delta);
			_bte_debug_print(BTE_DEBUG_RESIZE,
					"Scroll so bottom row stays\n");
		}
	}

	/* Don't clamp, they'll be clamped when restored. Until then remember off-screen_ values
	   since they might become on-screen_ again on subsequent resizes. */
        screen_->saved.cursor.row = cursor_saved_absolute.row - screen_->insert_delta;
        screen_->saved.cursor.col = cursor_saved_absolute.col;

	_bte_debug_print(BTE_DEBUG_RESIZE,
			"New  insert_delta=%ld  scroll_delta=%f\n"
                        "     cursor (absolute)  row=%ld  col=%ld\n"
			"     cursor_saved (relative to insert_delta)  row=%ld  col=%ld\n\n",
			screen_->insert_delta, new_scroll_delta,
                        screen_->cursor.row, screen_->cursor.col,
                        screen_->saved.cursor.row, screen_->saved.cursor.col);

	if (screen_ == m_screen)
		queue_adjustment_value_changed(new_scroll_delta);
	else
		screen_->scroll_delta = new_scroll_delta;
}

void
Terminal::set_size(long columns,
                             long rows)
{
	glong old_columns, old_rows;

	_bte_debug_print(BTE_DEBUG_RESIZE,
			"Setting PTY size to %ldx%ld.\n",
			columns, rows);

	old_rows = m_row_count;
	old_columns = m_column_count;

	if (pty()) {
		/* Try to set the terminal size, and read it back,
		 * in case something went awry.
                 */
		if (!pty()->set_size(rows,
                                     columns,
                                     m_cell_height,
                                     m_cell_width)) {
                        // nothing we can do here
                }
		refresh_size();
	} else {
		m_row_count = rows;
		m_column_count = columns;
                m_tabstops.resize(columns);
	}
	if (old_rows != m_row_count || old_columns != m_column_count) {
                m_scrolling_restricted = FALSE;

                _bte_ring_set_visible_rows(m_normal_screen.row_data, m_row_count);
                _bte_ring_set_visible_rows(m_alternate_screen.row_data, m_row_count);

		/* Resize the normal screen and (if rewrapping is enabled) rewrap it even if the alternate screen is visible: bug 415277 */
		screen_set_size(&m_normal_screen, old_columns, old_rows, m_rewrap_on_resize);
		/* Resize the alternate screen if it's the current one, but never rewrap it: bug 336238 comment 60 */
		if (m_screen == &m_alternate_screen)
			screen_set_size(&m_alternate_screen, old_columns, old_rows, false);

                /* Ensure scrollback buffers cover the screen. */
                set_scrollback_lines(m_scrollback_lines);

                /* Ensure the cursor is valid */
                m_screen->cursor.row = CLAMP (m_screen->cursor.row,
                                              _bte_ring_delta (m_screen->row_data),
                                              MAX (_bte_ring_delta (m_screen->row_data),
                                                   _bte_ring_next (m_screen->row_data) - 1));

		adjust_adjustments_full();
		ctk_widget_queue_resize_no_redraw(m_widget);
		/* Our visible text changed. */
		emit_text_modified();
	}
}

/* Redraw the widget. */
static void
bte_terminal_vadjustment_value_changed_cb(bte::terminal::Terminal* that) noexcept
try
{
        that->vadjustment_value_changed();
}
catch (...)
{
        bte::log_exception();
}

void
Terminal::vadjustment_value_changed()
{
	/* Read the new adjustment value and save the difference. */
        auto const adj = ctk_adjustment_get_value(m_vadjustment.get());
	double dy = adj - m_screen->scroll_delta;
	m_screen->scroll_delta = adj;

	/* Sanity checks. */
        if (G_UNLIKELY(!widget_realized()))
                return;

        /* FIXME: do this check in pixel space */
	if (!_bte_double_equal(dy, 0)) {
		_bte_debug_print(BTE_DEBUG_ADJ,
			    "Scrolling by %f\n", dy);
                invalidate_all();
                match_contents_clear();
		emit_text_scrolled(dy);
		queue_contents_changed();
	} else {
		_bte_debug_print(BTE_DEBUG_ADJ, "Not scrolling\n");
	}
}

void
Terminal::widget_set_vadjustment(bte::glib::RefPtr<CtkAdjustment>&& adjustment)
{
        if (adjustment && adjustment == m_vadjustment)
                return;
        if (!adjustment && m_vadjustment)
                return;

        if (m_vadjustment) {
		/* Disconnect our signal handlers from this object. */
                g_signal_handlers_disconnect_by_func(m_vadjustment.get(),
						     (void*)bte_terminal_vadjustment_value_changed_cb,
						     this);
	}

        if (adjustment)
                m_vadjustment = std::move(adjustment);
        else
                m_vadjustment = bte::glib::make_ref_sink(CTK_ADJUSTMENT(ctk_adjustment_new(0, 0, 0, 0, 0, 0)));

	/* We care about the offset, not the top or bottom. */
        g_signal_connect_swapped(m_vadjustment.get(),
				 "value-changed",
				 G_CALLBACK(bte_terminal_vadjustment_value_changed_cb),
				 this);
}

Terminal::Terminal(bte::platform::Widget* w,
                   BteTerminal *t) :
        m_real_widget(w),
        m_terminal(t),
        m_widget(&t->widget),
        m_normal_screen(BTE_SCROLLBACK_INIT, true),
        m_alternate_screen(BTE_ROWS, false),
        m_screen(&m_normal_screen)
{
	widget_set_vadjustment({});

        /* Inits allocation to 1x1 @ -1,-1 */
        cairo_rectangle_int_t allocation;
        ctk_widget_get_allocation(m_widget, &allocation);
        set_allocated_rect(allocation);

	int i;
	CdkDisplay *display;

	/* NOTE! We allocated zeroed memory, just fill in non-zero stuff. */

        // FIXMEegmont make this store row indices only, maybe convert to a bitmap
        m_update_rects = g_array_sized_new(FALSE /* zero terminated */,
                                           FALSE /* clear */,
                                           sizeof(cairo_rectangle_int_t),
                                           32 /* preallocated size */);

	/* Set up dummy metrics, value != 0 to avoid division by 0 */
        // FIXMEchpe this is wrong. These values must not be used before
        // the view has been set up, so if they are, that's a bug
	m_cell_width = 1;
	m_cell_height = 1;
	m_char_ascent = 1;
	m_char_descent = 1;
	m_char_padding = {0, 0, 0, 0};
	m_line_thickness = 1;
	m_underline_position = 1;
        m_double_underline_position = 1;
        m_undercurl_position = 1.;
	m_strikethrough_position = 1;
        m_overline_position = 1;
        m_regex_underline_position = 1;

        reset_default_attributes(true);

	/* Set up the desired palette. */
	set_colors_default();
	for (i = 0; i < BTE_PALETTE_SIZE; i++)
		m_palette[i].sources[BTE_COLOR_SOURCE_ESCAPE].is_set = FALSE;

	/* Set up I/O encodings. */
	m_outgoing = _bte_byte_array_new();

	/* Setting the terminal type and size requires the PTY master to
	 * be set up properly first. */
        set_size(BTE_COLUMNS, BTE_ROWS);

        /* Default is 0, forces update in bte_terminal_set_scrollback_lines */
	set_scrollback_lines(BTE_SCROLLBACK_INIT);

	/* Selection info. */
	display = ctk_widget_get_display(m_widget);
	m_clipboard[BTE_SELECTION_PRIMARY] = ctk_clipboard_get_for_display(display, CDK_SELECTION_PRIMARY);
	m_clipboard[BTE_SELECTION_CLIPBOARD] = ctk_clipboard_get_for_display(display, CDK_SELECTION_CLIPBOARD);
        m_selection_owned[BTE_SELECTION_PRIMARY] = false;
        m_selection_owned[BTE_SELECTION_CLIPBOARD] = false;

        /* Initialize the saved cursor. */
        save_cursor(&m_normal_screen);
        save_cursor(&m_alternate_screen);

	/* Matching data. */
        m_match_span.clear(); // FIXMEchpe unnecessary
	match_hilite_clear(); // FIXMEchpe unnecessary

        /* Word chars */
        set_word_char_exceptions(WORD_CHAR_EXCEPTIONS_DEFAULT);

        update_view_extents();

#ifdef BTE_DEBUG
        if (g_test_flags != 0) {
                feed("\e[1m\e[31mWARNING:\e[39m Test mode enabled. This is insecure!\e[0m\n\e[G"sv, false);
        }
#endif

#ifndef WITH_GNUTLS
        std::string str{"\e[1m\e[31m"};
        str.append(_("WARNING"));
        str.append(":\e[39m ");
        str.append(_("GnuTLS not enabled; data will be written to disk unencrypted!"));
        str.append("\e[0m\n\e[G");

        feed(str, false);
#endif
}

void
Terminal::widget_get_preferred_width(int *minimum_width,
                                               int *natural_width)
{
	_bte_debug_print(BTE_DEBUG_LIFECYCLE, "bte_terminal_get_preferred_width()\n");

	ensure_font();

        refresh_size();

	*minimum_width = m_cell_width * 2;  /* have room for a CJK or emoji */
        *natural_width = m_cell_width * m_column_count;

	*minimum_width += m_padding.left +
                          m_padding.right;
	*natural_width += m_padding.left +
                          m_padding.right;

	_bte_debug_print(BTE_DEBUG_WIDGET_SIZE,
			"[Terminal %p] minimum_width=%d, natural_width=%d for %ldx%ld cells (padding %d,%d;%d,%d).\n",
                        m_terminal,
			*minimum_width, *natural_width,
			m_column_count,
                         m_row_count,
                         m_padding.left, m_padding.right, m_padding.top, m_padding.bottom);
}

void
Terminal::widget_get_preferred_height(int *minimum_height,
                                                int *natural_height)
{
	_bte_debug_print(BTE_DEBUG_LIFECYCLE, "bte_terminal_get_preferred_height()\n");

	ensure_font();

        refresh_size();

	*minimum_height = m_cell_height * 1;
        *natural_height = m_cell_height * m_row_count;

	*minimum_height += m_padding.top +
			   m_padding.bottom;
	*natural_height += m_padding.top +
			   m_padding.bottom;

	_bte_debug_print(BTE_DEBUG_WIDGET_SIZE,
			"[Terminal %p] minimum_height=%d, natural_height=%d for %ldx%ld cells (padding %d,%d;%d,%d).\n",
                        m_terminal,
			*minimum_height, *natural_height,
			m_column_count,
                         m_row_count,
                         m_padding.left, m_padding.right, m_padding.top, m_padding.bottom);
}

void
Terminal::widget_size_allocate(CtkAllocation *allocation)
{
	glong width, height;
	gboolean repaint, update_scrollback;

	_bte_debug_print(BTE_DEBUG_LIFECYCLE,
			"bte_terminal_size_allocate()\n");

	width = (allocation->width - (m_padding.left + m_padding.right)) /
		m_cell_width;
	height = (allocation->height - (m_padding.top + m_padding.bottom)) /
		 m_cell_height;
	width = MAX(width, 1);
	height = MAX(height, 1);

	_bte_debug_print(BTE_DEBUG_WIDGET_SIZE,
			"[Terminal %p] Sizing window to %dx%d (%ldx%ld, padding %d,%d;%d,%d).\n",
                        m_terminal,
			allocation->width, allocation->height,
                         width, height,
                         m_padding.left, m_padding.right, m_padding.top, m_padding.bottom);

        auto current_allocation = get_allocated_rect();

	repaint = current_allocation.width != allocation->width
			|| current_allocation.height != allocation->height;
	update_scrollback = current_allocation.height != allocation->height;

	/* Set our allocation to match the structure. */
	ctk_widget_set_allocation(m_widget, allocation);
        set_allocated_rect(*allocation);

	if (width != m_column_count
			|| height != m_row_count
			|| update_scrollback)
	{
		/* Set the size of the pseudo-terminal. */
		set_size(width, height);

		/* Notify viewers that the contents have changed. */
		queue_contents_changed();
	}

	if (widget_realized()) {
		/* Force a repaint if we were resized. */
		if (repaint) {
			reset_update_rects();
			invalidate_all();
		}
	}
}

void
Terminal::widget_unmap()
{
        m_ringview.pause();
}

void
Terminal::widget_unrealize()
{
	/* Deallocate the cursors. */
        m_mouse_cursor_over_widget = FALSE;

	match_hilite_clear();

	m_im_preedit_active = FALSE;

	/* Drop font cache */
        m_draw.clear_font_cache();
	m_fontdirty = true;

        /* Remove the cursor blink timeout function. */
	remove_cursor_timeout();

        /* Remove the contents blink timeout function. */
        m_text_blink_timer.abort();

	/* Cancel any pending redraws. */
	remove_update_timeout(this);

	/* Cancel any pending signals */
	m_contents_changed_pending = FALSE;
	m_cursor_moved_pending = FALSE;
	m_text_modified_flag = FALSE;
	m_text_inserted_flag = FALSE;
	m_text_deleted_flag = FALSE;

	/* Clear modifiers. */
	m_modifiers = 0;
}

void
Terminal::set_blink_settings(bool blink,
                             int blink_time,
                             int blink_timeout) noexcept
{
        m_cursor_blink_cycle = blink_time / 2;
        m_cursor_blink_timeout = blink_timeout;

        update_cursor_blinks();

        /* Misuse ctk-cursor-blink-time for text blinking as well. This might change in the future. */
        m_text_blink_cycle = m_cursor_blink_cycle;
        if (m_text_blink_timer) {
                /* The current phase might have changed, and an already installed
                 * timer to blink might fire too late. So remove the timer and
                 * repaint the contents (which will install a correct new timer). */
                m_text_blink_timer.abort();
                invalidate_all();
        }
}

Terminal::~Terminal()
{
        /* Make sure not to change selection while in destruction. See issue bte#89. */
        m_changing_selection = true;

	int sel;

        terminate_child();
        unset_pty(false /* don't notify widget */);
        remove_update_timeout(this);

        /* Stop processing input. */
        stop_processing(this);

	/* Free matching data. */
	if (m_match_attributes != NULL) {
		g_array_free(m_match_attributes, TRUE);
	}
	g_free(m_match_contents);

	if (m_search_attrs)
		g_array_free (m_search_attrs, TRUE);

	/* Disconnect from autoscroll requests. */
	stop_autoscroll();

	/* Cancel pending adjustment change notifications. */
	m_adjustment_changed_pending = FALSE;

	/* Free any selected text, but if we currently own the selection,
	 * throw the text onto the clipboard without an owner so that it
	 * doesn't just disappear. */
	for (sel = BTE_SELECTION_PRIMARY; sel < LAST_BTE_SELECTION; sel++) {
		if (m_selection[sel] != nullptr) {
			if (m_selection_owned[sel]) {
                                // FIXMEchpe we should check m_selection_format[sel]
                                // and also put text/html on if it's BTE_FORMAT_HTML
				ctk_clipboard_set_text(m_clipboard[sel],
						       m_selection[sel]->str,
						       m_selection[sel]->len);
			}
			g_string_free(m_selection[sel], TRUE);
                        m_selection[sel] = nullptr;
		}
	}

        /* Stop listening for child-exited signals. */
        if (m_reaper) {
                g_signal_handlers_disconnect_by_func(m_reaper,
                                                     (gpointer)reaper_child_exited_cb,
                                                     this);
                g_object_unref(m_reaper);
        }

	/* Discard any pending data. */
	_bte_byte_array_free(m_outgoing);
        m_outgoing = nullptr;

	/* Free public-facing data. */
        if (m_vadjustment) {
		/* Disconnect our signal handlers from this object. */
                g_signal_handlers_disconnect_by_func(m_vadjustment.get(),
						     (void*)bte_terminal_vadjustment_value_changed_cb,
						     this);
	}

        /* Update rects */
        g_array_free(m_update_rects, TRUE /* free segment */);
}

void
Terminal::widget_realize()
{
        m_mouse_cursor_over_widget = FALSE;  /* We'll receive an enter_notify_event if the window appears under the cursor. */

	m_im_preedit_active = FALSE;

	/* Clear modifiers. */
	m_modifiers = 0;

        // Create the font cache
	ensure_font();
}

static inline void
swap (guint *a, guint *b)
{
	guint tmp;
	tmp = *a, *a = *b, *b = tmp;
}

// FIXMEchpe probably @attr should be passed by ref
void
Terminal::determine_colors(BteCellAttr const* attr,
                                     bool is_selected,
                                     bool is_cursor,
                                     guint *pfore,
                                     guint *pback,
                                     guint *pdeco) const
{
        guint fore, back, deco;

        g_assert(attr);

	/* Start with cell colors */
        bte_color_triple_get(attr->colors(), &fore, &back, &deco);

	/* Reverse-mode switches default fore and back colors */
        if (G_UNLIKELY (m_modes_private.DEC_REVERSE_IMAGE())) {
		if (fore == BTE_DEFAULT_FG)
			fore = BTE_DEFAULT_BG;
		if (back == BTE_DEFAULT_BG)
			back = BTE_DEFAULT_FG;
	}

	/* Handle bold by using set bold color or brightening */
        if (attr->bold()) {
                if (fore == BTE_DEFAULT_FG && get_color(BTE_BOLD_FG) != NULL) {
			fore = BTE_BOLD_FG;
                } else if (m_bold_is_bright &&
                           fore >= BTE_LEGACY_COLORS_OFFSET &&
                           fore < BTE_LEGACY_COLORS_OFFSET + BTE_LEGACY_COLOR_SET_SIZE) {
			fore += BTE_COLOR_BRIGHT_OFFSET;
		}
	}

        /* Handle dim colors.  Only apply to palette colors, dimming direct RGB wouldn't make sense.
         * Apply to the foreground color only, but do this before handling reverse/highlight so that
         * those can be used to dim the background instead. */
        if (attr->dim() && !(fore & BTE_RGB_COLOR_MASK(8, 8, 8))) {
	        fore |= BTE_DIM_COLOR;
        }

	/* Reverse cell? */
	if (attr->reverse()) {
		swap (&fore, &back);
	}

	/* Selection: use hightlight back/fore, or inverse */
	if (is_selected) {
		/* XXX what if hightlight back is same color as current back? */
		bool do_swap = true;
		if (get_color(BTE_HIGHLIGHT_BG) != NULL) {
			back = BTE_HIGHLIGHT_BG;
			do_swap = false;
		}
		if (get_color(BTE_HIGHLIGHT_FG) != NULL) {
			fore = BTE_HIGHLIGHT_FG;
			do_swap = false;
		}
		if (do_swap)
			swap (&fore, &back);
	}

	/* Cursor: use cursor back, or inverse */
	if (is_cursor) {
		/* XXX what if cursor back is same color as current back? */
                bool do_swap = true;
                if (get_color(BTE_CURSOR_BG) != NULL) {
                        back = BTE_CURSOR_BG;
                        do_swap = false;
                }
                if (get_color(BTE_CURSOR_FG) != NULL) {
                        fore = BTE_CURSOR_FG;
                        do_swap = false;
                }
                if (do_swap)
                        swap (&fore, &back);
	}

	/* Invisible? */
        /* FIXME: This is dead code, this is not where we actually handle invisibile.
         * Instead, draw_cells() is not called from draw_rows().
         * That is required for the foreground to be transparent if so is the background. */
        if (attr->invisible()) {
                fore = back;
                deco = BTE_DEFAULT_FG;
	}

	*pfore = fore;
	*pback = back;
        *pdeco = deco;
}

void
Terminal::determine_colors(BteCell const* cell,
                                     bool highlight,
                                     guint *fore,
                                     guint *back,
                                     guint *deco) const
{
	determine_colors(cell ? &cell->attr : &basic_cell.attr,
                         highlight, false /* not cursor */,
                         fore, back, deco);
}

void
Terminal::determine_cursor_colors(BteCell const* cell,
                                            bool highlight,
                                            guint *fore,
                                            guint *back,
                                            guint *deco) const
{
	determine_colors(cell ? &cell->attr : &basic_cell.attr,
                         highlight, true /* cursor */,
                         fore, back, deco);
}

// FIXMEchpe this constantly removes and reschedules the timer. improve this!
bool
Terminal::text_blink_timer_callback()
{
        invalidate_all();
        return false; /* don't run again */
}

/* Draw a string of characters with similar attributes. */
void
Terminal::draw_cells(bte::view::DrawingContext::TextRequest* items,
                               gssize n,
                               uint32_t fore,
                               uint32_t back,
                               uint32_t deco,
                               bool clear,
                               bool draw_default_bg,
                               uint32_t attr,
                               bool hyperlink,
                               bool hilite,
                               int column_width,
                               int row_height)
{
        int i, xl, xr, y;
	gint columns = 0;
        bte::color::rgb fg, bg, dc;

	g_assert(n > 0);
#if 0
	_BTE_DEBUG_IF(BTE_DEBUG_CELLS) {
		GString *str = g_string_new (NULL);
		gchar *tmp;
		for (i = 0; i < n; i++) {
			g_string_append_unichar (str, items[i].c);
		}
		tmp = g_string_free (str, FALSE);
                g_printerr ("draw_cells('%s', fore=%d, back=%d, deco=%d, bold=%d,"
                                " ul=%d, strike=%d, ol=%d, blink=%d,"
                                " hyperlink=%d, hilite=%d, boxed=%d)\n",
                                tmp, fore, back, deco, bold,
                                underline, strikethrough, overline, blink,
                                hyperlink, hilite, boxed);
		g_free (tmp);
	}
#endif

        rgb_from_index<8, 8, 8>(fore, fg);
        rgb_from_index<8, 8, 8>(back, bg);
        // FIXMEchpe defer resolving deco color until we actually need to draw an underline?
        if (deco == BTE_DEFAULT_FG)
                dc = fg;
        else
                rgb_from_index<4, 5, 4>(deco, dc);

        if (clear && (draw_default_bg || back != BTE_DEFAULT_BG)) {
                /* Paint the background. */
                i = 0;
                while (i < n) {
                        xl = items[i].x;
                        xr = items[i].x + items[i].columns * column_width;
                        y = items[i].y;
                        /* Items are not necessarily contiguous in LTR order.
                         * Combine as long as they form a single visual run. */
                        for (i++; i < n && items[i].y == y; i++) {
                                if (G_LIKELY (items[i].x == xr)) {
                                        xr += items[i].columns * column_width;  /* extend to the right */
                                } else if (items[i].x + items[i].columns * column_width == xl) {
                                        xl = items[i].x;                        /* extend to the left */
                                } else {
                                        break;                                  /* break the run */
                                }
                        }
			m_draw.fill_rectangle(
                                                 xl,
                                                 y,
                                                 xr - xl, row_height,
                                                 &bg, BTE_DRAW_OPAQUE);
                }
        }

        if (attr & BTE_ATTR_BLINK) {
                /* Notify the caller that cells with the "blink" attribute were encountered (regardless of
                 * whether they're actually painted or skipped now), so that the caller can set up a timer
                 * to make them blink if it wishes to. */
                m_text_to_blink = true;

                /* This is for the "off" state of blinking text. Invisible text could also be handled here,
                 * but it's not, it's handled outside by not even calling this method.
                 * Setting fg = bg and painting the text would not work for two reasons: it'd be opaque
                 * even if the background is translucent, and this method can be called with a continuous
                 * run of identical fg, yet different bg colored cells. So we simply bail out. */
                if (!m_text_blink_state)
                        return;
        }

        /* Draw whatever SFX are required. Do this before drawing the letters,
         * so that if the descent of a letter crosses an underline of a different color,
         * it's the letter's color that wins. Other kinds of decorations always have the
         * same color as the text, so the order is irrelevant there. */
        if ((attr & (BTE_ATTR_UNDERLINE_MASK |
                     BTE_ATTR_STRIKETHROUGH_MASK |
                     BTE_ATTR_OVERLINE_MASK |
                     BTE_ATTR_BOXED_MASK)) |
            hyperlink | hilite) {
		i = 0;
                while (i < n) {
                        xl = items[i].x;
                        xr = items[i].x + items[i].columns * column_width;
                        columns = items[i].columns;
			y = items[i].y;
                        /* Items are not necessarily contiguous in LTR order.
                         * Combine as long as they form a single visual run. */
                        for (i++; i < n && items[i].y == y; i++) {
                                if (G_LIKELY (items[i].x == xr)) {
                                        xr += items[i].columns * column_width;  /* extend to the right */
                                        columns += items[i].columns;
                                } else if (items[i].x + items[i].columns * column_width == xl) {
                                        xl = items[i].x;                        /* extend to the left */
                                        columns += items[i].columns;
                                } else {
                                        break;                                  /* break the run */
                                }
			}
                        switch (bte_attr_get_value(attr, BTE_ATTR_UNDERLINE_VALUE_MASK, BTE_ATTR_UNDERLINE_SHIFT)) {
                        case 1:
                                m_draw.draw_line(
                                                    xl,
                                                    y + m_underline_position,
                                                    xr - 1,
                                                    y + m_underline_position + m_underline_thickness - 1,
                                                    BTE_LINE_WIDTH,
                                                    &dc, BTE_DRAW_OPAQUE);
                                break;
                        case 2:
                                m_draw.draw_line(
                                                    xl,
                                                    y + m_double_underline_position,
                                                    xr - 1,
                                                    y + m_double_underline_position + m_double_underline_thickness - 1,
                                                    BTE_LINE_WIDTH,
                                                    &dc, BTE_DRAW_OPAQUE);
                                m_draw.draw_line(
                                                    xl,
                                                    y + m_double_underline_position + 2 * m_double_underline_thickness,
                                                    xr - 1,
                                                    y + m_double_underline_position + 3 * m_double_underline_thickness - 1,
                                                    BTE_LINE_WIDTH,
                                                    &dc, BTE_DRAW_OPAQUE);
                                break;
                        case 3:
                                m_draw.draw_undercurl(
                                                         xl,
                                                         y + m_undercurl_position,
                                                         m_undercurl_thickness,
                                                         columns,
                                                         &dc, BTE_DRAW_OPAQUE);
                                break;
			}
			if (attr & BTE_ATTR_STRIKETHROUGH) {
                                m_draw.draw_line(
                                                    xl,
                                                    y + m_strikethrough_position,
                                                    xr - 1,
                                                    y + m_strikethrough_position + m_strikethrough_thickness - 1,
                                                    BTE_LINE_WIDTH,
                                                    &fg, BTE_DRAW_OPAQUE);
			}
                        if (attr & BTE_ATTR_OVERLINE) {
                                m_draw.draw_line(
                                                    xl,
                                                    y + m_overline_position,
                                                    xr - 1,
                                                    y + m_overline_position + m_overline_thickness - 1,
                                                    BTE_LINE_WIDTH,
                                                    &fg, BTE_DRAW_OPAQUE);
                        }
			if (hilite) {
                                m_draw.draw_line(
                                                    xl,
                                                    y + m_regex_underline_position,
                                                    xr - 1,
                                                    y + m_regex_underline_position + m_regex_underline_thickness - 1,
                                                    BTE_LINE_WIDTH,
                                                    &fg, BTE_DRAW_OPAQUE);
                        } else if (hyperlink) {
                                for (double j = 1.0 / 6.0; j < columns; j += 0.5) {
                                        m_draw.fill_rectangle(
                                                                 xl + j * column_width,
                                                                 y + m_regex_underline_position,
                                                                 MAX(column_width / 6.0, 1.0),
                                                                 m_regex_underline_thickness,
                                                                 &fg, BTE_DRAW_OPAQUE);
                                }
                        }
			if (attr & BTE_ATTR_BOXED) {
                                m_draw.draw_rectangle(
                                                         xl,
                                                         y,
                                                         xr - xl,
                                                         row_height,
                                                         &fg, BTE_DRAW_OPAQUE);
			}
                }
	}

        m_draw.draw_text(
                       items, n,
                       attr,
                       &fg, BTE_DRAW_OPAQUE);
}

/* FIXME: we don't have a way to tell CTK+ what the default text attributes
 * should be, so for now at least it's assuming white-on-black is the norm and
 * is using "black-on-white" to signify "inverse".  Pick up on that state and
 * fix things.  Do this here, so that if we suddenly get red-on-black, we'll do
 * the right thing. */
void
Terminal::fudge_pango_colors(GSList *attributes,
                                       BteCell *cells,
                                       gsize n)
{
	gsize i, sumlen = 0;
	struct _fudge_cell_props{
		gboolean saw_fg, saw_bg;
		bte::color::rgb fg, bg;
		guint index;
	}*props = g_newa (struct _fudge_cell_props, n);

	for (i = 0; i < n; i++) {
		gchar ubuf[7];
		gint len = g_unichar_to_utf8 (cells[i].c, ubuf);
		props[i].index = sumlen;
		props[i].saw_fg = props[i].saw_bg = FALSE;
		sumlen += len;
	}

	while (attributes != NULL) {
		PangoAttribute *attr = (PangoAttribute *)attributes->data;
		PangoAttrColor *color;
		switch (attr->klass->type) {
		case PANGO_ATTR_FOREGROUND:
			for (i = 0; i < n; i++) {
				if (props[i].index < attr->start_index) {
					continue;
				}
				if (props[i].index >= attr->end_index) {
					break;
				}
				props[i].saw_fg = TRUE;
				color = (PangoAttrColor*) attr;
				props[i].fg = color->color;
			}
			break;
		case PANGO_ATTR_BACKGROUND:
			for (i = 0; i < n; i++) {
				if (props[i].index < attr->start_index) {
					continue;
				}
				if (props[i].index >= attr->end_index) {
					break;
				}
				props[i].saw_bg = TRUE;
				color = (PangoAttrColor*) attr;
				props[i].bg = color->color;
			}
			break;
		default:
			break;
		}
		attributes = g_slist_next(attributes);
	}

	for (i = 0; i < n; i++) {
		if (props[i].saw_fg && props[i].saw_bg &&
				(props[i].fg.red == 0xffff) &&
				(props[i].fg.green == 0xffff) &&
				(props[i].fg.blue == 0xffff) &&
				(props[i].bg.red == 0) &&
				(props[i].bg.green == 0) &&
				(props[i].bg.blue == 0)) {
                        cells[i].attr.copy_colors(m_color_defaults.attr);
			cells[i].attr.set_reverse(true);
		}
	}
}

/* Apply the attribute given in the PangoAttribute to the list of cells. */
void
Terminal::apply_pango_attr(PangoAttribute *attr,
                                     BteCell *cells,
                                     gsize n_cells)
{
	guint i, ival;
	PangoAttrInt *attrint;
	PangoAttrColor *attrcolor;

	switch (attr->klass->type) {
	case PANGO_ATTR_FOREGROUND:
	case PANGO_ATTR_BACKGROUND:
		attrcolor = (PangoAttrColor*) attr;
                ival = BTE_RGB_COLOR(8, 8, 8,
                                     ((attrcolor->color.red & 0xFF00) >> 8),
                                     ((attrcolor->color.green & 0xFF00) >> 8),
                                     ((attrcolor->color.blue & 0xFF00) >> 8));
		for (i = attr->start_index;
		     i < attr->end_index && i < n_cells;
		     i++) {
			if (attr->klass->type == PANGO_ATTR_FOREGROUND) {
                                cells[i].attr.set_fore(ival);
			}
			if (attr->klass->type == PANGO_ATTR_BACKGROUND) {
                                cells[i].attr.set_back(ival);
			}
		}
		break;
	case PANGO_ATTR_UNDERLINE_COLOR:
		attrcolor = (PangoAttrColor*) attr;
                ival = BTE_RGB_COLOR(4, 5, 4,
                                     ((attrcolor->color.red & 0xFF00) >> 8),
                                     ((attrcolor->color.green & 0xFF00) >> 8),
                                     ((attrcolor->color.blue & 0xFF00) >> 8));
		for (i = attr->start_index;
		     i < attr->end_index && i < n_cells;
		     i++) {
			if (attr->klass->type == PANGO_ATTR_UNDERLINE) {
                                cells[i].attr.set_deco(ival);
			}
		}
		break;
	case PANGO_ATTR_STRIKETHROUGH:
		attrint = (PangoAttrInt*) attr;
		ival = attrint->value;
		for (i = attr->start_index;
		     (i < attr->end_index) && (i < n_cells);
		     i++) {
			cells[i].attr.set_strikethrough(ival != FALSE);
		}
		break;
	case PANGO_ATTR_UNDERLINE:
		attrint = (PangoAttrInt*) attr;
		ival = attrint->value;
		for (i = attr->start_index;
		     (i < attr->end_index) && (i < n_cells);
		     i++) {
                        unsigned int underline = 0;
                        switch (ival) {
                        case PANGO_UNDERLINE_SINGLE:
                                underline = 1;
                                break;
                        case PANGO_UNDERLINE_DOUBLE:
                                underline = 2;
                                break;
                        case PANGO_UNDERLINE_ERROR:
                                underline = 3; /* wavy */
                                break;
                        case PANGO_UNDERLINE_NONE:
                        case PANGO_UNDERLINE_LOW: /* FIXME */
                                underline = 0;
                                break;
                        }
			cells[i].attr.set_underline(underline);
		}
		break;
	case PANGO_ATTR_WEIGHT:
		attrint = (PangoAttrInt*) attr;
		ival = attrint->value;
		for (i = attr->start_index;
		     (i < attr->end_index) && (i < n_cells);
		     i++) {
			cells[i].attr.set_bold(ival >= PANGO_WEIGHT_BOLD);
		}
		break;
	case PANGO_ATTR_STYLE:
		attrint = (PangoAttrInt*) attr;
		ival = attrint->value;
		for (i = attr->start_index;
		     (i < attr->end_index) && (i < n_cells);
		     i++) {
			cells[i].attr.set_italic(ival != PANGO_STYLE_NORMAL);
		}
		break;
	default:
		break;
	}
}

/* Convert a PangoAttrList and a location in that list to settings in a
 * charcell structure.  The cells array is assumed to contain enough items
 * so that all ranges in the attribute list can be mapped into the array, which
 * typically means that the cell array should have the same length as the
 * string (byte-wise) which the attributes describe. */
void
Terminal::translate_pango_cells(PangoAttrList *attrs,
                                          BteCell *cells,
                                          gsize n_cells)
{
	PangoAttribute *attr;
	PangoAttrIterator *attriter;
	GSList *list, *listiter;
	guint i;

	for (i = 0; i < n_cells; i++) {
                cells[i] = m_color_defaults;
	}

	attriter = pango_attr_list_get_iterator(attrs);
	if (attriter != NULL) {
		do {
			list = pango_attr_iterator_get_attrs(attriter);
			if (list != NULL) {
				for (listiter = list;
				     listiter != NULL;
				     listiter = g_slist_next(listiter)) {
					attr = (PangoAttribute *)listiter->data;
					apply_pango_attr(attr, cells, n_cells);
				}
				attr = (PangoAttribute *)list->data;
				fudge_pango_colors(
								 list,
								 cells +
								 attr->start_index,
								 MIN(n_cells, attr->end_index) -
								 attr->start_index);
				g_slist_free_full(list, (GDestroyNotify)pango_attribute_destroy);
			}
		} while (pango_attr_iterator_next(attriter) == TRUE);
		pango_attr_iterator_destroy(attriter);
	}
}

/* Draw the listed items using the given attributes.  Tricky because the
 * attribute string is indexed by byte in the UTF-8 representation of the string
 * of characters.  Because we draw a character at a time, this is slower. */
void
Terminal::draw_cells_with_attributes(bte::view::DrawingContext::TextRequest* items,
                                               gssize n,
                                               PangoAttrList *attrs,
                                               bool draw_default_bg,
                                               gint column_width,
                                               gint height)
{
        int i, j, cell_count;
	BteCell *cells;
	char scratch_buf[BTE_UTF8_BPC];
        guint fore, back, deco;

	/* Note: since this function is only called with the pre-edit text,
	 * all the items contain gunichar only, not bteunistr. */
        // FIXMEchpe is that really true for all input methods?

        uint32_t const attr_mask = m_allow_bold ? ~0 : ~BTE_ATTR_BOLD_MASK;

	for (i = 0, cell_count = 0; i < n; i++) {
		cell_count += g_unichar_to_utf8(items[i].c, scratch_buf);
	}
	cells = g_new(BteCell, cell_count);
	translate_pango_cells(attrs, cells, cell_count);
	for (i = 0, j = 0; i < n; i++) {
                determine_colors(&cells[j], false, &fore, &back, &deco);
		draw_cells(items + i, 1,
					fore,
					back,
                                        deco,
					TRUE, draw_default_bg,
					cells[j].attr.attr & attr_mask,
                                        m_allow_hyperlink && cells[j].attr.hyperlink_idx != 0,
					FALSE, column_width, height);
		j += g_unichar_to_utf8(items[i].c, scratch_buf);
	}
	g_free(cells);
}

void
Terminal::ringview_update()
{
        auto first_row = first_displayed_row();
        auto last_row = last_displayed_row();
        if (cursor_is_onscreen())
                last_row = std::max(last_row, m_screen->cursor.row);

        m_ringview.set_ring (m_screen->row_data);
        m_ringview.set_rows (first_row, last_row - first_row + 1);
        m_ringview.set_width (m_column_count);
        m_ringview.set_enable_bidi (m_enable_bidi);
        m_ringview.set_enable_shaping (m_enable_shaping);
        m_ringview.update ();
}

/* Paint the contents of a given row at the given location.  Take advantage
 * of multiple-draw APIs by finding runs of characters with identical
 * attributes and bundling them together. */
void
Terminal::draw_rows(BteScreen *screen_,
                    cairo_region_t const* region,
                    bte::grid::row_t start_row,
                    bte::grid::row_t end_row,
                    gint start_y, /* must be the start of a row */
                    gint column_width,
                    gint row_height)
{
        bte::grid::row_t row;
        bte::grid::column_t i, j, lcol, vcol;
        int y;
        guint fore = BTE_DEFAULT_FG, nfore, back = BTE_DEFAULT_BG, nback, deco = BTE_DEFAULT_FG, ndeco;
        gboolean hyperlink = FALSE, nhyperlink;  /* non-hovered explicit hyperlink, needs dashed underlining */
        gboolean hilite = FALSE, nhilite;        /* hovered explicit hyperlink or regex match, needs continuous underlining */
        gboolean selected;
        gboolean nrtl = FALSE, rtl;  /* for debugging */
        uint32_t attr = 0, nattr;
	guint item_count;
	const BteCell *cell;
	BteRowData const* row_data;
        bte::base::BidiRow const* bidirow;

        auto const column_count = m_column_count;
        uint32_t const attr_mask = m_allow_bold ? ~0 : ~BTE_ATTR_BOLD_MASK;

        /* Need to ensure the ringview is updated. */
        ringview_update();

        auto items = g_newa(bte::view::DrawingContext::TextRequest, column_count);

        /* Paint the background.
         * Do it first for all the cells we're about to paint, before drawing the glyphs,
         * so that overflowing bits of a glyph (to the right or downwards) won't be
         * chopped off by another cell's background, not even across changes of the
         * background or any other attribute.
         * Process each row independently. */
        int const rect_width = get_allocated_width();

        /* The rect contains the area of the row, and is moved row-wise in the loop. */
        auto rect = cairo_rectangle_int_t{-m_padding.left, start_y, rect_width, row_height};
        for (row = start_row, y = start_y;
             row < end_row;
             row++, y += row_height, rect.y = y /* same as rect.y += row_height */) {
                /* Check whether we need to draw this row at all */
                if (cairo_region_contains_rectangle(region, &rect) == CAIRO_REGION_OVERLAP_OUT)
                        continue;

		row_data = find_row_data(row);
                bidirow = m_ringview.get_bidirow(row);

                _BTE_DEBUG_IF (BTE_DEBUG_BIDI) {
                        /* Debug: Highlight the paddings of RTL rows with a slightly different background. */
                        if (bidirow->base_is_rtl()) {
                                bte::color::rgb bg;
                                rgb_from_index<8, 8, 8>(BTE_DEFAULT_BG, bg);
                                /* Go halfway towards #C0C0C0. */
                                bg.red   = (bg.red   + 0xC000) / 2;
                                bg.green = (bg.green + 0xC000) / 2;
                                bg.blue  = (bg.blue  + 0xC000) / 2;
                                m_draw.fill_rectangle(
                                                          -m_padding.left,
                                                          y,
                                                          m_padding.left,
                                                          row_height,
                                                          &bg, BTE_DRAW_OPAQUE);
                                m_draw.fill_rectangle(
                                                          column_count * column_width,
                                                          y,
                                                          rect_width - m_padding.left - column_count * column_width,
                                                          row_height,
                                                          &bg, BTE_DRAW_OPAQUE);
                        }
                }

                i = j = 0;
                /* Walk the line.
                 * Locate runs of identical bg colors within a row, and paint each run as a single rectangle. */
                do {
                        /* Get the first cell's contents. */
                        cell = row_data ? _bte_row_data_get (row_data, bidirow->vis2log(i)) : nullptr;
                        /* Find the colors for this cell. */
                        selected = cell_is_selected_vis(i, row);
                        determine_colors(cell, selected, &fore, &back, &deco);
                        rtl = bidirow->vis_is_rtl(i);

                        while (++j < column_count) {
                                /* Retrieve the next cell. */
                                cell = row_data ? _bte_row_data_get (row_data, bidirow->vis2log(j)) : nullptr;
                                /* Resolve attributes to colors where possible and
                                 * compare visual attributes to the first character
                                 * in this chunk. */
                                selected = cell_is_selected_vis(j, row);
                                determine_colors(cell, selected, &nfore, &nback, &ndeco);
                                nrtl = bidirow->vis_is_rtl(j);
                                if (nback != back || (_bte_debug_on (BTE_DEBUG_BIDI) && nrtl != rtl)) {
                                        break;
                                }
                        }
                        if (back != BTE_DEFAULT_BG) {
                                bte::color::rgb bg;
                                rgb_from_index<8, 8, 8>(back, bg);
                                m_draw.fill_rectangle(
                                                          i * column_width,
                                                          y,
                                                          (j - i) * column_width,
                                                          row_height,
                                                          &bg, BTE_DRAW_OPAQUE);
                        }

                        _BTE_DEBUG_IF (BTE_DEBUG_BIDI) {
                                /* Debug: Highlight RTL letters and RTL rows with a slightly different background. */
                                bte::color::rgb bg;
                                rgb_from_index<8, 8, 8>(back, bg);
                                /* Go halfway towards #C0C0C0. */
                                bg.red   = (bg.red   + 0xC000) / 2;
                                bg.green = (bg.green + 0xC000) / 2;
                                bg.blue  = (bg.blue  + 0xC000) / 2;
                                int y1 = y + round(row_height / 8.);
                                int y2 = y + row_height - round(row_height / 8.);
                                /* Paint the top and bottom eighth of the cell with this more gray background
                                 * if the paragraph has a resolved RTL base direction. */
                                if (bidirow->base_is_rtl()) {
                                        m_draw.fill_rectangle(
                                                                  i * column_width,
                                                                  y,
                                                                  (j - i) * column_width,
                                                                  y1 - y,
                                                                  &bg, BTE_DRAW_OPAQUE);
                                        m_draw.fill_rectangle(
                                                                  i * column_width,
                                                                  y2,
                                                                  (j - i) * column_width,
                                                                  y + row_height - y2,
                                                                  &bg, BTE_DRAW_OPAQUE);
                                }
                                /* Paint the middle three quarters of the cell with this more gray background
                                 * if the current character has a resolved RTL direction. */
                                if (rtl) {
                                        m_draw.fill_rectangle(
                                                                  i * column_width,
                                                                  y1,
                                                                  (j - i) * column_width,
                                                                  y2 - y1,
                                                                  &bg, BTE_DRAW_OPAQUE);
                                }
                        }

                        /* We'll need to continue at the first cell which didn't
                         * match the first one in this set. */
                        i = j;
                } while (i < column_count);
        }


        /* Render the text.
         * The rect contains the area of the row (enlarged a bit at the top and bottom
         * to allow the text to overdraw a bit), and is moved row-wise in the loop.
         */
        rect = cairo_rectangle_int_t{-m_padding.left,
                                     start_y - cell_overflow_top(),
                                     rect_width,
                                     row_height + cell_overflow_top() + cell_overflow_bottom()};

        for (row = start_row, y = start_y;
             row < end_row;
             row++, y += row_height, rect.y += row_height) {
                /* Check whether we need to draw this row at all */
                if (cairo_region_contains_rectangle(region, &rect) == CAIRO_REGION_OVERLAP_OUT)
                        continue;

                row_data = find_row_data(row);
                if (row_data == NULL)
                        continue; /* Skip row. */

                /* Ensure that drawing is restricted to the cell (plus the overdraw area) */
                _bte_draw_autoclip_t clipper{m_draw, &rect};

                bidirow = m_ringview.get_bidirow(row);

                /* Walk the line in logical order.
                 * Locate runs of identical attributes within a row, and draw each run using a single draw_cells() call. */
                item_count = 0;
                // FIXME No need for the "< column_count" safety cap once bug 135 is addressed.
                for (lcol = 0; lcol < row_data->len && lcol < column_count; ) {
                        vcol = bidirow->log2vis(lcol);

                        /* Get the character cell's contents. */
                        cell = _bte_row_data_get (row_data, lcol);
                        g_assert(cell != nullptr);

                        nhyperlink = (m_allow_hyperlink && cell->attr.hyperlink_idx != 0);
                        nhilite = (nhyperlink && cell->attr.hyperlink_idx == m_hyperlink_hover_idx) ||
                                  (!nhyperlink && regex_match_has_current() && m_match_span.contains(row, lcol));
                        if (cell->c == 0 ||
                                ((cell->c == ' ' || cell->c == '\t') &&  // FIXME '\t' is newly added now, double check
                                 cell->attr.has_none(BTE_ATTR_UNDERLINE_MASK |
                                                     BTE_ATTR_STRIKETHROUGH_MASK |
                                                     BTE_ATTR_OVERLINE_MASK) &&
                                 !nhyperlink &&
                                 !nhilite) ||
                            cell->attr.fragment() ||
                            cell->attr.invisible()) {
                                /* Skip empty or fragment cell. */
                                lcol++;
                                continue;
                        }

                        /* Find the colors for this cell. */
                        nattr = cell->attr.attr;
                        selected = cell_is_selected_log(lcol, row);
                        determine_colors(cell, selected, &nfore, &nback, &ndeco);

                        /* See if it no longer fits the run. */
                        if (item_count > 0 &&
                                   (((attr ^ nattr) & (BTE_ATTR_BOLD_MASK |
                                                       BTE_ATTR_ITALIC_MASK |
                                                       BTE_ATTR_UNDERLINE_MASK |
                                                       BTE_ATTR_STRIKETHROUGH_MASK |
                                                       BTE_ATTR_OVERLINE_MASK |
                                                       BTE_ATTR_BLINK_MASK |
                                                       BTE_ATTR_INVISIBLE_MASK)) ||  // FIXME or just simply "attr != nattr"?
                                    fore != nfore ||
                                    back != nback ||
                                    deco != ndeco ||
                                    hyperlink != nhyperlink ||
                                    hilite != nhilite)) {
                                /* Draw the completed run of cells and start a new one. */
                                draw_cells(items, item_count,
                                           fore, back, deco, FALSE, FALSE,
                                           attr & attr_mask,
                                           hyperlink, hilite,
                                           column_width, row_height);
                                item_count = 0;
                        }

                        /* Combine with subsequent spacing marks. */
                        bteunistr c = cell->c;
                        j = lcol + cell->attr.columns();
                        if (G_UNLIKELY (lcol == 0 && g_unichar_ismark (_bte_unistr_get_base (cell->c)))) {
                                /* A rare special case: the first cell contains a spacing mark.
                                 * Place on top of a NBSP, along with additional spacing marks if any,
                                 * and display beginning at offscreen column -1.
                                 * Additional spacing marks, if any, will be combined by the loop below. */
                                c = _bte_unistr_append_unistr (0x00A0, cell->c);
                                lcol = -1;
                        }
                        // FIXME No need for the "< column_count" safety cap once bug 135 is addressed.
                        while (j < row_data->len && j < column_count) {
                                /* Combine with subsequent spacing marks. */
                                cell = _bte_row_data_get (row_data, j);
                                if (cell && !cell->attr.fragment() && g_unichar_ismark (_bte_unistr_get_base (cell->c))) {
                                        c = _bte_unistr_append_unistr (c, cell->c);
                                        j += cell->attr.columns();
                                } else {
                                        break;
                                }
                        }

                        attr = nattr;
                        fore = nfore;
                        back = nback;
                        deco = ndeco;
                        hyperlink = nhyperlink;
                        hilite = nhilite;

                        g_assert_cmpint (item_count, <, column_count);
                        items[item_count].c = bidirow->vis_get_shaped_char(vcol, c);
                        items[item_count].columns = j - lcol;
                        items[item_count].x = (vcol - (bidirow->vis_is_rtl(vcol) ? items[item_count].columns - 1 : 0)) * column_width;
                        items[item_count].y = y;
                        items[item_count].mirror = bidirow->vis_is_rtl(vcol);
                        items[item_count].box_mirror = !!(row_data->attr.bidi_flags & BTE_BIDI_FLAG_BOX_MIRROR);
                        item_count++;

                        g_assert_cmpint (j, >, lcol);
                        lcol = j;
                }

                /* Draw the last run of cells in the row. */
                if (item_count > 0) {
                        draw_cells(items, item_count,
                                   fore, back, deco, FALSE, FALSE,
                                   attr & attr_mask,
                                   hyperlink, hilite,
                                   column_width, row_height);
                }
        }
}

void
Terminal::paint_cursor()
{
        bte::view::DrawingContext::TextRequest item;
        bte::grid::row_t drow;
        bte::grid::column_t lcol, vcol;
        int width, height, cursor_width;
        guint fore, back, deco;
	bte::color::rgb bg;
	int x, y;
	gboolean blink, selected, focus;

        //FIXMEchpe this should already be reflected in the m_cursor_blink_state below
	if (!m_modes_private.DEC_TEXT_CURSOR())
		return;

        if (m_im_preedit_active)
                return;

	focus = m_has_focus;
	blink = m_cursor_blink_state;

	if (focus && !blink)
		return;

        lcol = m_screen->cursor.col;
        drow = m_screen->cursor.row;
	width = m_cell_width;
	height = m_cell_height;

        if (!cursor_is_onscreen())
                return;
        if (CLAMP(lcol, 0, m_column_count - 1) != lcol)
		return;

        /* Need to ensure the ringview is updated. */
        ringview_update();

        /* Find the first cell of the character "under" the cursor.
         * This is for CJK.  For TAB, paint the cursor where it really is. */
        BteRowData const *row_data = find_row_data(drow);
        bte::base::BidiRow const *bidirow = m_ringview.get_bidirow(drow);

        auto cell = find_charcell(lcol, drow);
        while (cell != NULL && cell->attr.fragment() && cell->c != '\t' && lcol > 0) {
                lcol--;
                cell = find_charcell(lcol, drow);
	}

	/* Draw the cursor. */
        vcol = bidirow->log2vis(lcol);
        item.c = (cell && cell->c) ? bidirow->vis_get_shaped_char(vcol, cell->c) : ' ';
	item.columns = item.c == '\t' ? 1 : cell ? cell->attr.columns() : 1;
        item.x = (vcol - ((cell && bidirow->vis_is_rtl(vcol)) ? cell->attr.columns() - 1 : 0)) * width;
	item.y = row_to_pixel(drow);
        item.mirror = bidirow->vis_is_rtl(vcol);
        item.box_mirror = (row_data && (row_data->attr.bidi_flags & BTE_BIDI_FLAG_BOX_MIRROR));
        auto const attr = cell && cell->c ? cell->attr.attr : 0;

        selected = cell_is_selected_log(lcol, drow);
        determine_cursor_colors(cell, selected, &fore, &back, &deco);
        rgb_from_index<8, 8, 8>(back, bg);

	x = item.x;
	y = item.y;

        switch (decscusr_cursor_shape()) {

		case CursorShape::eIBEAM: {
                        /* Draw at the very left of the cell (before the spacing), even in case of CJK.
                         * IMO (egmont) not overrunning the letter improves readability, vertical movement
                         * looks good (no zigzag even when a somewhat wider glyph that starts filling up
                         * the left spacing, or CJK that begins further to the right is encountered),
                         * and also this is where it looks good if background colors change, including
                         * Shift+arrows highlighting experience in some editors. As per the behavior of
                         * word processors, don't increase the height by the line spacing. */
                        int stem_width;

                        stem_width = (int) (((float) (m_char_ascent + m_char_descent)) * m_cursor_aspect_ratio + 0.5);
                        stem_width = CLAMP (stem_width, BTE_LINE_WIDTH, m_cell_width);

                        /* The I-beam goes to the right edge of the cell if its character has RTL resolved direction. */
                        if (bidirow->vis_is_rtl(vcol))
                                x += item.columns * m_cell_width - stem_width;

                        m_draw.fill_rectangle(
                                                 x, y + m_char_padding.top, stem_width, m_char_ascent + m_char_descent,
                                                 &bg, BTE_DRAW_OPAQUE);

                        /* Show the direction of the current character if the paragraph contains a mixture
                         * of directions.
                         * FIXME Do this for the other cursor shapes, too. Need to find a good visual design. */
                        if (focus && bidirow->has_foreign())
                                m_draw.fill_rectangle(
                                                         bidirow->vis_is_rtl(vcol) ? x - stem_width : x + stem_width,
                                                         y + m_char_padding.top,
                                                         stem_width, stem_width,
                                                         &bg, BTE_DRAW_OPAQUE);
			break;
                }

		case CursorShape::eUNDERLINE: {
                        /* The width is at least the overall width of the cell (or two cells) minus the two
                         * half spacings on the two edges. That is, underlines under a CJK are more than twice
                         * as wide as narrow characters in case of letter spacing. Plus, if necessary, the width
                         * is increased to span under the entire glyph. Vertical position is not affected by
                         * line spacing. */

                        int line_height, left, right;

			/* use height (not width) so underline and ibeam will
			 * be equally visible */
                        line_height = (int) (((float) (m_char_ascent + m_char_descent)) * m_cursor_aspect_ratio + 0.5);
                        line_height = CLAMP (line_height, BTE_LINE_WIDTH, m_char_ascent + m_char_descent);

                        left = m_char_padding.left;
                        right = item.columns * m_cell_width - m_char_padding.right;

                        if (cell && cell->c != 0 && cell->c != ' ' && cell->c != '\t') {
                                int l, r;
                                m_draw.get_char_edges(cell->c, cell->attr.columns(), attr, l, r);
                                left = MIN(left, l);
                                right = MAX(right, r);
                        }

                        m_draw.fill_rectangle(
                                                 x + left, y + m_cell_height - m_char_padding.bottom - line_height,
                                                 right - left, line_height,
                                                 &bg, BTE_DRAW_OPAQUE);
			break;
                }

		case CursorShape::eBLOCK:
                        /* Include the spacings in the cursor, see bug 781479 comments 39-44.
                         * Make the cursor even wider if the glyph is wider. */

                        cursor_width = item.columns * width;
                        if (cell && cell->c != 0 && cell->c != ' ' && cell->c != '\t') {
                                int l, r;
                                m_draw.get_char_edges(cell->c, cell->attr.columns(), attr, l /* unused */, r);
                                cursor_width = MAX(cursor_width, r);
			}

                        uint32_t const attr_mask = m_allow_bold ? ~0 : ~BTE_ATTR_BOLD_MASK;

			if (focus) {
				/* just reverse the character under the cursor */
                                m_draw.fill_rectangle(
							     x, y,
                                                         cursor_width, height,
                                                         &bg, BTE_DRAW_OPAQUE);

                                if (cell && cell->c != 0 && cell->c != ' ' && cell->c != '\t') {
                                        draw_cells(
                                                        &item, 1,
                                                        fore, back, deco, TRUE, FALSE,
                                                        cell->attr.attr & attr_mask,
                                                        m_allow_hyperlink && cell->attr.hyperlink_idx != 0,
                                                        FALSE,
                                                        width,
                                                        height);
				}

			} else {
				/* draw a box around the character */
                                m_draw.draw_rectangle(
							     x - BTE_LINE_WIDTH,
							     y - BTE_LINE_WIDTH,
							     cursor_width + 2*BTE_LINE_WIDTH,
                                                         height + 2*BTE_LINE_WIDTH,
                                                         &bg, BTE_DRAW_OPAQUE);
			}

			break;
	}
}

void
Terminal::paint_im_preedit_string()
{
        int vcol, columns;
        long row;
	long width, height;
	int i, len;

	if (m_im_preedit.empty())
		return;

        /* Need to ensure the ringview is updated. */
        ringview_update();

        /* Get the row's BiDi information. */
        row = m_screen->cursor.row;
        if (row < first_displayed_row() || row > last_displayed_row())
                return;
        bte::base::BidiRow const *bidirow = m_ringview.get_bidirow(row);

	/* Keep local copies of rendering information. */
	width = m_cell_width;
	height = m_cell_height;

	/* Find out how many columns the pre-edit string takes up. */
	columns = get_preedit_width(false);
	len = get_preedit_length(false);

	/* If the pre-edit string won't fit on the screen if we start
	 * drawing it at the cursor's position, move it left. */
        vcol = bidirow->log2vis(m_screen->cursor.col);
        if (vcol + columns > m_column_count) {
                vcol = MAX(0, m_column_count - columns);
	}

	/* Draw the preedit string, boxed. */
	if (len > 0) {
		const char *preedit = m_im_preedit.c_str();
		int preedit_cursor;

                auto items = g_new0(bte::view::DrawingContext::TextRequest, len);
		for (i = columns = 0; i < len; i++) {
			items[i].c = g_utf8_get_char(preedit);
                        items[i].columns = _bte_unichar_width(items[i].c,
                                                              m_utf8_ambiguous_width);
                        items[i].x = (vcol + columns) * width;
			items[i].y = row_to_pixel(m_screen->cursor.row);
			columns += items[i].columns;
			preedit = g_utf8_next_char(preedit);
		}
                if (G_LIKELY(m_clear_background)) {
                        m_draw.clear(
                                        vcol * width,
                                        row_to_pixel(m_screen->cursor.row),
                                        width * columns,
                                        height,
                                        get_color(BTE_DEFAULT_BG), m_background_alpha);
                }
		draw_cells_with_attributes(
							items, len,
							m_im_preedit_attrs.get(),
							TRUE,
							width, height);
		preedit_cursor = m_im_preedit_cursor;

		if (preedit_cursor >= 0 && preedit_cursor < len) {
                        uint32_t fore, back, deco;
                        bte_color_triple_get(m_color_defaults.attr.colors(), &fore, &back, &deco);

			/* Cursored letter in reverse. */
			draw_cells(
						&items[preedit_cursor], 1,
                                                fore, back, deco,
                                                TRUE,  /* clear */
                                                TRUE,  /* draw_default_bg */
                                                BTE_ATTR_NONE | BTE_ATTR_BOXED,
                                                FALSE, /* hyperlink */
                                                FALSE, /* hilite */
						width, height);
		}
		g_free(items);
	}
}

void
Terminal::widget_draw(cairo_t *cr)
{
        cairo_rectangle_int_t clip_rect;
        cairo_region_t *region;
        int allocated_width, allocated_height;
        int extra_area_for_cursor;
        bool text_blink_enabled_now;
        gint64 now = 0;

        if (!cdk_cairo_get_clip_rectangle (cr, &clip_rect))
                return;

        _bte_debug_print(BTE_DEBUG_LIFECYCLE, "bte_terminal_draw()\n");
        _bte_debug_print (BTE_DEBUG_WORK, "+");
        _bte_debug_print (BTE_DEBUG_UPDATES, "Draw (%d,%d)x(%d,%d)\n",
                          clip_rect.x, clip_rect.y,
                          clip_rect.width, clip_rect.height);

        region = bte_cairo_get_clip_region (cr);
        if (region == NULL)
                return;

        allocated_width = get_allocated_width();
        allocated_height = get_allocated_height();

	/* Designate the start of the drawing operation and clear the area. */
	m_draw.set_cairo(cr);

        if (G_LIKELY(m_clear_background)) {
                m_draw.clear(0, 0,
                                 allocated_width, allocated_height,
                                 get_color(BTE_DEFAULT_BG), m_background_alpha);
        }

        /* Clip vertically, for the sake of smooth scrolling. We want the top and bottom paddings to be unused.
         * Don't clip horizontally so that antialiasing can legally overflow to the right padding. */
        cairo_save(cr);
        cairo_rectangle(cr, 0, m_padding.top, allocated_width, allocated_height - m_padding.top - m_padding.bottom);
        cairo_clip(cr);

        cairo_translate(cr, m_padding.left, m_padding.top);

        /* Transform to view coordinates */
        cairo_region_translate(region, -m_padding.left, -m_padding.top);

        /* Whether blinking text should be visible now */
        m_text_blink_state = true;
        text_blink_enabled_now = (unsigned)m_text_blink_mode & (unsigned)(m_has_focus ? TextBlinkMode::eFOCUSED : TextBlinkMode::eUNFOCUSED);
        if (text_blink_enabled_now) {
                now = g_get_monotonic_time() / 1000;
                if (now % (m_text_blink_cycle * 2) >= m_text_blink_cycle)
                        m_text_blink_state = false;
        }
        /* Painting will flip this if it encounters any cell with blink attribute */
        m_text_to_blink = false;

        /* and now paint them */
        auto const first_row = first_displayed_row();
        draw_rows(m_screen,
                  region,
                  first_row,
                  last_displayed_row() + 1,
                  row_to_pixel(first_row),
                  m_cell_width,
                  m_cell_height);

	paint_im_preedit_string();

        cairo_restore(cr);

        /* Re-clip, allowing BTE_LINE_WIDTH more pixel rows for the outline cursor. */
        /* TODOegmont: It's really ugly to do it here. */
        cairo_save(cr);
        extra_area_for_cursor = (decscusr_cursor_shape() == CursorShape::eBLOCK && !m_has_focus) ? BTE_LINE_WIDTH : 0;
        cairo_rectangle(cr, 0, m_padding.top - extra_area_for_cursor, allocated_width, allocated_height - m_padding.top - m_padding.bottom + 2 * extra_area_for_cursor);
        cairo_clip(cr);

        cairo_translate(cr, m_padding.left, m_padding.top);

	paint_cursor();

	cairo_restore(cr);

	/* Done with various structures. */
	m_draw.set_cairo(nullptr);

        cairo_region_destroy (region);

        /* If painting encountered any cell with blink attribute, we might need to set up a timer.
         * Blinking is implemented using a one-shot (not repeating) timer that keeps getting reinstalled
         * here as long as blinking cells are encountered during (re)painting. This way there's no need
         * for an explicit step to stop the timer when blinking cells are no longer present, this happens
         * implicitly by the timer not getting reinstalled anymore (often after a final unnecessary but
         * harmless repaint). */
        if (G_UNLIKELY (m_text_to_blink && text_blink_enabled_now && !m_text_blink_timer))
                m_text_blink_timer.schedule(m_text_blink_cycle - now % m_text_blink_cycle,
                                            bte::glib::Timer::Priority::eLOW);

        m_invalidated_all = FALSE;
}

/* Handle an expose event by painting the exposed area. */
static cairo_region_t *
bte_cairo_get_clip_region (cairo_t *cr)
{
        cairo_rectangle_list_t *list;
        cairo_region_t *region;
        int i;

        list = cairo_copy_clip_rectangle_list (cr);
        if (list->status == CAIRO_STATUS_CLIP_NOT_REPRESENTABLE) {
                cairo_rectangle_int_t clip_rect;

                cairo_rectangle_list_destroy (list);

                if (!cdk_cairo_get_clip_rectangle (cr, &clip_rect))
                        return NULL;
                return cairo_region_create_rectangle (&clip_rect);
        }


        region = cairo_region_create ();
        for (i = list->num_rectangles - 1; i >= 0; --i) {
                cairo_rectangle_t *rect = &list->rectangles[i];
                cairo_rectangle_int_t clip_rect;

                clip_rect.x = floor (rect->x);
                clip_rect.y = floor (rect->y);
                clip_rect.width = ceil (rect->x + rect->width) - clip_rect.x;
                clip_rect.height = ceil (rect->y + rect->height) - clip_rect.y;

                if (cairo_region_union_rectangle (region, &clip_rect) != CAIRO_STATUS_SUCCESS) {
                        cairo_region_destroy (region);
                        region = NULL;
                        break;
                }
        }

        cairo_rectangle_list_destroy (list);
        return region;
}

bool
Terminal::widget_mouse_scroll(MouseEvent const& event)
{
	gdouble v;
	gint cnt, i;
	int button;

        /* Need to ensure the ringview is updated. */
        ringview_update();

        auto rowcol = confined_grid_coords_from_event(event);

        m_modifiers = event.modifiers();

        switch (event.scroll_direction()) {
        case MouseEvent::ScrollDirection::eUP:
		m_mouse_smooth_scroll_delta -= 1.;
		_bte_debug_print(BTE_DEBUG_EVENTS, "Scroll up\n");
		break;
        case MouseEvent::ScrollDirection::eDOWN:
		m_mouse_smooth_scroll_delta += 1.;
		_bte_debug_print(BTE_DEBUG_EVENTS, "Scroll down\n");
		break;
        case MouseEvent::ScrollDirection::eSMOOTH: {
                auto const delta_y = event.scroll_delta_y();
		m_mouse_smooth_scroll_delta += delta_y;
		_bte_debug_print(BTE_DEBUG_EVENTS,
				"Smooth scroll by %f, delta now at %f\n",
				delta_y, m_mouse_smooth_scroll_delta);
		break;
        }
	default:
		break;
	}

	/* If we're running a mouse-aware application, map the scroll event
	 * to a button press on buttons four and five. */
	if (m_mouse_tracking_mode != MouseTrackingMode::eNONE) {
		cnt = m_mouse_smooth_scroll_delta;
		if (cnt == 0)
			return true;
		m_mouse_smooth_scroll_delta -= cnt;
		_bte_debug_print(BTE_DEBUG_EVENTS,
				"Scroll application by %d lines, smooth scroll delta set back to %f\n",
				cnt, m_mouse_smooth_scroll_delta);

		button = cnt > 0 ? 5 : 4;
		if (cnt < 0)
			cnt = -cnt;
		for (i = 0; i < cnt; i++) {
			/* Encode the parameters and send them to the app. */
                        feed_mouse_event(rowcol,
                                         button,
                                         false /* not drag */,
                                         false /* not release */);
		}
		return true;
	}

        v = MAX (1., ceil (ctk_adjustment_get_page_increment (m_vadjustment.get()) / 10.));
	_bte_debug_print(BTE_DEBUG_EVENTS,
			"Scroll speed is %d lines per non-smooth scroll unit\n",
			(int) v);
	if (m_screen == &m_alternate_screen &&
            m_modes_private.XTERM_ALTBUF_SCROLL()) {
		char *normal;
		gsize normal_length;

		cnt = v * m_mouse_smooth_scroll_delta;
		if (cnt == 0)
			return true;
		m_mouse_smooth_scroll_delta -= cnt / v;
		_bte_debug_print(BTE_DEBUG_EVENTS,
				"Scroll by %d lines, smooth scroll delta set back to %f\n",
				cnt, m_mouse_smooth_scroll_delta);

		/* In the alternate screen there is no scrolling,
		 * so fake a few cursor keystrokes. */

		_bte_keymap_map (
				cnt > 0 ? CDK_KEY_Down : CDK_KEY_Up,
				m_modifiers,
                                m_modes_private.DEC_APPLICATION_CURSOR_KEYS(),
                                m_modes_private.DEC_APPLICATION_KEYPAD(),
				&normal,
				&normal_length);
		if (cnt < 0)
			cnt = -cnt;
		for (i = 0; i < cnt; i++) {
			send_child({normal, normal_length});
		}
		g_free (normal);

                return true;
	} else {
		/* Perform a history scroll. */
		double dcnt = m_screen->scroll_delta + v * m_mouse_smooth_scroll_delta;
		queue_adjustment_value_changed_clamped(dcnt);
		m_mouse_smooth_scroll_delta = 0;

                return true;
	}

        return true;
}

bool
Terminal::set_audible_bell(bool setting)
{
        if (setting == m_audible_bell)
                return false;

	m_audible_bell = setting;
        return true;
}

bool
Terminal::set_text_blink_mode(TextBlinkMode setting)
{
        if (setting == m_text_blink_mode)
                return false;

        m_text_blink_mode = setting;
        invalidate_all();

        return true;
}

bool
Terminal::set_enable_bidi(bool setting)
{
        if (setting == m_enable_bidi)
                return false;

        m_enable_bidi = setting;
        m_ringview.invalidate();
        invalidate_all();

        /* Chances are that we can free up some BiDi/shaping buffers that we
         * won't need for a while. */
        if (!setting)
                m_ringview.pause();

        return true;
}

bool
Terminal::set_enable_shaping(bool setting)
{
        if (setting == m_enable_shaping)
                return false;

        m_enable_shaping = setting;
        m_ringview.invalidate();
        invalidate_all();

        /* Chances are that we can free up some BiDi/shaping buffers that we
         * won't need for a while. */
        if (!setting)
                m_ringview.pause();

        return true;
}

bool
Terminal::set_allow_bold(bool setting)
{
        if (setting == m_allow_bold)
                return false;

	m_allow_bold = setting;
	invalidate_all();

        return true;
}

bool
Terminal::set_bold_is_bright(bool setting)
{
        if (setting == m_bold_is_bright)
                return false;

	m_bold_is_bright = setting;
	invalidate_all();

        return true;
}

bool
Terminal::set_allow_hyperlink(bool setting)
{
        if (setting == m_allow_hyperlink)
                return false;

        if (setting == false) {
                m_hyperlink_hover_idx = _bte_ring_get_hyperlink_at_position(m_screen->row_data, -1, -1, true, NULL);
                g_assert (m_hyperlink_hover_idx == 0);
                m_hyperlink_hover_uri = NULL;
                emit_hyperlink_hover_uri_changed(NULL);  /* FIXME only emit if really changed */
                m_defaults.attr.hyperlink_idx = _bte_ring_get_hyperlink_idx(m_screen->row_data, NULL);
                g_assert (m_defaults.attr.hyperlink_idx == 0);
        }

        m_allow_hyperlink = setting;
        invalidate_all();

        return true;
}

bool
Terminal::set_scroll_on_output(bool scroll)
{
        if (scroll == m_scroll_on_output)
                return false;

        m_scroll_on_output = scroll;
        return true;
}

bool
Terminal::set_scroll_on_keystroke(bool scroll)
{
        if (scroll == m_scroll_on_keystroke)
                return false;

        m_scroll_on_keystroke = scroll;
        return true;
}

bool
Terminal::set_rewrap_on_resize(bool rewrap)
{
        if (rewrap == m_rewrap_on_resize)
                return false;

        m_rewrap_on_resize = rewrap;
        return true;
}

void
Terminal::update_cursor_blinks()
{
        bool blink = false;

        switch (decscusr_cursor_blink()) {
        case CursorBlinkMode::eSYSTEM:
                gboolean v;
                g_object_get(ctk_widget_get_settings(m_widget),
                                                     "ctk-cursor-blink",
                                                     &v, nullptr);
                blink = v != FALSE;
                break;
        case CursorBlinkMode::eON:
                blink = true;
                break;
        case CursorBlinkMode::eOFF:
                blink = false;
                break;
        }

	if (m_cursor_blinks == blink)
		return;

	m_cursor_blinks = blink;
	check_cursor_blink();
}

bool
Terminal::set_cursor_blink_mode(CursorBlinkMode mode)
{
        if (mode == m_cursor_blink_mode)
                return false;

        m_cursor_blink_mode = mode;
        update_cursor_blinks();

        return true;
}

bool
Terminal::set_cursor_shape(CursorShape shape)
{
        if (shape == m_cursor_shape)
                return false;

        m_cursor_shape = shape;
	invalidate_cursor_once();

        return true;
}

/* DECSCUSR set cursor style */
bool
Terminal::set_cursor_style(CursorStyle style)
{
        if (m_cursor_style == style)
                return false;

        m_cursor_style = style;
        update_cursor_blinks();
        /* and this will also make cursor shape match the DECSCUSR style */
        invalidate_cursor_once();

        return true;
}

/*
 * Terminal::decscusr_cursor_blink:
 *
 * Returns the cursor blink mode set by DECSCUSR. If DECSCUSR was never
 * called, or it set the blink mode to terminal default, this returns the
 * value set via API or in dconf. Internal use only.
 *
 * Return value: cursor blink mode
 */
Terminal::CursorBlinkMode
Terminal::decscusr_cursor_blink() const noexcept
{
        switch (m_cursor_style) {
        default:
        case CursorStyle::eTERMINAL_DEFAULT:
                return m_cursor_blink_mode;
        case CursorStyle::eBLINK_BLOCK:
        case CursorStyle::eBLINK_UNDERLINE:
        case CursorStyle::eBLINK_IBEAM:
                return CursorBlinkMode::eON;
        case CursorStyle::eSTEADY_BLOCK:
        case CursorStyle::eSTEADY_UNDERLINE:
        case CursorStyle::eSTEADY_IBEAM:
                return CursorBlinkMode::eOFF;
        }
}

/*
 * Terminal::decscusr_cursor_shape:
 * @terminal: a #BteTerminal
 *
 * Returns the cursor shape set by DECSCUSR. If DECSCUSR was never called,
 * or it set the cursor shape to terminal default, this returns the value
 * set via API. Internal use only.
 *
 * Return value: cursor shape
 */
Terminal::CursorShape
Terminal::decscusr_cursor_shape() const noexcept
{
        switch (m_cursor_style) {
        default:
        case CursorStyle::eTERMINAL_DEFAULT:
                return m_cursor_shape;
        case CursorStyle::eBLINK_BLOCK:
        case CursorStyle::eSTEADY_BLOCK:
                return CursorShape::eBLOCK;
        case CursorStyle::eBLINK_UNDERLINE:
        case CursorStyle::eSTEADY_UNDERLINE:
                return CursorShape::eUNDERLINE;
        case CursorStyle::eBLINK_IBEAM:
        case CursorStyle::eSTEADY_IBEAM:
                return CursorShape::eIBEAM;
        }
}

bool
Terminal::set_scrollback_lines(long lines)
{
        glong low, high, next;
        double scroll_delta;
	BteScreen *scrn;

	if (lines < 0)
		lines = G_MAXLONG;

#if 0
        /* FIXME: this breaks the scrollbar range, bug #562511 */
        if (lines == m_scrollback_lines)
                return false;
#endif

	_bte_debug_print (BTE_DEBUG_MISC,
			"Setting scrollback lines to %ld\n", lines);

	m_scrollback_lines = lines;

        /* The main screen gets the full scrollback buffer. */
        scrn = &m_normal_screen;
        lines = MAX (lines, m_row_count);
        next = MAX (m_screen->cursor.row + 1,
                    _bte_ring_next (scrn->row_data));
        _bte_ring_resize (scrn->row_data, lines);
        low = _bte_ring_delta (scrn->row_data);
        high = lines + MIN (G_MAXLONG - lines, low - m_row_count + 1);
        scrn->insert_delta = CLAMP (scrn->insert_delta, low, high);
        scrn->scroll_delta = CLAMP (scrn->scroll_delta, low, scrn->insert_delta);
        next = MIN (next, scrn->insert_delta + m_row_count);
        if (_bte_ring_next (scrn->row_data) > next){
                _bte_ring_shrink (scrn->row_data, next - low);
        }

        /* The alternate scrn isn't allowed to scroll at all. */
        scrn = &m_alternate_screen;
        _bte_ring_resize (scrn->row_data, m_row_count);
        scrn->scroll_delta = _bte_ring_delta (scrn->row_data);
        scrn->insert_delta = _bte_ring_delta (scrn->row_data);
        if (_bte_ring_next (scrn->row_data) > scrn->insert_delta + m_row_count){
                _bte_ring_shrink (scrn->row_data, m_row_count);
        }

	/* Adjust the scrollbar to the new location. */
	/* Hack: force a change in scroll_delta even if the value remains, so that
	   bte_term_q_adj_val_changed() doesn't shortcut to no-op, see bug 676075. */
        scroll_delta = m_screen->scroll_delta;
	m_screen->scroll_delta = -1;
	queue_adjustment_value_changed(scroll_delta);
	adjust_adjustments_full();

        return true;
}

bool
Terminal::set_backspace_binding(EraseMode binding)
{
        if (binding == m_backspace_binding)
                return false;

	m_backspace_binding = binding;
        return true;
}

bool
Terminal::set_delete_binding(EraseMode binding)
{
        if (binding == m_delete_binding)
                return false;

	m_delete_binding = binding;
        return true;
}

bool
Terminal::set_mouse_autohide(bool autohide)
{
        if (autohide == m_mouse_autohide)
                return false;

	m_mouse_autohide = autohide;

        if (m_mouse_cursor_autohidden) {
                hyperlink_hilite_update();
                match_hilite_update();
                apply_mouse_cursor();
        }
        return true;
}

void
Terminal::reset_decoder()
{
        switch (data_syntax()) {
        case DataSyntax::eECMA48_UTF8:
                m_utf8_decoder.reset();
                break;

#ifdef WITH_ICU
        case DataSyntax::eECMA48_PCTERM:
                m_converter->decoder().reset();
                break;
#endif

        default:
                g_assert_not_reached();
        }
}

/*
 * Terminal::reset:
 * @clear_tabstops: whether to reset tabstops
 * @clear_history: whether to empty the terminal's scrollback buffer
 *
 * Resets as much of the terminal's internal state as possible, discarding any
 * unprocessed input data, resetting character attributes, cursor state,
 * national character set state, status line, terminal modes (insert/delete),
 * selection state, and encoding.
 *
 */
void
Terminal::reset(bool clear_tabstops,
                          bool clear_history,
                          bool from_api)
{
        if (from_api && !m_input_enabled)
                return;

        auto const freezer = bte::glib::FreezeObjectNotify{m_terminal};

        m_bell_pending = false;

	/* Clear the output buffer. */
	_bte_byte_array_clear(m_outgoing);

	/* Reset charset substitution state. */

        /* Reset decoder */
        reset_decoder();

        /* Reset parser */
        m_parser.reset();
        m_last_graphic_character = 0;

        /* Reset modes */
        m_modes_ecma.reset();
        m_modes_private.clear_saved();
        m_modes_private.reset();

        /* Reset tabstops */
        if (clear_tabstops) {
                m_tabstops.reset();
        }

        /* Window title stack */
        if (clear_history) {
                m_window_title_stack.clear();
        }

        update_mouse_protocol();

	/* Reset the color palette. Only the 256 indexed colors, not the special ones, as per xterm. */
	for (int i = 0; i < 256; i++)
		m_palette[i].sources[BTE_COLOR_SOURCE_ESCAPE].is_set = FALSE;
	/* Reset the default attributes.  Reset the alternate attribute because
	 * it's not a real attribute, but we need to treat it as one here. */
        reset_default_attributes(true);
        /* Reset charset modes. */
        m_character_replacements[0] = BTE_CHARACTER_REPLACEMENT_NONE;
        m_character_replacements[1] = BTE_CHARACTER_REPLACEMENT_NONE;
        m_character_replacement = &m_character_replacements[0];
	/* Clear the scrollback buffers and reset the cursors. Switch to normal screen. */
	if (clear_history) {
                m_screen = &m_normal_screen;
                m_normal_screen.scroll_delta = m_normal_screen.insert_delta =
                        _bte_ring_reset(m_normal_screen.row_data);
                m_normal_screen.cursor.row = m_normal_screen.insert_delta;
                m_normal_screen.cursor.col = 0;
                m_alternate_screen.scroll_delta = m_alternate_screen.insert_delta =
                        _bte_ring_reset(m_alternate_screen.row_data);
                m_alternate_screen.cursor.row = m_alternate_screen.insert_delta;
                m_alternate_screen.cursor.col = 0;
                /* Adjust the scrollbar to the new location. */
                /* Hack: force a change in scroll_delta even if the value remains, so that
                   bte_term_q_adj_val_changed() doesn't shortcut to no-op, see bug 730599. */
                m_screen->scroll_delta = -1;
                queue_adjustment_value_changed(m_screen->insert_delta);
		adjust_adjustments_full();
	}
        /* DECSCUSR cursor style */
        set_cursor_style(CursorStyle::eTERMINAL_DEFAULT);
	/* Reset restricted scrolling regions, leave insert mode, make
	 * the cursor visible again. */
        m_scrolling_restricted = FALSE;
        /* Reset the visual bits of selection on hard reset, see bug 789954. */
        if (clear_history) {
                deselect_all();
                stop_autoscroll();  /* Required before setting m_selecting to false, see #105. */
                m_selecting = FALSE;
                m_selecting_had_delta = FALSE;
                m_selection_origin = m_selection_last = { -1, -1, 1 };
                m_selection_resolved.clear();
        }

	/* Reset mouse motion events. */
        m_mouse_pressed_buttons = 0;
        m_mouse_handled_buttons = 0;
	m_mouse_last_position = bte::view::coords(-1, -1);
	m_mouse_smooth_scroll_delta = 0.;
	/* Clear modifiers. */
	m_modifiers = 0;
        /* Reset the saved cursor. */
        save_cursor(&m_normal_screen);
        save_cursor(&m_alternate_screen);
        /* BiDi */
        m_bidi_rtl = FALSE;
	/* Cause everything to be redrawn (or cleared). */
	invalidate_all();

        /* Reset XTerm window controls */
        m_xterm_wm_iconified = false;
}

void
Terminal::unset_pty(bool notify_widget)
{
        /* This may be called from inside or from widget,
         * and must notify the widget if not called from it.
         */

        disconnect_pty_read();
        disconnect_pty_write();

        m_child_exited_eos_wait_timer.abort();

        /* Clear incoming and outgoing queues */
        m_input_bytes = 0;
        m_incoming_queue = {};
        _bte_byte_array_clear(m_outgoing);

        stop_processing(this); // FIXMEchpe only if m_incoming_queue.empty() !!!

        reset_decoder();

        m_pty.reset();

        if (notify_widget && widget())
                widget()->unset_pty();
}

bool
Terminal::set_pty(bte::base::Pty *new_pty)
{
        if (pty().get() == new_pty)
                return false;

        if (pty()) {
                unset_pty(false /* don't notify widget */);
        }

        m_pty = bte::base::make_ref(new_pty);
        if (!new_pty)
                return true;

        set_size(m_column_count, m_row_count);

        if (!pty()->set_utf8(data_syntax() == DataSyntax::eECMA48_UTF8)) {
                // nothing we can do here
        }

        /* Open channels to listen for input on. */
        connect_pty_read();

        return true;
}

bool
Terminal::terminate_child() noexcept
{
	if (m_pty_pid == -1)
                return false;

        auto pgrp = getpgid(m_pty_pid);
        if (pgrp != -1 && pgrp != getpgid(getpid())) {
                kill(-pgrp, SIGHUP);
        }

        kill(m_pty_pid, SIGHUP);
        m_pty_pid = -1;

        return true;
}

/* We need this bit of glue to ensure that accessible objects will always
 * get signals. */
void
Terminal::subscribe_accessible_events()
{
#ifdef WITH_A11Y
	m_accessible_emit = true;
#endif
}

void
Terminal::select_text(bte::grid::column_t start_col,
                                bte::grid::row_t start_row,
                                bte::grid::column_t end_col,
                                bte::grid::row_t end_row)
{
	deselect_all();

	m_selection_type = SelectionType::eCHAR;
	m_selecting_had_delta = true;
        m_selection_resolved.set ({ start_row, start_col },
                                  { end_row, end_col });
        widget_copy(BTE_SELECTION_PRIMARY, BTE_FORMAT_TEXT);
	emit_selection_changed();

        invalidate_rows(start_row, end_row);
}

void
Terminal::select_empty(bte::grid::column_t col,
                                 bte::grid::row_t row)
{
        select_text(col, row, col, row);
}

static void
remove_process_timeout_source(void)
{
	if (process_timeout_tag == 0)
                return;

        _bte_debug_print(BTE_DEBUG_TIMEOUT, "Removing process timeout\n");
        g_source_remove (process_timeout_tag);
        process_timeout_tag = 0;
}

static void
add_update_timeout(bte::terminal::Terminal* that)
{
	if (update_timeout_tag == 0) {
		_bte_debug_print (BTE_DEBUG_TIMEOUT,
				"Starting update timeout\n");
		update_timeout_tag =
			g_timeout_add_full (CDK_PRIORITY_REDRAW,
					BTE_UPDATE_TIMEOUT,
					update_timeout, NULL,
					NULL);
	}
	if (!in_process_timeout) {
                remove_process_timeout_source();
        }
	if (that->m_active_terminals_link == nullptr) {
		_bte_debug_print (BTE_DEBUG_TIMEOUT,
				"Adding terminal to active list\n");
		that->m_active_terminals_link = g_active_terminals =
			g_list_prepend(g_active_terminals, that);
	}
}

void
Terminal::reset_update_rects()
{
        g_array_set_size(m_update_rects, 0);
	m_invalidated_all = FALSE;
}

static bool
remove_from_active_list(bte::terminal::Terminal* that)
{
	if (that->m_active_terminals_link == nullptr ||
            that->m_update_rects->len != 0)
                return false;

        _bte_debug_print(BTE_DEBUG_TIMEOUT, "Removing terminal from active list\n");
        g_active_terminals = g_list_delete_link(g_active_terminals, that->m_active_terminals_link);
        that->m_active_terminals_link = nullptr;
        return true;
}

static void
stop_processing(bte::terminal::Terminal* that)
{
        if (!remove_from_active_list(that))
                return;

        if (g_active_terminals != nullptr)
                return;

        if (!in_process_timeout) {
                remove_process_timeout_source();
        }
        if (in_update_timeout == FALSE &&
            update_timeout_tag != 0) {
                _bte_debug_print(BTE_DEBUG_TIMEOUT, "Removing update timeout\n");
                g_source_remove (update_timeout_tag);
                update_timeout_tag = 0;
        }
}

static void
remove_update_timeout(bte::terminal::Terminal* that)
{
	that->reset_update_rects();
        stop_processing(that);
}

static void
add_process_timeout(bte::terminal::Terminal* that)
{
	_bte_debug_print(BTE_DEBUG_TIMEOUT,
			"Adding terminal to active list\n");
	that->m_active_terminals_link = g_active_terminals =
		g_list_prepend(g_active_terminals, that);
	if (update_timeout_tag == 0 &&
			process_timeout_tag == 0) {
		_bte_debug_print(BTE_DEBUG_TIMEOUT,
				"Starting process timeout\n");
		process_timeout_tag =
			g_timeout_add (BTE_DISPLAY_TIMEOUT,
					process_timeout, NULL);
	}
}

void
Terminal::start_processing()
{
	if (!is_processing())
		add_process_timeout(this);
}

void
Terminal::emit_pending_signals()
{
        auto const freezer = bte::glib::FreezeObjectNotify{m_terminal};

	emit_adjustment_changed();

	if (m_window_title_changed) {
                if (m_window_title != m_window_title_pending) {
                        m_window_title.swap(m_window_title_pending);

                        _bte_debug_print(BTE_DEBUG_SIGNALS,
                                         "Emitting `window-title-changed'.\n");
                        g_signal_emit(freezer.get(), signals[SIGNAL_WINDOW_TITLE_CHANGED], 0);
                        g_object_notify_by_pspec(freezer.get(), pspecs[PROP_WINDOW_TITLE]);
                }

                m_window_title_pending.clear();
                m_window_title_changed = false;
	}

	if (m_icon_title_changed) {
                if (m_icon_title != m_icon_title_pending) {
                        m_icon_title.swap(m_icon_title_pending);

                        _bte_debug_print(BTE_DEBUG_SIGNALS,
                                         "Emitting `icon-title-changed'.\n");
                        g_signal_emit(freezer.get(), signals[SIGNAL_ICON_TITLE_CHANGED], 0);
                        g_object_notify_by_pspec(freezer.get(), pspecs[PROP_ICON_TITLE]);
                }

		m_icon_title_pending.clear();
		m_icon_title_changed = false;
	}

	if (m_current_directory_uri_changed) {
                if (m_current_directory_uri != m_current_directory_uri_pending) {
                        m_current_directory_uri.swap(m_current_directory_uri_pending);

                        _bte_debug_print(BTE_DEBUG_SIGNALS,
                                         "Emitting `current-directory-uri-changed'.\n");
                        g_signal_emit(freezer.get(), signals[SIGNAL_CURRENT_DIRECTORY_URI_CHANGED], 0);
                        g_object_notify_by_pspec(freezer.get(), pspecs[PROP_CURRENT_DIRECTORY_URI]);
                }

                m_current_directory_uri_pending.clear();
                m_current_directory_uri_changed = false;
        }

        if (m_current_file_uri_changed) {
                if (m_current_file_uri != m_current_file_uri_pending) {
                        m_current_file_uri.swap(m_current_file_uri_pending);

                        _bte_debug_print(BTE_DEBUG_SIGNALS,
                                         "Emitting `current-file-uri-changed'.\n");
                        g_signal_emit(freezer.get(), signals[SIGNAL_CURRENT_FILE_URI_CHANGED], 0);
                        g_object_notify_by_pspec(freezer.get(), pspecs[PROP_CURRENT_FILE_URI]);
                }

                m_current_file_uri_pending.clear();
                m_current_file_uri_changed = false;
        }

	/* Flush any pending "inserted" signals. */

        if (m_cursor_moved_pending) {
                _bte_debug_print(BTE_DEBUG_SIGNALS,
                                 "Emitting `cursor-moved'.\n");
                g_signal_emit(freezer.get(), signals[SIGNAL_CURSOR_MOVED], 0);
                m_cursor_moved_pending = false;
        }
        if (m_text_modified_flag) {
                _bte_debug_print(BTE_DEBUG_SIGNALS,
                                 "Emitting buffered `text-modified'.\n");
                emit_text_modified();
                m_text_modified_flag = false;
        }
        if (m_text_inserted_flag) {
                _bte_debug_print(BTE_DEBUG_SIGNALS,
                                 "Emitting buffered `text-inserted'\n");
                emit_text_inserted();
                m_text_inserted_flag = false;
        }
        if (m_text_deleted_flag) {
                _bte_debug_print(BTE_DEBUG_SIGNALS,
                                 "Emitting buffered `text-deleted'\n");
                emit_text_deleted();
                m_text_deleted_flag = false;
	}
	if (m_contents_changed_pending) {
                /* Update hyperlink and dingus match set. */
		match_contents_clear();
		if (m_mouse_cursor_over_widget) {
                        hyperlink_hilite_update();
                        match_hilite_update();
		}

		_bte_debug_print(BTE_DEBUG_SIGNALS,
				"Emitting `contents-changed'.\n");
		g_signal_emit(m_terminal, signals[SIGNAL_CONTENTS_CHANGED], 0);
		m_contents_changed_pending = false;
	}
        if (m_bell_pending) {
                auto const timestamp = g_get_monotonic_time();
                if ((timestamp - m_bell_timestamp) >= BTE_BELL_MINIMUM_TIME_DIFFERENCE) {
                        beep();
                        emit_bell();

                        m_bell_timestamp = timestamp;
                 }

                m_bell_pending = false;
        }

        auto const eos = m_eos_pending;
        if (m_eos_pending) {
                queue_eof();
                m_eos_pending = false;

                unset_pty();
        }

        if (m_child_exited_after_eos_pending && eos) {
                /* The signal handler could destroy the terminal, so send the signal on idle */
                queue_child_exited();
                m_child_exited_after_eos_pending = false;
        }
}

void
Terminal::time_process_incoming()
{
	g_timer_reset(process_timer);
	process_incoming();
	auto elapsed = g_timer_elapsed(process_timer, NULL) * 1000;
	gssize target = BTE_MAX_PROCESS_TIME / elapsed * m_input_bytes;
	m_max_input_bytes = (m_max_input_bytes + target) / 2;
}

bool
Terminal::process(bool emit_adj_changed)
{
        if (pty()) {
                if (m_pty_input_active ||
                    m_pty_input_source == 0) {
                        m_pty_input_active = false;
                        /* Do one read directly. FIXMEchpe: Why? */
                        pty_io_read(pty()->fd(), G_IO_IN);
                }
                connect_pty_read();
        }
        if (emit_adj_changed)
                emit_adjustment_changed();

        bool is_active = !m_incoming_queue.empty();
        if (is_active) {
                if (BTE_MAX_PROCESS_TIME) {
                        time_process_incoming();
                } else {
                        process_incoming();
                }
                m_input_bytes = 0;
        } else
                emit_pending_signals();

        return is_active;
}


/* We need to keep a reference to the terminals in the
 * g_active_terminals list while iterating over it, since
 * in some language bindings the callbacks we emit
 * during processing may cause their GC to run, causing
 * later elements in this list to be removed from the list.
 * See issue bte#270.
 */

static void
unref_active_terminals(GList* list)
{
        g_list_free_full(list, GDestroyNotify(g_object_unref));
}

static auto
ref_active_terminals() noexcept
{
        GList* list = nullptr;
        for (auto l = g_active_terminals; l != nullptr; l = l->next) {
                auto that = reinterpret_cast<bte::terminal::Terminal*>(l->data);
                list = g_list_prepend(list, g_object_ref(that->bte_terminal()));
        }

        return std::unique_ptr<GList, decltype(&unref_active_terminals)>{list, &unref_active_terminals};
}

/* This function is called after DISPLAY_TIMEOUT ms.
 * It makes sure initial output is never delayed by more than DISPLAY_TIMEOUT
 */
static gboolean
process_timeout (gpointer data) noexcept
try
{
	GList *l, *next;
	gboolean again;

	in_process_timeout = TRUE;

	_bte_debug_print (BTE_DEBUG_WORK, "<");
	_bte_debug_print (BTE_DEBUG_TIMEOUT,
                          "Process timeout:  %d active\n",
                          g_list_length(g_active_terminals));

        auto death_grip = ref_active_terminals();

	for (l = g_active_terminals; l != NULL; l = next) {
		auto that = reinterpret_cast<bte::terminal::Terminal*>(l->data);
		bool active;

		next = l->next;

		if (l != g_active_terminals) {
			_bte_debug_print (BTE_DEBUG_WORK, "T");
		}

                // FIXMEchpe find out why we don't emit_adjustment_changed() here!!
                active = that->process(false);

		if (!active) {
                        remove_from_active_list(that);
		}
	}

	_bte_debug_print (BTE_DEBUG_WORK, ">");

	if (g_active_terminals != nullptr && update_timeout_tag == 0) {
		again = TRUE;
	} else {
		_bte_debug_print(BTE_DEBUG_TIMEOUT,
				"Stopping process timeout\n");
		process_timeout_tag = 0;
		again = FALSE;
	}

	in_process_timeout = FALSE;

	if (again) {
		/* Force us to relinquish the CPU as the child is running
		 * at full tilt and making us run to keep up...
		 */
		g_usleep (0);
	} else if (update_timeout_tag == 0) {
		/* otherwise free up memory used to capture incoming data */
                bte::base::Chunk::prune();
	}

	return again;
}
catch (...)
{
        bte::log_exception();
        return true; // false?
}

bool
Terminal::invalidate_dirty_rects_and_process_updates()
{
        if (G_UNLIKELY(!widget_realized()))
                return false;

	if (G_UNLIKELY (!m_update_rects->len))
		return false;

        auto region = cairo_region_create();
        auto n_rects = m_update_rects->len;
        for (guint i = 0; i < n_rects; i++) {
                cairo_rectangle_int_t *rect = &g_array_index(m_update_rects, cairo_rectangle_int_t, i);
                cairo_region_union_rectangle(region, rect);
	}
        g_array_set_size(m_update_rects, 0);
	m_invalidated_all = false;

        auto allocation = get_allocated_rect();
        cairo_region_translate(region,
                               allocation.x + m_padding.left,
                               allocation.y + m_padding.top);

	/* and perform the merge with the window visible area */
        ctk_widget_queue_draw_region(m_widget, region);
	cairo_region_destroy (region);

	return true;
}

static gboolean
update_repeat_timeout (gpointer data)
{
	GList *l, *next;
	bool again;

	in_update_timeout = TRUE;

	_bte_debug_print (BTE_DEBUG_WORK, "[");
	_bte_debug_print (BTE_DEBUG_TIMEOUT,
                          "Repeat timeout:  %d active\n",
                          g_list_length(g_active_terminals));

        auto death_grip = ref_active_terminals();

	for (l = g_active_terminals; l != NULL; l = next) {
		auto that = reinterpret_cast<bte::terminal::Terminal*>(l->data);

                next = l->next;

		if (l != g_active_terminals) {
			_bte_debug_print (BTE_DEBUG_WORK, "T");
		}

                that->process(true);

		again = that->invalidate_dirty_rects_and_process_updates();
		if (!again) {
                        remove_from_active_list(that);
		}
	}

	_bte_debug_print (BTE_DEBUG_WORK, "]");

	/* We only stop the timer if no update request was received in this
         * past cycle.  Technically, always stop this timer object and maybe
         * reinstall a new one because we need to delay by the amount of time
         * it took to repaint the screen: bug 730732.
	 */
	if (g_active_terminals == nullptr) {
		_bte_debug_print(BTE_DEBUG_TIMEOUT,
				"Stopping update timeout\n");
		update_timeout_tag = 0;
		again = false;
        } else {
                update_timeout_tag =
                        g_timeout_add_full (G_PRIORITY_DEFAULT_IDLE,
                                            BTE_UPDATE_REPEAT_TIMEOUT,
                                            update_repeat_timeout, NULL,
                                            NULL);
                again = true;
	}

	in_update_timeout = FALSE;

	if (again) {
		/* Force us to relinquish the CPU as the child is running
		 * at full tilt and making us run to keep up...
		 */
		g_usleep (0);
	} else {
		/* otherwise free up memory used to capture incoming data */
                bte::base::Chunk::prune();
	}

        return FALSE;  /* If we need to go again, we already have a new timer for that. */
}

static gboolean
update_timeout (gpointer data) noexcept
try
{
	GList *l, *next;

	in_update_timeout = TRUE;

	_bte_debug_print (BTE_DEBUG_WORK, "{");
	_bte_debug_print (BTE_DEBUG_TIMEOUT,
                          "Update timeout:  %d active\n",
                          g_list_length(g_active_terminals));

        remove_process_timeout_source();

	for (l = g_active_terminals; l != NULL; l = next) {
		auto that = reinterpret_cast<bte::terminal::Terminal*>(l->data);

                next = l->next;

		if (l != g_active_terminals) {
			_bte_debug_print (BTE_DEBUG_WORK, "T");
		}

                that->process(true);

                that->invalidate_dirty_rects_and_process_updates();
	}

	_bte_debug_print (BTE_DEBUG_WORK, "}");

	/* Set a timer such that we do not invalidate for a while. */
	/* This limits the number of times we draw to ~40fps. */
	update_timeout_tag =
		g_timeout_add_full (G_PRIORITY_DEFAULT_IDLE,
				    BTE_UPDATE_REPEAT_TIMEOUT,
				    update_repeat_timeout, NULL,
				    NULL);
	in_update_timeout = FALSE;

	return FALSE;
}
catch (...)
{
        bte::log_exception();
        return true; // false?
}

bool
Terminal::write_contents_sync (GOutputStream *stream,
                                         BteWriteFlags flags,
                                         GCancellable *cancellable,
                                         GError **error)
{
	return _bte_ring_write_contents (m_screen->row_data,
					 stream, flags,
					 cancellable, error);
}

/*
 * Buffer search
 */

/* TODO Add properties & signals */

/*
 * Terminal::search_set_regex:
 * @regex: (allow-none): a #BteRegex, or %nullptr
 * @flags: PCRE2 match flags, or 0
 *
 * Sets the regex to search for. Unsets the search regex when passed %nullptr.
 */
bool
Terminal::search_set_regex (bte::base::RefPtr<bte::base::Regex>&& regex,
                            uint32_t flags)
{
        if (regex == m_search_regex &&
            flags == m_search_regex_match_flags)
                return false;

        m_search_regex = std::move(regex);
        m_search_regex_match_flags = flags;

	invalidate_all();

        return true;
}

bool
Terminal::search_set_wrap_around(bool wrap)
{
        if (wrap == m_search_wrap_around)
                return false;

        m_search_wrap_around = wrap;
        return true;
}

bool
Terminal::search_rows(pcre2_match_context_8 *match_context,
                      pcre2_match_data_8 *match_data,
                      bte::grid::row_t start_row,
                      bte::grid::row_t end_row,
                      bool backward)
{
	int start, end;
	long start_col, end_col;
	BteCharAttributes *ca;
	GArray *attrs;
	gdouble value, page_size;

	auto row_text = get_text(start_row, 0,
                                 end_row, 0,
                                 false /* block */,
                                 true /* wrap */,
                                 nullptr);

        int (* match_fn) (const pcre2_code_8 *,
                          PCRE2_SPTR8, PCRE2_SIZE, PCRE2_SIZE, uint32_t,
                          pcre2_match_data_8 *, pcre2_match_context_8 *);
        gsize *ovector, so, eo;
        int r;

        if (m_search_regex->jited())
                match_fn = pcre2_jit_match_8;
        else
                match_fn = pcre2_match_8;

        r = match_fn(m_search_regex->code(),
                     (PCRE2_SPTR8)row_text->str, row_text->len , /* subject, length */
                     0, /* start offset */
                     m_search_regex_match_flags |
                     PCRE2_NO_UTF_CHECK | PCRE2_NOTEMPTY | PCRE2_PARTIAL_SOFT /* FIXME: HARD? */,
                     match_data,
                     match_context);

        if (r == PCRE2_ERROR_NOMATCH) {
                g_string_free (row_text, TRUE);
                return false;
        }
        // FIXME: handle partial matches (PCRE2_ERROR_PARTIAL)
        if (r < 0) {
                g_string_free (row_text, TRUE);
                return false;
        }

        ovector = pcre2_get_ovector_pointer_8(match_data);
        so = ovector[0];
        eo = ovector[1];
        if (G_UNLIKELY(so == PCRE2_UNSET || eo == PCRE2_UNSET)) {
                g_string_free (row_text, TRUE);
                return false;
        }

        start = so;
        end = eo;

	/* Fetch text again, with attributes */
	g_string_free(row_text, TRUE);
	if (!m_search_attrs)
		m_search_attrs = g_array_new (FALSE, TRUE, sizeof (BteCharAttributes));
	attrs = m_search_attrs;
	row_text = get_text(start_row, 0,
                            end_row, 0,
                            false /* block */,
                            true /* wrap */,
                            attrs);

	ca = &g_array_index (attrs, BteCharAttributes, start);
	start_row = ca->row;
	start_col = ca->column;
	ca = &g_array_index (attrs, BteCharAttributes, end - 1);
	end_row = ca->row;
        end_col = ca->column + ca->columns;

	g_string_free (row_text, TRUE);

	select_text(start_col, start_row, end_col, end_row);
	/* Quite possibly the math here should not access adjustment directly... */
        value = ctk_adjustment_get_value(m_vadjustment.get());
        page_size = ctk_adjustment_get_page_size(m_vadjustment.get());
	if (backward) {
		if (end_row < value || end_row > value + page_size - 1)
			queue_adjustment_value_changed_clamped(end_row - page_size + 1);
	} else {
		if (start_row < value || start_row > value + page_size - 1)
			queue_adjustment_value_changed_clamped(start_row);
	}

	return true;
}

bool
Terminal::search_rows_iter(pcre2_match_context_8 *match_context,
                                     pcre2_match_data_8 *match_data,
                                     bte::grid::row_t start_row,
                                     bte::grid::row_t end_row,
                                     bool backward)
{
	const BteRowData *row;
	long iter_start_row, iter_end_row;

	if (backward) {
		iter_start_row = end_row;
		while (iter_start_row > start_row) {
			iter_end_row = iter_start_row;

			do {
				iter_start_row--;
				row = find_row_data(iter_start_row);
			} while (row && row->attr.soft_wrapped);

			if (search_rows(match_context, match_data,
                                        iter_start_row, iter_end_row, backward))
				return true;
		}
	} else {
		iter_end_row = start_row;
		while (iter_end_row < end_row) {
			iter_start_row = iter_end_row;

			do {
				row = find_row_data(iter_end_row);
				iter_end_row++;
			} while (row && row->attr.soft_wrapped);

			if (search_rows(match_context, match_data,
                                        iter_start_row, iter_end_row, backward))
				return true;
		}
	}

	return false;
}

bool
Terminal::search_find (bool backward)
{
        bte::grid::row_t buffer_start_row, buffer_end_row;
        bte::grid::row_t last_start_row, last_end_row;
        bool match_found = true;

        if (!m_search_regex)
                return false;

	/* TODO
	 * Currently We only find one result per extended line, and ignore columns
	 * Moreover, the whole search thing is implemented very inefficiently.
	 */

        auto match_context = create_match_context();
        auto match_data = pcre2_match_data_create_8(256 /* should be plenty */, nullptr /* general context */);

	buffer_start_row = _bte_ring_delta (m_screen->row_data);
	buffer_end_row = _bte_ring_next (m_screen->row_data);

        if (!m_selection_resolved.empty()) {
                last_start_row = m_selection_resolved.start_row();
                last_end_row = m_selection_resolved.end_row() + 1;
	} else {
		last_start_row = m_screen->scroll_delta + m_row_count;
		last_end_row = m_screen->scroll_delta;
	}
	last_start_row = MAX (buffer_start_row, last_start_row);
	last_end_row = MIN (buffer_end_row, last_end_row);

	/* If search fails, we make an empty selection at the last searched
	 * position... */
	if (backward) {
		if (search_rows_iter (match_context, match_data,
                                      buffer_start_row, last_start_row, backward))
			goto found;
		if (m_search_wrap_around &&
		    search_rows_iter (match_context, match_data,
                                      last_end_row, buffer_end_row, backward))
			goto found;
                if (!m_selection_resolved.empty()) {
			if (m_search_wrap_around)
                            select_empty(m_selection_resolved.start_column(), m_selection_resolved.start_row());
			else
			    select_empty(-1, buffer_start_row - 1);
		}
                match_found = false;
	} else {
		if (search_rows_iter (match_context, match_data,
                                      last_end_row, buffer_end_row, backward))
			goto found;
		if (m_search_wrap_around &&
		    search_rows_iter (match_context, match_data,
                                      buffer_start_row, last_start_row, backward))
			goto found;
                if (!m_selection_resolved.empty()) {
			if (m_search_wrap_around)
                                select_empty(m_selection_resolved.end_column(), m_selection_resolved.end_row());
			else
                                select_empty(0, buffer_end_row);
		}
                match_found = false;
	}

 found:

        pcre2_match_data_free_8(match_data);
        pcre2_match_context_free_8(match_context);

	return match_found;
}

/*
 * Terminal::set_input_enabled:
 * @enabled: whether to enable user input
 *
 * Enables or disables user input. When user input is disabled,
 * the terminal's child will not receive any key press, or mouse button
 * press or motion events sent to it.
 *
 * Returns: %true iff the setting changed
 */
bool
Terminal::set_input_enabled (bool enabled)
{
        if (enabled == m_input_enabled)
                return false;

        m_input_enabled = enabled;

        auto context = ctk_widget_get_style_context(m_widget);

        /* FIXME: maybe hide cursor when input disabled, too? */

        if (enabled) {
                if (m_has_focus)
                        widget()->im_focus_in();

                ctk_style_context_remove_class (context, CTK_STYLE_CLASS_READ_ONLY);
        } else {
                im_reset();
                if (m_has_focus)
                        widget()->im_focus_out();

                disconnect_pty_write();
                _bte_byte_array_clear(m_outgoing);

                ctk_style_context_add_class (context, CTK_STYLE_CLASS_READ_ONLY);
        }

        return true;
}

std::optional<std::vector<char32_t>>
Terminal::process_word_char_exceptions(std::string_view str_view) const noexcept
{
        auto str = str_view.data();

        auto array = std::vector<char32_t>{};
        array.reserve(g_utf8_strlen(str, -1));

        for (auto const* p = str; *p; p = g_utf8_next_char(p)) {
                auto const c = g_utf8_get_char(p);

                /* For forward compatibility reasons, we skip
                 * characters that aren't supposed to be here,
                 * instead of erroring out.
                 */
                /* '-' must only be used*  at the start of the string */
                if (c == (gunichar)'-' && p != str)
                        continue;
                if (!g_unichar_isgraph(c))
                        continue;
                if (g_unichar_isspace(c))
                        continue;
                if (g_unichar_isalnum(c))
                        continue;

                array.push_back(c);
        }

        /* Sort the result since we want to use bsearch on it */
        std::sort(std::begin(array), std::end(array));

        /* Check that no character occurs twice */
        for (size_t i = 1; i < array.size(); ++i) {
                if (array[i-1] != array[i])
                        continue;

                return std::nullopt;
        }

#if 0
        /* Debug */
        for (auto const c : array) {
                char utf[7];
                utf[g_unichar_to_utf8(c, utf)] = '\0';
                g_printerr("Word char exception: U+%04X %s\n", c, utf);
        }
#endif

        return array;
}

/*
 * Terminal::set_word_char_exceptions:
 * @exceptions: a string of ASCII punctuation characters, or %nullptr
 *
 * With this function you can provide a set of characters which will
 * be considered parts of a word when doing word-wise selection, in
 * addition to the default which only considers alphanumeric characters
 * part of a word.
 *
 * The characters in @exceptions must be non-alphanumeric, each character
 * must occur only once, and if @exceptions contains the character
 * U+002D HYPHEN-MINUS, it must be at the start of the string.
 *
 * Use %nullptr to reset the set of exception characters to the default.
 *
 * Returns: %true if the word char exceptions changed
 */
bool
Terminal::set_word_char_exceptions(std::optional<std::string_view> stropt)
{
        if (auto array = process_word_char_exceptions(stropt ? stropt.value() : WORD_CHAR_EXCEPTIONS_DEFAULT)) {
                m_word_char_exceptions = *array;
                return true;
        }

        return false;
}

void
Terminal::set_clear_background(bool setting)
{
        if (m_clear_background == setting)
                return;

        m_clear_background = setting;
        invalidate_all();
}

} // namespace terminal
} // namespace bte