File: pangoterm.c

package info (click to toggle)
pangoterm 0~bzr613-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 180 kB
  • sloc: ansic: 2,256; makefile: 86; sh: 15
file content (2187 lines) | stat: -rw-r--r-- 60,363 bytes parent folder | download
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
#include "pangoterm.h"

#include <string.h>  // memmove
#include <wctype.h>

#include <cairo/cairo.h>
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <gdk/gdkkeysyms.h>
#include <gdk/gdkx.h>

#include "conf.h"

CONF_STRING(foreground, 0, "gray90", "Foreground colour", "COL");
CONF_STRING(background, 0, "black",  "Background colour", "COL");
CONF_STRING(cursor,     0, "white",  "Cursor colour",     "COL");

CONF_INT(border, 0, 2, "Border width", "PIXELS");

static struct {
  GdkColor col;
  gboolean is_set;
} colours[16];

static void apply_colour(int index, ConfigValue v)
{
  if(index < 0 || index > 16)
    return;

  colours[index].col = (GdkColor){ 0, 0, 0 };
  gdk_color_parse(v.s, &colours[index].col);
  colours[index].is_set = true;
}
CONF_PARAMETRIC_STRING(colour, 0, apply_colour, "Palette colour", "COL");

CONF_INT(cursor_shape, 0, 1, "Cursor shape (1=block 2=underbar 3=vertical bar)", "SHAPE");

CONF_DOUBLE(size, 's', 9.0, "Font size", "NUM");

CONF_INT(cursor_blink_interval, 0, 500, "Cursor blink interval", "MSEC");

CONF_BOOL(bold_highbright, 0, TRUE, "Bold is high-brightness");
CONF_BOOL(altscreen, 0, TRUE, "Alternate screen buffer switching");

CONF_BOOL(altscreen_scroll, 0, FALSE, "Emulate arrows for mouse scrolling in alternate screen buffer");

CONF_INT(scrollback_size, 0, 1000, "Scrollback size", "LINES");

CONF_INT(scrollbar_width, 0, 3, "Scroll bar width", "PIXELS");

CONF_INT(scroll_wheel_delta, 0, 3, "Number of lines to scroll on mouse wheel", "LINES");

CONF_BOOL(unscroll_on_output, 0, TRUE, "Scroll to bottom on output");
CONF_BOOL(unscroll_on_key,    0, TRUE, "Scroll to bottom on keypress");

CONF_BOOL(doubleclick_fullword, 0, FALSE, "Double-click selects fullwords (until whitespace)");

CONF_STRING(geometry, 0, "", "Initial window geometry", "GEOM");

CONF_BOOL(chord_shift_space,     0, TRUE, "Shift-Space chording");
CONF_BOOL(chord_shift_backspace, 0, TRUE, "Shift-Backspace chording");
CONF_BOOL(chord_shift_enter,     0, TRUE, "Shift-Enter chording");

#define VTERM_COLOR_FROM_GDK_COLOR(c) \
  ((VTermColor){ .type = 0, .rgb.red = (c).red / 257, .rgb.green = (c).green / 257, .rgb.blue = (c).blue / 257 })

#define GDK_COLOR_FROM_VTERM_COLOR(c) \
  ((GdkColor){ .red = 257 * (c).rgb.red, .green = 257 * (c).rgb.green, .blue = 257 * (c).rgb.blue })

#ifdef DEBUG
# define DEBUG_PRINT_INPUT
#endif

/* To accomodate scrollback scrolling, we'll adopt the convention that VTermPos
 * and VTermRect instances always refer to virtual locations within the
 * VTermScreen buffer (or our scrollback buffer if row is negative), and
 * PhyPos and PhyRect instances refer to physical onscreen positions
 */

typedef struct {
  int prow, pcol;
} PhyPos;

#define PHYSPOS_FROM_VTERMPOS(pt, pos) \
  {                                    \
    .prow = pos.row + pt->scroll_offs, \
    .pcol = pos.col,                   \
  }

#define VTERMPOS_FROM_PHYSPOS(pt, pos) \
  {                                    \
    .row = pos.prow - pt->scroll_offs, \
    .col = pos.pcol,                   \
  }

typedef struct {
  int start_prow, end_prow, start_pcol, end_pcol;
} PhyRect;

#define PHYRECT_FROM_VTERMRECT(pt, rect)            \
  {                                                 \
    .start_prow = rect.start_row + pt->scroll_offs, \
    .end_prow   = rect.end_row   + pt->scroll_offs, \
    .start_pcol = rect.start_col,                   \
    .end_pcol   = rect.end_col,                     \
  }

typedef struct {
  int cols;
  VTermScreenCell cells[];
} PangoTermScrollbackLine;

struct PangoTerm {
  VTerm *vt;
  VTermScreen *vts;

  GtkIMContext *im_context;

  int mousemode;

  GdkRectangle pending_area;
  /* Pending glyphs to flush in flush_pending */
  GString *glyphs;
  GArray *glyph_widths;
  /* Pending area to erase in flush_pending */
  int erase_columns;
  /* Is pending area DWL? */
  int pending_dwl;

  struct {
    struct {
      unsigned int bold      : 1;
      unsigned int underline : 2;
      unsigned int italic    : 1;
      unsigned int reverse   : 1;
      unsigned int strike    : 1;
      unsigned int font      : 4;
      unsigned int dwl       : 1;
      unsigned int dhl       : 2;
    } attrs;
    GdkColor fg_col;
    GdkColor bg_col;
    PangoAttrList *pangoattrs;
    PangoLayout *layout;
  } pen;

  int rows;
  int cols;

  int on_altscreen;
  int scroll_offs;

  int scroll_size;
  int scroll_current;
  PangoTermScrollbackLine **sb_buffer;

  PangoTermWriteFn *writefn;
  void *writefn_data;

  PangoTermResizedFn *resizedfn;
  void *resizedfn_data;

  int n_fonts;
  char **fonts;
  double font_size;

  int cell_width_pango;
  int cell_width;
  int cell_height;

  GdkColor fg_col;
  GdkColor bg_col;

  int has_focus;
  int cursor_visible;    /* VTERM_PROP_CURSORVISIBLE */
  int cursor_blinkstate; /* during high state of blink */
  int cursor_hidden_for_redraw; /* true to temporarily hide during redraw */
  VTermPos cursorpos;
  GdkColor cursor_col;
  int cursor_shape;

#define CURSOR_ENABLED(pt) ((pt)->cursor_visible && !(pt)->cursor_hidden_for_redraw)

  guint cursor_timer_id;

  GtkWidget *termwin;

  cairo_surface_t *buffer;
  GdkWindow *termdraw;
  /* area in buffer that needs flushing to termdraw */
  GdkRectangle dirty_area;

  /* These four positions relate to the click/drag highlight state */

  enum { NO_DRAG, DRAG_PENDING, DRAGGING } dragging;
  /* Initial mouse position of selection drag */
  VTermPos drag_start;
  /* Current mouse position of selection drag */
  VTermPos drag_pos;

  /* Start and stop bounds of the selection */
  bool highlight_valid;
  VTermPos highlight_start;
  VTermPos highlight_stop;

  GtkClipboard *selection_primary;
  GtkClipboard *selection_clipboard;

  GString *outbuffer;
};

/*
 * Utility functions
 */

static VTermKey convert_keyval(guint gdk_keyval, VTermModifier *statep)
{
  if(gdk_keyval >= GDK_KEY_F1 && gdk_keyval <= GDK_KEY_F35)
    return VTERM_KEY_FUNCTION(gdk_keyval - GDK_KEY_F1 + 1);

  switch(gdk_keyval) {
  case GDK_KEY_BackSpace:
    return VTERM_KEY_BACKSPACE;
  case GDK_KEY_Tab:
  case GDK_KEY_KP_Tab:
    return VTERM_KEY_TAB;
  case GDK_KEY_Return:
    return VTERM_KEY_ENTER;
  case GDK_KEY_Escape:
    return VTERM_KEY_ESCAPE;

  case GDK_KEY_Up:
    return VTERM_KEY_UP;
  case GDK_KEY_Down:
    return VTERM_KEY_DOWN;
  case GDK_KEY_Left:
    return VTERM_KEY_LEFT;
  case GDK_KEY_Right:
    return VTERM_KEY_RIGHT;

  case GDK_KEY_Insert:
    return VTERM_KEY_INS;
  case GDK_KEY_Delete:
    return VTERM_KEY_DEL;
  case GDK_KEY_Home:
    return VTERM_KEY_HOME;
  case GDK_KEY_End:
    return VTERM_KEY_END;
  case GDK_KEY_Page_Up:
    return VTERM_KEY_PAGEUP;
  case GDK_KEY_Page_Down:
    return VTERM_KEY_PAGEDOWN;

  case GDK_KEY_ISO_Left_Tab:
    /* This is Shift-Tab */
    *statep |= VTERM_MOD_SHIFT;
    return VTERM_KEY_TAB;

  case GDK_KEY_KP_Insert:
    return VTERM_KEY_KP_0;
  case GDK_KEY_KP_End:
    return VTERM_KEY_KP_1;
  case GDK_KEY_KP_Down:
    return VTERM_KEY_KP_2;
  case GDK_KEY_KP_Page_Down:
    return VTERM_KEY_KP_3;
  case GDK_KEY_KP_Left:
    return VTERM_KEY_KP_4;
  case GDK_KEY_KP_Begin:
    return VTERM_KEY_KP_5;
  case GDK_KEY_KP_Right:
    return VTERM_KEY_KP_6;
  case GDK_KEY_KP_Home:
    return VTERM_KEY_KP_7;
  case GDK_KEY_KP_Up:
    return VTERM_KEY_KP_8;
  case GDK_KEY_KP_Page_Up:
    return VTERM_KEY_KP_9;
  case GDK_KEY_KP_Delete:
    return VTERM_KEY_KP_PERIOD;
  case GDK_KEY_KP_Enter:
    return VTERM_KEY_KP_ENTER;
  case GDK_KEY_KP_Add:
    return VTERM_KEY_KP_PLUS;
  case GDK_KEY_KP_Subtract:
    return VTERM_KEY_KP_MINUS;
  case GDK_KEY_KP_Multiply:
    return VTERM_KEY_KP_MULT;
  case GDK_KEY_KP_Divide:
    return VTERM_KEY_KP_DIVIDE;
  case GDK_KEY_KP_Equal:
    return VTERM_KEY_KP_EQUAL;

  default:
    return VTERM_KEY_NONE;
  }
}

