[go: up one dir, main page]

File: selection.c

package info (click to toggle)
foot 1.6.4-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,492 kB
  • sloc: ansic: 21,242; python: 170; sh: 26; makefile: 7
file content (2018 lines) | stat: -rw-r--r-- 56,336 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
#include "selection.h"

#include <ctype.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <wctype.h>

#include <sys/epoll.h>
#include <sys/timerfd.h>

#define LOG_MODULE "selection"
#define LOG_ENABLE_DBG 0
#include "log.h"

#include "async.h"
#include "commands.h"
#include "config.h"
#include "extract.h"
#include "grid.h"
#include "misc.h"
#include "render.h"
#include "uri.h"
#include "util.h"
#include "vt.h"
#include "xmalloc.h"

static const char *const mime_type_map[] = {
    [DATA_OFFER_MIME_UNSET] = NULL,
    [DATA_OFFER_MIME_TEXT_PLAIN] = "text/plain",
    [DATA_OFFER_MIME_TEXT_UTF8] = "text/plain;charset=utf-8",
    [DATA_OFFER_MIME_URI_LIST] = "text/uri-list",
};

bool
selection_enabled(const struct terminal *term, struct seat *seat)
{
    return
        seat->mouse.col >= 0 && seat->mouse.row >= 0 &&
        (term->mouse_tracking == MOUSE_NONE ||
         term_mouse_grabbed(term, seat) ||
         term->is_searching);
}

bool
selection_on_rows(const struct terminal *term, int row_start, int row_end)
{
    LOG_DBG("on rows: %d-%d, range: %d-%d (offset=%d)",
            term->selection.start.row, term->selection.end.row,
            row_start, row_end, term->grid->offset);

    if (term->selection.end.row < 0)
        return false;

    assert(term->selection.start.row != -1);

    row_start += term->grid->offset;
    row_end += term->grid->offset;

    const struct coord *start = &term->selection.start;
    const struct coord *end = &term->selection.end;

    if ((row_start <= start->row && row_end >= start->row) ||
        (row_start <= end->row && row_end >= end->row))
    {
        /* The range crosses one of the selection boundaries */
        return true;
    }

    /* For the last check we must ensure start <= end */
    if (start->row > end->row) {
        const struct coord *tmp = start;
        start = end;
        end = tmp;
    }

    if (row_start >= start->row && row_end <= end->row) {
        LOG_INFO("ON ROWS");
        return true;
    }

    return false;
}

void
selection_view_up(struct terminal *term, int new_view)
{
    if (likely(term->selection.start.row < 0))
        return;

    if (likely(new_view < term->grid->view))
        return;

    term->selection.start.row += term->grid->num_rows;
    if (term->selection.end.row >= 0)
        term->selection.end.row += term->grid->num_rows;
}

void
selection_view_down(struct terminal *term, int new_view)
{
    if (likely(term->selection.start.row < 0))
        return;

    if (likely(new_view > term->grid->view))
        return;

    term->selection.start.row &= term->grid->num_rows - 1;
    if (term->selection.end.row >= 0)
        term->selection.end.row &= term->grid->num_rows - 1;
}

static void
foreach_selected_normal(
    struct terminal *term, struct coord _start, struct coord _end,
    bool (*cb)(struct terminal *term, struct row *row, struct cell *cell, int col, void *data),
    void *data)
{
    const struct coord *start = &_start;
    const struct coord *end = &_end;

    int start_row, end_row;
    int start_col, end_col;

    if (start->row < end->row) {
        start_row = start->row;
        end_row = end->row;
        start_col = start->col;
        end_col = end->col;
    } else if (start->row > end->row) {
        start_row = end->row;
        end_row = start->row;
        start_col = end->col;
        end_col = start->col;
    } else {
        start_row = end_row = start->row;
        start_col = min(start->col, end->col);
        end_col = max(start->col, end->col);
    }

    for (int r = start_row; r <= end_row; r++) {
        size_t real_r = r & (term->grid->num_rows - 1);
        struct row *row = term->grid->rows[real_r];
        assert(row != NULL);

        for (int c = start_col;
             c <= (r == end_row ? end_col : term->cols - 1);
             c++)
        {
            if (!cb(term, row, &row->cells[c], c, data))
                return;
        }

        start_col = 0;
    }
}

static void
foreach_selected_block(
    struct terminal *term, struct coord _start, struct coord _end,
    bool (*cb)(struct terminal *term, struct row *row, struct cell *cell, int col, void *data),
    void *data)
{
    const struct coord *start = &_start;
    const struct coord *end = &_end;

    struct coord top_left = {
        .row = min(start->row, end->row),
        .col = min(start->col, end->col),
    };

    struct coord bottom_right = {
        .row = max(start->row, end->row),
        .col = max(start->col, end->col),
    };

    for (int r = top_left.row; r <= bottom_right.row; r++) {
        size_t real_r = r & (term->grid->num_rows - 1);
        struct row *row = term->grid->rows[real_r];
        assert(row != NULL);

        for (int c = top_left.col; c <= bottom_right.col; c++) {
            if (!cb(term, row, &row->cells[c], c, data))
                return;
        }
    }
}

static void
foreach_selected(
    struct terminal *term, struct coord start, struct coord end,
    bool (*cb)(struct terminal *term, struct row *row, struct cell *cell, int col, void *data),
    void *data)
{
    switch (term->selection.kind) {
    case SELECTION_NORMAL:
        foreach_selected_normal(term, start, end, cb, data);
        return;

    case SELECTION_BLOCK:
        foreach_selected_block(term, start, end, cb, data);
        return;

    case SELECTION_NONE:
        assert(false);
        return;
    }

    assert(false);
}

static bool
extract_one_const_wrapper(struct terminal *term,
                          struct row *row, struct cell *cell,
                          int col, void *data)
{
    return extract_one(term, row, cell, col, data);
}

char *
selection_to_text(const struct terminal *term)
{
    if (term->selection.end.row == -1)
        return NULL;

    struct extraction_context *ctx = extract_begin(term->selection.kind);
    if (ctx == NULL)
        return NULL;

    foreach_selected(
        (struct terminal *)term, term->selection.start, term->selection.end,
        &extract_one_const_wrapper, ctx);

    char *text;
    return extract_finish(ctx, &text, NULL) ? text : NULL;
}

void
selection_start(struct terminal *term, int col, int row,
                enum selection_kind kind)
{
    selection_cancel(term);

    LOG_DBG("%s selection started at %d,%d",
            kind == SELECTION_NORMAL ? "normal" :
            kind == SELECTION_BLOCK ? "block" : "<unknown>",
            row, col);

    term->selection.kind = kind;
    term->selection.start = (struct coord){col, term->grid->view + row};
    term->selection.end = (struct coord){-1, -1};
    term->selection.
}

/* Context used while (un)marking selected cells, to be able to
 * exclude empty cells */
struct mark_context {
    const struct row *last_row;
    int empty_count;
};

static bool
unmark_selected(struct terminal *term, struct row *row, struct cell *cell,
                int col, void *data)
{
    if (cell->attrs.selected == 0 || (cell->attrs.selected & 2)) {
        /* Ignore if already deselected, or if premarked for updated selection */
        return true;
    }

    row->dirty = true;
    cell->attrs.selected = 0;
    cell->attrs.clean = 0;
    return true;
}


