1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
|
#include "osc.h"
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <sys/epoll.h>
#define LOG_MODULE "osc"
#define LOG_ENABLE_DBG 0
#include "log.h"
#include "base64.h"
#include "config.h"
#include "macros.h"
#include "notify.h"
#include "selection.h"
#include "terminal.h"
#include "uri.h"
#include "util.h"
#include "xmalloc.h"
#include "xsnprintf.h"
#define UNHANDLED() LOG_DBG("unhandled: OSC: %.*s", (int)term->vt.osc.idx, term->vt.osc.data)
static void
osc_to_clipboard(struct terminal *term, const char *target,
const char *base64_data)
{
bool to_clipboard = false;
bool to_primary = false;
if (target[0] == '\0')
to_clipboard = true;
for (const char *t = target; *t != '\0'; t++) {
switch (*t) {
case 'c':
to_clipboard = true;
break;
case 's':
case 'p':
to_primary = true;
break;
default:
LOG_WARN("unimplemented: clipboard target '%c'", *t);
break;
}
}
/* Find a seat in which the terminal has focus */
struct seat *seat = term_first_focused_seat(term);
if (seat == NULL) {
LOG_WARN("OSC-52: client tried to write to clipboard data while window was unfocused");
return;
}
if (!term_osc_copy_allowed(term)) {
LOG_DBG("OSC-52: ignoring copy request: disabled in configuration");
return;
}
char *decoded = base64_decode(base64_data, NULL);
if (decoded == NULL || decoded[0] == '\0') {
if (decoded == NULL) {
if (errno == EINVAL)
LOG_WARN("OSC: invalid clipboard data: %s", base64_data);
else
LOG_ERRNO("base64_decode() failed");
}
if (to_clipboard)
selection_clipboard_unset(seat);
if (to_primary)
selection_primary_unset(seat);
free(decoded);
return;
}
LOG_DBG("decoded: %s", decoded);
if (to_clipboard) {
char *copy = xstrdup(decoded);
if (!text_to_clipboard(seat, term, copy, NULL, seat->kbd.serial))
free(copy);
}
if (to_primary) {
char *copy = xstrdup(decoded);
if (!text_to_primary(seat, term, copy, NULL, seat->kbd.serial))
free(copy);
}
free(decoded);
}
struct clip_context {
struct seat *seat;
struct terminal *term;
uint8_t buf[3];
int idx;
struct {
bool is_kitty;
bool from_primary;
size_t chunk_bytes_written; /* Bytes written so far, in current chunk */
char *encoded_mime_type; /* Currently "active" mime-type, base64 encoded */
tll(char *) mime_types; /* Remaining mime-types */
} kitty;
};
static void
from_clipboard_cb(char *text, size_t size, void *user)
{
struct clip_context *ctx = user;
struct terminal *term = ctx->term;
xassert(ctx->idx >= 0 && ctx->idx <= 2);
const char *t = text;
size_t left = size;
if (ctx->idx > 0) {
for (size_t i = ctx->idx; i < 3 && left > 0; i++, t++, left--)
ctx->buf[ctx->idx++] = *t;
xassert(ctx->idx <= 3);
if (ctx->idx == 3) {
char *chunk = base64_encode(ctx->buf, 3);
xassert(chunk != NULL);
xassert(strlen(chunk) == 4);
term_paste_data_to_slave(term, chunk, 4);
free(chunk);
ctx->kitty.chunk_bytes_written += 3;
ctx->idx = 0;
}
}
if (left == 0)
return;
xassert(ctx->idx == 0);
const int remaining = left % 3;
for (int i = remaining; i > 0; i--)
ctx->buf[ctx->idx++] = text[size - i];
xassert(ctx->idx == remaining);
const size_t count = left / 3 * 3;
char *chunk = base64_encode(t, count);
xassert(chunk != NULL);
xassert(strlen(chunk) % 4 == 0);
if (unlikely(ctx->kitty.is_kitty && ctx->kitty.chunk_bytes_written + count > 4096)) {
/* New chunk */
term_paste_data_to_slave(term, "\033\\", 2);
term_paste_data_to_slave(term, "\033]5522;type=read:status=DATA:mime=", 34);
term_paste_data_to_slave(term, ctx->kitty.encoded_mime_type,
strlen(ctx->kitty.encoded_mime_type));
term_paste_data_to_slave(term, ";", 1);
ctx->kitty.chunk_bytes_written = 0;
}
term_paste_data_to_slave(term, chunk, strlen(chunk));
ctx->kitty.chunk_bytes_written += count;
free(chunk);
}
static void kitty_clipboard_read_next_mime_type(struct clip_context *ctx);
static void
from_clipboard_done(void *user)
{
struct clip_context *ctx = user;
struct terminal *term = ctx->term;
if (ctx->idx > 0) {
char res[4];
base64_encode_final(ctx->buf, ctx->idx, res);
term_paste_data_to_slave(term, res, 4);
ctx->idx = 0;
}
if (term->vt.osc.bel)
term_paste_data_to_slave(term, "\a", 1);
else
term_paste_data_to_slave(term, "\033\\", 2);
if (ctx->kitty.is_kitty) {
free(ctx->kitty.encoded_mime_type);
ctx->kitty.encoded_mime_type = NULL;
/* Continue with the next mime-type, if there are any left */
if (tll_length(ctx->kitty.mime_types) > 0) {
kitty_clipboard_read_next_mime_type(ctx);
return;
}
/* If not, we're done! */
term_paste_data_to_slave(term, "\033]5522;type=read:status=DONE\033\\", 30);
}
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);
free(ctx);
}
static void
osc_from_clipboard(struct terminal *term, const char *source)
{
/* Find a seat in which the terminal has focus */
struct seat *seat = term_first_focused_seat(term);
if (seat == NULL) {
LOG_WARN("OSC-52: client tried to read clipboard data while window was unfocused");
return;
}
if (!term_osc_paste_allowed(term)) {
LOG_DBG("OSC-52: ignoring paste request: disabled in configuration");
return;
}
/* Use clipboard if no source has been specified */
char src = source[0] == '\0' ? 'c' : 0;
bool from_clipboard = src == 'c';
bool from_primary = false;
for (const char *s = source;
*s != '\0' && !from_clipboard && !from_primary;
s++)
{
if (*s == 'c' || *s == 'p' || *s == 's') {
src = *s;
switch (src) {
case 'c':
from_clipboard = selection_clipboard_has_data(seat);
break;
case 's':
case 'p':
from_primary = selection_primary_has_data(seat);
break;
}
} else
LOG_WARN("unimplemented: clipboard source '%c'", *s);
}
if (!from_clipboard && !from_primary)
return;
if (term->is_sending_paste_data) {
/* FIXME: we should wait for the paste to end, then continue
with the OSC-52 reply */
term_to_slave(term, "\033]52;", 5);
term_to_slave(term, &src, 1);
term_to_slave(term, ";", 1);
if (term->vt.osc.bel)
term_to_slave(term, "\a", 1);
else
term_to_slave(term, "\033\\", 2);
return;
}
term->is_sending_paste_data = true;
term_paste_data_to_slave(term, "\033]52;", 5);
term_paste_data_to_slave(term, &src, 1);
term_paste_data_to_slave(term, ";", 1);
struct clip_context *ctx = xmalloc(sizeof(*ctx));
*ctx = (struct clip_context) {.seat = seat, .term = term};
if (from_clipboard) {
text_from_clipboard(
seat, term, true, &from_clipboard_cb, &from_clipboard_done, ctx, NULL);
}
if (from_primary) {
text_from_primary(
seat, term, true, &from_clipboard_cb, &from_clipboard_done, ctx, NULL);
}
}
static void
osc_selection(struct terminal *term, char *string)
{
char *p = string;
bool clipboard_done = false;
/* The first parameter is a string of clipbard sources/targets */
while (*p != '\0' && !clipboard_done) {
switch (*p) {
case ';':
clipboard_done = true;
*p = '\0';
break;
}
p++;
}
LOG_DBG("clipboard: target = %s data = %s", string, p);
if (p[0] == '?' && p[1] == '\0')
osc_from_clipboard(term, string);
else
osc_to_clipboard(term, string, p);
}
void
kitty_clipboard_query(struct terminal *term, bool primary)
{
/*
* Enumerate the available mime-types
*/
LOG_DBG("OSC-5522: query mime-types: primary=%d", primary);
if (!term_osc_paste_allowed(term)) {
LOG_DBG("OSC-5522: ignoring paste request: disabled in configuration");
term_to_slave(term, "\033]5522;type=read:status=EPERM\033\\", 31);
return;
}
/* Find a seat in which the terminal has focus */
struct seat *seat = term_first_focused_seat(term);
if (seat == NULL) {
LOG_WARN("OSC-5522: client tried to read clipboard data "
"while window was unfocused");
term_to_slave(term, "\033]5522;type=read:status=ENOSYS\033\\", 32);
return;
}
const mime_list_t *mime_list = !primary
? &seat->clipboard.all_mime_types
: &seat->primary.all_mime_types;
term_to_slave(term, "\033]5522;type=read:", 17);
if (primary)
term_to_slave(term, "loc=primary:", 12);
term_to_slave(term, "status=OK\033\\", 11);
term_to_slave(term, "\033]5522;type=read:status=DATA:mime=Lg==;", 39); /* base64(".") == "Lg==" */
char *mime_types = NULL;
size_t len = 0;
size_t pos = 0;
/* Calculate total length of the mime list */
tll_foreach(*mime_list, it)
len += strlen(it->item) + 1;
mime_types = xmalloc(len + 1);
mime_types[0] = '\0';
tll_foreach(*mime_list, it) {
strcpy(mime_types + pos, it->item);
pos += strlen(it->item);
mime_types[pos++] = ' ';
}
if (len > 0) {
/* Shave off the last ' ' */
len--;
mime_types[len] = '\0';
} else {
mime_types[0] = '\0';
}
char *encoded_mime_list = base64_encode_oneshot(mime_types, len);
term_to_slave(term, encoded_mime_list, strlen(encoded_mime_list));
free(encoded_mime_list);
free(mime_types);
term_to_slave(term, "\033\\", 2);
term_to_slave(term, "\033]5522;type=read:status=DONE\033\\", 30);
}
static void
kitty_clipboard_read_next_mime_type(struct clip_context *ctx)
{
struct terminal *term = ctx->term;
struct seat *seat = ctx->seat;
xassert(term->is_sending_paste_data);
xassert(ctx->kitty.encoded_mime_type == NULL);
xassert(tll_length(ctx->kitty.mime_types) > 0);
/* Pop next mime-type to read */
char *mime_type = tll_pop_front(ctx->kitty.mime_types);
const size_t mime_len = strlen(mime_type);
ctx->kitty.encoded_mime_type = base64_encode_oneshot(mime_type, mime_len);
term_paste_data_to_slave(term, "\033]5522;type=read:status=OK\033\\", 28);
term_paste_data_to_slave(term, "\033]5522;type=read:status=DATA:mime=", 34);
term_paste_data_to_slave(term, ctx->kitty.encoded_mime_type,
strlen(ctx->kitty.encoded_mime_type));
term_paste_data_to_slave(term, ";", 1);
if (!ctx->kitty.from_primary) {
text_from_clipboard(
seat, term, true, &from_clipboard_cb, &from_clipboard_done,
ctx, mime_type);
} else {
text_from_primary(
seat, term, true, &from_clipboard_cb, &from_clipboard_done,
ctx, mime_type);
}
free(mime_type);
}
static void
kitty_clipboard_read(struct terminal *term, bool primary, char *mime_types)
{
LOG_DBG("OSC-5522: read: primary=%d, mime-type=%s", primary, mime_types);
if (!term_osc_paste_allowed(term)) {
LOG_DBG("OSC-5522: ignoring paste request: disabled in configuration");
term_to_slave(term, "\033]5522;type=read:status=EPERM\033\\", 31);
return;
}
if (term->is_sending_paste_data) {
term_to_slave(term, "\033]5522;type=read:status=EBUSY\033\\", 31);
return;
}
/* Find a seat in which the terminal has focus */
struct seat *seat = term_first_focused_seat(term);
if (seat == NULL) {
LOG_WARN("OSC-5522: client tried to read clipboard data "
"while window was unfocused");
term_to_slave(term, "\033]5522;type=read:status=ENOSYS\033\\", 32);
return;
}
struct clip_context *ctx = xmalloc(sizeof(*ctx));
*ctx = (struct clip_context) {
.seat = seat,
.term = term,
.kitty = {
.is_kitty = true,
.from_primary = primary,
.mime_types = tll_init(),
},
};
/* Split upt the space-separated list of mime-types we're about to read */
for (char *save = NULL, *mime_type = strtok_r(mime_types, " ", &save);
mime_type != NULL;
mime_type = strtok_r(NULL, " ", &save))
{
tll_push_back(ctx->kitty.mime_types, xstrdup(mime_type));
}
/* Start reading the first mime-type */
term->is_sending_paste_data = true;
kitty_clipboard_read_next_mime_type(ctx);
}
void
kitty_clipboard_reset(struct terminal *term)
{
free(term->kitty_clipboard.active_mime_type);
free(term->kitty_clipboard.data);
tll_foreach(term->kitty_clipboard.committed_mime_data, it) {
struct kitty_mime_data *mime_data = &it->item;
free(mime_data->mime_type);
free(mime_data->data);
tll_remove(term->kitty_clipboard.committed_mime_data, it);
}
tll_foreach(term->kitty_clipboard.mime_aliases, it) {
struct kitty_mime_alias *alias = &it->item;
free(alias->target);
free(alias->alias);
tll_remove(term->kitty_clipboard.mime_aliases, it);
}
term->kitty_clipboard.for_primary = false;
term->kitty_clipboard.has_error = false;
term->kitty_clipboard.error = NULL;
term->kitty_clipboard.active_mime_type = NULL;
term->kitty_clipboard.data = NULL;
term->kitty_clipboard.data_len = 0;
}
static void
kitty_clipboard_wdata_commit(struct terminal *term)
{
if (term->kitty_clipboard.active_mime_type == NULL)
return;
LOG_DBG("committing %zu bytes of %s data",
term->kitty_clipboard.data_len,
term->kitty_clipboard.active_mime_type);
tll_push_back(term->kitty_clipboard.committed_mime_data,
((struct kitty_mime_data){
.mime_type = term->kitty_clipboard.active_mime_type,
.data = term->kitty_clipboard.data,
.data_len = term->kitty_clipboard.data_len}));
term->kitty_clipboard.active_mime_type = NULL;
term->kitty_clipboard.data = NULL;
term->kitty_clipboard.data_len = 0;
}
static void
kitty_clipboard_write_finish(struct terminal *term)
{
if (term->kitty_clipboard.has_error) {
/* There were error(s) along the way - report the first error */
char reply[64];
int n = snprintf(reply, sizeof(reply),
"\033]5522;type=write:status=%s\033\\",
term->kitty_clipboard.error);
term_to_slave(term, reply, n);
return;
}
/*
* No errors, now it's time to actually write to the clipboard
*/
struct seat *seat = term_first_focused_seat(term);
if (seat == NULL) {
LOG_WARN("OSC-5522: client tried to write6 clipboard data "
"while window was unfocused");
term_to_slave(term, "\033]5522;type=write:status=ENOSYS\033\\", 33);
return;
}
const size_t data_count = tll_length(term->kitty_clipboard.committed_mime_data);
const size_t mime_count = data_count + tll_length(term->kitty_clipboard.mime_aliases);
/* Package clipboard contents for text_to_{clipboard,primary}() */
struct kitty_clipboard_offer clip;
clip.data = xmalloc(data_count * sizeof(seat->clipboard.kitty.data[0]));
clip.data_len = xmalloc(data_count * sizeof(seat->clipboard.kitty.data_len[0]));
clip.data_count = data_count;
clip.mime_data_map = xmalloc(mime_count * sizeof(seat->clipboard.kitty.mime_data_map[0]));
clip.mime_data_map_count = mime_count;
size_t i = 0;
tll_foreach(term->kitty_clipboard.committed_mime_data, it) {
clip.data[i] = it->item.data;
clip.data_len[i] = it->item.data_len;
clip.mime_data_map[i].mime_type = it->item.mime_type;
clip.mime_data_map[i].data_idx = i;
i++;
/* Remove without freeing, data is now owned by clip */
tll_remove(term->kitty_clipboard.committed_mime_data, it);
}
xassert(i == data_count);
/* i keeps counting... */
tll_foreach(term->kitty_clipboard.mime_aliases, it) {
const struct kitty_mime_alias *alias = &it->item;
/* Find target index */
ssize_t idx = -1;
for (size_t j = 0; j < data_count; j++) {
if (streq(clip.mime_data_map[j].mime_type, alias->target)) {
idx = j;
break;
}
}
if (likely(idx >= 0)) {
xassert(idx < data_count);
clip.mime_data_map[i].mime_type = alias->alias;
clip.mime_data_map[i].data_idx = idx;
i++;
/* TODO: can we make target point to the original mime-type, so that we don't have to free it here? */
free(alias->target);
} else {
LOG_WARN(
"OSC-5522: invalid WALIAS: %s is not a valid target mime-type",
alias->target);
free(alias->target);
free(alias->alias);
}
tll_remove(term->kitty_clipboard.mime_aliases, it);
}
xassert(i <= mime_count); /* We _may_ have fewer, if there were invalid walias */
clip.mime_data_map_count = i;
if (!term->kitty_clipboard.for_primary)
text_to_clipboard(seat, term, NULL, &clip, seat->kbd.serial);
else
text_to_primary(seat, term, NULL, &clip, seat->kbd.serial);
term_to_slave(term, "\033]5522;type=write:status=DONE\033\\", 31);
}
static void
kitty_clipboard(struct terminal *term, char *string)
{
char *ctx = NULL;
char *params = strtok_r(string, ";", &ctx);
char *encoded_payload = strtok_r(NULL, ";", &ctx);
enum { UNSPECIFIED, READ, WRITE, WDATA, WALIAS } type = UNSPECIFIED;
enum { CLIPBOARD, PRIMARY } location = CLIPBOARD;
const char *encoded_mime_type = NULL;
/* Parse the parameter (key/value pairs) section */
ctx = NULL;
for (char *p = strtok_r(params, ":", &ctx);
p != NULL;
p = strtok_r(NULL, ":", &ctx))
{
char *value = strchr(p, '=');
if (value == NULL)
continue;
*value = '\0';
value++;
LOG_DBG("OSC-5522: param: %s=%s", p, value);
if (streq(p, "type")) {
if (streq(value, "read"))
type = READ;
else if (streq(value, "write"))
type = WRITE;
else if (streq(value, "wdata"))
type = WDATA;
else if (streq(value, "walias"))
type = WALIAS;
else
LOG_WARN("OSC-5522: invalid 'type': %s", value);
}
else if (streq(p, "loc")) {
if (streq(value, "primary"))
location = PRIMARY;
else
LOG_WARN("OSC-5522: invalid 'loc': %s", value);
}
else if (streq(p, "mime")) {
encoded_mime_type = value;
}
else if (streq(p, "pw"))
;
else if (streq(p, "name"))
;
else
LOG_WARN("OSC-5522: unrecognized key/value parameter: %s=%s",
p, value);
}
if (type == UNSPECIFIED) {
LOG_WARN("OSC-5522: 'type' not specified");
/* Can't reply with status=EINVAL since we don't have a valid type */
return;
}
char *mime_type = encoded_mime_type != NULL
? base64_decode(encoded_mime_type, NULL)
: NULL;
size_t payload_len = 0;
char *payload = encoded_payload != NULL
? base64_decode(encoded_payload, &payload_len)
: NULL;
switch (type) {
case READ:
if (unlikely(payload == NULL))
term_to_slave(term, "\033]5522;type=read:status=EINVAL\033\\", 32);
else {
if (streq(payload, "."))
kitty_clipboard_query(term, location == PRIMARY);
else
kitty_clipboard_read(term, location == PRIMARY, payload);
}
break;
case WRITE: {
/* Reset */
kitty_clipboard_reset(term);
if (!term_osc_copy_allowed(term)) {
LOG_DBG("OSC-5522: ignoring copy request: disabled in configuration");
term->kitty_clipboard.has_error = true;
term->kitty_clipboard.error = "EPERM";
} else if (term->is_sending_paste_data) {
term->kitty_clipboard.has_error = true;
term->kitty_clipboard.error = "EBUSY";
} else
term->kitty_clipboard.for_primary = location == PRIMARY;
break;
}
case WDATA:
if (encoded_mime_type == NULL && encoded_payload == NULL) {
/* This was the last packet */
kitty_clipboard_wdata_commit(term);
kitty_clipboard_write_finish(term);
kitty_clipboard_reset(term);
} else if (!term->kitty_clipboard.has_error) {
if (unlikely(mime_type == NULL || payload == NULL)) {
term->kitty_clipboard.has_error = true;
term->kitty_clipboard.error = "EINVAL";
} else {
if (term->kitty_clipboard.active_mime_type == NULL ||
!streq(term->kitty_clipboard.active_mime_type, mime_type))
{
/*
* This chunk has a different mime-type than the
* last one. We need to commit the last one, start
* a new buffer for the new mime-type.
*/
if (term->kitty_clipboard.active_mime_type != NULL)
kitty_clipboard_wdata_commit(term);
term->kitty_clipboard.active_mime_type = mime_type;
mime_type = NULL;
}
const size_t old_len = term->kitty_clipboard.data_len;
const size_t new_len = old_len + payload_len;
term->kitty_clipboard.data = xrealloc(term->kitty_clipboard.data, new_len);
memcpy(&term->kitty_clipboard.data[old_len], payload, payload_len);
term->kitty_clipboard.data_len = new_len;
}
}
break;
case WALIAS:
if (!term->kitty_clipboard.has_error) {
if (unlikely(mime_type == NULL || payload == NULL)) {
term->kitty_clipboard.has_error = true;
term->kitty_clipboard.error = "EINVAL";
} else {
/* Aliases is a space separated list of mime-types */
char *save = NULL;
for (const char *alias = strtok_r(payload, " ", &save);
alias != NULL;
alias = strtok_r(NULL, " ", &save))
{
tll_push_back(
term->kitty_clipboard.mime_aliases,
((struct kitty_mime_alias){
.target = xstrdup(mime_type),
.alias = xstrdup(alias)}));
}
}
}
break;
case UNSPECIFIED:
BUG("'type' is unspecified");
break;
}
free(mime_type);
free(payload);
}
static void
osc_flash(struct terminal *term)
{
/* Our own private - flash */
term_flash(term, 50);
}
static bool
parse_legacy_color(const char *string, uint32_t *color, bool *_have_alpha,
uint16_t *_alpha)
{
bool have_alpha = false;
uint16_t alpha = 0xffff;
if (string[0] == '[') {
/* e.g. \E]11;[50]#00ff00 */
const char *start = &string[1];
errno = 0;
char *end;
unsigned long percent = strtoul(start, &end, 10);
if (errno != 0 || *end != ']')
return false;
have_alpha = true;
alpha = (0xffff * min(percent, 100) + 50) / 100;
string = end + 1;
}
if (string[0] != '#')
return false;
string++;
const size_t len = strlen(string);
if (len % 3 != 0)
return false;
const int digits = len / 3;
int rgb[3];
for (size_t i = 0; i < 3; i++) {
rgb[i] = 0;
for (size_t j = 0; j < digits; j++) {
size_t idx = i * digits + j;
char c = string[idx];
rgb[i] <<= 4;
if (!isxdigit(c))
rgb[i] |= 0;
else
rgb[i] |= c >= '0' && c <= '9' ? c - '0' :
c >= 'a' && c <= 'f' ? c - 'a' + 10 : c - 'A' + 10;
}
/* Values with less than 16 bits represent the *most
* significant bits*. I.e. the values are *not* scaled */
rgb[i] <<= 16 - (4 * digits);
}
/* Re-scale to 8-bit */
uint8_t r = 256 * (rgb[0] / 65536.);
uint8_t g = 256 * (rgb[1] / 65536.);
uint8_t b = 256 * (rgb[2] / 65536.);
LOG_DBG("legacy: %02x%02x%02x (alpha=%04x)", r, g, b,
have_alpha ? alpha : 0xffff);
*color = r << 16 | g << 8 | b;
if (_have_alpha != NULL)
*_have_alpha = have_alpha;
if (_alpha != NULL)
*_alpha = alpha;
return true;
}
static bool
parse_rgb(const char *string, uint32_t *color, bool *_have_alpha,
uint16_t *_alpha)
{
size_t len = strlen(string);
bool have_alpha = len >= 4 && strncmp(string, "rgba", 4) == 0;
/* Verify we have the minimum required length (for "") */
if (have_alpha) {
if (len < STRLEN("rgba:x/x/x/x"))
return false;
} else {
if (len < STRLEN("rgb:x/x/x"))
return false;
}
/* Verify prefix is "rgb:" or "rgba:" */
if (have_alpha) {
if (strncmp(string, "rgba:", 5) != 0)
return false;
string += 5;
len -= 5;
} else {
if (strncmp(string, "rgb:", 4) != 0)
return false;
string += 4;
len -= 4;
}
int rgb[4];
int digits[4];
for (size_t i = 0; i < (have_alpha ? 4 : 3); i++) {
for (rgb[i] = 0, digits[i] = 0;
len > 0 && *string != '/';
len--, string++, digits[i]++)
{
char c = *string;
rgb[i] <<= 4;
if (!isxdigit(c))
rgb[i] |= 0;
else
rgb[i] |= c >= '0' && c <= '9' ? c - '0' :
c >= 'a' && c <= 'f' ? c - 'a' + 10 : c - 'A' + 10;
}
if (i >= (have_alpha ? 3 : 2))
break;
if (len == 0 || *string != '/')
return false;
string++; len--;
}
/* Re-scale to 8-bit */
uint8_t r = 256 * (rgb[0] / (double)(1 << (4 * digits[0])));
uint8_t g = 256 * (rgb[1] / (double)(1 << (4 * digits[1])));
uint8_t b = 256 * (rgb[2] / (double)(1 << (4 * digits[2])));
uint16_t alpha = 0xffff;
if (have_alpha)
alpha = 65536 * (rgb[3] / (double)(1 << (4 * digits[3])));
if (have_alpha)
LOG_DBG("rgba: %02x%02x%02x (alpha=%04x)", r, g, b, alpha);
else
LOG_DBG("rgb: %02x%02x%02x", r, g, b);
if (_have_alpha != NULL)
*_have_alpha = have_alpha;
if (_alpha != NULL)
*_alpha = alpha;
*color = r << 16 | g << 8 | b;
return true;
}
static void
osc_set_pwd(struct terminal *term, char *string)
{
LOG_DBG("PWD: URI: %s", string);
char *scheme, *host, *path;
if (!uri_parse(string, strlen(string), &scheme, NULL, NULL, &host, NULL, &path, NULL, NULL)) {
LOG_ERR("OSC7: invalid URI: %s", string);
return;
}
if (streq(scheme, "file") && hostname_is_localhost(host)) {
LOG_DBG("OSC7: pwd: %s", path);
free(term->cwd);
term->cwd = path;
} else
free(path);
free(scheme);
free(host);
}
static void
osc_uri(struct terminal *term, char *string)
{
/*
* \E]8;<params>;URI\e\\
*
* Params are key=value pairs, separated by ':'.
*
* The only defined key (as of 2020-05-31) is 'id', which is used
* to group split-up URIs:
*
* ╔═ file1 ════╗
* ║ ╔═ file2 ═══╗
* ║http://exa║Lorem ipsum║
* ║le.com ║ dolor sit ║
* ║ ║amet, conse║
* ╚══════════║ctetur adip║
* ╚═══════════╝
*
* This lets a terminal emulator highlight both parts at the same
* time (e.g. when hovering over one of the parts with the mouse).
*/
char *params = string;
char *params_end = strchr(params, ';');
if (params_end == NULL)
return;
*params_end = '\0';
const char *uri = params_end + 1;
uint64_t id = (uint64_t)rand() << 32 | rand();
char *ctx = NULL;
for (const char *key_value = strtok_r(params, ":", &ctx);
key_value != NULL;
key_value = strtok_r(NULL, ":", &ctx))
{
const char *key = key_value;
char *operator = (char *)strchr(key_value, '=');
if (operator == NULL)
continue;
*operator = '\0';
const char *value = operator + 1;
if (streq(key, "id"))
id = sdbm_hash(value);
}
if (uri[0] == '\0') {
LOG_DBG("OSC-8: close");
term_osc8_close(term);
} else {
LOG_DBG("OSC-8: URL=%s, id=%" PRIu64, uri, id);
term_osc8_open(term, id, uri);
}
}
static void
osc_notify(struct terminal *term, char *string)
{
/*
* The 'notify' perl extension
* (https://pub.phyks.me/scripts/urxvt/notify) is very simple:
*
* #!/usr/bin/perl
*
* sub on_osc_seq_perl {
* my ($term, $osc, $resp) = @_;
* if ($osc =~ /^notify;(\S+);(.*)$/) {
* system("notify-send '$1' '$2'");
* }
* }
*
* As can be seen, the notification text is not encoded in any
* way. The regex does a greedy match of the ';' separator. Thus,
* any extra ';' will end up being part of the title. There's no
* way to have a ';' in the message body.
*
* I've changed that behavior slightly in; we split the title from
* body on the *first* ';', allowing us to have semicolons in the
* message body, but *not* in the title.
*/
char *ctx = NULL;
const char *title = strtok_r(string, ";", &ctx);
const char *msg = strtok_r(NULL, "\x00", &ctx);
if (title == NULL)
return;
if (mbsntoc32(NULL, title, strlen(title), 0) == (size_t)-1) {
LOG_WARN("%s: notification title is not valid UTF-8, ignoring", title);
return;
}
if (msg != NULL && mbsntoc32(NULL, msg, strlen(msg), 0) == (size_t)-1) {
LOG_WARN("%s: notification message is not valid UTF-8, ignoring", msg);
return;
}
char *msgdup = NULL;
if (msg != NULL)
msgdup = xstrdup(msg);
notify_notify(term, &(struct notification){
.title = xstrdup(title),
.body = msgdup,
.expire_time = -1,
.focus = true,
});
}
IGNORE_WARNING("-Wpedantic")
static bool
verify_kitty_id_is_valid(const char *id)
{
const size_t len = strlen(id);
for (size_t i = 0; i < len; i++) {
switch (id[i]) {
case 'a' ... 'z':
case 'A' ... 'Z':
case '0' ... '9':
case '_':
case '-':
case '+':
case '.':
break;
default:
return false;
}
}
return true;
}
UNIGNORE_WARNINGS
static void
kitty_notification(struct terminal *term, char *string)
{
/* https://sw.kovidgoyal.net/kitty/desktop-notifications */
char *payload_raw = strchr(string, ';');
if (payload_raw == NULL)
return;
char *parameters = string;
*payload_raw = '\0';
payload_raw++;
char *id = NULL; /* The 'i' parameter */
char *app_id = NULL; /* The 'f' parameter */
char *icon_cache_id = NULL; /* The 'g' parameter */
char *symbolic_icon = NULL; /* The 'n' parameter */
char *category = NULL; /* The 't' parameter */
char *sound_name = NULL; /* The 's' parameter */
char *payload = NULL;
bool focus = true; /* The 'a' parameter */
bool report_activated = false; /* The 'a' parameter */
bool report_closed = false; /* The 'c' parameter */
bool done = true; /* The 'd' parameter */
bool base64 = false; /* The 'e' parameter */
int32_t expire_time = -1; /* The 'w' parameter */
size_t payload_size;
enum {
PAYLOAD_TITLE,
PAYLOAD_BODY,
PAYLOAD_CLOSE,
PAYLOAD_ALIVE,
PAYLOAD_ICON,
PAYLOAD_BUTTON,
} payload_type = PAYLOAD_TITLE; /* The 'p' parameter */
enum notify_when when = NOTIFY_ALWAYS;
enum notify_urgency urgency = NOTIFY_URGENCY_NORMAL;
bool have_a = false;
bool have_c = false;
bool have_o = false;
bool have_u = false;
bool have_w = false;
char *ctx = NULL;
for (char *param = strtok_r(parameters, ":", &ctx);
param != NULL;
param = strtok_r(NULL, ":", &ctx))
{
/* All parameters are on the form X=value, where X is always
exactly one character */
if (param[0] == '\0' || param[1] != '=')
continue;
char *value = ¶m[2];
switch (param[0]) {
case 'a': {
/* notification activation action: focus|report|-focus|-report */
have_a = true;
char *a_ctx = NULL;
for (const char *v = strtok_r(value, ",", &a_ctx);
v != NULL;
v = strtok_r(NULL, ",", &a_ctx))
{
bool reverse = v[0] == '-';
if (reverse)
v++;
if (streq(v, "focus"))
focus = !reverse;
else if (streq(v, "report"))
report_activated = !reverse;
}
break;
}
case 'c':
if (value[0] == '1' && value[1] == '\0')
report_closed = true;
else if (value[0] == '0' && value[1] == '\0')
report_closed = false;
have_c = true;
break;
case 'd':
/* done: 0|1 */
if (value[0] == '0' && value[1] == '\0')
done = false;
else if (value[0] == '1' && value[1] == '\0')
done = true;
break;
case 'e':
/* base64 (payload encoding): 0=utf8, 1=base64(utf8) */
if (value[0] == '0' && value[1] == '\0')
base64 = false;
else if (value[0] == '1' && value[1] == '\0')
base64 = true;
break;
case 'i':
/* id */
if (verify_kitty_id_is_valid(value)) {
free(id);
id = xstrdup(value);
} else
LOG_WARN("OSC-99: ignoring invalid 'i' identifier");
break;
case 'p':
/* payload content: title|body */
if (streq(value, "title"))
payload_type = PAYLOAD_TITLE;
else if (streq(value, "body"))
payload_type = PAYLOAD_BODY;
else if (streq(value, "close"))
payload_type = PAYLOAD_CLOSE;
else if (streq(value, "alive"))
payload_type = PAYLOAD_ALIVE;
else if (streq(value, "icon"))
payload_type = PAYLOAD_ICON;
else if (streq(value, "buttons"))
payload_type = PAYLOAD_BUTTON;
else if (streq(value, "?")) {
/* Query capabilities */
const char *reply_id = id != NULL ? id : "0";
const char *p_caps = "title,body,?,close,alive,icon,buttons";
const char *a_caps = "focus,report";
const char *u_caps = "0,1,2";
char when_caps[64];
strcpy(when_caps, "unfocused");
if (!term->conf->desktop_notifications.inhibit_when_focused)
strcat(when_caps, ",always");
const char *terminator = term->vt.osc.bel ? "\a" : "\033\\";
char reply[512];
size_t n = xsnprintf(
reply, sizeof(reply),
"\033]99;i=%s:p=?;p=%s:a=%s:o=%s:u=%s:c=1:w=1:s=system,silent,error,warn,warning,info,question%s",
reply_id, p_caps, a_caps, when_caps, u_caps, terminator);
term_to_slave(term, reply, n);
goto out;
}
break;
case 'o':
/* honor when: always|unfocused|invisible */
have_o = true;
if (streq(value, "always"))
when = NOTIFY_ALWAYS;
else if (streq(value, "unfocused"))
when = NOTIFY_UNFOCUSED;
else if (streq(value, "invisible"))
when = NOTIFY_INVISIBLE;
break;
case 'u':
/* urgency: 0=low, 1=normal, 2=critical */
have_u = true;
if (value[0] == '0' && value[1] == '\0')
urgency = NOTIFY_URGENCY_LOW;
else if (value[0] == '1' && value[1] == '\0')
urgency = NOTIFY_URGENCY_NORMAL;
else if (value[0] == '2' && value[1] == '\0')
urgency = NOTIFY_URGENCY_CRITICAL;
break;
case 'w': {
/* Notification timeout */
errno = 0;
char *end = NULL;
long timeout = strtol(value, &end, 10);
if (errno == 0 && *end == '\0' && timeout <= INT32_MAX) {
expire_time = timeout;
have_w = true;
}
break;
}
case 'f': {
/* App-name */
char *decoded = base64_decode(value, NULL);
if (decoded != NULL) {
free(app_id);
app_id = decoded;
}
break;
}
case 't': {
/* Type (category) */
char *decoded = base64_decode(value, NULL);
if (decoded != NULL) {
if (category == NULL)
category = decoded;
else {
/* Append, comma separated */
char *old_category = category;
category = xstrjoin3(old_category, ",", decoded);
free(decoded);
free(old_category);
}
}
break;
}
case 's': {
/* Sound */
char *decoded = base64_decode(value, NULL);
if (decoded != NULL) {
free(sound_name);
sound_name = decoded;
const char *translated_name = NULL;
if (streq(decoded, "error"))
translated_name = "dialog-error";
else if (streq(decoded, "warn") || streq(decoded, "warning"))
translated_name = "dialog-warning";
else if (streq(decoded, "info"))
translated_name = "dialog-information";
else if (streq(decoded, "question"))
translated_name = "dialog-question";
if (translated_name != NULL) {
free(sound_name);
sound_name = xstrdup(translated_name);
}
}
break;
}
case 'g':
/* graphical ID (see 'n' and 'p=icon') */
free(icon_cache_id);
icon_cache_id = xstrdup(value);
break;
case 'n': {
/* Symbolic icon name, may used with 'g' */
/*
* Sigh, protocol says 'n' can be used multiple times, and
* that the terminal picks the first one that it can
* resolve.
*
* We can't resolve any icons at all. So, enter
* heuristics... let's pick the *shortest* symbolic
* name. The idea is that icon *names* are typically
* shorter than .desktop names, and macOS bundle
* identifiers.
*/
char *maybe_new_symbolic_icon = base64_decode(value, NULL);
if (maybe_new_symbolic_icon == NULL)
break;
if (symbolic_icon == NULL ||
strlen(maybe_new_symbolic_icon) < strlen(symbolic_icon))
{
free(symbolic_icon);
symbolic_icon = maybe_new_symbolic_icon;
/* Translate OSC-99 "special" names */
if (symbolic_icon != NULL) {
const char *translated_name = NULL;
if (streq(symbolic_icon, "error"))
translated_name = "dialog-error";
else if (streq(symbolic_icon, "warn") ||
streq(symbolic_icon, "warning"))
translated_name = "dialog-warning";
else if (streq(symbolic_icon, "info"))
translated_name = "dialog-information";
else if (streq(symbolic_icon, "question"))
translated_name = "dialog-question";
else if (streq(symbolic_icon, "help"))
translated_name = "system-help";
else if (streq(symbolic_icon, "file-manager"))
translated_name = "system-file-manager";
else if (streq(symbolic_icon, "system-monitor"))
translated_name = "utilities-system-monitor";
else if (streq(symbolic_icon, "text-editor"))
translated_name = "text-editor";
if (translated_name != NULL) {
free(symbolic_icon);
symbolic_icon = xstrdup(translated_name);
}
}
} else {
free(maybe_new_symbolic_icon);
}
break;
}
}
}
if (base64) {
payload = base64_decode(payload_raw, &payload_size);
if (payload == NULL)
goto out;
} else {
payload = xstrdup(payload_raw);
payload_size = strlen(payload);
}
/* Append metadata to previous notification chunk */
struct notification *notif = &term->kitty_notification;
if (!((id == NULL && notif->id == NULL) ||
(id != NULL && notif->id != NULL && streq(id, notif->id))) ||
!notif->may_be_programatically_closed) /* Free:d notification has this as false... */
{
/* ID mismatch, ignore previous notification state */
notify_free(term, notif);
notif->id = id;
notif->when = when;
notif->urgency = urgency;
notif->expire_time = expire_time;
notif->focus = focus;
notif->may_be_programatically_closed = true;
notif->report_activated = report_activated;
notif->report_closed = report_closed;
id = NULL; /* Prevent double free */
}
if (have_a) {
notif->focus = focus;
notif->report_activated = report_activated;
}
if (have_c)
notif->report_closed = report_closed;
if (have_o)
notif->when = when;
if (have_u)
notif->urgency = urgency;
if (have_w)
notif->expire_time = expire_time;
if (icon_cache_id != NULL) {
free(notif->icon_cache_id);
notif->icon_cache_id = icon_cache_id;
icon_cache_id = NULL; /* Prevent double free */
}
if (symbolic_icon != NULL) {
free(notif->icon_symbolic_name);
notif->icon_symbolic_name = symbolic_icon;
symbolic_icon = NULL;
}
if (app_id != NULL) {
free(notif->app_id);
notif->app_id = app_id;
app_id = NULL; /* Prevent double free */
}
if (category != NULL) {
if (notif->category == NULL) {
notif->category = category;
category = NULL; /* Prevent double free */
} else {
/* Append, comma separated */
char *new_category = xstrjoin3(notif->category, ",", category);
free(notif->category);
notif->category = new_category;
}
}
if (sound_name != NULL) {
notif->muted = streq(sound_name, "silent");
if (notif->muted || streq(sound_name, "system")) {
free(notif->sound_name);
notif->sound_name = NULL;
} else {
free(notif->sound_name);
notif->sound_name = sound_name;
sound_name = NULL; /* Prevent double free */
}
}
/* Handled chunked payload - append to existing metadata */
switch (payload_type) {
case PAYLOAD_TITLE:
case PAYLOAD_BODY: {
char **ptr = payload_type == PAYLOAD_TITLE
? ¬if->title
: ¬if->body;
if (*ptr == NULL) {
*ptr = payload;
payload = NULL;
} else {
char *old = *ptr;
*ptr = xstrjoin(old, payload);
free(old);
}
break;
}
case PAYLOAD_CLOSE:
case PAYLOAD_ALIVE:
/* Ignore payload */
break;
case PAYLOAD_ICON:
if (notif->icon_data == NULL) {
notif->icon_data = (uint8_t *)payload;
notif->icon_data_sz = payload_size;
payload = NULL;
} else {
notif->icon_data = xrealloc(
notif->icon_data, notif->icon_data_sz + payload_size);
memcpy(¬if->icon_data[notif->icon_data_sz], payload, payload_size);
notif->icon_data_sz += payload_size;
}
break;
case PAYLOAD_BUTTON: {
char *ctx = NULL;
for (const char *button = strtok_r(payload, "\u2028", &ctx);
button != NULL;
button = strtok_r(NULL, "\u2028", &ctx))
{
if (button[0] != '\0') {
tll_push_back(notif->actions, xstrdup(button));
}
}
break;
}
}
if (done) {
/* Update icon cache, if necessary */
if (notif->icon_cache_id != NULL &&
(notif->icon_symbolic_name != NULL || notif->icon_data != NULL))
{
notify_icon_del(term, notif->icon_cache_id);
notify_icon_add(term, notif->icon_cache_id,
notif->icon_symbolic_name,
notif->icon_data, notif->icon_data_sz);
/* Don't need this anymore */
free(notif->icon_symbolic_name);
free(notif->icon_data);
notif->icon_symbolic_name = NULL;
notif->icon_data = NULL;
notif->icon_data_sz = 0;
}
if (payload_type == PAYLOAD_CLOSE) {
if (notif->id != NULL)
notify_close(term, notif->id);
} else if (payload_type == PAYLOAD_ALIVE) {
char *alive_ids = NULL;
tll_foreach(term->active_notifications, it) {
/* TODO: check with kitty: use "0" for all
notifications with no ID? */
const char *item_id = it->item.id != NULL ? it->item.id : "0";
if (alive_ids == NULL)
alive_ids = xstrdup(item_id);
else {
char *old_alive_ids = alive_ids;
alive_ids = xstrjoin3(old_alive_ids, ",", item_id);
free(old_alive_ids);
}
}
char *reply = xasprintf(
"\033]99;i=%s:p=alive;%s\033\\",
notif->id != NULL ? notif->id : "0",
alive_ids != NULL ? alive_ids : "");
term_to_slave(term, reply, strlen(reply));
free(reply);
free(alive_ids);
} else {
/*
* Show notification.
*
* The checks for title|body is to handle notifications that
* only load icon data into the icon cache
*/
if (notif->title != NULL || notif->body != NULL) {
notify_notify(term, notif);
}
}
notify_free(term, notif);
}
out:
free(id);
free(app_id);
free(icon_cache_id);
free(symbolic_icon);
free(payload);
free(category);
free(sound_name);
}
static void
kitty_text_size(struct terminal *term, char *string)
{
char *text = strchr(string, ';');
if (text == NULL)
return;
char *parameters = string;
*text = '\0';
text++;
char32_t *wchars = ambstoc32(text);
if (wchars == NULL)
return;
int forced_width = 0;
char *ctx = NULL;
for (char *param = strtok_r(parameters, ":", &ctx);
param != NULL;
param = strtok_r(NULL, ":", &ctx))
{
/* All parameters are on the form X=value, where X is always
exactly one character */
if (param[0] == '\0' || param[1] != '=')
continue;
char *value = ¶m[2];
switch (param[0]) {
case 'w': {
errno = 0;
char *end = NULL;
unsigned long w = strtoul(value, &end, 10);
if (*end == '\0' && errno == 0 && w <= 7) {
forced_width = (int)w;
break;
} else
LOG_ERR("OSC-66: invalid 'w' value, ignoring");
break;
}
case 's':
case 'n':
case 'd':
case 'v':
LOG_WARN("OSC-66: unsupported: '%c' parameter, ignoring", param[0]);
break;
}
}
const size_t len = c32len(wchars);
if (forced_width == 0) {
/*
* w=0 means we split the text up as we'd normally do... Since
* we don't support any other parameters of the text-sizing
* protocol, that means we just process the string as if it
* has been printed without this OSC.
*/
for (size_t i = 0; i < len; i++)
term_process_and_print_non_ascii(term, wchars[i]);
free(wchars);
return;
}
size_t max_cp_width = 0;
size_t all_cp_width = 0;
for (size_t i = 0; i < len; i++) {
const size_t cp_width = c32width(wchars[i]);
all_cp_width += cp_width;
max_cp_width = max(max_cp_width, cp_width);
}
size_t calculated_width = 0;
switch (term->conf->tweak.grapheme_width_method) {
case GRAPHEME_WIDTH_WCSWIDTH: calculated_width = all_cp_width; break;
case GRAPHEME_WIDTH_MAX: calculated_width = max_cp_width; break;
case GRAPHEME_WIDTH_DOUBLE: calculated_width = min(max_cp_width, 2); break;
}
const size_t width = forced_width == 0 ? calculated_width : forced_width;
LOG_DBG("len=%zu, forced=%d, calculated=%zu, using=%zu",
len, forced_width, calculated_width, width);
#if 0
if (len == 1 && calculated_width == forced_width) {
/*
* Optimization: if there's a single codepoint, and either
* w=0, or the 'w' matches the calculated width, print
* codepoint directly instead of creating a combining
* character.
*/
term_print(term, wchars[0], width);
free(wchars);
return;
}
#endif
uint32_t key = composed_key_from_chars(wchars, len);
const struct composed *composed = composed_lookup_without_collision(
term->composed, &key, wchars, len - 1, wchars[len - 1], forced_width);
if (composed == NULL) {
struct composed *new_cc = xmalloc(sizeof(*new_cc));
new_cc->chars = wchars;
new_cc->count = len;
new_cc->key = key;
new_cc->width = width;
new_cc->forced_width = forced_width;
term->composed_count++;
composed_insert(&term->composed, new_cc);
composed = new_cc;
} else if (composed->width == width) {
free(wchars);
}
term_print(
term, CELL_COMB_CHARS_LO + composed->key,
composed->forced_width > 0 ? composed->forced_width : composed->width,
false);
}
void
osc_dispatch(struct terminal *term)
{
unsigned param = 0;
int data_ofs = 0;
for (size_t i = 0; i < term->vt.osc.idx; i++, data_ofs++) {
char c = term->vt.osc.data[i];
if (c == ';') {
data_ofs++;
break;
}
if (!isdigit(c)) {
UNHANDLED();
return;
}
param *= 10;
param += c - '0';
}
LOG_DBG("OSC: %.*s (param = %d)",
(int)term->vt.osc.idx, term->vt.osc.data, param);
char *string = (char *)&term->vt.osc.data[data_ofs];
switch (param) {
case 0: /* icon + title */
term_set_window_title(term, string);
break;
case 1: /* icon */
break;
case 2: /* title */
term_set_window_title(term, string);
break;
case 4: {
/* Set color<idx> */
string--;
if (*string != ';')
break;
xassert(*string == ';');
for (const char *s_idx = strtok(string, ";"), *s_color = strtok(NULL, ";");
s_idx != NULL && s_color != NULL;
s_idx = strtok(NULL, ";"), s_color = strtok(NULL, ";"))
{
/* Parse <idx> parameter */
unsigned idx = 0;
for (; *s_idx != '\0'; s_idx++) {
char c = *s_idx;
idx *= 10;
idx += c - '0';
}
if (idx >= ALEN(term->colors.table)) {
LOG_WARN("invalid OSC 4 color index: %u", idx);
break;
}
/* Client queried for current value */
if (s_color[0] == '?' && s_color[1] == '\0') {
uint32_t color = term->colors.table[idx];
uint8_t r = (color >> 16) & 0xff;
uint8_t g = (color >> 8) & 0xff;
uint8_t b = (color >> 0) & 0xff;
const char *terminator = term->vt.osc.bel ? "\a" : "\033\\";
char reply[32];
size_t n = xsnprintf(
reply, sizeof(reply),
"\033]4;%u;rgb:%02hhx%02hhx/%02hhx%02hhx/%02hhx%02hhx%s",
idx, r, r, g, g, b, b, terminator);
term_to_slave(term, reply, n);
}
else {
uint32_t color;
bool color_is_valid = s_color[0] == '#' || s_color[0] == '['
? parse_legacy_color(s_color, &color, NULL, NULL)
: parse_rgb(s_color, &color, NULL, NULL);
if (!color_is_valid)
continue;
LOG_DBG("change color definition for #%u from %06x to %06x",
idx, term->colors.table[idx], color);
term->colors.table[idx] = color;
term_damage_color(term, COLOR_BASE256, idx);
}
}
break;
}
case 7:
/* Update terminal's understanding of PWD */
osc_set_pwd(term, string);
break;
case 8:
osc_uri(term, string);
break;
case 9: {
/* iTerm2 Growl notifications */
const char *sep = strchr(string, ';');
if (sep != NULL) {
errno = 0;
char *end = NULL;
strtoul(string, &end, 10);
if (end == sep && errno == 0) {
/* Ignore ConEmu/Windows Terminal escape */
break;
}
}
osc_notify(term, string);
break;
}
case 10: /* fg */
case 11: /* bg */
case 12: /* cursor */
case 17: /* highlight (selection) fg */
case 19: { /* highlight (selection) bg */
/* Set default foreground/background/highlight-bg/highlight-fg color */
/* Client queried for current value */
if (string[0] == '?' && string[1] == '\0') {
uint32_t color = param == 10
? term->colors.fg
: param == 11
? term->colors.bg
: param == 12
? term->colors.cursor_bg
: param == 17
? term->colors.selection_bg
: term->colors.selection_fg;
uint8_t r = (color >> 16) & 0xff;
uint8_t g = (color >> 8) & 0xff;
uint8_t b = (color >> 0) & 0xff;
const char *terminator = term->vt.osc.bel ? "\a" : "\033\\";
/*
* Reply in XParseColor format
* E.g. for color 0xdcdccc we reply "\033]10;rgb:dc/dc/cc\033\\"
*/
char reply[32];
size_t n = xsnprintf(
reply, sizeof(reply),
"\033]%u;rgb:%02hhx%02hhx/%02hhx%02hhx/%02hhx%02hhx%s",
param, r, r, g, g, b, b, terminator);
term_to_slave(term, reply, n);
break;
}
uint32_t color;
bool have_alpha = false;
uint16_t alpha = 0xffff;
if (string[0] == '#' || string[0] == '['
? !parse_legacy_color(string, &color, &have_alpha, &alpha)
: !parse_rgb(string, &color, &have_alpha, &alpha))
{
break;
}
LOG_DBG("change color definition for %s to %06x",
param == 10 ? "foreground" :
param == 11 ? "background" :
param == 12 ? "cursor" :
param == 17 ? "selection background" :
"selection foreground",
color);
switch (param) {
case 10:
term->colors.fg = color;
term_damage_color(term, COLOR_DEFAULT, 0);
break;
case 11:
term->colors.bg = color;
if (!have_alpha)
alpha = term_theme_get(term)->alpha;
const bool changed = term->colors.alpha != alpha;
term->colors.alpha = alpha;
if (changed) {
wayl_win_alpha_changed(term->window);
term_font_subpixel_changed(term);
}
term_damage_color(term, COLOR_DEFAULT, 0);
term_damage_margins(term);
break;
case 12:
term->colors.cursor_bg = 1u << 31 | color;
term_damage_cursor(term);
break;
case 17:
term->colors.selection_bg = color;
break;
case 19:
term->colors.selection_fg = color;
break;
}
break;
}
case 22: /* Set mouse cursor */
term_set_user_mouse_cursor(term, string);
break;
case 30: /* Set tab title */
break;
case 52: /* Copy to/from clipboard/primary */
osc_selection(term, string);
break;
case 5522:
kitty_clipboard(term, string);
break;
case 66: /* text-size protocol (kitty) */
kitty_text_size(term, string);
break;
case 99: /* Kitty notifications */
kitty_notification(term, string);
break;
case 104: {
/* Reset Color Number 'c' (whole table if no parameter) */
const struct color_theme *theme = term_theme_get(term);
if (string[0] == '\0') {
LOG_DBG("resetting all colors");
memcpy(term->colors.table, theme->table, sizeof(term->colors.table));
term_damage_view(term);
}
else {
for (const char *s_idx = strtok(string, ";");
s_idx != NULL;
s_idx = strtok(NULL, ";"))
{
unsigned idx = 0;
for (; *s_idx != '\0'; s_idx++) {
char c = *s_idx;
idx *= 10;
idx += c - '0';
}
if (idx >= ALEN(term->colors.table)) {
LOG_WARN("invalid OSC 104 color index: %u", idx);
continue;
}
LOG_DBG("resetting color #%u", idx);
term->colors.table[idx] = theme->table[idx];
term_damage_color(term, COLOR_BASE256, idx);
}
}
break;
}
case 105: /* Reset Special Color Number 'c' */
break;
case 110: /* Reset default text foreground color */
LOG_DBG("resetting foreground color");
const struct color_theme *theme = term_theme_get(term);
term->colors.fg = theme->fg;
term_damage_color(term, COLOR_DEFAULT, 0);
break;
case 111: { /* Reset default text background color */
LOG_DBG("resetting background color");
const struct color_theme *theme = term_theme_get(term);
bool alpha_changed = term->colors.alpha != theme->alpha;
term->colors.bg = theme->bg;
term->colors.alpha = theme->alpha;
if (alpha_changed) {
wayl_win_alpha_changed(term->window);
term_font_subpixel_changed(term);
}
term_damage_color(term, COLOR_DEFAULT, 0);
term_damage_margins(term);
break;
}
case 112: {
LOG_DBG("resetting cursor color");
const struct color_theme *theme = term_theme_get(term);
term->colors.cursor_fg = theme->cursor.text;
term->colors.cursor_bg = theme->cursor.cursor;
if (term->conf->colors_dark.use_custom.cursor) {
term->colors.cursor_fg |= 1u << 31;
term->colors.cursor_bg |= 1u << 31;
}
term_damage_cursor(term);
break;
}
case 117: {
LOG_DBG("resetting selection background color");
const struct color_theme *theme = term_theme_get(term);
term->colors.selection_bg = theme->selection_bg;
break;
}
case 119: {
LOG_DBG("resetting selection foreground color");
const struct color_theme *theme = term_theme_get(term);
term->colors.selection_fg = theme->selection_fg;
break;
}
case 133:
/*
* Shell integration; see
* https://iterm2.com/documentation-escape-codes.html (Shell
* Integration/FinalTerm)
*
* [PROMPT]prompt% [COMMAND_START] ls -l
* [COMMAND_EXECUTED]
* -rw-r--r-- 1 user group 127 May 1 2016 filename
* [COMMAND_FINISHED]
*/
switch (string[0]) {
case 'A':
LOG_DBG("FTCS_PROMPT: %dx%d",
term->grid->cursor.point.row,
term->grid->cursor.point.col);
term->grid->cur_row->shell_integration.prompt_marker = true;
break;
case 'B':
LOG_DBG("FTCS_COMMAND_START");
break;
case 'C':
LOG_DBG("FTCS_COMMAND_EXECUTED: %dx%d",
term->grid->cursor.point.row,
term->grid->cursor.point.col);
term->grid->cur_row->shell_integration.cmd_start = term->grid->cursor.point.col;
break;
case 'D':
LOG_DBG("FTCS_COMMAND_FINISHED: %dx%d",
term->grid->cursor.point.row,
term->grid->cursor.point.col);
term->grid->cur_row->shell_integration.cmd_end = term->grid->cursor.point.col;
break;
}
break;
case 176:
if (string[0] == '?' && string[1] == '\0') {
#if 0 /* Disabled for now, see #1894 */
const char *terminator = term->vt.osc.bel ? "\a" : "\033\\";
char *reply = xasprintf(
"\033]176;%s%s",
term->app_id != NULL ? term->app_id : term->conf->app_id,
terminator);
term_to_slave(term, reply, strlen(reply));
free(reply);
#else
LOG_WARN("OSC-176 app-id query ignored");
#endif
break;
}
term_set_app_id(term, string);
break;
case 555:
osc_flash(term);
break;
case 777: {
/*
* OSC 777 is an URxvt generic escape used to send commands to
* perl extensions. The generic syntax is: \E]777;<command>;<string>ST
*
* We only recognize the 'notify' command, which is, if not
* well established, at least fairly well known.
*/
char *param_brk = strchr(string, ';');
if (param_brk == NULL) {
UNHANDLED();
return;
}
if (strncmp(string, "notify", param_brk - string) == 0)
osc_notify(term, param_brk + 1);
else
UNHANDLED();
break;
}
default:
UNHANDLED();
break;
}
}
bool
osc_ensure_size(struct terminal *term, size_t required_size)
{
if (likely(required_size <= term->vt.osc.size))
return true;
const size_t pow2_max = ~(SIZE_MAX >> 1);
if (unlikely(required_size > pow2_max)) {
LOG_ERR("required OSC buffer size (%zu) exceeds limit (%zu)",
required_size, pow2_max);
return false;
}
size_t new_size = max(term->vt.osc.size, 4096);
while (new_size < required_size) {
new_size <<= 1;
}
uint8_t *new_data = realloc(term->vt.osc.data, new_size);
if (new_data == NULL) {
LOG_ERRNO("failed to increase size of OSC buffer");
return false;
}
LOG_DBG("resized OSC buffer: %zu", new_size);
term->vt.osc.data = new_data;
term->vt.osc.size = new_size;
return true;
}
|