static VTermModifier convert_modifier(int state)
{
  VTermModifier mod = VTERM_MOD_NONE;
  if(state & GDK_SHIFT_MASK)
    mod |= VTERM_MOD_SHIFT;
  if(state & GDK_CONTROL_MASK)
    mod |= VTERM_MOD_CTRL;
  if(state & GDK_MOD1_MASK)
    mod |= VTERM_MOD_ALT;

  return mod;
}

static void flush_outbuffer(PangoTerm *pt)
{
  if(pt->outbuffer->len) {
    (*pt->writefn)(pt->outbuffer->str, pt->outbuffer->len, pt->writefn_data);
    pt->outbuffer->len = 0;
  }
}

static void term_output(const char *s, size_t len, void *user)
{
  PangoTerm *pt = user;

  g_string_append_len(pt->outbuffer, s, len);
}

static void term_push_string(PangoTerm *pt, gchar *str, gboolean paste)
{
  if(paste)
    vterm_keyboard_start_paste(pt->vt);

  while(str && str[0]) {
    vterm_keyboard_unichar(pt->vt, g_utf8_get_char(str), 0);
    str = g_utf8_next_char(str);
  }

  if(paste)
    vterm_keyboard_end_paste(pt->vt);

  flush_outbuffer(pt);
}

static void pos_next(PangoTerm *pt, VTermPos *pos)
{
  pos->col++;
  if(pos->col >= pt->cols) {
    pos->row++;
    pos->col = 0;
  }
}

static void pos_prev(PangoTerm *pt, VTermPos *pos)
{
  pos->col--;
  if(pos->col < 0) {
    pos->row--;
    pos->col = pt->cols - 1;
  }
}

static void fetch_cell(PangoTerm *pt, VTermPos pos, VTermScreenCell *cell)
{
  if(pos.row < 0) {
    if(-pos.row > pt->scroll_current) {
      fprintf(stderr, "ARGH! Attempt to fetch scrollback beyond buffer at line %d\n", -pos.row);
      abort();
    }

    /* pos.row == -1 => sb_buffer[0], -2 => [1], etc... */
    PangoTermScrollbackLine *sb_line = pt->sb_buffer[-pos.row-1];
    if(pos.col < sb_line->cols)
      *cell = sb_line->cells[pos.col];
    else {
      *cell = (VTermScreenCell) { { 0 } };
      cell->width = 1;
      cell->bg = sb_line->cells[sb_line->cols - 1].bg;
    }
  }
  else {
    vterm_screen_get_cell(pt->vts, pos, cell);
  }
}

static int fetch_is_eol(PangoTerm *pt, VTermPos pos)
{
  if(pos.row >= 0)
    return vterm_screen_is_eol(pt->vts, pos);

  PangoTermScrollbackLine *sb_line = pt->sb_buffer[-pos.row-1];
  for(int col = pos.col; col < sb_line->cols; ) {
    if(sb_line->cells[col].chars[0])
      return 0;
    col += sb_line->cells[col].width;
  }
  return 1;
}

static size_t fetch_line_text(PangoTerm *pt, gchar *str, size_t len, VTermRect rect)
{
  size_t ret = 0;
  int skipped_blank = 0;
  int end_blank = 0;

  VTermPos pos = {
    .row = rect.start_row,
    .col = rect.start_col,
  };
  while(pos.col < rect.end_col) {
    VTermScreenCell cell;
    fetch_cell(pt, pos, &cell);
    if(!cell.chars[0])
      skipped_blank++;
    else
      for(; skipped_blank; skipped_blank--) {
        if(str)
          str[ret] = 0x20;
        ret++;
      }

    for(int i = 0; cell.chars[i]; i++)
      ret += g_unichar_to_utf8(cell.chars[i], str ? str + ret : NULL);

    end_blank = !cell.chars[0];

    pos.col += cell.width;
  }

  if(end_blank) {
    if(str)
      str[ret] = 0x0a;
    ret++;
  }

  return ret;
}

static gchar *fetch_flow_text(PangoTerm *pt, VTermPos start, VTermPos stop)
{
  size_t strlen = 0;
  char *str = NULL;

  // This logic looks so similar each time it's easier to loop it
  while(1) {
    size_t thislen = 0;

    VTermRect rect;
    if(start.row == stop.row) {
      rect.start_row = start.row;
      rect.start_col = start.col;
      rect.end_row   = start.row + 1;
      rect.end_col   = stop.col + 1;
      thislen += fetch_line_text(pt,
          str ? str    + thislen : NULL,
          str ? strlen - thislen : 0,
          rect);
    }
    else {
      rect.start_row = start.row;
      rect.start_col = start.col;
      rect.end_row   = start.row + 1;
      rect.end_col   = pt->cols;
      thislen += fetch_line_text(pt,
          str ? str    + thislen : NULL,
          str ? strlen - thislen : 0,
          rect);

      for(int row = start.row + 1; row < stop.row; row++) {
        rect.start_row = row;
        rect.start_col = 0;
        rect.end_row   = row + 1;
        rect.end_col   = pt->cols;

        thislen += fetch_line_text(pt,
            str ? str    + thislen : NULL,
            str ? strlen - thislen : 0,
            rect);
      }

      rect.start_row = stop.row;
      rect.start_col = 0;
      rect.end_row   = stop.row + 1;
      rect.end_col   = stop.col + 1;
      thislen += fetch_line_text(pt,
          str ? str    + thislen : NULL,
          str ? strlen - thislen : 0,
          rect);
    }

    if(str)
      break;

    strlen = thislen;
    str = malloc(strlen + 1); // Terminating NUL
  }

  str[strlen] = 0;

  return str;
}

#define GDKRECTANGLE_FROM_PHYRECT(pt, rect)                        \
  {                                                                \
    .x      = rect.start_pcol * pt->cell_width,                    \
    .y      = rect.start_prow * pt->cell_height,                   \
    .width  = (rect.end_pcol - rect.start_pcol) * pt->cell_width,  \
    .height = (rect.end_prow - rect.start_prow) * pt->cell_height, \
  }

#define GDKRECTANGLE_FROM_PHYPOS_CELLS(pt, pos, width_mult) \
  {                                                         \
    .x      = pos.pcol * pt->cell_width,                    \
    .y      = pos.prow * pt->cell_height,                   \
    .width  = pt->cell_width * width_mult,                  \
    .height = pt->cell_height,                              \
  }

static int is_wordchar(uint32_t c)
{
  if(CONF_doubleclick_fullword)
    return c && !iswspace(c);
  else
    return iswalnum(c) || (c == '_');
}

static void lf_to_cr(gchar *str)
{
  for( ; str[0]; str++)
    if(str[0] == '\n')
      str[0] = '\r';
}

/*
 * Repainting operations
 */

static void blit_buffer(PangoTerm *pt, GdkRectangle *area)
{
  cairo_surface_flush(pt->buffer);

  cairo_t* gc = gdk_cairo_create(pt->termdraw);
  gdk_cairo_rectangle(gc, area);
  cairo_clip(gc);

  int whole_width = 2 * CONF_border + pt->cols * pt->cell_width;
  bool scrollbar = (area->x + area->width) > (whole_width - CONF_scrollbar_width);

  int whole_height;
  GdkRectangle scrollbar_area;

  if(scrollbar) {
    /* Erase old scrollbar */
    whole_height = pt->rows * pt->cell_height + 2 * CONF_border;
    scrollbar_area = (GdkRectangle){
        .x = whole_width - CONF_scrollbar_width,
        .y = 0,
        .width = CONF_scrollbar_width,
        .height = whole_height,
    };

    cairo_save(gc);

    gdk_cairo_rectangle(gc, &scrollbar_area);
    cairo_clip(gc);
    cairo_set_source_rgb(gc,
        pt->bg_col.red   / 65535.0,
        pt->bg_col.green / 65535.0,
        pt->bg_col.blue  / 65535.0);
    cairo_paint(gc);

    cairo_restore(gc);
  }

  {
    cairo_save(gc);

    /* clip rectangle will solve this efficiently */
    cairo_set_source_surface(gc, pt->buffer, CONF_border, CONF_border);
    cairo_paint(gc);

    cairo_restore(gc);
  }

  if(scrollbar && pt->scroll_offs) {
    /* Map the whole pt->rows + pt->scrollback_current extent onto the entire
     * height of the window, and draw a brighter rectangle to represent the
     * part currently visible
     */
    int pixels_from_bottom = (whole_height * pt->scroll_offs) /
                             (pt->rows + pt->scroll_current);
    int pixels_tall = (whole_height * pt->rows) /
                      (pt->rows + pt->scroll_current);

    cairo_save(gc);

    gdk_cairo_rectangle(gc, &scrollbar_area);
    cairo_clip(gc);
    cairo_set_source_rgba(gc,
        pt->fg_col.red   / 65535.0,
        pt->fg_col.green / 65535.0,
        pt->fg_col.blue  / 65535.0,
        0.3);
    cairo_paint(gc);

    scrollbar_area.height = pixels_tall;
    scrollbar_area.y = whole_height - pixels_tall - pixels_from_bottom;
    gdk_cairo_rectangle(gc, &scrollbar_area);
    cairo_clip(gc);
    cairo_set_source_rgba(gc,
        pt->fg_col.red   / 65535.0,
        pt->fg_col.green / 65535.0,
        pt->fg_col.blue  / 65535.0,
        0.7);
    cairo_paint(gc);

    cairo_restore(gc);
  }

  cairo_destroy(gc);
}