static bool
premark_selected(struct terminal *term, struct row *row, struct cell *cell,
                 int col, void *data)
{
    struct mark_context *ctx = data;
    assert(ctx != NULL);

    if (ctx->last_row != row) {
        ctx->last_row = row;
        ctx->empty_count = 0;
    }

    if (cell->wc == 0 && term->selection.kind == SELECTION_NORMAL) {
        ctx->empty_count++;
        return true;
    }

    /* Tell unmark to leave this be */
    for (int i = 0; i < ctx->empty_count + 1; i++)
        row->cells[col - i].attrs.selected |= 2;

    return true;
}

static bool
mark_selected(struct terminal *term, struct row *row, struct cell *cell,
              int col, void *data)
{
    struct mark_context *ctx = data;
    assert(ctx != NULL);

    if (ctx->last_row != row) {
        ctx->last_row = row;
        ctx->empty_count = 0;
    }

    if (cell->wc == 0 && term->selection.kind == SELECTION_NORMAL) {
        ctx->empty_count++;
        return true;
    }

    for (int i = 0; i < ctx->empty_count + 1; i++) {
        struct cell *c = &row->cells[col - i];
        if (c->attrs.selected & 1)
            c->attrs.selected = 1; /* Clear the pre-mark bit */
        else {
            row->dirty = true;
            c->attrs.selected = 1;
            c->attrs.clean = 0;
        }
    }

    return true;
}

static void
selection_modify(struct terminal *term, struct coord start, struct coord end)
{
    assert(term->selection.start.row != -1);
    assert(start.row != -1 && start.col != -1);
    assert(end.row != -1 && end.col != -1);

    struct mark_context ctx = {0};

    /* Premark all cells that *will* be selected */
    foreach_selected(term, start, end, &premark_selected, &ctx);
    memset(&ctx, 0, sizeof(ctx));

    if (term->selection.end.row >= 0) {
        /* Unmark previous selection, ignoring cells that are part of
         * the new selection */
        foreach_selected(term, term->selection.start, term->selection.end,
                         &unmark_selected, &ctx);
        memset(&ctx, 0, sizeof(ctx));
    }

    term->selection.start = start;
    term->selection.end = end;

    /* Mark new selection */
    foreach_selected(term, start, end, &mark_selected, &ctx);
    render_refresh(term);
}

void
selection_update(struct terminal *term, int col, int row)
{
    if (term->selection.start.row < 0)
        return;

    if (!term->selection.ongoing)
        return;

    LOG_DBG("selection updated: start = %d,%d, end = %d,%d -> %d, %d",
            term->selection.start.row, term->selection.start.col,
            term->selection.end.row, term->selection.end.col,
            row, col);

    assert(term->grid->view + row != -1);

    struct coord new_start = term->selection.start;
    struct coord new_end = {col, term->grid->view + row};

    size_t start_row_idx = new_start.row & (term->grid->num_rows - 1);
    size_t end_row_idx = new_end.row & (term->grid->num_rows - 1);
    const struct row *row_start = term->grid->rows[start_row_idx];
    const struct row *row_end = term->grid->rows[end_row_idx];

    /* Adjust start point if the selection has changed 'direction' */
    if (!(new_end.row == new_start.row && new_end.col == new_start.col)) {
        enum selection_direction new_direction;

        if (new_end.row > new_start.row ||
            (new_end.row == new_start.row && new_end.col > new_start.col))
        {
            /* New end point is after the start point */
            new_direction = SELECTION_RIGHT;
        } else {
            /* The new end point is before the start point */
            new_direction = SELECTION_LEFT;
        }

        if (term->selection.direction != new_direction) {
            if (term->selection.direction != SELECTION_UNDIR) {
                if (new_direction == SELECTION_LEFT) {
                    bool keep_going = true;
                    while (keep_going) {
                        const wchar_t wc = row_start->cells[new_start.col].wc;
                        keep_going = wc == CELL_MULT_COL_SPACER;

                        new_start.col--;
                        if (new_start.col < 0) {
                            new_start.col = term->cols - 1;
                            new_start.row--;
                        }
                    }
                } else {
                    bool keep_going = true;
                    while (keep_going) {
                        const wchar_t wc = new_start.col < term->cols - 1
                            ? row_start->cells[new_start.col + 1].wc
                            : 0;

                        keep_going = wc == CELL_MULT_COL_SPACER;

                        new_start.col++;
                        if (new_start.col >= term->cols) {
                            new_start.col = 0;
                            new_start.row++;
                        }
                    }
                }
            }

            term->selection.direction = new_direction;
        }
    }

    /* If an end point is in the middle of a multi-column character,
     * expand the selection to cover the entire character */
    if (new_start.row < new_end.row ||
        (new_start.row == new_end.row && new_start.col <= new_end.col))
    {
        while (new_start.col >= 1 &&
               row_start->cells[new_start.col].wc == CELL_MULT_COL_SPACER)
            new_start.col--;
        while (new_end.col < term->cols - 1 &&
               row_end->cells[new_end.col + 1].wc == CELL_MULT_COL_SPACER)
            new_end.col++;
    } else {
        while (new_end.col >= 1 &&
               row_end->cells[new_end.col].wc == CELL_MULT_COL_SPACER)
            new_end.col--;
        while (new_start.col < term->cols - 1 &&
               row_start->cells[new_start.col + 1].wc == CELL_MULT_COL_SPACER)
            new_start.col++;
    }

    selection_modify(term, new_start, new_end);
}

void
selection_dirty_cells(struct terminal *term)
{
    if (term->selection.start.row < 0 || term->selection.end.row < 0)
        return;

    foreach_selected(
        term, term->selection.start, term->selection.end, &mark_selected,
        &(struct mark_context){0});
}

static void
selection_extend_normal(struct terminal *term, int col, int row, uint32_t serial)
{
    const struct coord *start = &term->selection.start;
    const struct coord *end = &term->selection.end;

    if (start->row > end->row ||
        (start->row == end->row && start->col > end->col))
    {
        const struct coord *tmp = start;
        start = end;
        end = tmp;
    }

    assert(start->row < end->row || start->col < end->col);

    struct coord new_start, new_end;
    enum selection_direction direction;

    if (row < start->row || (row == start->row && col < start->col)) {
        /* Extend selection to start *before* current start */
        new_start = *end;
        new_end = (struct coord){col, row};
        direction = SELECTION_LEFT;
    }

    else if (row > end->row || (row == end->row && col > end->col)) {
        /* Extend selection to end *after* current end */
        new_start = *start;
        new_end = (struct coord){col, row};
        direction = SELECTION_RIGHT;
    }

    else {
        /* Shrink selection from start or end, depending on which one is closest */

        const int linear = row * term->cols + col;

        if (abs(linear - (start->row * term->cols + start->col)) <
            abs(linear - (end->row * term->cols + end->col)))
        {
            /* Move start point */
            new_start = *end;
            new_end = (struct coord){col, row};
            direction = SELECTION_LEFT;
        }

        else {
            /* Move end point */
            new_start = *start;
            new_end = (struct coord){col, row};
            direction = SELECTION_RIGHT;
        }
    }

    term->selection.direction = direction;
    selection_modify(term, new_start, new_end);
}

