forked from rgriege/Violet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwindows.h
680 lines (579 loc) · 15 KB
/
windows.h
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
#include "violet/core.h"
#include "violet/os.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <tchar.h>
#include <process.h>
#include <ShlObj.h>
#include <shobjidl.h>
#include <Shellapi.h>
#include <TlHelp32.h>
const char *g_file_path_separator = "\\";
b32 os_string_to_utf8(char *dst, size_t dstlen, const wchar_t* src)
{
return WideCharToMultiByte(CP_UTF8, 0, src, -1, dst, (int)dstlen, NULL, NULL) != 0;
}
size_t os_string_to_utf8_size(const wchar_t* src)
{
return (size_t)WideCharToMultiByte(CP_UTF8, 0, src, -1, NULL, 0, NULL, NULL);
}
b32 os_string_from_utf8(wchar_t *dst, size_t dstlen, const char *src)
{
return MultiByteToWideChar(CP_UTF8, 0, src, -1, dst, (int)dstlen) != 0;
}
size_t os_string_from_utf8_size(const char *src)
{
return (size_t)MultiByteToWideChar(CP_UTF8, 0, src, -1, NULL, 0);
}
const wchar_t *os_imstr_from_utf8(const char *str)
{
static thread_local wchar_t str_w[IMPRINT_BUFFER_SIZE];
if (!os_string_from_utf8(B2PC(str_w), str))
str_w[0] = 0;
return str_w;
}
const char *os_imstr_to_utf8(const wchar_t *str)
{
static thread_local char str_utf8[IMPRINT_BUFFER_SIZE];
if (!os_string_to_utf8(B2PC(str_utf8), str))
str_utf8[0] = 0;
return str_utf8;
}
static
b32 file_dialog__os_from_utf8(const char *src, const wchar_t **pdst)
{
const size_t sz = os_string_from_utf8_size(src);
wchar_t *dst = amalloc(sz * sizeof(wchar_t), g_temp_allocator);
const b32 ret = os_string_from_utf8(dst, sz, src);
*pdst = dst;
return ret;
}
static
b32 file__dialog(char *filename, u32 fname_sz,
const file_dialog_filter_t filters[], u32 num_filters,
CLSID clsid, IID iid)
{
temp_memory_mark_t mark = temp_memory_save(g_temp_allocator);
b32 retval = false;
const wchar_t *ext;
wchar_t *filename_w;
void *vp = NULL;
IFileDialog *dialog;
COMDLG_FILTERSPEC *filterspec = NULL;
IShellItem *item;
assert(num_filters > 0);
if (!SUCCEEDED(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED
| COINIT_DISABLE_OLE1DDE)))
goto out;
if (!SUCCEEDED(CoCreateInstance(&clsid, NULL, CLSCTX_ALL, &iid, &vp)))
goto err_init;
dialog = vp;
for (u32 i = 0; i < num_filters; ++i) {
if (!( strlen(filters[i].pattern) > 2
&& filters[i].pattern[0] == '*'
&& filters[i].pattern[1] == '.')) {
assert(false);
goto err_fltr;
}
}
if ( !file_dialog__os_from_utf8(filters[0].pattern+2, &ext)
|| !SUCCEEDED(dialog->lpVtbl->SetDefaultExtension(dialog, ext)))
goto err_fltr;
filterspec = amalloc(num_filters * sizeof(COMDLG_FILTERSPEC), g_temp_allocator);
for (u32 i = 0; i < num_filters; ++i) {
if ( !file_dialog__os_from_utf8(filters[i].name, &filterspec[i].pszName)
|| !file_dialog__os_from_utf8(filters[i].pattern, &filterspec[i].pszSpec))
goto err_fltr;
}
if (!SUCCEEDED(dialog->lpVtbl->SetFileTypes(dialog, num_filters, filterspec)))
goto err_fltr;
if (!SUCCEEDED(dialog->lpVtbl->Show(dialog, NULL)))
goto err_dlg;
if (!SUCCEEDED(dialog->lpVtbl->GetResult(dialog, &item)))
goto err_dlg;
if (!SUCCEEDED(item->lpVtbl->GetDisplayName(item, SIGDN_FILESYSPATH, &filename_w)))
goto err_itm;
retval = os_string_to_utf8(filename, fname_sz, filename_w);
CoTaskMemFree(filename_w);
err_itm:
item->lpVtbl->Release(item);
err_dlg:
dialog->lpVtbl->Release(dialog);
err_fltr:
err_init:
CoUninitialize();
out:
temp_memory_restore(mark);
return retval;
}
b32 file_open_dialog(char *fname, u32 fname_sz,
const file_dialog_filter_t filters[], u32 num_filters)
{
return file__dialog(fname, fname_sz, filters, num_filters,
CLSID_FileOpenDialog, IID_IFileOpenDialog);
}
b32 file_save_dialog(char *fname, u32 fname_sz,
const file_dialog_filter_t filters[], u32 num_filters)
{
return file__dialog(fname, fname_sz, filters, num_filters,
CLSID_FileSaveDialog, IID_IFileSaveDialog);
}
b32 file_exists(const char *path)
{
wchar_t path_w[PATH_MAX];
DWORD attrib;
if (!os_string_from_utf8(B2PC(path_w), path)) {
log_error("%s(%s): os_string_from_utf8(%s) error %d",
__FUNCTION__, path, path, GetLastError());
return false;
}
attrib = GetFileAttributesW(path_w);
return attrib != INVALID_FILE_ATTRIBUTES
&& !(attrib & FILE_ATTRIBUTE_DIRECTORY);
}
s64 file_modified_time(const char *path)
{
wchar_t path_w[PATH_MAX];
struct _stat s;
if (!os_string_from_utf8(B2PC(path_w), path)) {
log_error("%s(%s): os_string_from_utf8(%s) error %d",
__FUNCTION__, path, path, GetLastError());
return 0;
}
return _tstat(path_w, &s) == 0 ? s.st_mtime : 0;
}
b32 dir_exists(const char *path)
{
wchar_t path_w[PATH_MAX];
DWORD attrib;
if (!os_string_from_utf8(B2PC(path_w), path)) {
log_error("%s(%s): os_string_from_utf8(%s) error %d",
__FUNCTION__, path, path, GetLastError());
return false;
}
attrib = GetFileAttributesW(path_w);
return attrib != INVALID_FILE_ATTRIBUTES
&& (attrib & FILE_ATTRIBUTE_DIRECTORY);
}
void path_append(char *lhs, const char *rhs)
{
strcat(lhs, g_file_path_separator);
strcat(lhs, rhs);
}
void path_appendn(char *lhs, const char *rhs, u32 sz)
{
strcat(lhs, g_file_path_separator);
strncat(lhs, rhs, sz);
}
static
b32 CreateOrReuseDirectory(const wchar_t *path)
{
return CreateDirectoryW(path, NULL) || GetLastError() == ERROR_ALREADY_EXISTS;
}
b32 mkpath(const char *path)
{
char path_mod[PATH_MAX];
wchar_t path_w[PATH_MAX];
char *p;
char swap;
if (dir_exists(path))
return true;
if (path[0] == '.' && path[1] == g_file_path_separator[0]) {
strbcpy(path_mod, path);
p = path_mod + 2;
} else if (path[0] == g_file_path_separator[0] && path[1] == g_file_path_separator[0]) {
strbcpy(path_mod, path);
p = path_mod + 2;
} else if (path[0] != 0 && path[1] == ':') {
strbcpy(path_mod, path);
p = path_mod + 2;
} else {
strbcpy(path_mod, path);
p = path_mod;
}
if (p[0] == 0)
return true;
swap = 0;
for (p = p + 1; *p; ++p) {
if (*p == g_file_path_separator[0]) {
memswp(swap, *p, char);
if (!os_string_from_utf8(B2PC(path_w), path_mod)) {
log_error("%s(%s): os_string_from_utf8(%s) error %d",
__FUNCTION__, path, path_mod, GetLastError());
return false;
}
if (!CreateOrReuseDirectory(path_w)) {
log_error("%s(%s): CreateDirectory(%s) error %d",
__FUNCTION__, path, path_mod, GetLastError());
return false;
}
memswp(swap, *p, char);
}
}
if (!os_string_from_utf8(B2PC(path_w), path_mod)) {
log_error("%s(%s): os_string_from_utf8(%s) error %d",
__FUNCTION__, path, path_mod, GetLastError());
return false;
}
if (!CreateOrReuseDirectory(path_w)) {
log_error("%s(%s): CreateDirectory(%s) error %d",
__FUNCTION__, path, path_mod, GetLastError());
return false;
}
return true;
}
#ifdef VLT_USE_TINYDIR
static
b32 rmdir_fw(const wchar_t *path_w)
{
char path[PATH_MAX];
b32 success = false;
tinydir_dir dir;
if (tinydir_open(&dir, path_w) == -1) {
if (!os_string_to_utf8(B2PS(path), path_w))
strbcpy(path, "<unprintable>");
log_error("rmdir: error reading directory '%s'", path);
goto out;
}
while (dir.has_next) {
tinydir_file file;
if (tinydir_readfile(&dir, &file) != -1) {
if ( wcscmp(file.name, L".") != 0
&& wcscmp(file.name, L"..") != 0) {
if (file.is_dir) {
rmdir_fw(file.path);
} else if (_wremove(file.path)) {
if (!os_string_to_utf8(B2PS(path), file.path))
strbcpy(path, "<unprintable>");
log_error("rmdir: error removing '%s'", path);
goto out;
}
}
} else {
log_error("rmdir: error examining file");
goto out;
}
if (tinydir_next(&dir) == -1) {
log_error("rmdir: error iterating directory");
goto out;
}
}
if (RemoveDirectoryW(path_w)) {
success = true;
} else {
if (!os_string_to_utf8(B2PS(path), path_w))
strbcpy(path, "<unprintable>");
log_error("error removing '%s'", path);
}
out:
tinydir_close(&dir);
return success;
}
b32 rmdir_f(const char *path)
{
wchar_t path_w[PATH_MAX];
return os_string_from_utf8(B2PC(path_w), path)
&& rmdir_fw(path_w);
}
#endif // VLT_USE_TINYDIR
char *impathcat(char *imstr, const char *path)
{
return imstrcatn(imstrcatn(imstr, g_file_path_separator), path);
}
char *impathcatprintf(char *imstr, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
imstrcatprintfv(imstrcatn(imstr, g_file_path_separator), fmt, args);
va_end(args);
return imstr;
}
char *imappdir(void)
{
static thread_local char path[PATH_MAX] = {0};
wchar_t path_w[PATH_MAX];
char *last;
if (path[0] != 0)
goto out;
if (GetModuleFileNameW(NULL, B2PC(path_w)) == 0)
goto out;
if (!os_string_to_utf8(B2PC(path), path_w))
goto out;
if ((last = strrchr(path, '\\')) != NULL)
*last = 0;
out:
return imstrcpy(path);
}
char *imapppath(const char *resource)
{
return impathcat(imappdir(), resource);
}
static
char *imknownfolderdir(KNOWNFOLDERID id, const char *default_dir)
{
#ifdef WINDOWS_PACKAGE_NAME
HRESULT result;
PWSTR wpath;
if ((result = SHGetKnownFolderPath(&id, 0, NULL, &wpath)) != S_OK) {
log_error("%s() SHGetKnownFolderPath error %d", __FUNCTION__, result);
imstrcpy(default_dir);
goto out;
}
if (!os_string_to_utf8(imstr(), IMPRINT_BUFFER_SIZE, wpath)) {
log_error("%s() os_string_to_utf8 error %d", __FUNCTION__, GetLastError());
imstrcpy(default_dir);
goto err;
}
impathcat(imstr(), WINDOWS_PACKAGE_NAME);
err:
CoTaskMemFree(wpath);
out:
return imstr();
#else
return imapppath(default_dir);
#endif
}
static
char *improgdatadir(void)
{
return imknownfolderdir(FOLDERID_ProgramData, ".ProgramData");
}
static
char *improgdatapath(const char *resource)
{
return impathcat(improgdatadir(), resource);
}
char *imresdir(void)
{
return imappdir();
}
char *imrespath(const char *resource)
{
return imapppath(resource);
}
char *imlogdir(void)
{
return improgdatapath(".logs");
}
char *imlogpath(const char *resource)
{
return impathcat(imlogdir(), resource);
}
char *imcachedir(void)
{
return improgdatadir();
}
char *imcachepath(const char *resource)
{
return impathcat(imcachedir(), resource);
}
char *imdatadir(void)
{
return improgdatadir();
}
char *imdatapath(const char *resource)
{
return impathcat(imdatadir(), resource);
}
char *imuserdatadir(void)
{
return imknownfolderdir(FOLDERID_LocalAppData, ".UserData");
}
char *imuserdatapath(const char *resource)
{
return impathcat(imuserdatadir(), resource);
}
FILE *file_open(const char *fname, const char *mode)
{
wchar_t fname_w[PATH_MAX];
wchar_t mode_w[PATH_MAX];
FILE *fp;
if (!os_string_from_utf8(B2PS(fname_w), fname)) {
log_error("%s(%s): os_string_from_utf8(%s) error %d",
__FUNCTION__, fname, fname, GetLastError());
return NULL;
}
if (!os_string_from_utf8(B2PS(mode_w), mode)) {
log_error("%s(%s): os_string_from_utf8(%s) error %d",
__FUNCTION__, fname, mode, GetLastError());
return NULL;
}
if (!(fp = _wfopen(fname_w, mode_w))) {
log_error("%s(%s, %s): _wfopen() error %d", __FUNCTION__, fname, mode, errno);
return NULL;
}
return fp;
}
void *file_read_all(const char *fname, const char *mode, size_t *sz, allocator_t *a)
{
FILE *fp;
size_t file_size;
void *bytes = NULL;
fp = file_open(fname, mode);
if (!fp)
return NULL;
if (fseek(fp, 0, SEEK_END) == -1)
goto out;
file_size = ftell(fp);
bytes = amalloc(file_size, a);
fseek(fp, 0, SEEK_SET);
if (fread(bytes, 1, file_size, fp) != file_size) {
afree(bytes, a);
bytes = NULL;
goto out;
}
if (sz)
*sz = file_size;
out:
fclose(fp);
return bytes;
}
/* Dynamic library */
#ifndef VIOLET_NO_LIB
lib_handle lib_load(const char *filename)
{
static const wchar_t *ext = L".dll";
lib_handle hnd = NULL;
const size_t sz = os_string_from_utf8_size(filename);
wchar_t *filename_w = amalloc(sz + wcslen(ext), g_temp_allocator);
if (!os_string_from_utf8(filename_w, sz, filename))
goto out;
wcscat(filename_w, ext);
hnd = LoadLibraryW(filename_w);
out:
afree(filename_w, g_temp_allocator);
return hnd;
}
void *lib_func(lib_handle hnd, const char *name)
{
return GetProcAddress(hnd, name);
}
b32 lib_close(lib_handle hnd)
{
return FreeLibrary(hnd);
}
const char *lib_err(void)
{
static thread_local char buf[256];
wchar_t buf_w[256];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), B2PC(buf_w), NULL);
if (!os_string_to_utf8(B2PC(buf), buf_w))
buf[0] = 0;
return buf;
}
#endif // VIOLET_NO_LIB
/* IO */
size_t vgetdelim(char **lineptr, size_t *n, int delim, FILE *stream, allocator_t *a)
{
if (!lineptr || !n || !stream) {
errno = EINVAL;
return -1;
}
if (!*lineptr) {
*n = 32;
*lineptr = amalloc(*n, a);
} else if (*n == 0) {
errno = EINVAL;
return -1;
}
int i = 0, c;
while ((c = fgetc(stream)) != EOF) {
if (i == *n-1) {
*n *= 2;
*lineptr = arealloc(*lineptr, *n, a);
}
(*lineptr)[i++] = c;
if (c == delim)
break;
}
if (ferror(stream) || feof(stream))
return -1;
(*lineptr)[i] = '\0';
return i;
}
size_t vgetline(char **lineptr, size_t *n, FILE *stream, allocator_t *a)
{
return vgetdelim(lineptr, n, '\n', stream, a);
}
/* Other applications */
void exec(char *const argv[])
{
_execv(argv[0], argv);
}
b32 open_file_external(const char *filename)
{
wchar_t filename_w[PATH_MAX];
INT_PTR ret;
if (!os_string_from_utf8(B2PC(filename_w), filename))
return false;
ret = (INT_PTR)ShellExecuteW(NULL, L"open", filename_w,
NULL, NULL, SW_SHOWNORMAL);
if (ret <= 32) {
log_error("failed to open %s in an external program with error %d",
filename, ret);
return false;
}
return true;
}
/* System */
s32 cpu_max_sse(void)
{
int info[4] = {0};
int max_function_id;
__cpuid(info, 0);
max_function_id = info[0];
if (max_function_id < 1) {
log_error("failed to fetch highest cpuid functionid");
return OS_SSE_VERSION_UNKNOWN;
}
__cpuid(info, 1);
return cpu_max_sse_(info);
}
b32 cpu_supports_sse41(void)
{
return cpu_max_sse() >= OS_SSE_VERSION_41;
}
void cpu_vendor(char vendor[32])
{
int info[4] = {0};
__cpuid(info, 0);
cpu_vendor_(info, vendor);
}
os_utsname_t os_uname(void)
{
os_utsname_t os_utsname = {0};
strbcpy(os_utsname.sysname, "Windows");
return os_utsname;
}
// This is a "good enough" solution for finding out if there's another instance of this
// application that might be using the same data directory. Release builds will always
// choose their datadir based on WINDOWS_PACKAGE_NAME, regardless of where they are installed.
b32 is_data_dir_in_use_by_another_instance(void)
{
#ifndef WINDOWS_PACKAGE_NAME
return false;
#else
wchar_t app_name[64];
HANDLE snapshot;
if ( !os_string_from_utf8(app_name, 64, WINDOWS_PACKAGE_NAME ".exe")
|| (snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)) == INVALID_HANDLE_VALUE) {
assert(false);
return false;
}
u32 open_instances = 0;
PROCESSENTRY32 pe32 = (PROCESSENTRY32){ .dwSize = sizeof(PROCESSENTRY32) };
if (!Process32First(snapshot, &pe32)) {
assert(false);
goto out;
}
do {
if (_wcsicmp(app_name, pe32.szExeFile) == 0)
++open_instances;
} while (open_instances < 2 && Process32Next(snapshot, &pe32));
out:
CloseHandle(snapshot);
return open_instances > 1;
#endif
}