static void blit_dirty(PangoTerm *pt)
{
  if(!pt->dirty_area.height || !pt->dirty_area.width)
    return;

  blit_buffer(pt, &(GdkRectangle){
      .x      = pt->dirty_area.x + CONF_border,
      .y      = pt->dirty_area.y + CONF_border,
      .width  = pt->dirty_area.width,
      .height = pt->dirty_area.height,
  });

  pt->dirty_area.width  = 0;
  pt->dirty_area.height = 0;
}

static void flush_pending(PangoTerm *pt)
{
  if(!pt->pending_area.width)
    return;

  cairo_t* gc = cairo_create(pt->buffer);
  GdkRectangle pending_area = pt->pending_area;
  int glyphs_x = pending_area.x;
  int glyphs_y = pending_area.y;

  if(pt->pen.attrs.dwl)
    cairo_scale(gc, 2.0, 1.0);

  if(pt->pen.attrs.dhl) {
    cairo_scale(gc, 1.0, 2.0);
    pending_area.y /= 2;
    pending_area.height /= 2;
    glyphs_y = pending_area.y;

    if(pt->pen.attrs.dhl == 2)
      glyphs_y -= pending_area.height;
  }

  /* Background fill */
  {
    cairo_save(gc);

    gdk_cairo_rectangle(gc, &pending_area);
    cairo_clip(gc);

    GdkColor bg = pt->pen.attrs.reverse ? pt->pen.fg_col : pt->pen.bg_col;
    gdk_cairo_set_source_color(gc, &bg);
    cairo_paint(gc);

    cairo_restore(gc);
  }

  if(pt->glyphs->len) {
    PangoLayout *layout = pt->pen.layout;

    pango_layout_set_text(layout, pt->glyphs->str, pt->glyphs->len);

    if(pt->pen.pangoattrs)
      pango_layout_set_attributes(layout, pt->pen.pangoattrs);

    // Now adjust all the widths
    PangoLayoutIter *iter = pango_layout_get_iter(layout);
    do {
      PangoLayoutRun *run = pango_layout_iter_get_run(iter);
      if(!run)
        continue;

      PangoGlyphString *glyph_str = run->glyphs;
      int i;
      for(i = 0; i < glyph_str->num_glyphs; i++) {
        PangoGlyphInfo *glyph = &glyph_str->glyphs[i];
        int str_index = run->item->offset + glyph_str->log_clusters[i];
        int char_width = g_array_index(pt->glyph_widths, int, str_index);
        if(glyph->geometry.width && glyph->geometry.width != char_width * pt->cell_width_pango) {
          /* Adjust its x_offset to match the width change, to ensure it still
           * remains centered in the cell */
          glyph->geometry.x_offset -= (glyph->geometry.width - char_width * pt->cell_width_pango) / 2;
          glyph->geometry.width = char_width * pt->cell_width_pango;
        }
      }
    } while(pango_layout_iter_next_run(iter));

    pango_layout_iter_free(iter);

    /* Draw glyphs */
    GdkColor fg = pt->pen.attrs.reverse ? pt->pen.bg_col : pt->pen.fg_col;
    gdk_cairo_set_source_color(gc, &fg);
    cairo_move_to(gc, glyphs_x, glyphs_y);
    pango_cairo_show_layout(gc, layout);

    g_string_truncate(pt->glyphs, 0);
  }

  if(pt->pen.attrs.dwl)
    pt->pending_area.x *= 2, pt->pending_area.width *= 2;

  if(pt->dirty_area.width && pt->pending_area.height)
    gdk_rectangle_union(&pt->pending_area, &pt->dirty_area, &pt->dirty_area);
  else
    pt->dirty_area = pt->pending_area;

  pt->pending_area.width = 0;
  pt->pending_area.height = 0;
  pt->erase_columns = 0;

  cairo_destroy(gc);
}

static void put_glyph(PangoTerm *pt, const uint32_t chars[], int width, VTermPos pos)
{
  PhyPos ph_pos = PHYSPOS_FROM_VTERMPOS(pt, pos);
  if(ph_pos.prow < 0 || ph_pos.prow >= pt->rows)
    return;

  GdkRectangle destarea = GDKRECTANGLE_FROM_PHYPOS_CELLS(pt, ph_pos, width);

  if(pt->erase_columns)
    flush_pending(pt);
  if(destarea.y != pt->pending_area.y || destarea.x != pt->pending_area.x + pt->pending_area.width)
    flush_pending(pt);

  char *chars_str = g_ucs4_to_utf8(chars, VTERM_MAX_CHARS_PER_CELL, NULL, NULL, NULL);

  g_array_set_size(pt->glyph_widths, pt->glyphs->len + 1);
  g_array_index(pt->glyph_widths, int, pt->glyphs->len) = width;

  g_string_append(pt->glyphs, chars_str);

  g_free(chars_str);

  if(pt->pending_area.width && pt->pending_area.height)
    gdk_rectangle_union(&destarea, &pt->pending_area, &pt->pending_area);
  else
    pt->pending_area = destarea;
}

static void put_erase(PangoTerm *pt, int width, VTermPos pos)
{
  PhyPos ph_pos = PHYSPOS_FROM_VTERMPOS(pt, pos);
  if(ph_pos.prow < 0 || ph_pos.prow >= pt->rows)
    return;

  GdkRectangle destarea = GDKRECTANGLE_FROM_PHYPOS_CELLS(pt, ph_pos, width);

  if(!pt->erase_columns)
    flush_pending(pt);
  if(destarea.y != pt->pending_area.y || destarea.x != pt->pending_area.x + pt->pending_area.width)
    flush_pending(pt);

  if(pt->pending_area.width && pt->pending_area.height)
    gdk_rectangle_union(&destarea, &pt->pending_area, &pt->pending_area);
  else
    pt->pending_area = destarea;

  pt->erase_columns += width;
}

static void chpen(VTermScreenCell *cell, void *user_data, int cursoroverride)
{
  PangoTerm *pt = user_data;
  GdkColor col;

#define ADDATTR(a) \
  do { \
    PangoAttribute *newattr = (a); \
    newattr->start_index = 0; \
    newattr->end_index = -1; \
    pango_attr_list_change(pt->pen.pangoattrs, newattr); \
  } while(0)

  if(cell->attrs.bold != pt->pen.attrs.bold) {
    int bold = pt->pen.attrs.bold = cell->attrs.bold;
    flush_pending(pt);
    ADDATTR(pango_attr_weight_new(bold ? PANGO_WEIGHT_BOLD : PANGO_WEIGHT_NORMAL));
  }

  if(cell->attrs.underline != pt->pen.attrs.underline) {
    int underline = pt->pen.attrs.underline = cell->attrs.underline;
    flush_pending(pt);
    switch(underline) {
      case VTERM_UNDERLINE_OFF:
        ADDATTR(pango_attr_underline_new(PANGO_UNDERLINE_NONE));
        break;
      case VTERM_UNDERLINE_DOUBLE:
        ADDATTR(pango_attr_underline_new(PANGO_UNDERLINE_DOUBLE));
        break;
      case VTERM_UNDERLINE_CURLY:
        /* PANGO_UNDERLINE_ERROR is usually rendered with a wavy shape */
        ADDATTR(pango_attr_underline_new(PANGO_UNDERLINE_ERROR));
        break;
      default:
        ADDATTR(pango_attr_underline_new(PANGO_UNDERLINE_SINGLE));
    }
  }

  if(cell->attrs.italic != pt->pen.attrs.italic) {
    int italic = pt->pen.attrs.italic = cell->attrs.italic;
    flush_pending(pt);
    ADDATTR(pango_attr_style_new(italic ? PANGO_STYLE_ITALIC : PANGO_STYLE_NORMAL));
  }

  if(cell->attrs.reverse != pt->pen.attrs.reverse) {
    flush_pending(pt);
    pt->pen.attrs.reverse = cell->attrs.reverse;
  }

  if(cell->attrs.strike != pt->pen.attrs.strike) {
    int strike = pt->pen.attrs.strike = cell->attrs.strike;
    flush_pending(pt);
    ADDATTR(pango_attr_strikethrough_new(strike));
  }

  if(cell->attrs.font != pt->pen.attrs.font) {
    int font = pt->pen.attrs.font = cell->attrs.font;
    if(font >= pt->n_fonts)
      font = 0;
    flush_pending(pt);
    ADDATTR(pango_attr_family_new(pt->fonts[font]));
  }

  if(cell->attrs.dwl != pt->pen.attrs.dwl ||
     cell->attrs.dhl != pt->pen.attrs.dhl) {
    pt->pen.attrs.dwl = cell->attrs.dwl;
    pt->pen.attrs.dhl = cell->attrs.dhl;
    flush_pending(pt);
  }

  vterm_screen_convert_color_to_rgb(pt->vts, &cell->fg);
  col = GDK_COLOR_FROM_VTERM_COLOR(cell->fg);

  if(cursoroverride) {
    int grey = ((int)pt->cursor_col.red + pt->cursor_col.green + pt->cursor_col.blue)*2 > 65535*3
        ? 0 : 65535;
    col.red = col.green = col.blue = grey;
  }

  if(col.red   != pt->pen.fg_col.red || col.green != pt->pen.fg_col.green || col.blue  != pt->pen.fg_col.blue) {
    flush_pending(pt);
    pt->pen.fg_col = col;
  }

  vterm_screen_convert_color_to_rgb(pt->vts, &cell->bg);
  col = GDK_COLOR_FROM_VTERM_COLOR(cell->bg);

  if(cursoroverride)
    col = pt->cursor_col;

  if(col.red   != pt->pen.bg_col.red || col.green != pt->pen.bg_col.green || col.blue  != pt->pen.bg_col.blue) {
    flush_pending(pt);
    pt->pen.bg_col = col;
  }
}