static void
selection_extend_block(struct terminal *term, int col, int row, uint32_t serial)
{
    const struct coord *start = &term->selection.start;
    const struct coord *end = &term->selection.end;

    struct coord top_left = {
        .row = min(start->row, end->row),
        .col = min(start->col, end->col),
    };

    struct coord top_right = {
        .row = min(start->row, end->row),
        .col = max(start->col, end->col),
    };

    struct coord bottom_left = {
        .row = max(start->row, end->row),
        .col = min(start->col, end->col),
    };

    struct coord bottom_right = {
        .row = max(start->row, end->row),
        .col = max(start->col, end->col),
    };

    struct coord new_start;
    struct coord new_end;

    if (row <= top_left.row ||
        abs(row - top_left.row) < abs(row - bottom_left.row))
    {
        /* Move one of the top corners */

        if (abs(col - top_left.col) < abs(col - top_right.col)) {
            new_start = bottom_right;
            new_end = (struct coord){col, row};
        }

        else {
            new_start = bottom_left;
            new_end = (struct coord){col, row};
        }
    }

    else {
        /* Move one of the bottom corners */

        if (abs(col - bottom_left.col) < abs(col - bottom_right.col)) {
            new_start = top_right;
            new_end = (struct coord){col, row};
        }

        else {
            new_start = top_left;
            new_end = (struct coord){col, row};
        }
    }

    selection_modify(term, new_start, new_end);
}

void
selection_extend(struct seat *seat, struct terminal *term,
                 int col, int row, uint32_t serial)
{
    if (term->selection.start.row < 0 || term->selection.end.row < 0) {
        /* No existing selection */
        return;
    }

    term->selection.

    row += term->grid->view;

    if ((row == term->selection.start.row && col == term->selection.start.col) ||
        (row == term->selection.end.row && col == term->selection.end.col))
    {
        /* Extension point *is* one of the current end points */
        return;
    }

    switch (term->selection.kind) {
    case SELECTION_NONE:
        assert(false);
        return;

    case SELECTION_NORMAL:
        selection_extend_normal(term, col, row, serial);
        break;

    case SELECTION_BLOCK:
        selection_extend_block(term, col, row, serial);
        break;
    }

    selection_to_primary(seat, term, serial);
}

//static const struct zwp_primary_selection_source_v1_listener primary_selection_source_listener;

void
selection_finalize(struct seat *seat, struct terminal *term, uint32_t serial)
{
    if (!term->selection.ongoing)
        return;

    LOG_DBG("selection finalize");

    selection_stop_scroll_timer(term);
    term->selection.

    if (term->selection.start.row < 0 || term->selection.end.row < 0)
        return;

    assert(term->selection.start.row != -1);
    assert(term->selection.end.row != -1);

    if (term->selection.start.row > term->selection.end.row ||
        (term->selection.start.row == term->selection.end.row &&
         term->selection.start.col > term->selection.end.col))
    {
        struct coord tmp = term->selection.start;
        term->selection.start = term->selection.end;
        term->selection.end = tmp;
    }

    assert(term->selection.start.row <= term->selection.end.row);

    switch (term->conf->selection_target) {
    case SELECTION_TARGET_NONE:
        break;

    case SELECTION_TARGET_PRIMARY:
        selection_to_primary(seat, term, serial);
        break;
    case SELECTION_TARGET_CLIPBOARD:
        selection_to_clipboard(seat, term, serial);
        break;

    case SELECTION_TARGET_BOTH:
        selection_to_primary(seat, term, serial);
        selection_to_clipboard(seat, term, serial);
        break;
    }
}

void
selection_cancel(struct terminal *term)
{
    LOG_DBG("selection cancelled: start = %d,%d end = %d,%d",
            term->selection.start.row, term->selection.start.col,
            term->selection.end.row, term->selection.end.col);

    selection_stop_scroll_timer(term);

    if (term->selection.start.row >= 0 && term->selection.end.row >= 0) {
        foreach_selected(
            term, term->selection.start, term->selection.end,
            &unmark_selected, &(struct mark_context){0});
        render_refresh(term);
    }

    term->selection.kind = SELECTION_NONE;
    term->selection.start = (struct coord){-1, -1};
    term->selection.end = (struct coord){-1, -1};
    term->selection.direction = SELECTION_UNDIR;
    term->selection.
}

bool
selection_clipboard_has_data(const struct seat *seat)
{
    return seat->clipboard.data_offer != NULL;
}

bool
selection_primary_has_data(const struct seat *seat)
{
    return seat->primary.data_offer != NULL;
}

void
selection_clipboard_unset(struct seat *seat)
{
    struct wl_clipboard *clipboard = &seat->clipboard;

    if (clipboard->data_source == NULL)
        return;

    /* Kill previous data source */
    assert(clipboard->serial != 0);
    wl_data_device_set_selection(seat->data_device, NULL, clipboard->serial);
    wl_data_source_destroy(clipboard->data_source);

    clipboard->data_source = NULL;
    clipboard->serial = 0;

    free(clipboard->text);
    clipboard->text = NULL;
}

void
selection_primary_unset(struct seat *seat)
{
    struct wl_primary *primary = &seat->primary;

    if (primary->data_source == NULL)
        return;

    assert(primary->serial != 0);
    zwp_primary_selection_device_v1_set_selection(
        seat->primary_selection_device, NULL, primary->serial);
    zwp_primary_selection_source_v1_destroy(primary->data_source);

    primary->data_source = NULL;
    primary->serial = 0;

    free(primary->text);
    primary->text = NULL;
}

void
selection_mark_word(struct seat *seat, struct terminal *term, int col, int row,
                    bool spaces_only, uint32_t serial)
{
    selection_cancel(term);

    struct coord start = {col, row};
    struct coord end = {col, row};

    const struct row *r = grid_row_in_view(term->grid, start.row);
    wchar_t c = r->cells[start.col].wc;

    if (!(c == 0 || !isword(c, spaces_only, term->conf->word_delimiters))) {
        while (true) {
            int next_col = start.col - 1;
            int next_row = start.row;

            /* Linewrap */
            if (next_col < 0) {
                next_col = term->cols - 1;
                if (--next_row < 0)
                    break;
            }

            const struct row *row = grid_row_in_view(term->grid, next_row);

            c = row->cells[next_col].wc;
            if (c == 0 || !isword(c, spaces_only, term->conf->word_delimiters))
                break;

            start.col = next_col;
            start.row = next_row;
        }
    }

    r = grid_row_in_view(term->grid, end.row);
    c = r->cells[end.col].wc;

    if (!(c == 0 || !isword(c, spaces_only, term->conf->word_delimiters))) {
        while (true) {
            int next_col = end.col + 1;
            int next_row = end.row;

            /* Linewrap */
            if (next_col >= term->cols) {
                next_col = 0;
                if (++next_row >= term->rows)
                    break;
            }

            const struct row *row = grid_row_in_view(term->grid, next_row);

            c = row->cells[next_col].wc;
            if (c == '\0' || !isword(c, spaces_only, term->conf->word_delimiters))
                break;

            end.col = next_col;
            end.row = next_row;
        }
    }

    selection_start(term, start.col, start.row, SELECTION_NORMAL);
    selection_update(term, end.col, end.row);
    selection_finalize(seat, term, serial);
}

