forked from mintty/mintty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
winclip.c
1563 lines (1420 loc) · 41.5 KB
/
winclip.c
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
// winclip.c (part of mintty)
// Copyright 2008-23 Andy Koppe, 2018 Thomas Wolff
// Adapted from code from PuTTY-0.60 by Simon Tatham and team.
// Licensed under the terms of the GNU General Public License v3 or later.
#include "winpriv.h"
#include "termpriv.h" // term_get_html
#include "charset.h"
#include "child.h"
#include "res.h" // DIALOG_CLASS
#include <winnls.h>
#include <richedit.h>
#include <shellapi.h>
#include <wtypes.h>
#include <objidl.h>
#include <oleidl.h>
#ifdef __CYGWIN__
#include <sys/cygwin.h> // cygwin_internal
#endif
#ifdef check_cygdrive
// Adapt /cygdrive prefix to actual configured one (like / or anything else);
// this experimental approach is not enabled as it is only used for WSL and
// dynamic adaptation is hardly useful.
static char * _cygdrive = 0;
static wchar * _wcygdrive = 0;
static char *
cygdrive(void)
{
if (!_cygdrive) {
char target [99];
int ret = readlink ("/proc/cygdrive", target, sizeof (target) - 1);
if (ret >= 0) {
target [ret] = '\0';
_cygdrive = strdup(target);
}
else
#if defined(__MSYS__) || defined(__MINGW32)
_cygdrive = "/";
#else
_cygdrive = "/cygdrive";
#endif
_wcygdrive = cs__mbstowcs(target);
}
return _cygdrive;
}
static wchar *
wcygdrive(void)
{
(void)cygdrive();
return _wcygdrive;
}
#endif
static DWORD WINAPI
shell_exec_thread(void *data)
{
wchar *wpath = data;
#ifdef __CYGWIN__
/* Need to sync the Windows environment */
cygwin_internal(CW_SYNC_WINENV);
#endif
SetLastError(ERROR_PATH_NOT_FOUND); // in case !*wpath
if (!*wpath || (INT_PTR)ShellExecuteW(wnd, 0, wpath, 0, 0, SW_SHOWNORMAL) <= 32) {
uint error = GetLastError();
if (error != ERROR_CANCELLED) {
int msglen = 1024;
wchar * msg = newn(wchar, msglen);
FormatMessageW(
FORMAT_MESSAGE_FROM_SYSTEM | 64,
0, error, 0, msg, msglen, 0
);
wchar sep[] = W("\n");
msg = renewn(msg, wcslen(msg) + wcslen(sep) + wcslen(wpath) + 1);
wcscat(msg, sep);
wcscat(msg, wpath);
message_box_w(0, msg, null, MB_ICONERROR, null);
}
}
free(wpath);
return 0;
}
void
shell_exec(wstring wpath)
// frees wpath
{
CreateThread(0, 0, shell_exec_thread, (void *)wpath, 0, 0);
// this frees wpath via shell_exec_thread
}
#define dont_debug_wslpath 3
static struct {
string p;
wstring w;
} lxss_mounts [] = {
{"cache", W("cache")},
{"data", W("data")},
{"home", W("home")},
{"mnt", W("mnt")},
{"root", W("root")},
};
static bool
ispathprefix(string pref, string path)
{
if (*pref == '/')
pref++;
if (*path == '/')
path++;
int len = strlen(pref);
if (0 == strncmp(pref, path, len)) {
path += len;
if (!*path || *path == '/')
return true;
}
return false;
}
static char * wsl_conf_mnt = 0;
static struct {
char * dev_fs;
char * mount_point;
} * wsl_fstab = 0;
static int wsl_fstab_len = 0;
static char *
skip(char * s)
{
while (iswspace(*s))
s++;
return s;
}
static int
pathpref(char * x, char * y)
{
char _x = *x;
char _y = *y;
if (!_x) {
if (!_y)
return 2; // equal
else
return 1; // prefix
}
if (_x == '\\')
_x = '/';
if (_y == '\\')
_y = '/';
if (_x != _y)
return 0;
return pathpref(x + 1, y + 1);
}
#if 0
static char *
strsubst(char * str, char c, char d)
{
char * s = str;
while ((s = strchr(s, c)))
*s = d;
return str;
}
#endif
#ifdef debug_wslpath
static inline void
show_fstab(void)
{
#if defined(debug_wslpath) && debug_wslpath > 2
for (int i = 0; i < wsl_fstab_len; i++)
printf("wslpath[%d] <%s> <%s>\n", i, wsl_fstab[i].dev_fs, wsl_fstab[i].mount_point);
#endif
}
#endif
static void
windrives(void)
{
HANDLE hnet;
if (WNetOpenEnum(RESOURCE_CONNECTED, RESOURCETYPE_DISK, 0, NULL, &hnet))
return;
DWORD bufsiz = 16384;
NETRESOURCEW * nr = malloc(bufsiz);
for (;;) {
//int res = WNetEnumResourceW(hnet, &(DWORD){1}, nr, &bufsiz);
DWORD nrn = 1;
int res = WNetEnumResourceW(hnet, &nrn, nr, &bufsiz);
if (res == NO_ERROR || res == ERROR_MORE_DATA) {
#if defined(debug_wslpath) && debug_wslpath > 1
printf("net use <%ls> <%ls>\n", nr->lpLocalName, nr->lpRemoteName);
#endif
if (!nr->lpLocalName)
continue; // skip false matches on UNC path net mounts
// we accept some initial memory leak of configuration strings here
char * localdrive = cs__wcstoutf(nr->lpLocalName);
char * remoteshare = cs__wcstoutf(nr->lpRemoteName);
// adjust fstab with {"X:", "\\host\share"}
for (int i = 0; i < wsl_fstab_len; i++) {
// for {"X:", "\\host\share"},
// and all wsl_fstab entries
// {"//host/share", "/mnt/..."} or
// {"\\host\share", "/mnt/..."},
// replace "//host/share" with "X:",
// also with subdir entries like
// {"//host/share/subdir", "/mnt/..."}
// replace "//host/share/subdir" with "X:\subdir"
switch (pathpref(remoteshare, wsl_fstab[i].dev_fs)) {
when 2: wsl_fstab[i].dev_fs = localdrive;
when 1: { // prefix
char * subdir = wsl_fstab[i].dev_fs + strlen(remoteshare);
wsl_fstab[i].dev_fs = asform("%s%s", localdrive, subdir);
}
}
}
}
else
break;
}
WNetCloseEnum(hnet);
}
static bool
wslmntmapped(void)
{
static bool wslmnt_init = false;
if (!wslmnt_init && *wsl_basepath) {
char linebuf[222];
char * rootfs = path_win_w_to_posix(wsl_basepath);
char * wsl$conf = asform("%s/etc/wsl.conf", rootfs);
char * fstab = asform("%s/etc/fstab", rootfs);
FILE * conf = fopen(wsl$conf, "r");
if (conf) {
bool automount = false;
while (fgets(linebuf, sizeof linebuf, conf)) {
char * p = skip(linebuf);
if (*p == '[') {
automount = false;
if (0 == strncasecmp(p, "[automount]", 11)) {
p = skip(p + 11);
if (!*p)
automount = true;
}
}
else if (automount && !strncasecmp(p, "root", 4)) {
p = skip(p + 4);
if (*p == '=') {
p = skip(p + 1);
char * x = strchr(p, '\n');
if (x) {
*x = 0;
if (x-- > p && *x == '/')
*x = 0;
}
wsl_conf_mnt = strdup(p);
}
}
}
fclose(conf);
}
FILE * mtab = fopen(fstab, "r");
if (mtab) {
while (fgets(linebuf, sizeof linebuf, mtab)) {
char * p1 = skip(linebuf);
if (*p1 != '#') {
char * x = p1;
while (!iswspace(*x))
x++;
*x++ = 0;
char * p2 = skip(x);
x = p2;
while (!iswspace(*x))
x++;
*x = 0;
if (x-- > p2 && *x == '/')
*x = 0;
if (*p1 && *p2) {
#if defined(debug_wslpath)
printf("fstab <%s> <%s>\n", p1, p2);
#endif
wsl_fstab = renewn(wsl_fstab, wsl_fstab_len + 1);
wsl_fstab[wsl_fstab_len].dev_fs = strdup(p1);
wsl_fstab[wsl_fstab_len].mount_point = strdup(p2);
wsl_fstab_len++;
}
}
}
fclose(mtab);
}
free(fstab);
free(wsl$conf);
free(rootfs);
wslmnt_init = true;
// substitute fstab dev_fs entries with Windows notation
windrives();
}
return wsl_conf_mnt || wsl_fstab;
}
static char *
wslpath(char * path)
{
char * res = null;
if (wslmntmapped() &&
#if defined(__MSYS__) || defined(__MINGW32)
path[2] == '/'
#else
ispathprefix("/cygdrive", path)
#endif
)
{ // check drive path
#if defined(__MSYS__) || defined(__MINGW32)
#else
path += 9;
#endif
if (*path == '/')
path++; // point to drive letter
if (wsl_conf_mnt) { // [automount] configured
res = asform("%s/%s", wsl_conf_mnt, path);
}
else if (path[1] == '/') {
for (int i = 0; i < wsl_fstab_len; i++) {
#if defined(debug_wslpath) && debug_wslpath > 2
printf("wslpath <%s> fstab <%s> <%s>\n", path, wsl_fstab[i].dev_fs, wsl_fstab[i].mount_point);
#endif
if (tolower((int)*path) == tolower((int)wsl_fstab[i].dev_fs[0])
&& wsl_fstab[i].dev_fs[1] == ':'
)
{
char * dev = &wsl_fstab[i].dev_fs[2];
if (strlen(dev) == 1) {
//path <x/dir/file> fstab <X:\> </mnt/mountpoint>
res = asform("%s%s", wsl_fstab[i].mount_point, path + 1);
break;
}
else if (pathpref(dev, path + 1)) {
//path <x/dir/file> fstab <X:\subdir> </mnt/mountpoint>
res = asform("%s%s", wsl_fstab[i].mount_point, path + 1 + strlen(dev));
break;
}
}
}
}
}
else if (wslmntmapped()) { // check UNC path
for (int i = 0; i < wsl_fstab_len; i++) {
#if defined(debug_wslpath) && debug_wslpath > 2
printf("wslpath <%s> <%s> (%s)\n", path, wsl_fstab[i].mount_point, wsl_fstab[i].dev_fs);
#endif
if (pathpref(wsl_fstab[i].dev_fs, path)) {
res = asform("%s%s", wsl_fstab[i].mount_point, path + strlen(wsl_fstab[i].dev_fs));
break;
}
}
}
// cygwin-internal paths not supported
return res;
}
#ifdef pathname_conversion_here
static bool
ispathprefixw(wstring pref, wstring path)
{
if (*pref == '/')
pref++;
if (*path == '/')
path++;
int len = wcslen(pref);
if (0 == wcsncmp(pref, path, len)) {
path += len;
if (!*path || *path == '/')
return true;
}
return false;
}
static char *
unwslpath(wchar * wpath)
{
char * res = null;
if (wslmntmapped()) {
char * wslpath = cs__wcstoutf(wpath);
if (wsl_conf_mnt && ispathprefix(wsl_conf_mnt, wslpath))
res = asform("/cygdrive%s", &wslpath[strlen(wsl_conf_mnt)]);
else
for (int i = 0; i < wsl_fstab_len; i++) {
#if defined(debug_wslpath) && debug_wslpath > 2
printf("unwslpath <%s> <%s> (%s)\n", wslpath, wsl_fstab[i].mount_point, wsl_fstab[i].dev_fs);
#endif
if (ispathprefix(wsl_fstab[i].mount_point, wslpath)) {
if (wsl_fstab[i].dev_fs[1] == ':') {
res = asform(
#if defined(__MSYS__) || defined(__MINGW32)
#else
"/cygdrive"
#endif
"/%c%s%s",
tolower((int)wsl_fstab[i].dev_fs[0]),
&wsl_fstab[i].dev_fs[2],
&wslpath[strlen(wsl_fstab[i].mount_point)]);
break;
}
else { // handle UNC path mount
res = asform("%s%s", wsl_fstab[i].dev_fs, wslpath + strlen(wsl_fstab[i].mount_point));
for (char * r = res; *r; r++)
// cygwin path conversion fails on backslash UNC paths
if (*r == '\\')
*r = '/';
}
}
}
free(wslpath);
}
return res;
}
wchar *
dewsl(wchar * wpath)
{
#ifdef debug_wslpath
printf("dewsl <%ls>\n", wpath);
#endif
char * unwslp = unwslpath(wpath);
if (unwslp) {
wchar * unwsl = cs__utftowcs(unwslp);
free(unwslp);
delete(wpath);
wpath = unwsl;
}
else if (wcsncmp(wpath, W("/mnt/"), 5) == 0) {
wchar * unwsl = newn(wchar, wcslen(wpath) + 6);
wcscpy(unwsl, W("/cygdrive"));
wcscat(unwsl, wpath + 4);
delete(wpath);
wpath = unwsl;
}
else if (*wpath == '/' && *wsl_basepath) {
static wchar * wbase = 0;
if (!wbase) {
char * pbase = path_win_w_to_posix(wsl_basepath);
wbase = cs__mbstowcs(pbase);
free(pbase);
}
wchar * unwsl = newn(wchar, wcslen(wbase) + wcslen(wpath) + 1);
wcscpy(unwsl, wbase);
wcscat(unwsl, wpath);
delete(wpath);
wpath = unwsl;
}
else if (*wpath == '/') { // prepend %LOCALAPPDATA%\lxss[\rootfs]
// deprecated case; for WSL, wsl_basepath should be set
char * appd = getenv("LOCALAPPDATA");
if (appd) {
wchar * wappd = cs__mbstowcs(appd);
appd = path_win_w_to_posix(wappd);
free(wappd);
wappd = cs__mbstowcs(appd);
free(appd);
bool rootfs_mount = true;
for (uint i = 0; i < lengthof(lxss_mounts); i++) {
if (ispathprefixw(lxss_mounts[i].w, wpath)) {
rootfs_mount = false;
break;
}
}
wchar * unwsl = newn(wchar, wcslen(wappd) + wcslen(wpath) + 13);
wcscpy(unwsl, wappd);
free(wappd);
wcscat(unwsl, W("/lxss"));
if (rootfs_mount)
wcscat(unwsl, W("/rootfs"));
wcscat(unwsl, wpath);
delete(wpath);
wpath = unwsl;
}
}
return wpath;
}
#endif
#if CYGWIN_VERSION_API_MINOR < 206
#define wcsncasecmp wcsncmp
#define wmemcpy(t, s, n) memcpy(t, s, 2 * n)
#endif
void
win_open(wstring wpath, bool adjust_dir)
// frees wpath
{
size_t wl = wcslen(wpath);
wchar *wbuf = newn(wchar, wl + 1);
if (wl > 2 && (*wpath == '"' || *wpath == '\'') && wpath[wl - 1] == *wpath) {
// Remove pair of leading and trailing quotes.
wl -= 2;
wmemcpy(wbuf, wpath + 1, wl);
}
else if (!wcsncmp(wpath, W("\\\\"), 2)) {
// Assume that a path starting with two backslashes is a Windows UNC path
// and copy it unmodified.
wmemcpy(wbuf, wpath, wl);
}
else {
// Remove backslashes, but only if they precede shell special characters.
// Other backslashes are more likely to be Windows path separators.
wstring p = wpath;
wl = 0;
while (*p) {
if (*p == '\\' && wcschr(W(" \t\n|&;<>()$`\\\"'*?![]#~=%^"), p[1]))
p++;
wbuf[wl++] = *p++;
}
}
wbuf[wl] = 0;
//printf("win_open %ls wbuf %ls\n", wpath, wbuf);
delete(wpath);
// check for URL
wchar *p = wbuf;
while (iswalpha(*p)) p++;
if (*p == ':' && p - wbuf > 2) {
shell_exec(wbuf); // frees wbuf
return;
}
// guard file opening against foreign network access
char * buf = cs__wcstoutf(wbuf);
char * gbuf = guardpath(buf, 4);
//printf("win_open buf %s grd %s\n", buf, gbuf);
free(buf);
if (!gbuf)
return;
{
#ifdef pathname_conversion_here
#warning now deprecated; handled via guardpath
// Need to convert POSIX path to Windows first
if (support_wsl) {
// First, we need to replicate some of the handling of relative paths
// as implemented in child_conv_path, because the dewsl functionality
// would actually go in between the workflow of child_conv_path.
// We cannot determine the WSL foreground process and its current
// directory, so we can only consider the working directory explicitly
// communicated via the OSC 7 escape sequence here.
if (*wbuf != '/' && wcsncmp(wbuf, W("~/"), 2)) {
if (child_dir && *child_dir) {
wchar * cd = cs__mbstowcs(child_dir);
cd = renewn(cd, wcslen(cd) + wl + 2);
cd[wcslen(cd)] = '/';
wcscpy(&cd[wcslen(cd) + 1], wbuf);
delete(wbuf);
wbuf = cd;
}
}
wbuf = dewsl(wbuf);
}
wstring conv_wpath = child_conv_path(wbuf, adjust_dir);
#else
(void)adjust_dir;
wchar *conv_wpath = path_posix_to_win_w(gbuf);
free(gbuf);
#endif
#ifdef debug_wslpath
printf("win_open <%ls> <%ls>\n", wbuf, conv_wpath);
#endif
delete(wbuf);
if (conv_wpath)
shell_exec(conv_wpath); // frees conv_wpath
else
message_box(0, strerror(errno), null, MB_ICONERROR, null);
}
}
// Convert RGB24 to xterm-256 8-bit value (always >= 16)
// For simplicity, assume RGB space is perceptually uniform.
// There are 5 places where one of two outputs needs to be chosen when the
// input is the exact middle:
// - The r/g/b channels and the gray value: the higher value output is chosen.
// - If the gray and color have same distance from the input - color is chosen.
static uchar
rgb_to_x256(uchar r, uchar g, uchar b)
{
// Calculate the nearest 0-based color index at 16 .. 231
# define v2ci(v) (v < 48 ? 0 : v < 115 ? 1 : (v - 35) / 40)
int ir = v2ci(r), ig = v2ci(g), ib = v2ci(b); // 0..5 each
# define color_index() (36 * ir + 6 * ig + ib) /* 0..215, lazy evaluation */
// Calculate the nearest 0-based gray index at 232 .. 255
int average = (r + g + b) / 3;
int gray_index = average > 238 ? 23 : (average - 3) / 10; // 0..23
// Calculate the represented colors back from the index
static const int i2cv[6] = {0, 0x5f, 0x87, 0xaf, 0xd7, 0xff};
int cr = i2cv[ir], cg = i2cv[ig], cb = i2cv[ib]; // r/g/b, 0..255 each
int gv = 8 + 10 * gray_index; // same value for r/g/b, 0..255
// Return the one which is nearer to the original input rgb value
# define dist_square(A,B,C, a,b,c) ((A-a)*(A-a) + (B-b)*(B-b) + (C-c)*(C-c))
int color_err = dist_square(cr, cg, cb, r, g, b);
int gray_err = dist_square(gv, gv, gv, r, g, b);
return color_err <= gray_err ? 16 + color_index() : 232 + gray_index;
}
static cattrflags
apply_attr_colour_rtf(cattr ca, attr_colour_mode mode, int * pfgi, int * pbgi)
{
ca = apply_attr_colour(ca, mode);
*pfgi = (ca.attr & ATTR_FGMASK) >> ATTR_FGSHIFT;
*pbgi = (ca.attr & ATTR_BGMASK) >> ATTR_BGSHIFT;
// For ACM_RTF_GEN: COLOUR_NUM means "no colour" (-1)
if (*pfgi == COLOUR_NUM && mode == ACM_RTF_GEN) *pfgi = -1;
if (*pbgi == COLOUR_NUM && mode == ACM_RTF_GEN) *pbgi = -1;
if (CCL_TRUEC(*pfgi))
*pfgi = rgb_to_x256(red(ca.truefg), green(ca.truefg), blue(ca.truefg));
if (CCL_TRUEC(*pbgi))
*pbgi = rgb_to_x256(red(ca.truebg), green(ca.truebg), blue(ca.truebg));
return ca.attr;
}
void
win_copy_text(const char *s)
{
unsigned int size;
wchar *text = cs__mbstowcs(s);
if (text == NULL) {
return;
}
size = wcslen(text);
if (size > 0) {
win_copy(text, 0, size + 1);
}
free(text);
}
void
win_copy(const wchar *data, cattr *cattrs, int len)
{
win_copy_as(data, cattrs, len, 0);
}
void
win_copy_as(const wchar *data, cattr *cattrs, int len, char what)
{
//printf("win_copy %d '%c'\n", len, what);
HGLOBAL clipdata, clipdata2, clipdata3 = 0;
int len2;
void *lock, *lock2, *lock3;
len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, null, null);
clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len * sizeof(wchar));
clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2);
if (!clipdata || !clipdata2) {
if (clipdata)
GlobalFree(clipdata);
if (clipdata2)
GlobalFree(clipdata2);
return;
}
if (!(lock = GlobalLock(clipdata))) {
GlobalFree(clipdata);
GlobalFree(clipdata2);
return;
}
if (!(lock2 = GlobalLock(clipdata2))) {
GlobalUnlock(clipdata);
GlobalFree(clipdata);
GlobalFree(clipdata2);
return;
}
memcpy(lock, data, len * sizeof(wchar));
WideCharToMultiByte(CP_ACP, 0, data, len, lock2, len2, null, null);
if (cattrs && ((cfg.copy_as_rtf && !what) || what == 'r')) {
wchar unitab[256];
char *rtf = null;
uchar *tdata = (uchar *) lock2;
wchar *udata = (wchar *) lock;
int rtflen = 0, uindex = 0, tindex = 0;
int rtfsize = 0;
int multilen, blen, alen, totallen;
char before[16], after[4];
int fgcolour, lastfgcolour = 0;
int bgcolour, lastbgcolour = 0;
int attrBold, lastAttrBold = 0;
int attrUnder, lastAttrUnder = 0;
int attrItalic, lastAttrItalic = 0;
int attrStrikeout, lastAttrStrikeout = 0;
int attrHidden, lastAttrHidden = 0;
int palette[COLOUR_NUM];
int numcolours;
for (int i = 0; i < 256; i++)
MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS,
(char[]){i}, 1, unitab + i, 1);
wstring cfgfont = *cfg.copy_as_rtf_font ? cfg.copy_as_rtf_font : cfg.font.name;
int cfgsize = cfg.copy_as_rtf_font_size ? cfg.copy_as_rtf_font_size : cfg.font.size;
char * rtffontname = newn(char, wcslen(cfgfont) * 9 + 1);
char * rtffnpoi = rtffontname;
for (uint i = 0; i < wcslen(cfgfont); i++)
if (!(cfgfont[i] & 0xFF80) && !strchr("\\;{}", cfgfont[i]))
*rtffnpoi++ = cfgfont[i];
else
rtffnpoi += sprintf(rtffnpoi, "\\u%d '", cfgfont[i]);
*rtffnpoi = '\0';
rtfsize = 100 + strlen(rtffontname);
rtf = newn(char, rtfsize);
rtflen = sprintf(rtf,
"{\\rtf1\\ansi\\deff0{\\fonttbl{\\f0\\fmodern\\fprq1 %s;}}\\f0\\fs%d",
rtffontname, cfgsize * 2);
free(rtffontname);
/*
* Add colour palette
* {\colortbl;\red255\green0\blue0;\red0\green0\blue128;...}
*/
/*
* First - Determine all colours in use
* o Foreground and background colours share the same palette
*/
memset(palette, 0, sizeof(palette));
for (int i = 0; i < (len - 1); i++) {
apply_attr_colour_rtf(cattrs[i], ACM_RTF_PALETTE, &fgcolour, &bgcolour);
palette[fgcolour]++;
palette[bgcolour]++;
}
/*
* Next - Create a reduced palette
*/
numcolours = 0;
for (int i = 0; i < COLOUR_NUM; i++) {
if (palette[i] != 0)
palette[i] = ++numcolours;
}
/*
* Finally - Write the colour table
*/
rtf = renewn(rtf, rtfsize + (numcolours * 25));
strcat(rtf, "{\\colortbl;");
rtflen = strlen(rtf);
for (int i = 0; i < COLOUR_NUM; i++) {
if (palette[i] != 0) {
rtflen +=
sprintf(&rtf[rtflen], "\\red%d\\green%d\\blue%d;",
GetRValue(colours[i]),
GetGValue(colours[i]),
GetBValue(colours[i]));
}
}
strcpy(&rtf[rtflen], "}");
rtflen++;
/*
* We want to construct a piece of RTF that specifies the
* same Unicode text. To do this we will read back in
* parallel from the Unicode data in `udata' and the
* non-Unicode data in `tdata'. For each character in
* `tdata' which becomes the right thing in `udata' when
* looked up in `unitab', we just copy straight over from
* tdata. For each one that doesn't, we must WCToMB it
* individually and produce a \u escape sequence.
*
* It would probably be more robust to just bite the bullet
* and WCToMB each individual Unicode character one by one,
* then MBToWC each one back to see if it was an accurate
* translation; but that strikes me as a horrifying number
* of Windows API calls so I want to see if this faster way
* will work. If it screws up badly we can always revert to
* the simple and slow way.
*/
while (tindex < len2 && uindex < len && tdata[tindex] && udata[uindex]) {
/* Skip carriage returns */
if (tdata[tindex] == '\r')
tindex++, uindex++;
/*
* Set text attributes, if any, except on newlines
*/
if (tdata[tindex] != '\n') {
uint attr = cattrs[uindex].attr;
if (rtfsize < rtflen + 64) {
rtfsize = rtflen + 512;
rtf = renewn(rtf, rtfsize);
}
/*
* Determine foreground and background colours
*/
attr = apply_attr_colour_rtf(cattrs[uindex], ACM_RTF_GEN, &fgcolour, &bgcolour);
attrBold = attr & ATTR_BOLD;
attrUnder = attr & UNDER_MASK;
attrItalic = attr & ATTR_ITALIC;
attrStrikeout = attr & ATTR_STRIKEOUT;
attrHidden = attr & ATTR_INVISIBLE;
/*
* Write RTF text attributes
*/
if (lastfgcolour != fgcolour) {
lastfgcolour = fgcolour;
rtflen +=
sprintf(&rtf[rtflen], "\\cf%d ",
(fgcolour >= 0) ? palette[fgcolour] : 0);
}
if (lastbgcolour != bgcolour) {
lastbgcolour = bgcolour;
rtflen +=
sprintf(&rtf[rtflen], "\\highlight%d ",
(bgcolour >= 0) ? palette[bgcolour] : 0);
}
if (lastAttrBold != attrBold) {
lastAttrBold = attrBold;
rtflen += sprintf(&rtf[rtflen], "%s", attrBold ? "\\b " : "\\b0 ");
}
if (lastAttrItalic != attrItalic) {
lastAttrItalic = attrItalic;
rtflen += sprintf(&rtf[rtflen], "%s", attrItalic ? "\\i " : "\\i0 ");
}
if (lastAttrUnder != attrUnder) {
lastAttrUnder = attrUnder;
rtflen +=
sprintf(&rtf[rtflen], "%s", attrUnder ? "\\ul " : "\\ulnone ");
}
if (lastAttrStrikeout != attrStrikeout) {
lastAttrStrikeout = attrStrikeout;
rtflen += sprintf(&rtf[rtflen], "%s", attrStrikeout ? "\\strike " : "\\strike0 ");
}
if (lastAttrHidden != attrHidden) {
lastAttrHidden = attrHidden;
rtflen += sprintf(&rtf[rtflen], "%s", attrHidden ? "\\v " : "\\v0 ");
}
}
if (unitab[tdata[tindex]] == udata[uindex]) {
multilen = 1;
before[0] = '\0';
after[0] = '\0';
blen = alen = 0;
}
else {
multilen = WideCharToMultiByte(CP_ACP, 0, &udata[uindex], 1,
null, 0, null, null);
if (multilen != 1) {
blen = sprintf(before, "{\\uc%d\\u%d", multilen, udata[uindex]);
alen = 1;
strcpy(after, "}");
}
else {
blen = sprintf(before, "\\u%d", udata[uindex]);
alen = 0;
after[0] = '\0';
}
}
assert(tindex + multilen <= len2);
totallen = blen + alen;
for (int i = 0; i < multilen; i++) {
if (tdata[tindex + i] == '\\' || tdata[tindex + i] == '{' ||
tdata[tindex + i] == '}')
totallen += 2;
else if (tdata[tindex + i] == '\n')
totallen += 6; /* \par\r\n */
else if (tdata[tindex + i] > 0x7E || tdata[tindex + i] < 0x20)
totallen += 4;
else
totallen++;
}
if (rtfsize < rtflen + totallen + 3) {
rtfsize = rtflen + totallen + 512;
rtf = renewn(rtf, rtfsize);
}
strcpy(rtf + rtflen, before);
rtflen += blen;
for (int i = 0; i < multilen; i++) {
if (tdata[tindex + i] == '\\' || tdata[tindex + i] == '{' ||
tdata[tindex + i] == '}') {
rtf[rtflen++] = '\\';
rtf[rtflen++] = tdata[tindex + i];
}
else if (tdata[tindex + i] == '\n') {
rtflen += sprintf(rtf + rtflen, "\\par\r\n");
}
else if (tdata[tindex + i] > 0x7E || tdata[tindex + i] < 0x20) {
rtflen += sprintf(rtf + rtflen, "\\'%02x", tdata[tindex + i]);
}
else {
rtf[rtflen++] = tdata[tindex + i];
}
}
strcpy(rtf + rtflen, after);
rtflen += alen;
tindex += multilen;
uindex++;
}
rtf[rtflen++] = '}'; /* Terminate RTF stream */
rtf[rtflen++] = '\0';
rtf[rtflen++] = '\0';
clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtflen);
if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != null) {
memcpy(lock3, rtf, rtflen);
GlobalUnlock(clipdata3);
}
free(rtf);
}
GlobalUnlock(clipdata);
GlobalUnlock(clipdata2);
//printf("OpenClipboard win_copy\n");
if (OpenClipboard(wnd)) {
clipboard_token = true;
EmptyClipboard();
// copy clipboard text formats
SetClipboardData(CF_UNICODETEXT, clipdata);
SetClipboardData(CF_TEXT, clipdata2);
// copy clipboard RTF format
if (clipdata3)
SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3);
// determine HTML format level requested
int level = 0;
if (cfg.copy_as_html && !what)
//level = cfg.copy_as_rtf ? 2 : 3;
level = cfg.copy_as_html;
else if (what == 'h')
level = 1;
else if (what == 'f')
level = 2;
else if (what == 'H')
level = 3;
// copy clipboard HTML format
UINT CF_HTML = level ? RegisterClipboardFormatA("HTML Format") : 0;
if (CF_HTML) {
char * html = term_get_html(level);
char * htmlpre = "<html><!--StartFragment-->";
char * htmlpost = "<!--EndFragment--></html>";
int htmldescrlen = 92;
char * htmlcb = asform(
"Version:0.9\n"
"StartHTML:%08d\n"
"EndHTML:%08d\n"
"StartFragment:%08d\n"
"EndFragment:%08d\n"
"%s%s%s",
htmldescrlen,
htmldescrlen + strlen(htmlpre) + strlen(html) + strlen(htmlpost),
htmldescrlen + strlen(htmlpre),
htmldescrlen + strlen(htmlpre) + strlen(html),
htmlpre, html, htmlpost);
free(html);
int len = strlen(htmlcb);
//printf("clipboard HTML Format:\n%s\n", htmlcb);