static void repaint_phyrect(PangoTerm *pt, PhyRect ph_rect)
{
  PhyPos ph_pos;

  for(ph_pos.prow = ph_rect.start_prow; ph_pos.prow < ph_rect.end_prow; ph_pos.prow++) {
    for(ph_pos.pcol = ph_rect.start_pcol; ph_pos.pcol < ph_rect.end_pcol; ) {
      VTermPos pos = VTERMPOS_FROM_PHYSPOS(pt, ph_pos);

      VTermScreenCell cell;
      fetch_cell(pt, pos, &cell);

      if(cell.attrs.dwl != pt->pending_dwl)
        flush_pending(pt);
      pt->pending_dwl = cell.attrs.dwl;

      /* Invert the RV attribute if this cell is selected */
      if(pt->highlight_valid) {
        VTermPos start = pt->highlight_start,
                 stop  = pt->highlight_stop;

        int highlighted = (pos.row > start.row || (pos.row == start.row && pos.col >= start.col)) &&
                          (pos.row < stop.row  || (pos.row == stop.row  && pos.col <= stop.col));

        if(highlighted)
          cell.attrs.reverse = !cell.attrs.reverse;
      }

      int cursor_here = pos.row == pt->cursorpos.row && pos.col == pt->cursorpos.col;
      int cursor_visible = CURSOR_ENABLED(pt) && (pt->cursor_blinkstate || !pt->has_focus);
      int draw_cursor = cursor_visible && cursor_here;

      chpen(&cell, pt, draw_cursor && pt->cursor_shape == VTERM_PROP_CURSORSHAPE_BLOCK);

      if(cell.chars[0] == 0) {
        put_erase(pt, cell.width, pos);
      }
      else {
        put_glyph(pt, cell.chars, cell.width, pos);
      }

      if(draw_cursor) {
        GdkRectangle cursor_area = GDKRECTANGLE_FROM_PHYPOS_CELLS(pt, ph_pos, 1);
        gtk_im_context_set_cursor_location(pt->im_context, &cursor_area);

        if (pt->cursor_shape != VTERM_PROP_CURSORSHAPE_BLOCK) {
            flush_pending(pt);

            cairo_t *gc = cairo_create(pt->buffer);

            gdk_cairo_rectangle(gc, &cursor_area);
            cairo_clip(gc);

            switch(pt->cursor_shape) {
            case VTERM_PROP_CURSORSHAPE_UNDERLINE:
              gdk_cairo_set_source_color(gc, &pt->cursor_col);
              cairo_rectangle(gc,
                  cursor_area.x,
                  cursor_area.y + (int)(cursor_area.height * 0.85),
                  cursor_area.width,
                  (int)(cursor_area.height * 0.15));
              cairo_fill(gc);
              break;
            case VTERM_PROP_CURSORSHAPE_BAR_LEFT:
              gdk_cairo_set_source_color(gc, &pt->cursor_col);
              cairo_rectangle(gc,
                  cursor_area.x,
                  cursor_area.y,
                  (cursor_area.width * 0.15),
                  cursor_area.height);
              cairo_fill(gc);
              break;
            }

            cairo_destroy(gc);
          }
      }

      ph_pos.pcol += cell.width;
    }
  }
}

static void repaint_rect(PangoTerm *pt, VTermRect rect)
{
  PhyRect ph_rect = PHYRECT_FROM_VTERMRECT(pt, rect);
  repaint_phyrect(pt, ph_rect);
}

static void repaint_cell(PangoTerm *pt, VTermPos pos)
{
  VTermRect rect = {
    .start_col = pos.col,
    .end_col   = pos.col + 1,
    .start_row = pos.row,
    .end_row   = pos.row + 1,
  };

  repaint_rect(pt, rect);
}

static void repaint_flow(PangoTerm *pt, VTermPos start, VTermPos stop)
{
  VTermRect rect;

  if(start.row == stop.row) {
    rect.start_col = start.col;
    rect.start_row = start.row;
    rect.end_col   = stop.col + 1;
    rect.end_row   = start.row + 1;
    repaint_rect(pt, rect);
  }
  else {
    rect.start_col = start.col;
    rect.start_row = start.row;
    rect.end_col   = pt->cols;
    rect.end_row   = start.row + 1;
    repaint_rect(pt, rect);

    if(start.row + 1 < stop.row) {
      rect.start_col = 0;
      rect.start_row = start.row + 1;
      rect.end_col   = pt->cols;
      rect.end_row   = stop.row;
      repaint_rect(pt, rect);
    }

    rect.start_col = 0;
    rect.start_row = stop.row;
    rect.end_col   = stop.col + 1;
    rect.end_row   = stop.row + 1;
    repaint_rect(pt, rect);
  }
}

static gboolean cursor_blink(void *user_data)
{
  PangoTerm *pt = user_data;

  pt->cursor_blinkstate = !pt->cursor_blinkstate;

  if(CURSOR_ENABLED(pt)) {
    repaint_cell(pt, pt->cursorpos);

    flush_pending(pt);
    blit_dirty(pt);
  }

  return TRUE;
}

static void cursor_start_blinking(PangoTerm *pt)
{
  if(!CONF_cursor_blink_interval)
    return;

  pt->cursor_timer_id = g_timeout_add(CONF_cursor_blink_interval, cursor_blink, pt);

  /* Should start blinking in visible state */
  pt->cursor_blinkstate = 1;

  if(CURSOR_ENABLED(pt))
    repaint_cell(pt, pt->cursorpos);
}

static void cursor_stop_blinking(PangoTerm *pt)
{
  g_source_remove(pt->cursor_timer_id);
  pt->cursor_timer_id = 0;

  /* Should always be in visible state */
  pt->cursor_blinkstate = 1;

  if(CURSOR_ENABLED(pt))
    repaint_cell(pt, pt->cursorpos);
}

static void store_clipboard(PangoTerm *pt)
{
  VTermPos start = pt->highlight_start,
           stop  = pt->highlight_stop;

  gchar *text = fetch_flow_text(pt, start, stop);

  gtk_clipboard_clear(pt->selection_primary);
  gtk_clipboard_set_text(pt->selection_primary, text, -1);

  free(text);
}

static void cancel_highlight(PangoTerm *pt)
{
  if(!pt->highlight_valid)
    return;

  pt->highlight_valid = FALSE;

  repaint_flow(pt, pt->highlight_start, pt->highlight_stop);
  flush_pending(pt);
  blit_dirty(pt);
}

/*
 * VTerm event handlers
 */

static int term_damage(VTermRect rect, void *user_data)
{
  PangoTerm *pt = user_data;

  if(pt->highlight_valid) {
    if((pt->highlight_start.row < rect.end_row - 1 ||
        (pt->highlight_start.row == rect.end_row - 1 && pt->highlight_start.col < rect.end_col - 1)) &&
       (pt->highlight_stop.row > rect.start_row ||
        (pt->highlight_stop.row == rect.start_row && pt->highlight_stop.col > rect.start_col))) {
      /* Damage overlaps highlighted region */
      cancel_highlight(pt);
    }
  }

  repaint_rect(pt, rect);

  return 1;
}

static int term_sb_pushline(int cols, const VTermScreenCell *cells, void *user_data)
{
  PangoTerm *pt = user_data;

  PangoTermScrollbackLine *linebuffer = NULL;
  if(pt->scroll_current == pt->scroll_size) {
    /* Recycle old row if it's the right size */
    if(pt->sb_buffer[pt->scroll_current-1]->cols == cols)
      linebuffer = pt->sb_buffer[pt->scroll_current-1];
    else
      free(pt->sb_buffer[pt->scroll_current-1]);

    memmove(pt->sb_buffer + 1, pt->sb_buffer, sizeof(pt->sb_buffer[0]) * (pt->scroll_current - 1));
  }
  else if(pt->scroll_current > 0) {
    memmove(pt->sb_buffer + 1, pt->sb_buffer, sizeof(pt->sb_buffer[0]) * pt->scroll_current);
  }

  if(!linebuffer) {
    linebuffer = g_malloc0(sizeof(PangoTermScrollbackLine) + cols * sizeof(linebuffer->cells[0]));
    linebuffer->cols = cols;
  }

  pt->sb_buffer[0] = linebuffer;

  if(pt->scroll_current < pt->scroll_size)
    pt->scroll_current++;

  memcpy(linebuffer->cells, cells, sizeof(cells[0]) * cols);

  return 1;
}