void
selection_mark_row(
    struct seat *seat, struct terminal *term, int row, uint32_t serial)
{
    selection_start(term, 0, row, SELECTION_NORMAL);
    selection_update(term, term->cols - 1, row);
    selection_finalize(seat, term, serial);
}

static bool
fdm_scroll_timer(struct fdm *fdm, int fd, int events, void *data)
{
    if (events & EPOLLHUP)
        return false;

    struct terminal *term = data;

    uint64_t expiration_count;
    ssize_t ret = read(
        term->selection.auto_scroll.fd,
        &expiration_count, sizeof(expiration_count));

    if (ret < 0) {
        if (errno == EAGAIN)
            return true;

        LOG_ERRNO("failed to read selection scroll timer");
        return false;
    }

    switch (term->selection.auto_scroll.direction) {
    case SELECTION_SCROLL_NOT:
        return true;

    case SELECTION_SCROLL_UP:
        cmd_scrollback_up(term, expiration_count);
        selection_update(term, term->selection.auto_scroll.col, 0);
        break;

    case SELECTION_SCROLL_DOWN:
        cmd_scrollback_down(term, expiration_count);
        selection_update(term, term->selection.auto_scroll.col, term->rows - 1);
        break;
    }


    return true;
}

void
selection_start_scroll_timer(struct terminal *term, int interval_ns,
                             enum selection_scroll_direction direction, int col)
{
    assert(direction != SELECTION_SCROLL_NOT);

    if (!term->selection.ongoing)
        return;

    if (term->selection.auto_scroll.fd < 0) {
        int fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK);
        if (fd < 0) {
            LOG_ERRNO("failed to create selection scroll timer");
            goto err;
        }

        if (!fdm_add(term->fdm, fd, EPOLLIN, &fdm_scroll_timer, term)) {
            close(fd);
            return;
        }

        term->selection.auto_scroll.fd = fd;
    }

    struct itimerspec timer;
    if (timerfd_gettime(term->selection.auto_scroll.fd, &timer) < 0) {
        LOG_ERRNO("failed to get current selection scroll timer value");
        goto err;
    }

    if (timer.it_value.tv_sec == 0 && timer.it_value.tv_nsec == 0)
        timer.it_value.tv_nsec = 1;

    timer.it_interval.tv_sec = interval_ns / 1000000000;
    timer.it_interval.tv_nsec = interval_ns % 1000000000;

    if (timerfd_settime(term->selection.auto_scroll.fd, 0, &timer, NULL) < 0) {
        LOG_ERRNO("failed to set new selection scroll timer value");
        goto err;
    }

    term->selection.auto_scroll.direction = direction;
    term->selection.auto_scroll.col = col;
    return;

err:
    selection_stop_scroll_timer(term);
    return;
}

void
selection_stop_scroll_timer(struct terminal *term)
{
    if (term->selection.auto_scroll.fd < 0) {
        assert(term->selection.auto_scroll.direction == SELECTION_SCROLL_NOT);
        return;
    }

    fdm_del(term->fdm, term->selection.auto_scroll.fd);
    term->selection.auto_scroll.fd = -1;
    term->selection.auto_scroll.direction = SELECTION_SCROLL_NOT;
}

static void
target(void *data, struct wl_data_source *wl_data_source, const char *mime_type)
{
    LOG_DBG("TARGET: mime-type=%s", mime_type);
}

struct clipboard_send {
    char *data;
    size_t len;
    size_t idx;
};

static bool
fdm_send(struct fdm *fdm, int fd, int events, void *data)
{
    struct clipboard_send *ctx = data;

    if (events & EPOLLHUP)
        goto done;

    switch (async_write(fd, ctx->data, ctx->len, &ctx->idx)) {
    case ASYNC_WRITE_REMAIN:
        return true;

    case ASYNC_WRITE_DONE:
        break;

    case ASYNC_WRITE_ERR:
        LOG_ERRNO(
            "failed to asynchronously write %zu of selection data to FD=%d",
            ctx->len - ctx->idx, fd);
        break;
    }

done:
    fdm_del(fdm, fd);
    free(ctx->data);
    free(ctx);
    return true;
}

static void
send_clipboard_or_primary(struct seat *seat, int fd, const char *selection,
                          const char *source_name)
{
    /* Make it NONBLOCK:ing right away - we don't want to block if the
     * initial attempt to send the data synchronously fails */
    int flags;
    if ((flags = fcntl(fd, F_GETFL)) < 0 ||
        fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0)
    {
        LOG_ERRNO("failed to set O_NONBLOCK");
        return;
    }

    size_t len = strlen(selection);
    size_t async_idx = 0;

    switch (async_write(fd, selection, len, &async_idx)) {
    case ASYNC_WRITE_REMAIN: {
        struct clipboard_send *ctx = xmalloc(sizeof(*ctx));
        *ctx = (struct clipboard_send) {
            .data = xstrdup(&selection[async_idx]),
            .len = len - async_idx,
            .idx = 0,
        };

        if (fdm_add(seat->wayl->fdm, fd, EPOLLOUT, &fdm_send, ctx))
            return;

        free(ctx->data);
        free(ctx);
        break;
    }

    case ASYNC_WRITE_DONE:
        break;

    case ASYNC_WRITE_ERR:
        LOG_ERRNO("failed write %zu bytes of %s selection data to FD=%d",
                  len, source_name, fd);
        break;
    }

    close(fd);
}

static void
send(void *data, struct wl_data_source *wl_data_source, const char *mime_type,
     int32_t fd)
{
    struct seat *seat = data;
    const struct wl_clipboard *clipboard = &seat->clipboard;

    assert(clipboard->text != NULL);
    send_clipboard_or_primary(seat, fd, clipboard->text, "clipboard");
}

static void
cancelled(void *data, struct wl_data_source *wl_data_source)
{
    struct seat *seat = data;
    struct wl_clipboard *clipboard = &seat->clipboard;
    assert(clipboard->data_source == wl_data_source);

    wl_data_source_destroy(clipboard->data_source);
    clipboard->data_source = NULL;
    clipboard->serial = 0;

    free(clipboard->text);
    clipboard->text = NULL;
}

/* We don’t support dragging *from* */
static void
dnd_drop_performed(void *data, struct wl_data_source *wl_data_source)
{
    //LOG_DBG("DnD drop performed");
}

static void
dnd_finished(void *data, struct wl_data_source *wl_data_source)
{
    //LOG_DBG("DnD finished");
}

static void
action(void *data, struct wl_data_source *wl_data_source, uint32_t dnd_action)
{
    //LOG_DBG("DnD action: %u", dnd_action);
}

static const struct wl_data_source_listener data_source_listener = {
    .target = &target,
    .send = &send,
    .cancelled = &cancelled,
    .dnd_drop_performed = &dnd_drop_performed,
    .dnd_finished = &dnd_finished,
    .action = &action,
};

static void
primary_send(void *data,
             struct zwp_primary_selection_source_v1 *zwp_primary_selection_source_v1,
             const char *mime_type, int32_t fd)
{
    struct seat *seat = data;
    const struct wl_primary *primary = &seat->primary;

    assert(primary->text != NULL);
    send_clipboard_or_primary(seat, fd, primary->text, "primary");
}

static void
primary_cancelled(void *data,
                  struct zwp_primary_selection_source_v1 *zwp_primary_selection_source_v1)
{
    struct seat *seat = data;
    struct wl_primary *primary = &seat->primary;

    zwp_primary_selection_source_v1_destroy(primary->data_source);
    primary->data_source = NULL;
    primary->serial = 0;

    free(primary->text);
    primary->text = NULL;
}

static const struct zwp_primary_selection_source_v1_listener primary_selection_source_listener = {
    .send = &primary_send,
    .cancelled = &primary_cancelled,
};

bool
text_to_clipboard(struct seat *seat, struct terminal *term, char *text, uint32_t serial)
{
    struct wl_clipboard *clipboard = &seat->clipboard;

    if (clipboard->data_source != NULL) {
        /* Kill previous data source */
        assert(clipboard->serial != 0);
        wl_data_device_set_selection(seat->data_device, NULL, clipboard->serial);
        wl_data_source_destroy(clipboard->data_source);
        free(clipboard->text);

        clipboard->data_source = NULL;
        clipboard->serial = 0;
        clipboard->text = NULL;
    }

    clipboard->data_source
        = wl_data_device_manager_create_data_source(term->wl->data_device_manager);

    if (clipboard->data_source == NULL) {
        LOG_ERR("failed to create clipboard data source");
        return false;
    }

    clipboard->text = text;

    /* Configure source */
    wl_data_source_offer(clipboard->data_source, mime_type_map[DATA_OFFER_MIME_TEXT_UTF8]);
    wl_data_source_offer(clipboard->data_source, mime_type_map[DATA_OFFER_MIME_TEXT_PLAIN]);
    wl_data_source_offer(clipboard->data_source, "STRING");
    wl_data_source_offer(clipboard->data_source, "TEXT");
    wl_data_source_offer(clipboard->data_source, "UTF8_STRING");

    wl_data_source_add_listener(clipboard->data_source, &data_source_listener, seat);
    wl_data_device_set_selection(seat->data_device, clipboard->data_source, serial);

    /* Needed when sending the selection to other client */
    assert(serial != 0);
    clipboard->serial = serial;
    return true;
}

void
selection_to_clipboard(struct seat *seat, struct terminal *term, uint32_t serial)
{
    if (term->selection.start.row < 0 || term->selection.end.row < 0)
        return;

    /* Get selection as a string */
    char *text = selection_to_text(term);
    if (!text_to_clipboard(seat, term, text, serial))
        free(text);
}

struct clipboard_receive {
    int read_fd;
    int timeout_fd;
    struct itimerspec timeout;
    bool bracketed;

    void (*decoder)(struct clipboard_receive *ctx, char *data, size_t size);
    void (*finish)(struct clipboard_receive *ctx);

    /* URI state */
    bool add_space;
    struct {
        char *data;
        size_t sz;
        size_t idx;
    } buf;

    /* Callback data */
    void (*cb)(char *data, size_t size, void *user);
    void (*done)(void *user);
    void *user;
};

static void
clipboard_receive_done(struct fdm *fdm, struct clipboard_receive *ctx)
{
    fdm_del(fdm, ctx->timeout_fd);
    fdm_del(fdm, ctx->read_fd);
    ctx->done(ctx->user);
    free(ctx->buf.data);
    free(ctx);
}

static bool
fdm_receive_timeout(struct fdm *fdm, int fd, int events, void *data)
{
    struct clipboard_receive *ctx = data;
    if (events & EPOLLHUP)
        return false;

    assert(events & EPOLLIN);

    uint64_t expire_count;
    ssize_t ret = read(fd, &expire_count, sizeof(expire_count));
    if (ret < 0) {
        if (errno == EAGAIN)
            return true;

        LOG_ERRNO("failed to read clipboard timeout timer");
        return false;
    }

    LOG_WARN("no data received from clipboard in %llu seconds, aborting",
             (unsigned long long)ctx->timeout.it_value.tv_sec);

    clipboard_receive_done(fdm, ctx);
    return true;
}

static void
fdm_receive_decoder_plain(struct clipboard_receive *ctx, char *data, size_t size)
{
    ctx->cb(data, size, ctx->user);
}

static void
fdm_receive_finish_plain(struct clipboard_receive *ctx)
{
}

static bool
decode_one_uri(struct clipboard_receive *ctx, char *uri, size_t len)
{
    LOG_DBG("URI: \"%.*s\"", (int)len, uri);

    if (len == 0)
        return false;

    char *scheme, *host, *path;
    if (!uri_parse(uri, len, &scheme, NULL, NULL, &host, NULL, &path, NULL, NULL)) {
        LOG_ERR("drag-and-drop: invalid URI: %.*s", (int)len, uri);
        return false;
    }

    if (ctx->add_space)
        ctx->cb(" ", 1, ctx->user);
    ctx->add_space = true;

    if (strcmp(scheme, "file") == 0 && hostname_is_localhost(host)) {
        ctx->cb("'", 1, ctx->user);
        ctx->cb(path, strlen(path), ctx->user);
        ctx->cb("'", 1, ctx->user);
    } else
        ctx->cb(uri, len, ctx->user);

    free(scheme);
    free(host);
    free(path);
    return true;
}

static void
fdm_receive_decoder_uri(struct clipboard_receive *ctx, char *data, size_t size)
{
    while (ctx->buf.idx + size > ctx->buf.sz) {
        size_t new_sz = ctx->buf.sz == 0 ? size : 2 * ctx->buf.sz;
        ctx->buf.data = xrealloc(ctx->buf.data, new_sz);
        ctx->buf.sz = new_sz;
    }

    memcpy(&ctx->buf.data[ctx->buf.idx], data, size);
    ctx->buf.idx += size;

    char *start = ctx->buf.data;
    char *end = NULL;

    while (true) {
        for (end = start; end < &ctx->buf.data[ctx->buf.idx]; end++) {
            if (*end == '\r' || *end == '\n')
                break;
        }

        if (end >= &ctx->buf.data[ctx->buf.idx])
            break;

        decode_one_uri(ctx, start, end - start);
        start = end + 1;
    }

    const size_t ofs = start - ctx->buf.data;
    const size_t left = ctx->buf.idx - ofs;

    memmove(&ctx->buf.data[0], &ctx->buf.data[ofs], left);
    ctx->buf.idx = left;
}

static void
fdm_receive_finish_uri(struct clipboard_receive *ctx)
{
    LOG_DBG("finish: %.*s", (int)ctx->buf.idx, ctx->buf.data);
    decode_one_uri(ctx, ctx->buf.data, ctx->buf.idx);
}