static int term_sb_popline(int cols, VTermScreenCell *cells, void *user_data)
{
  PangoTerm *pt = user_data;

  if(!pt->scroll_current)
    return 0;

  PangoTermScrollbackLine *linebuffer = pt->sb_buffer[0];
  pt->scroll_current--;
  memmove(pt->sb_buffer, pt->sb_buffer + 1, sizeof(pt->sb_buffer[0]) * (pt->scroll_current));

  int cols_to_copy = cols;
  if(cols_to_copy > linebuffer->cols)
    cols_to_copy = linebuffer->cols;

  memcpy(cells, linebuffer->cells, sizeof(cells[0]) * cols_to_copy);

  for(int col = cols_to_copy; col < cols; col++) {
    cells[col] = (VTermScreenCell){
      .chars = {0},
      .width = 1,
      .attrs = {},
      .fg = VTERM_COLOR_FROM_GDK_COLOR(pt->fg_col),
      .bg = VTERM_COLOR_FROM_GDK_COLOR(pt->bg_col),
    };
  }

  free(linebuffer);

  return 1;
}

static int term_moverect(VTermRect dest, VTermRect src, void *user_data)
{
  PangoTerm *pt = user_data;

  flush_pending(pt);
  blit_dirty(pt);

  if(pt->highlight_valid) {
    int start_inside = vterm_rect_contains(src, pt->highlight_start);
    int stop_inside  = vterm_rect_contains(src, pt->highlight_stop);

    if(start_inside && stop_inside &&
        (pt->highlight_start.row == pt->highlight_stop.row ||
         (src.start_col == 0 && src.end_col == pt->cols))) {
      int delta_row = dest.start_row - src.start_row;
      int delta_col = dest.start_col - src.start_col;

      pt->highlight_start.row += delta_row;
      pt->highlight_start.col += delta_col;
      pt->highlight_stop.row  += delta_row;
      pt->highlight_stop.col  += delta_col;
    }
    else if(start_inside || stop_inside) {
      cancel_highlight(pt);
    }
  }

  PhyRect ph_dest = PHYRECT_FROM_VTERMRECT(pt, dest);

  if(ph_dest.end_prow < 0 || ph_dest.start_prow >= pt->rows)
    return 1;
  if(ph_dest.start_prow < 0)
    ph_dest.start_prow = 0;
  if(ph_dest.end_prow >= pt->rows)
    ph_dest.end_prow = pt->rows;

  GdkRectangle destarea = GDKRECTANGLE_FROM_PHYRECT(pt, ph_dest);

  cairo_surface_flush(pt->buffer);
  cairo_t* gc = cairo_create(pt->buffer);
  gdk_cairo_rectangle(gc, &destarea);
  cairo_clip(gc);
  cairo_set_source_surface(gc,
      pt->buffer,
      (dest.start_col - src.start_col) * pt->cell_width,
      (dest.start_row - src.start_row) * pt->cell_height);
  cairo_paint(gc);

  cairo_destroy(gc);

  blit_buffer(pt, &(GdkRectangle){
      .x      = destarea.x + CONF_border,
      .y      = destarea.y + CONF_border,
      .width  = destarea.width,
      .height = destarea.height,
  });

  return 1;
}

static int term_movecursor(VTermPos pos, VTermPos oldpos, int visible, void *user_data)
{
  PangoTerm *pt = user_data;

  pt->cursorpos = pos;
  pt->cursor_blinkstate = 1;

  return 1;
}

static int term_settermprop(VTermProp prop, VTermValue *val, void *user_data)
{
  PangoTerm *pt = user_data;

  switch(prop) {
  case VTERM_PROP_CURSORVISIBLE:
    pt->cursor_visible = val->boolean;
    break;

  case VTERM_PROP_CURSORBLINK:
    if(val->boolean && !pt->cursor_timer_id)
      cursor_start_blinking(pt);
    else if(!val->boolean && pt->cursor_timer_id)
      cursor_stop_blinking(pt);
    break;

  case VTERM_PROP_CURSORSHAPE:
    pt->cursor_shape = val->number;
    break;

  case VTERM_PROP_ICONNAME:
    gdk_window_set_icon_name(GDK_WINDOW(gtk_widget_get_window(pt->termwin)), val->string);
    break;

  case VTERM_PROP_TITLE:
    gtk_window_set_title(GTK_WINDOW(pt->termwin), val->string);
    break;

  case VTERM_PROP_ALTSCREEN:
    pt->on_altscreen = val->boolean;
    break;

  case VTERM_PROP_MOUSE:
    pt->mousemode = val->number;
    break;

  default:
    return 0;
  }

  return 1;
}

static int term_bell(void *user_data)
{
  PangoTerm *pt = user_data;

  gtk_widget_error_bell(GTK_WIDGET(pt->termwin));
  return 1;
}

static VTermScreenCallbacks cb = {
  .damage      = term_damage,
  .moverect    = term_moverect,
  .movecursor  = term_movecursor,
  .settermprop = term_settermprop,
  .bell        = term_bell,
  .sb_pushline = term_sb_pushline,
  .sb_popline  = term_sb_popline,
};

static void altscreen_scroll(PangoTerm *pt, int delta, GtkOrientation orientation)
{
  if (CONF_altscreen_scroll) {
    VTermKey which_arrow;
    if(delta > 0) {
      which_arrow = ((orientation == GTK_ORIENTATION_VERTICAL) ? VTERM_KEY_UP : VTERM_KEY_RIGHT);
    } else if(delta < 0) {
      which_arrow = ((orientation == GTK_ORIENTATION_VERTICAL) ? VTERM_KEY_DOWN : VTERM_KEY_LEFT);
    }
    for(int i=0; i < ((delta <= -1) ? -delta : delta); i++) {
      vterm_keyboard_key(pt->vt, which_arrow, 0);
    }
    flush_outbuffer(pt);
  }
}

static void hscroll_delta(PangoTerm *pt, int delta)
{
  if(pt->on_altscreen) {
    altscreen_scroll(pt, delta, GTK_ORIENTATION_HORIZONTAL);
  }
}

static void vscroll_delta(PangoTerm *pt, int delta)
{
  if(pt->on_altscreen) {
    altscreen_scroll(pt, delta, GTK_ORIENTATION_VERTICAL);
    return;
  }

  if(delta > 0) {
    if(pt->scroll_offs + delta > pt->scroll_current)
      delta = pt->scroll_current - pt->scroll_offs;
  }
  else if(delta < 0) {
    if(delta < -pt->scroll_offs)
      delta = -pt->scroll_offs;
  }

  if(!delta)
    return;

  pt->scroll_offs += delta;

  pt->cursor_hidden_for_redraw = 1;
  repaint_cell(pt, pt->cursorpos);

  PhyRect ph_repaint = {
      .start_pcol = 0,
      .end_pcol   = pt->cols,
      .start_prow = 0,
      .end_prow   = pt->rows,
  };

  if(abs(delta) < pt->rows) {
    PhyRect ph_dest = {
      .start_pcol = 0,
      .end_pcol   = pt->cols,
      .start_prow = 0,
      .end_prow   = pt->rows,
    };

    if(delta > 0) {
      ph_dest.start_prow  = delta;
      ph_repaint.end_prow = delta;
    }
    else {
      ph_dest.end_prow      = pt->rows + delta;
      ph_repaint.start_prow = pt->rows + delta;
    }

    GdkRectangle destarea = GDKRECTANGLE_FROM_PHYRECT(pt, ph_dest);

    cairo_surface_flush(pt->buffer);
    cairo_t *gc = cairo_create(pt->buffer);
    gdk_cairo_rectangle(gc, &destarea);
    cairo_clip(gc);
    cairo_set_source_surface(gc, pt->buffer, 0, delta * pt->cell_height);
    cairo_paint(gc);

    cairo_destroy(gc);
  }

  repaint_phyrect(pt, ph_repaint);

  pt->cursor_hidden_for_redraw = 0;
  repaint_cell(pt, pt->cursorpos);

  flush_pending(pt);

  GdkRectangle whole_screen = {
    .x = 0,
    .y = 0,
    .width  = pt->cols * pt->cell_width  + 2 * CONF_border,
    .height = pt->rows * pt->cell_height + 2 * CONF_border,
  };
  blit_buffer(pt, &whole_screen);
}

/*
 * GTK widget event handlers
 */