static bool
fdm_receive(struct fdm *fdm, int fd, int events, void *data)
{
    struct clipboard_receive *ctx = data;

    if ((events & EPOLLHUP) && !(events & EPOLLIN))
        goto done;

    /* Reset timeout timer */
    if (timerfd_settime(ctx->timeout_fd, 0, &ctx->timeout, NULL) < 0) {
        LOG_ERRNO("failed to re-arm clipboard timeout timer");
        return false;
    }

    /* Read until EOF */
    while (true) {
        char text[256];
        ssize_t count = read(fd, text, sizeof(text));

        if (count == -1) {
            if (errno == EAGAIN || errno == EWOULDBLOCK)
                return true;

            LOG_ERRNO("failed to read clipboard data");
            break;
        }

        if (count == 0)
            break;

        /*
         * Call cb while at same time replace:
         *   - \r\n -> \r
         *   - \n -> \r
         *   - C0 -> <nothing>  (strip non-formatting C0 characters)
         *   - \e -> <nothing>  (i.e. strip ESC)
         */
        char *p = text;
        size_t left = count;

#define skip_one()                              \
        do {                                    \
            ctx->decoder(ctx, p, i);            \
            assert(i + 1 <= left);              \
            p += i + 1;                         \
            left -= i + 1;                      \
        } while (0)

    again:
        for (size_t i = 0; i < left; i++) {
            switch (p[i]) {
            default:
                break;

            case '\n':
                if (!ctx->bracketed)
                    p[i] = '\r';
                break;

            case '\r':
                /* Convert \r\n -> \r */
                if (!ctx->bracketed && i + 1 < left && p[i + 1] == '\n') {
                    i++;
                    skip_one();
                    goto again;
                }
                break;

            /* C0 non-formatting control characters (\b \t \n \r excluded) */
            case '\x01': case '\x02': case '\x03': case '\x04': case '\x05':
            case '\x06': case '\x07': case '\x0e': case '\x0f': case '\x10':
            case '\x11': case '\x12': case '\x13': case '\x14': case '\x15':
            case '\x16': case '\x17': case '\x18': case '\x19': case '\x1a':
            case '\x1b': case '\x1c': case '\x1d': case '\x1e': case '\x1f':
                skip_one();
                goto again;

            /* Additional control characters stripped by default (but
             * configurable) in XTerm: BS, HT, DEL */
            case '\b': case '\t': case '\v': case '\f': case '\x7f':
                if (!ctx->bracketed) {
                    skip_one();
                    goto again;
                }
                break;
            }
        }

        ctx->decoder(ctx, p, left);
        left = 0;
    }

#undef skip_one

done:
    ctx->finish(ctx);
    clipboard_receive_done(fdm, ctx);
    return true;
}

static void
begin_receive_clipboard(struct terminal *term, int read_fd,
                        enum data_offer_mime_type mime_type,
                        void (*cb)(char *data, size_t size, void *user),
                        void (*done)(void *user), void *user)
{
    int timeout_fd = -1;
    struct clipboard_receive *ctx = NULL;

    int flags;
    if ((flags = fcntl(read_fd, F_GETFL)) < 0 ||
        fcntl(read_fd, F_SETFL, flags | O_NONBLOCK) < 0)
    {
        LOG_ERRNO("failed to set O_NONBLOCK");
        goto err;
    }

    timeout_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
    if (timeout_fd < 0) {
        LOG_ERRNO("failed to create clipboard timeout timer FD");
        goto err;
    }

    const struct itimerspec timeout = {.it_value = {.tv_sec = 2}};
    if (timerfd_settime(timeout_fd, 0, &timeout, NULL) < 0) {
        LOG_ERRNO("failed to arm clipboard timeout timer");
        goto err;
    }

    ctx = xmalloc(sizeof(*ctx));
    *ctx = (struct clipboard_receive) {
        .read_fd = read_fd,
        .timeout_fd = timeout_fd,
        .timeout = timeout,
        .bracketed = term->bracketed_paste,
        .decoder = (mime_type == DATA_OFFER_MIME_URI_LIST
                    ? &fdm_receive_decoder_uri
                    : &fdm_receive_decoder_plain),
        .finish = (mime_type == DATA_OFFER_MIME_URI_LIST
                   ? &fdm_receive_finish_uri
                   : &fdm_receive_finish_plain),
        .cb = cb,
        .done = done,
        .user = user,
    };

    if (!fdm_add(term->fdm, read_fd, EPOLLIN, &fdm_receive, ctx) ||
        !fdm_add(term->fdm, timeout_fd, EPOLLIN, &fdm_receive_timeout, ctx))
    {
        goto err;
    }

    return;

err:
    free(ctx);
    fdm_del(term->fdm, timeout_fd);
    fdm_del(term->fdm, read_fd);
    done(user);
}

void
text_from_clipboard(struct seat *seat, struct terminal *term,
                    void (*cb)(char *data, size_t size, void *user),
                    void (*done)(void *user), void *user)
{
    struct wl_clipboard *clipboard = &seat->clipboard;
    if (clipboard->data_offer == NULL ||
        clipboard->mime_type == DATA_OFFER_MIME_UNSET)
    {
        done(user);
        return;
    }

    /* Prepare a pipe the other client can write its selection to us */
    int fds[2];
    if (pipe2(fds, O_CLOEXEC) == -1) {
        LOG_ERRNO("failed to create pipe");
        done(user);
        return;
    }

    LOG_DBG("receive from clipboard: mime-type=%s",
            mime_type_map[clipboard->mime_type]);

    int read_fd = fds[0];
    int write_fd = fds[1];

    /* Give write-end of pipe to other client */
    wl_data_offer_receive(
        clipboard->data_offer, mime_type_map[clipboard->mime_type], write_fd);

    /* Don't keep our copy of the write-end open (or we'll never get EOF) */
    close(write_fd);

    begin_receive_clipboard(term, read_fd, clipboard->mime_type, cb, done, user);
}

static void
receive_offer(char *data, size_t size, void *user)
{
    struct terminal *term = user;
    assert(term->is_sending_paste_data);
    term_paste_data_to_slave(term, data, size);
}
static void
receive_offer_done(void *user)
{
    struct terminal *term = user;

    if (term->bracketed_paste)
        term_paste_data_to_slave(term, "\033[201~", 6);

    term->is_sending_paste_data = false;

    /* Make sure we send any queued up non-paste data */
    if (tll_length(term->ptmx_buffers) > 0)
        fdm_event_add(term->fdm, term->ptmx, EPOLLOUT);
}

void
selection_from_clipboard(struct seat *seat, struct terminal *term, uint32_t serial)
{
    if (term->is_sending_paste_data) {
        /* We're already pasting... */
        return;
    }

    struct wl_clipboard *clipboard = &seat->clipboard;
    if (clipboard->data_offer == NULL)
        return;

    term->is_sending_paste_data = true;

    if (term->bracketed_paste)
        term_paste_data_to_slave(term, "\033[200~", 6);

    text_from_clipboard(seat, term, &receive_offer, &receive_offer_done, term);
}