static gboolean widget_keypress(GtkWidget *widget, GdkEventKey *event, gpointer user_data)
{
  PangoTerm *pt = user_data;
  /* GtkIMContext will eat a Shift-Space and not tell us about shift.
   * Also don't let IME eat any GDK_KEY_KP_ events
   */
  gboolean ret = (event->state & GDK_SHIFT_MASK && event->keyval == ' ') ? FALSE
               : (event->keyval >= GDK_KEY_KP_Space && event->keyval <= GDK_KEY_KP_Divide) ? FALSE
               : gtk_im_context_filter_keypress(pt->im_context, event);

  if(ret)
    return TRUE;

  // We don't need to track the state of modifier bits
  if(event->is_modifier)
    return FALSE;

  if((event->keyval == GDK_KEY_Insert && event->state & GDK_SHIFT_MASK) ||
     ((event->keyval == 'v' || event->keyval == 'V') &&
      event->state & GDK_CONTROL_MASK && event->state & GDK_SHIFT_MASK)) {
    /* Shift-Insert or Ctrl-Shift-V pastes clipboard */
    gchar *str = gtk_clipboard_wait_for_text(event->keyval == GDK_KEY_Insert
                                             ? pt->selection_primary
                                             : pt->selection_clipboard);
    if(!str)
      return TRUE;

    lf_to_cr(str);

    term_push_string(pt, str, TRUE);
    return TRUE;
  }
  if((event->keyval == 'c' || event->keyval == 'C') &&
     event->state & GDK_CONTROL_MASK && event->state & GDK_SHIFT_MASK) {
    /* Ctrl-Shift-C copies to clipboard */
    if(!pt->highlight_valid)
      return TRUE;

    gchar *text = fetch_flow_text(pt, pt->highlight_start, pt->highlight_stop);
    if(!text)
      return TRUE;

    gtk_clipboard_clear(pt->selection_clipboard);
    gtk_clipboard_set_text(pt->selection_clipboard, text, -1);

    free(text);
    return TRUE;
  }
  if(event->keyval == GDK_KEY_Page_Down && event->state & GDK_SHIFT_MASK) {
    vscroll_delta(pt, -pt->rows / 2);
    return TRUE;
  }
  if(event->keyval == GDK_KEY_Page_Up && event->state & GDK_SHIFT_MASK) {
    vscroll_delta(pt, +pt->rows / 2);
    return TRUE;
  }

  VTermModifier mod = convert_modifier(event->state);
  VTermKey keyval = convert_keyval(event->keyval, &mod);

  /*
   * See also
   *   /usr/include/gtk-2.0/gdk/gdkkeysyms.h
   */

  if(keyval) {
    /* Shift-Enter and Shift-Backspace are too easy to mistype accidentally
     * Optionally remove shift if it's the only modifier
     */
    if(mod == VTERM_MOD_SHIFT)
      switch(keyval) {
        case VTERM_KEY_ENTER:
          if(!CONF_chord_shift_enter)
            mod = 0;
          break;

        case VTERM_KEY_BACKSPACE:
          if(!CONF_chord_shift_backspace)
            mod = 0;
          break;

        default:
          break;
      }

    vterm_keyboard_key(pt->vt, keyval, mod);
  }
  else if(event->keyval >= 0x10000000) /* Extension key, not printable Unicode */
    return FALSE;
  else if(event->keyval >= 0x01000000) /* Unicode shifted */
    vterm_keyboard_unichar(pt->vt, event->keyval - 0x01000000, mod);
  else if(event->keyval < 0x0f00) {
    /* GDK key code; convert to Unicode */
    guint32 unichar = gdk_keyval_to_unicode(event->keyval);
    if (unichar == 0)
      return FALSE;

    /* Shift-Space is too easy to mistype so optionally ignore that */
    if(mod == VTERM_MOD_SHIFT && event->keyval == ' ')
      if(!CONF_chord_shift_space)
        mod = 0;

    vterm_keyboard_unichar(pt->vt, unichar, mod);
  }
  else if(event->keyval >= GDK_KEY_KP_0 && event->keyval <= GDK_KEY_KP_9)
    /* event->keyval is a keypad number; just treat it as Unicode */
    vterm_keyboard_unichar(pt->vt, event->keyval - GDK_KEY_KP_0 + '0', mod);
  else
    return FALSE;

  if(CONF_unscroll_on_key && pt->scroll_offs)
    vscroll_delta(pt, -pt->scroll_offs);

  flush_outbuffer(pt);

  return FALSE;
}

static gboolean widget_keyrelease(GtkWidget *widget, GdkEventKey *event, gpointer user_data)
{
  PangoTerm *pt = user_data;
  return gtk_im_context_filter_keypress(pt->im_context, event);
}

static gboolean widget_mousepress(GtkWidget *widget, GdkEventButton *event, gpointer user_data)
{
  PangoTerm *pt = user_data;

  PhyPos ph_pos = {
    .pcol = (event->x - CONF_border) / pt->cell_width,
    .prow = (event->y - CONF_border) / pt->cell_height,
  };

  /* If the mouse is being dragged, we'll get motion events even outside our
   * window */
  int is_inside = (ph_pos.pcol >= 0 && ph_pos.pcol < pt->cols &&
                   ph_pos.prow >= 0 && ph_pos.prow < pt->rows);

  VTermPos pos = VTERMPOS_FROM_PHYSPOS(pt, ph_pos);

  /* Shift modifier bypasses terminal mouse handling */
  if(pt->mousemode && !(event->state & GDK_SHIFT_MASK) && is_inside) {
    VTermModifier state = convert_modifier(event->state);
    int is_press;
    switch(event->type) {
    case GDK_BUTTON_PRESS:
      is_press = 1;
      break;
    case GDK_BUTTON_RELEASE:
      is_press = 0;
      break;
    default:
      return TRUE;
    }
    vterm_mouse_move(pt->vt, pos.row, pos.col, state);
    vterm_mouse_button(pt->vt, event->button, is_press, state);
    flush_outbuffer(pt);
  }
  else if(event->button == 2 && event->type == GDK_BUTTON_PRESS && is_inside) {
    /* Middle-click pastes primary selection */
    gchar *str = gtk_clipboard_wait_for_text(pt->selection_primary);
    if(!str)
      return FALSE;

    lf_to_cr(str);

    term_push_string(pt, str, TRUE);
  }
  else if(event->button == 1 && event->type == GDK_BUTTON_PRESS && is_inside) {
    cancel_highlight(pt);

    pt->dragging = DRAG_PENDING;
    pt->drag_start = pos;
  }
  else if(event->button == 1 && event->type == GDK_BUTTON_RELEASE && pt->dragging != NO_DRAG) {
    /* Always accept a release even when outside */
    pt->dragging = NO_DRAG;

    if(pt->highlight_valid)
      store_clipboard(pt);
  }
  else if(event->button == 1 && event->type == GDK_2BUTTON_PRESS && is_inside) {
    /* Highlight a word. start with the position, and extend it both sides
     * over word characters
     */
    VTermPos start_pos = pos;
    while(start_pos.col > 0 || start_pos.row > 0) {
      VTermPos cellpos = start_pos;
      VTermScreenCell cell;

      pos_prev(pt, &cellpos);
      fetch_cell(pt, cellpos, &cell);
      if(!is_wordchar(cell.chars[0]))
        break;

      start_pos = cellpos;
    }

    VTermPos stop_pos = pos;
    while(stop_pos.col < pt->cols - 1 || stop_pos.row < pt->rows - 1) {
      VTermPos cellpos = stop_pos;
      VTermScreenCell cell;

      pos_next(pt, &cellpos);
      fetch_cell(pt, cellpos, &cell);
      if(!is_wordchar(cell.chars[0]))
        break;

      stop_pos = cellpos;
    }

    pt->highlight_valid = true;
    pt->highlight_start = start_pos;
    pt->highlight_stop  = stop_pos;

    repaint_flow(pt, pt->highlight_start, pt->highlight_stop);
    flush_pending(pt);
    blit_dirty(pt);
    store_clipboard(pt);
  }
  else if(event->button == 1 && event->type == GDK_3BUTTON_PRESS && is_inside) {
    /* Highlight an entire line */
    pt->highlight_valid = true;
    pt->highlight_start.row = pos.row;
    pt->highlight_start.col = 0;
    pt->highlight_stop.row  = pos.row;
    pt->highlight_stop.col  = pt->cols - 1;

    repaint_flow(pt, pt->highlight_start, pt->highlight_stop);
    flush_pending(pt);
    blit_dirty(pt);
    store_clipboard(pt);
  }

  return FALSE;
}

static gboolean widget_mousemove(GtkWidget *widget, GdkEventMotion *event, gpointer user_data)
{
  PangoTerm *pt = user_data;

  PhyPos ph_pos = {
    .pcol = (event->x - CONF_border) / pt->cell_width,
    .prow = (event->y - CONF_border) / pt->cell_height,
  };

  /* If the mouse is being dragged, we'll get motion events even outside our
   * window */
  int is_inside = (ph_pos.pcol >= 0 && ph_pos.pcol < pt->cols &&
                   ph_pos.prow >= 0 && ph_pos.prow < pt->rows);

  if(ph_pos.pcol < 0)         ph_pos.pcol = 0;
  if(ph_pos.pcol > pt->cols)  ph_pos.pcol = pt->cols; /* allow off-by-1 */
  if(ph_pos.prow < 0)         ph_pos.prow = 0;
  if(ph_pos.prow >= pt->rows) ph_pos.prow = pt->rows - 1;

  VTermPos pos = VTERMPOS_FROM_PHYSPOS(pt, ph_pos);

  /* Shift modifier bypasses terminal mouse handling */
  if(pt->mousemode > VTERM_PROP_MOUSE_CLICK && !(event->state & GDK_SHIFT_MASK) && is_inside) {
    if(pos.row < 0 || pos.row >= pt->rows)
      return TRUE;
    VTermModifier state = convert_modifier(event->state);
    vterm_mouse_move(pt->vt, pos.row, pos.col, state);
    flush_outbuffer(pt);
  }
  else if(event->state & GDK_BUTTON1_MASK) {
    VTermPos old_pos = pt->dragging == DRAGGING ? pt->drag_pos : pt->drag_start;
    if(pos.row == old_pos.row && pos.col == old_pos.col)
      /* Unchanged; stop here */
      return FALSE;

    pt->dragging = DRAGGING;
    pt->drag_pos = pos;

    VTermPos pos_left1 = pt->drag_pos;
    if(pos_left1.col > 0) pos_left1.col--;

    pt->highlight_valid = true;

    VTermPos repaint_start = pt->highlight_start;
    VTermPos repaint_stop  = pt->highlight_stop;

    if(vterm_pos_cmp(pt->drag_start, pt->drag_pos) > 0) {
      pt->highlight_start = pt->drag_pos;
      pt->highlight_stop  = pt->drag_start;
    }
    else {
      pt->highlight_start = pt->drag_start;
      pt->highlight_stop  = pt->drag_pos;

      if(pt->highlight_stop.col > 0)
        pt->highlight_stop.col--; /* exclude partial cell */

      if(fetch_is_eol(pt, pt->highlight_stop))
        pt->highlight_stop.col = pt->cols - 1;
    }

    if(vterm_pos_cmp(pt->highlight_start, repaint_start) < 0)
      repaint_start = pt->highlight_start;
    if(vterm_pos_cmp(pt->highlight_stop, repaint_stop) > 0)
      repaint_stop  = pt->highlight_stop;

    repaint_flow(pt, repaint_start, repaint_stop);

    flush_pending(pt);
    blit_dirty(pt);
  }

  return FALSE;
}