bool
text_to_primary(struct seat *seat, struct terminal *term, char *text, uint32_t serial)
{
    if (term->wl->primary_selection_device_manager == NULL)
        return false;

    struct wl_primary *primary = &seat->primary;

    /* TODO: somehow share code with the clipboard equivalent */
    if (seat->primary.data_source != NULL) {
        /* Kill previous data source */

        assert(primary->serial != 0);
        zwp_primary_selection_device_v1_set_selection(
            seat->primary_selection_device, NULL, primary->serial);
        zwp_primary_selection_source_v1_destroy(primary->data_source);
        free(primary->text);

        primary->data_source = NULL;
        primary->serial = 0;
        primary->text = NULL;
    }

    primary->data_source
        = zwp_primary_selection_device_manager_v1_create_source(
            term->wl->primary_selection_device_manager);

    if (primary->data_source == NULL) {
        LOG_ERR("failed to create clipboard data source");
        return false;
    }

    /* Get selection as a string */
    primary->text = text;

    /* Configure source */
    zwp_primary_selection_source_v1_offer(primary->data_source, mime_type_map[DATA_OFFER_MIME_TEXT_UTF8]);
    zwp_primary_selection_source_v1_offer(primary->data_source, mime_type_map[DATA_OFFER_MIME_TEXT_PLAIN]);
    zwp_primary_selection_source_v1_offer(primary->data_source, "STRING");
    zwp_primary_selection_source_v1_offer(primary->data_source, "TEXT");
    zwp_primary_selection_source_v1_offer(primary->data_source, "UTF8_STRING");

    zwp_primary_selection_source_v1_add_listener(primary->data_source, &primary_selection_source_listener, seat);
    zwp_primary_selection_device_v1_set_selection(seat->primary_selection_device, primary->data_source, serial);

    /* Needed when sending the selection to other client */
    primary->serial = serial;
    return true;
}

void
selection_to_primary(struct seat *seat, struct terminal *term, uint32_t serial)
{
    if (term->wl->primary_selection_device_manager == NULL)
        return;

    /* Get selection as a string */
    char *text = selection_to_text(term);
    if (!text_to_primary(seat, term, text, serial))
        free(text);
}

void
text_from_primary(
    struct seat *seat, struct terminal *term,
    void (*cb)(char *data, size_t size, void *user),
    void (*done)(void *user), void *user)
{
    if (term->wl->primary_selection_device_manager == NULL) {
        done(user);
        return;
    }

    struct wl_primary *primary = &seat->primary;
    if (primary->data_offer == NULL ||
        primary->mime_type == DATA_OFFER_MIME_UNSET)
    {
        done(user);
        return;
    }

    /* Prepare a pipe the other client can write its selection to us */
    int fds[2];
    if (pipe2(fds, O_CLOEXEC) == -1) {
        LOG_ERRNO("failed to create pipe");
        done(user);
        return;
    }

    LOG_DBG("receive from primary: mime-type=%s",
            mime_type_map[primary->mime_type]);

    int read_fd = fds[0];
    int write_fd = fds[1];

    /* Give write-end of pipe to other client */
    zwp_primary_selection_offer_v1_receive(
        primary->data_offer, mime_type_map[primary->mime_type], write_fd);

    /* Don't keep our copy of the write-end open (or we'll never get EOF) */
    close(write_fd);

    begin_receive_clipboard(term, read_fd, primary->mime_type, cb, done, user);
}

void
selection_from_primary(struct seat *seat, struct terminal *term)
{
    if (term->wl->primary_selection_device_manager == NULL)
        return;

    if (term->is_sending_paste_data) {
        /* We're already pasting... */
        return;
    }

    struct wl_primary *primary = &seat->primary;
    if (primary->data_offer == NULL)
        return;

    term->is_sending_paste_data = true;
    if (term->bracketed_paste)
        term_paste_data_to_slave(term, "\033[200~", 6);

    text_from_primary(seat, term, &receive_offer, &receive_offer_done, term);
}

static void
select_mime_type_for_offer(const char *_mime_type,
                           enum data_offer_mime_type *type)
{
    enum data_offer_mime_type mime_type = DATA_OFFER_MIME_UNSET;

    /* Translate offered mime type to our mime type enum */
    for (size_t i = 0; i < ALEN(mime_type_map); i++) {
        if (mime_type_map[i] == NULL)
            continue;

        if (strcmp(_mime_type, mime_type_map[i]) == 0) {
            mime_type = i;
            break;
        }
    }

    LOG_DBG("mime-type: %s -> %s (offered type was %s)",
            mime_type_map[*type], mime_type_map[mime_type], _mime_type);

    /* Mime-type transition; if the new mime-type is "better" than
     * previously offered types, use the new type */

    switch (mime_type) {
    case DATA_OFFER_MIME_TEXT_PLAIN:
        /* text/plain is our least preferred type. Only use if current
         * type is unset */
        switch (*type) {
        case DATA_OFFER_MIME_UNSET:
            *type = mime_type;
            break;

        default:
            break;
        }
        break;

    case DATA_OFFER_MIME_TEXT_UTF8:
        /* text/plain;charset=utf-8 is preferred over text/plain */
        switch (*type) {
        case DATA_OFFER_MIME_UNSET:
        case DATA_OFFER_MIME_TEXT_PLAIN:
            *type = mime_type;
            break;

        default:
            break;
        }
        break;

    case DATA_OFFER_MIME_URI_LIST:
        /* text/uri-list is always used when offered */
        *type = mime_type;
        break;

    case DATA_OFFER_MIME_UNSET:
        break;
    }
}

static void
data_offer_reset(struct wl_clipboard *clipboard)
{
    if (clipboard->data_offer != NULL) {
        wl_data_offer_destroy(clipboard->data_offer);
        clipboard->data_offer = NULL;
    }

    clipboard->window = NULL;
    clipboard->mime_type = DATA_OFFER_MIME_UNSET;
}

static void
offer(void *data, struct wl_data_offer *wl_data_offer, const char *mime_type)
{
    struct seat *seat = data;
    select_mime_type_for_offer(mime_type, &seat->clipboard.mime_type);
}

static void
source_actions(void *data, struct wl_data_offer *wl_data_offer,
                uint32_t source_actions)
{
#if defined(_DEBUG) && LOG_ENABLE_DBG
    char actions_as_string[1024];
    size_t idx = 0;

    actions_as_string[0] = '\0';
    actions_as_string[sizeof(actions_as_string) - 1] = '\0';

    for (size_t i = 0; i < 31; i++) {
        if (((source_actions >> i) & 1) == 0)
            continue;

        enum wl_data_device_manager_dnd_action action = 1 << i;

        const char *s = NULL;

        switch (action) {
        case WL_DATA_DEVICE_MANAGER_DND_ACTION_NONE: s = NULL; break;
        case WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY: s = "copy"; break;
        case WL_DATA_DEVICE_MANAGER_DND_ACTION_MOVE: s = "move"; break;
        case WL_DATA_DEVICE_MANAGER_DND_ACTION_ASK: s = "ask"; break;
        }

        if (s == NULL)
            continue;

        strncat(actions_as_string, s, sizeof(actions_as_string) - idx - 1);
        idx += strlen(s);
        strncat(actions_as_string, ", ", sizeof(actions_as_string) - idx - 1);
        idx += 2;
    }

    /* Strip trailing ", " */
    if (strlen(actions_as_string) > 2)
        actions_as_string[strlen(actions_as_string) - 2] = '\0';

    LOG_DBG("DnD actions: %s (0x%08x)", actions_as_string, source_actions);
#endif
}