static gboolean widget_scroll(GtkWidget *widget, GdkEventScroll *event, gpointer user_data)
{
  PangoTerm *pt = user_data;

  PhyPos ph_pos = {
    .pcol = (event->x - CONF_border) / pt->cell_width,
    .prow = (event->y - CONF_border) / pt->cell_height,
  };

  if(pt->mousemode && !(event->state & GDK_SHIFT_MASK)) {
    VTermPos pos = VTERMPOS_FROM_PHYSPOS(pt, ph_pos);
    if(pos.row < 0 || pos.row >= pt->rows)
      return TRUE;

    /* Translate scroll direction back into a button number */

    int button;
    switch(event->direction) {
      case GDK_SCROLL_UP:    button = 4; break;
      case GDK_SCROLL_DOWN:  button = 5; break;
      default:
                             return FALSE;
    }
    VTermModifier state = convert_modifier(event->state);

    vterm_mouse_move(pt->vt, pos.row, pos.col, state);
    vterm_mouse_button(pt->vt, button, 1, state);
    flush_outbuffer(pt);
  }
  else {
    switch(event->direction) {
      case GDK_SCROLL_UP:    vscroll_delta(pt, +CONF_scroll_wheel_delta); break;
      case GDK_SCROLL_DOWN:  vscroll_delta(pt, -CONF_scroll_wheel_delta); break;
      case GDK_SCROLL_RIGHT: hscroll_delta(pt, +1); break;
      case GDK_SCROLL_LEFT:  hscroll_delta(pt, -1); break;
      default:              return FALSE;
    }
  }

  return FALSE;
}

static gboolean widget_im_commit(GtkIMContext *context, gchar *str, gpointer user_data)
{
  PangoTerm *pt = user_data;

  term_push_string(pt, str, FALSE);

  if(CONF_unscroll_on_key && pt->scroll_offs)
    vscroll_delta(pt, -pt->scroll_offs);

  return FALSE;
}

static gboolean widget_expose(GtkWidget *widget, GdkEventExpose *event, gpointer user_data)
{
  PangoTerm *pt = user_data;

  /* GDK always sends resize events before expose events, so it's possible this
   * expose event is for a region that now doesn't exist.
   */
  int right  = 2 * CONF_border + pt->cols * pt->cell_width;
  int bottom = 2 * CONF_border + pt->rows * pt->cell_height;

  /* Trim to still-valid area, or ignore if there's nothing remaining */
  if(event->area.x + event->area.width > right)
    event->area.width = right - event->area.x;
  if(event->area.y + event->area.height > bottom)
    event->area.height = bottom - event->area.y;

  if(event->area.height && event->area.width)
    blit_buffer(pt, &event->area);

  return TRUE;
}

static void widget_resize(GtkContainer* widget, gpointer user_data)
{
  PangoTerm *pt = user_data;

  gint raw_width, raw_height;
  gtk_window_get_size(GTK_WINDOW(widget), &raw_width, &raw_height);

  raw_width  -= 2 * CONF_border;
  raw_height -= 2 * CONF_border;

  int cols = raw_width  / pt->cell_width;
  int rows = raw_height / pt->cell_height;

  if(cols == pt->cols && rows == pt->rows)
    return;

  // Clamp to a minimum 1x1 size because libvterm doesn't like zero
  if(!cols)
    cols = 1;
  if(!rows)
    rows = 1;

  pt->cols = cols;
  pt->rows = rows;

  if(pt->resizedfn)
    (*pt->resizedfn)(rows, cols, pt->resizedfn_data);

  cairo_surface_t* new_buffer = gdk_window_create_similar_surface(pt->termdraw,
      CAIRO_CONTENT_COLOR,
      cols * pt->cell_width,
      rows * pt->cell_height);

  cairo_t* gc = cairo_create(new_buffer);
  cairo_set_source_surface(gc, pt->buffer, 0, 0);
  cairo_paint(gc);
  cairo_destroy(gc);

  cairo_surface_destroy(pt->buffer);
  pt->buffer = new_buffer;

  vterm_set_size(pt->vt, rows, cols);
  vterm_screen_flush_damage(pt->vts);

  return;
}

static void widget_focus_in(GtkWidget *widget, GdkEventFocus *event, gpointer user_data)
{
  PangoTerm *pt = user_data;
  pt->has_focus = 1;

  VTermState *state = vterm_obtain_state(pt->vt);
  vterm_state_focus_in(state);

  if(CURSOR_ENABLED(pt)) {
    repaint_cell(pt, pt->cursorpos);

    flush_pending(pt);
    blit_dirty(pt);
  }

  gtk_im_context_focus_in(pt->im_context);
}

static void widget_focus_out(GtkWidget *widget, GdkEventFocus *event, gpointer user_data)
{
  PangoTerm *pt = user_data;
  pt->has_focus = 0;

  VTermState *state = vterm_obtain_state(pt->vt);
  vterm_state_focus_out(state);

  if(CURSOR_ENABLED(pt)) {
    repaint_cell(pt, pt->cursorpos);

    flush_pending(pt);
    blit_dirty(pt);
  }
  gtk_im_context_focus_out(pt->im_context);
}

static void widget_quit(GtkContainer* widget, gpointer unused_data)
{
  gtk_main_quit();
}

static GdkPixbuf *load_icon(GdkColor *background)
{
  /* This technique stolen from
   *   http://git.gnome.org/browse/gtk+/tree/gtk/gtkicontheme.c#n3180
   *
   *   Updated because rsvg no longer supports loading file: URL scheme, only
   *   data:.
   */

  gchar *icon;
  gsize icon_len;
  if(!g_file_get_contents(PANGOTERM_SHAREDIR "/pixmaps/pangoterm.svg", &icon, &icon_len, NULL))
    return NULL;

  gchar *icon_base64 = g_base64_encode((guchar*)icon, icon_len);
  g_free(icon);

  gchar *str = g_strdup_printf(
      "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"
      "<svg version=\"1.1\"\n"
      "     xmlns=\"http://www.w3.org/2000/svg\"\n"
      "     xmlns:xi=\"http://www.w3.org/2001/XInclude\"\n"
      "     width=\"64\"\n"
      "     height=\"64\">\n"
      "  <style type=\"text/css\">\n"
      "    #screen {\n"
      "      fill: #%02x%02x%02x !important;\n"
      "    }\n"
      "  </style>\n"
      "  <xi:include href=\"data:image/svg+xml;base64,%s" "\"/>\n"
      "</svg>",
      background->red   / 255,
      background->green / 255,
      background->blue  / 255,
      icon_base64);
  g_free(icon_base64);

  GInputStream *stream = g_memory_input_stream_new_from_data(str, -1, g_free);

  GdkPixbuf *ret = gdk_pixbuf_new_from_stream(stream, NULL, NULL);

  g_object_unref(stream);

  return ret;
}

PangoTerm *pangoterm_new(int rows, int cols)
{
  PangoTerm *pt = g_new0(PangoTerm, 1);

  pt->rows = rows;
  pt->cols = cols;

  pt->writefn = NULL;
  pt->resizedfn = NULL;

  pt->n_fonts = 1;
  pt->fonts = malloc(sizeof(char *) * 2);
  pt->fonts[0] = g_strdup("Monospace");
  pt->fonts[1] = NULL;
  pt->font_size = CONF_size;

  pt->cursor_col = (GdkColor){ 0xffff, 0xffff, 0xffff };
  gdk_color_parse(CONF_cursor, &pt->cursor_col);

  /* Create VTerm */
  pt->vt = vterm_new(rows, cols);
  vterm_set_utf8(pt->vt, 1);

  /* Set up state */
  VTermState *state = vterm_obtain_state(pt->vt);
  vterm_state_set_bold_highbright(state, CONF_bold_highbright);

  for(int index = 0; index < sizeof(colours)/sizeof(colours[0]); index++) {
    if(!colours[index].is_set)
      continue;

    vterm_state_set_palette_color(state, index,
        &VTERM_COLOR_FROM_GDK_COLOR(colours[index].col));
  }

  /* Set up screen */
  pt->vts = vterm_obtain_screen(pt->vt);
  vterm_screen_enable_altscreen(pt->vts, CONF_altscreen);
  vterm_screen_set_callbacks(pt->vts, &cb, pt);
  vterm_screen_set_damage_merge(pt->vts, VTERM_DAMAGE_SCROLL);

  /* Set up GTK widget */

  pt->termwin = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_widget_set_double_buffered(pt->termwin, FALSE);
  gtk_widget_modify_bg(pt->termwin, GTK_STATE_NORMAL, &pt->bg_col);

  pt->glyphs = g_string_sized_new(128);
  pt->glyph_widths = g_array_new(FALSE, FALSE, sizeof(int));

  gtk_widget_realize(pt->termwin);

  pt->termdraw = gtk_widget_get_window(pt->termwin);

  gdk_window_set_cursor(GDK_WINDOW(pt->termdraw), gdk_cursor_new(GDK_XTERM));

  cursor_start_blinking(pt);
  pt->cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;

  GdkEventMask mask = gdk_window_get_events(pt->termdraw);
  gdk_window_set_events(pt->termdraw, mask|GDK_BUTTON_PRESS_MASK|GDK_BUTTON_RELEASE_MASK|GDK_POINTER_MOTION_MASK);

  g_signal_connect(G_OBJECT(pt->termwin), "expose-event", G_CALLBACK(widget_expose), pt);
  g_signal_connect(G_OBJECT(pt->termwin), "key-press-event", G_CALLBACK(widget_keypress), pt);
  g_signal_connect(G_OBJECT(pt->termwin), "key-release-event", G_CALLBACK(widget_keyrelease), pt);
  g_signal_connect(G_OBJECT(pt->termwin), "button-press-event",   G_CALLBACK(widget_mousepress), pt);
  g_signal_connect(G_OBJECT(pt->termwin), "button-release-event", G_CALLBACK(widget_mousepress), pt);
  g_signal_connect(G_OBJECT(pt->termwin), "motion-notify-event",  G_CALLBACK(widget_mousemove), pt);
  g_signal_connect(G_OBJECT(pt->termwin), "scroll-event",  G_CALLBACK(widget_scroll), pt);
  g_signal_connect(G_OBJECT(pt->termwin), "focus-in-event",  G_CALLBACK(widget_focus_in),  pt);
  g_signal_connect(G_OBJECT(pt->termwin), "focus-out-event", G_CALLBACK(widget_focus_out), pt);
  g_signal_connect(G_OBJECT(pt->termwin), "destroy", G_CALLBACK(widget_quit), pt);

  pt->im_context = gtk_im_multicontext_new();
  GdkWindow *gdkwin = gtk_widget_get_window(GTK_WIDGET(pt->termwin));
  gtk_im_context_set_client_window(pt->im_context, gdkwin);
  gtk_im_context_set_use_preedit(pt->im_context, false);

  g_signal_connect(G_OBJECT(pt->im_context), "commit", G_CALLBACK(widget_im_commit), pt);
  g_signal_connect(G_OBJECT(pt->termwin), "check-resize", G_CALLBACK(widget_resize), pt);

  pt->dragging = NO_DRAG;

  pt->selection_primary   = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
  pt->selection_clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);

  pt->scroll_size = CONF_scrollback_size;
  pt->sb_buffer = g_new0(PangoTermScrollbackLine*, pt->scroll_size);

  pt->outbuffer = g_string_sized_new(256);

  vterm_output_set_callback(pt->vt, term_output, pt);

  return pt;
}

void pangoterm_free(PangoTerm *pt)
{
  g_strfreev(pt->fonts);

  vterm_free(pt->vt);
}

guint32 pangoterm_get_windowid(PangoTerm *pt)
{
  /* TODO: return 0 when not on X11 */
  return GDK_DRAWABLE_XID(gtk_widget_get_window(GTK_WIDGET(pt->termwin)));
}

void pangoterm_set_default_colors(PangoTerm *pt, GdkColor *fg_col, GdkColor *bg_col)
{
  pt->fg_col = *fg_col;
  pt->bg_col = *bg_col;

  vterm_state_set_default_colors(vterm_obtain_state(pt->vt),
      &VTERM_COLOR_FROM_GDK_COLOR(*fg_col),
      &VTERM_COLOR_FROM_GDK_COLOR(*bg_col));

  /* TODO: Do the equivalent using raw Xlib calls when using X backend,
   * as basically all these calls are deprecated. */
  /*
  GdkColormap* colormap = gdk_colormap_get_system();
  gdk_rgb_find_color(colormap, bg_col);
  gdk_window_set_background(pt->termdraw, bg_col);
  */

  GdkPixbuf *icon = load_icon(bg_col);
  if(icon) {
    gtk_window_set_icon(GTK_WINDOW(pt->termwin), icon);
    g_object_unref(icon);
  }
}

void pangoterm_set_fonts(PangoTerm *pt, char *font, char **alt_fonts)
{
  int n_fonts = 1;
  while(alt_fonts[n_fonts-1])
    n_fonts++;

  g_strfreev(pt->fonts);

  pt->n_fonts = n_fonts;

  pt->fonts = malloc(sizeof(char*) * (n_fonts + 1));
  pt->fonts[0] = g_strdup(font);

  for(int i = 1; i < n_fonts; i++)
    pt->fonts[i] = g_strdup(alt_fonts[i-1]);

  pt->fonts[n_fonts] = NULL;
}

void pangoterm_set_font_size(PangoTerm *pt, double size)
{
  pt->font_size = size;
}

void pangoterm_set_title(PangoTerm *pt, const char *title)
{
  gtk_window_set_title(GTK_WINDOW(pt->termwin), title);
}

void pangoterm_set_write_fn(PangoTerm *pt, PangoTermWriteFn *fn, void *user)
{
  pt->writefn = fn;
  pt->writefn_data = user;
}

void pangoterm_set_resized_fn(PangoTerm *pt, PangoTermResizedFn *fn, void *user)
{
  pt->resizedfn = fn;
  pt->resizedfn_data = user;
}

void pangoterm_start(PangoTerm *pt)
{
  /* Finish the rest of the setup and start */

  cairo_t *cctx = gdk_cairo_create(pt->termdraw);
  PangoContext *pctx = pango_cairo_create_context(cctx);

  PangoFontDescription *fontdesc = pango_font_description_from_string(pt->fonts[0]);
  if(pango_font_description_get_size(fontdesc) == 0)
    pango_font_description_set_size(fontdesc, pt->font_size * PANGO_SCALE);

  pango_context_set_font_description(pctx, fontdesc);
  pango_cairo_context_set_resolution(pctx, gdk_screen_get_resolution(gdk_screen_get_default()));

  pt->pen.pangoattrs = pango_attr_list_new();
  pt->pen.layout = pango_layout_new(pctx);
  pango_layout_set_font_description(pt->pen.layout, fontdesc);

  PangoFontMetrics *metrics = pango_context_get_metrics(pctx,
      pango_context_get_font_description(pctx), pango_context_get_language(pctx));

  int width = (pango_font_metrics_get_approximate_char_width(metrics) +
               pango_font_metrics_get_approximate_digit_width(metrics)) / 2;

  int height = pango_font_metrics_get_ascent(metrics) + pango_font_metrics_get_descent(metrics);

  pt->cell_width_pango = width;
  pt->cell_width  = PANGO_PIXELS_CEIL(width);
  pt->cell_height = PANGO_PIXELS_CEIL(height);

  GdkColor fg_col = { 0xffff * 0.90, 0xffff * 0.90, 0xffff * 0.90 };
  gdk_color_parse(CONF_foreground, &fg_col);

  GdkColor bg_col = { 0, 0, 0 };
  gdk_color_parse(CONF_background, &bg_col);

  pangoterm_set_default_colors(pt, &fg_col, &bg_col);

  gtk_window_resize(GTK_WINDOW(pt->termwin),
      pt->cols * pt->cell_width  + 2 * CONF_border,
      pt->rows * pt->cell_height + 2 * CONF_border);

  pt->buffer = gdk_window_create_similar_surface(pt->termdraw,
      CAIRO_CONTENT_COLOR,
      pt->cols * pt->cell_width,
      pt->rows * pt->cell_height);

  GdkGeometry hints;

  hints.min_width  = pt->cell_width  + 2 * CONF_border;
  hints.min_height = pt->cell_height + 2 * CONF_border;
  hints.width_inc  = pt->cell_width;
  hints.height_inc = pt->cell_height;

  gtk_window_set_resizable(GTK_WINDOW(pt->termwin), TRUE);
  gtk_window_set_geometry_hints(GTK_WINDOW(pt->termwin), GTK_WIDGET(pt->termwin), &hints, GDK_HINT_RESIZE_INC | GDK_HINT_MIN_SIZE);

  vterm_screen_reset(pt->vts, 1);

  VTermState *state = vterm_obtain_state(pt->vt);
  vterm_state_set_termprop(state, VTERM_PROP_CURSORSHAPE, &(VTermValue){ .number = CONF_cursor_shape });

  if(CONF_geometry && CONF_geometry[0])
    gtk_window_parse_geometry(GTK_WINDOW(pt->termwin), CONF_geometry);

  gtk_widget_show_all(pt->termwin);
}

void pangoterm_push_bytes(PangoTerm *pt, const char *bytes, size_t len)
{
  if(CONF_unscroll_on_output && pt->scroll_offs)
    vscroll_delta(pt, -pt->scroll_offs);

  vterm_input_write(pt->vt, bytes, len);
}

void pangoterm_begin_update(PangoTerm *pt)
{
  /* Hide cursor during damage flush */

  pt->cursor_hidden_for_redraw = 1;
  repaint_cell(pt, pt->cursorpos);
}

void pangoterm_end_update(PangoTerm *pt)
{
  vterm_screen_flush_damage(pt->vts);

  pt->cursor_hidden_for_redraw = 0;
  repaint_cell(pt, pt->cursorpos);

  flush_pending(pt);
  blit_dirty(pt);
  flush_outbuffer(pt);
}