static void
offer_action(void *data, struct wl_data_offer *wl_data_offer, uint32_t dnd_action)
{
#if defined(_DEBUG) && LOG_ENABLE_DBG
    const char *s = NULL;

    switch (dnd_action) {
    case WL_DATA_DEVICE_MANAGER_DND_ACTION_NONE: s = "<none>"; break;
    case WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY: s = "copy"; break;
    case WL_DATA_DEVICE_MANAGER_DND_ACTION_MOVE: s = "move"; break;
    case WL_DATA_DEVICE_MANAGER_DND_ACTION_ASK: s = "ask"; break;
    }

    LOG_DBG("DnD offer action: %s (0x%08x)", s, dnd_action);
#endif
}

static const struct wl_data_offer_listener data_offer_listener = {
    .offer = &offer,
    .source_actions = &source_actions,
    .action = &offer_action,
};

static void
data_offer(void *data, struct wl_data_device *wl_data_device,
           struct wl_data_offer *offer)
{
    struct seat *seat = data;
    data_offer_reset(&seat->clipboard);
    seat->clipboard.data_offer = offer;
    wl_data_offer_add_listener(offer, &data_offer_listener, seat);
}

static void
enter(void *data, struct wl_data_device *wl_data_device, uint32_t serial,
      struct wl_surface *surface, wl_fixed_t x, wl_fixed_t y,
      struct wl_data_offer *offer)
{
    struct seat *seat = data;
    struct wayland *wayl = seat->wayl;

    assert(offer == seat->clipboard.data_offer);

    /* Remember _which_ terminal the current DnD offer is targeting */
    assert(seat->clipboard.window == NULL);
    tll_foreach(wayl->terms, it) {
        if (term_surface_kind(it->item, surface) == TERM_SURF_GRID &&
            !it->item->is_sending_paste_data)
        {
            wl_data_offer_accept(
                offer, serial, mime_type_map[seat->clipboard.mime_type]);
            wl_data_offer_set_actions(
                offer,
                WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY,
                WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY);

            seat->clipboard.window = it->item->window;
            return;
        }
    }

    /* Either terminal is already busy sending paste data, or mouse
     * pointer isn’t over the grid */
    seat->clipboard.window = NULL;
    wl_data_offer_set_actions(offer, 0, 0);
}

static void
leave(void *data, struct wl_data_device *wl_data_device)
{
    struct seat *seat = data;
    seat->clipboard.window = NULL;
}

static void
motion(void *data, struct wl_data_device *wl_data_device, uint32_t time,
       wl_fixed_t x, wl_fixed_t y)
{
}

struct dnd_context {
    struct terminal *term;
    struct wl_data_offer *data_offer;
};

static void
receive_dnd(char *data, size_t size, void *user)
{
    struct dnd_context *ctx = user;
    receive_offer(data, size, ctx->term);
}

static void
receive_dnd_done(void *user)
{
    struct dnd_context *ctx = user;

    wl_data_offer_finish(ctx->data_offer);
    wl_data_offer_destroy(ctx->data_offer);
    receive_offer_done(ctx->term);
    free(ctx);
}

static void
drop(void *data, struct wl_data_device *wl_data_device)
{
    struct seat *seat = data;

    assert(seat->clipboard.window != NULL);
    struct terminal *term = seat->clipboard.window->term;

    struct wl_clipboard *clipboard = &seat->clipboard;

    struct dnd_context *ctx = xmalloc(sizeof(*ctx));
    *ctx = (struct dnd_context){
        .term = term,
        .data_offer = clipboard->data_offer,
    };

    /* Prepare a pipe the other client can write its selection to us */
    int fds[2];
    if (pipe2(fds, O_CLOEXEC) == -1) {
        LOG_ERRNO("failed to create pipe");
        free(ctx);
        return;
    }

    int read_fd = fds[0];
    int write_fd = fds[1];

    LOG_DBG("DnD drop: mime-type=%s", mime_type_map[clipboard->mime_type]);

    /* Give write-end of pipe to other client */
    wl_data_offer_receive(
        clipboard->data_offer, mime_type_map[clipboard->mime_type], write_fd);

    /* Don't keep our copy of the write-end open (or we'll never get EOF) */
    close(write_fd);

    term->is_sending_paste_data = true;

    if (term->bracketed_paste)
        term_paste_data_to_slave(term, "\033[200~", 6);

    begin_receive_clipboard(
        term, read_fd, clipboard->mime_type,
        &receive_dnd, &receive_dnd_done, ctx);

    /* data offer is now “owned” by the receive context */
    clipboard->data_offer = NULL;
    clipboard->mime_type = DATA_OFFER_MIME_UNSET;
}

static void
selection(void *data, struct wl_data_device *wl_data_device,
          struct wl_data_offer *offer)
{
    /* Selection offer from other client */
    struct seat *seat = data;
    if (offer == NULL)
        data_offer_reset(&seat->clipboard);
    else
        assert(offer == seat->clipboard.data_offer);
}

const struct wl_data_device_listener data_device_listener = {
    .data_offer = &data_offer,
    .enter = &enter,
    .leave = &leave,
    .motion = &motion,
    .drop = &drop,
    .selection = &selection,
};

static void
primary_offer(void *data,
              struct zwp_primary_selection_offer_v1 *zwp_primary_selection_offer,
              const char *mime_type)
{
    LOG_DBG("primary offer: %s", mime_type);
    struct seat *seat = data;
    select_mime_type_for_offer(mime_type, &seat->primary.mime_type);
}

static const struct zwp_primary_selection_offer_v1_listener primary_selection_offer_listener = {
    .offer = &primary_offer,
};

static void
primary_offer_reset(struct wl_primary *primary)
{
    if (primary->data_offer != NULL) {
        zwp_primary_selection_offer_v1_destroy(primary->data_offer);
        primary->data_offer = NULL;
    }

    primary->mime_type = DATA_OFFER_MIME_UNSET;
}

static void
primary_data_offer(void *data,
                   struct zwp_primary_selection_device_v1 *zwp_primary_selection_device,
                   struct zwp_primary_selection_offer_v1 *offer)
{
    struct seat *seat = data;
    primary_offer_reset(&seat->primary);
    seat->primary.data_offer = offer;
    zwp_primary_selection_offer_v1_add_listener(
        offer, &primary_selection_offer_listener, seat);
}

static void
primary_selection(void *data,
                  struct zwp_primary_selection_device_v1 *zwp_primary_selection_device,
                  struct zwp_primary_selection_offer_v1 *offer)
{
    /* Selection offer from other client, for primary */

    struct seat *seat = data;
    if (offer == NULL)
        primary_offer_reset(&seat->primary);
    else
        assert(seat->primary.data_offer == offer);
}

const struct zwp_primary_selection_device_v1_listener primary_selection_device_listener = {
    .data_offer = &primary_data_offer,
    .selection = &primary_selection,
};