Debian Codegraph @

bypy/windows/file_dialogs.cpp

raw
1 /*
2 * file_dialogs.c
3 * Copyright (C) 2016 Kovid Goyal <kovid at kovidgoyal.net>
4 *
5 * Distributed under terms of the GPL3 license.
6 */
7
8 #ifndef _UNICODE
9 #define _UNICODE
10 #endif
11 #include <Windows.h>
12 #include <Shobjidl.h>
13 #include <comdef.h>
14 #include <stdio.h>
15 #include <string.h>
16 #include <io.h>
17 #include <fcntl.h>
18
19 #define PRINTERR(x) \
20 fprintf(stderr, "%s", x); \
21 fflush(stderr);
22 #define SECRET_SIZE 32
23
24 void
25 set_dpi_aware() {
26 // Try SetProcessDpiAwareness first
27 HINSTANCE sh_core = LoadLibraryW(L"Shcore.dll");
28
29 if (sh_core) {
30 enum ProcessDpiAwareness { ProcessDpiUnaware = 0, ProcessSystemDpiAware = 1, ProcessPerMonitorDpiAware = 2 };
31
32 typedef HRESULT(WINAPI * SetProcessDpiAwarenessFuncType)(ProcessDpiAwareness);
33 SetProcessDpiAwarenessFuncType SetProcessDpiAwarenessFunc =
34 reinterpret_cast<SetProcessDpiAwarenessFuncType>(GetProcAddress(sh_core, "SetProcessDpiAwareness"));
35
36 if (SetProcessDpiAwarenessFunc) {
37 // We only check for E_INVALIDARG because we would get
38 // E_ACCESSDENIED if the DPI was already set previously
39 // and S_OK means the call was successful
40 if (SetProcessDpiAwarenessFunc(ProcessPerMonitorDpiAware) == E_INVALIDARG) {
41 PRINTERR("Failed to set process DPI awareness using SetProcessDpiAwareness");
42 } else {
43 FreeLibrary(sh_core);
44 return;
45 }
46 }
47
48 FreeLibrary(sh_core);
49 }
50
51 // Fall back to SetProcessDPIAware if SetProcessDpiAwareness
52 // is not available on this system
53 HINSTANCE user32 = LoadLibraryW(L"user32.dll");
54
55 if (user32) {
56 typedef BOOL(WINAPI * SetProcessDPIAwareFuncType)(void);
57 SetProcessDPIAwareFuncType SetProcessDPIAwareFunc = reinterpret_cast<SetProcessDPIAwareFuncType>(GetProcAddress(user32, "SetProcessDPIAware"));
58
59 if (SetProcessDPIAwareFunc) {
60 if (!SetProcessDPIAwareFunc()) { PRINTERR("Failed to set process DPI awareness using SetProcessDPIAware"); }
61 }
62
63 FreeLibrary(user32);
64 }
65 }
66
67 bool
68 write_bytes(HANDLE pipe, DWORD sz, const char *buf) {
69 DWORD written = 0;
70 if (!WriteFile(pipe, buf, sz, &written, NULL)) {
71 fprintf(stderr, "Failed to write to pipe. GetLastError()=%d\n", GetLastError());
72 fflush(stderr);
73 return false;
74 }
75 if (written != sz) {
76 fprintf(stderr, "Failed to write to pipe. Incomplete write, leftover bytes: %d", sz - written);
77 fflush(stderr);
78 return false;
79 }
80 return true;
81 }
82
83 bool
84 read_bytes(size_t sz, char *buf, bool allow_incomplete = false) {
85 char *ptr = buf, *limit = buf + sz;
86 while (limit > ptr && !feof(stdin) && !ferror(stdin)) { ptr += fread(ptr, 1, limit - ptr, stdin); }
87 if (ferror(stdin)) {
88 PRINTERR("Failed to read from stdin!");
89 return false;
90 }
91 if (ptr - buf != sz) {
92 if (!allow_incomplete) PRINTERR("Truncated input!");
93 return false;
94 }
95 return true;
96 }
97
98 bool
99 from_utf8(size_t sz, const char *src, LPWSTR *ans) {
100 int asz = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, src, (int)sz, NULL, 0);
101 if (!asz) {
102 PRINTERR("Failed to get size of UTF-8 string");
103 return false;
104 }
105 *ans = (LPWSTR)calloc(asz + 1, sizeof(wchar_t));
106 if (*ans == NULL) {
107 PRINTERR("Out of memory!");
108 return false;
109 }
110 asz = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, src, (int)sz, *ans, asz);
111 if (!asz) {
112 PRINTERR("Failed to convert UTF-8 string");
113 return false;
114 }
115 return true;
116 }
117
118 char *
119 to_utf8(LPCWSTR src, int *sz) {
120 // Convert to a null-terminated UTF-8 encoded bytearray, allocated on the heap
121 char *ans = NULL;
122 *sz = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, src, -1, NULL, 0, NULL, NULL);
123 if (!*sz) {
124 PRINTERR("Failed to get size of UTF-16 string");
125 return NULL;
126 }
127 ans = (char *)calloc((*sz) + 1, sizeof(char));
128 if (ans == NULL) {
129 PRINTERR("Out of memory!");
130 return NULL;
131 }
132 *sz = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, src, -1, ans, *sz, NULL, NULL);
133 if (!*sz) {
134 PRINTERR("Failed to convert UTF-16 string");
135 return NULL;
136 }
137 return ans;
138 }
139
140 static char *rsbuf = NULL;
141
142 bool
143 read_string(unsigned short sz, LPWSTR *ans) {
144 memset(rsbuf, 0, 65537);
145 if (!read_bytes(sz, rsbuf)) return false;
146 if (!from_utf8(sz, rsbuf, ans)) return false;
147 return true;
148 }
149
150 COMDLG_FILTERSPEC *
151 read_file_types(UINT *num_file_types) {
152 char buf[10] = {0};
153 COMDLG_FILTERSPEC *ans = NULL;
154
155 if (!read_bytes(sizeof(unsigned short), buf)) return NULL;
156 *num_file_types = *((unsigned short *)buf);
157 if (*num_file_types < 1 || *num_file_types > 500) {
158 PRINTERR("Invalid number of file types");
159 return NULL;
160 }
161 ans = (COMDLG_FILTERSPEC *)calloc((*num_file_types) + 1, sizeof(COMDLG_FILTERSPEC));
162 if (ans == NULL) {
163 PRINTERR("Out of memory!");
164 return NULL;
165 }
166
167 for (unsigned short i = 0; i < *num_file_types; i++) {
168 if (!read_bytes(sizeof(unsigned short), buf)) return NULL;
169 if (!read_string(*((unsigned short *)buf), (LPWSTR *)&(ans[i].pszName))) return NULL;
170 if (!read_bytes(sizeof(unsigned short), buf)) return NULL;
171 if (!read_string(*((unsigned short *)buf), (LPWSTR *)&(ans[i].pszSpec))) return NULL;
172 }
173 return ans;
174 }
175
176 static void
177 print_com_error(HRESULT hr, const char *msg) {
178 _com_error err(hr);
179 LPCWSTR emsg = (LPCWSTR)err.ErrorMessage();
180 int sz = 0;
181 const char *buf = to_utf8(emsg, &sz);
182 if (buf == NULL) {
183 fprintf(stderr, "%s", msg);
184 } else {
185 fprintf(stderr, "%s: (HRESULT=0x%x) %s\n", msg, hr, buf);
186 }
187 fflush(stderr);
188 }
189
190 #define REPORTERR(hr, x) \
191 { \
192 print_com_error(hr, x); \
193 ret = 1; \
194 goto error; \
195 }
196 #define CALLCOM(x, err) \
197 hr = x; \
198 if (FAILED(hr)) REPORTERR(hr, err)
199
200 int
201 show_dialog(
202 HANDLE pipe,
203 char *secret,
204 HWND parent,
205 bool save_dialog,
206 LPWSTR title,
207 LPWSTR folder,
208 LPWSTR filename,
209 LPWSTR save_path,
210 bool multiselect,
211 bool confirm_overwrite,
212 bool only_dirs,
213 bool no_symlinks,
214 COMDLG_FILTERSPEC *file_types,
215 UINT num_file_types,
216 LPWSTR default_extension) {
217 int ret = 0, name_sz = 0;
218 IFileDialog *pfd = NULL;
219 IShellItemArray *items = NULL;
220 IShellItem *item = NULL, *folder_item = NULL, *save_path_item = NULL;
221 char *path = NULL;
222 DWORD options = 0, item_count = 0;
223 LPWSTR name = NULL;
224 HRESULT hr = S_OK;
225 hr = CoInitialize(NULL);
226 if (FAILED(hr)) {
227 PRINTERR("Failed to initialize COM");
228 return 1;
229 }
230
231 CALLCOM(
232 CoCreateInstance(
233 (save_dialog ? CLSID_FileSaveDialog : CLSID_FileOpenDialog),
234 NULL,
235 CLSCTX_INPROC_SERVER,
236 (save_dialog ? IID_IFileSaveDialog : IID_IFileOpenDialog),
237 reinterpret_cast<LPVOID *>(&pfd)),
238 "Failed to create COM object for file dialog")
239 CALLCOM(pfd->GetOptions(&options), "Failed to get options")
240 options |= FOS_PATHMUSTEXIST;
241 if (no_symlinks) options |= FOS_NODEREFERENCELINKS;
242 if (save_dialog) {
243 options |= FOS_NOREADONLYRETURN;
244 if (confirm_overwrite) options |= FOS_OVERWRITEPROMPT;
245 if (save_path != NULL) {
246 hr = SHCreateItemFromParsingName(save_path, NULL, IID_IShellItem, reinterpret_cast<void **>(&save_path_item));
247 // Failure to set initial save path is not critical
248 if (SUCCEEDED(hr)) ((IFileSaveDialog *)pfd)->SetSaveAsItem(save_path_item);
249 }
250 } else {
251 if (multiselect) options |= FOS_ALLOWMULTISELECT;
252 if (only_dirs) options |= FOS_PICKFOLDERS;
253 options |= FOS_FILEMUSTEXIST;
254 }
255 CALLCOM(pfd->SetOptions(options), "Failed to set options")
256 if (title != NULL) { CALLCOM(pfd->SetTitle(title), "Failed to set title") }
257 if (folder != NULL) {
258 hr = SHCreateItemFromParsingName(folder, NULL, IID_IShellItem, reinterpret_cast<void **>(&folder_item));
259 // Failure to set initial folder is not critical
260 if (SUCCEEDED(hr)) pfd->SetFolder(folder_item);
261 }
262 if (filename != NULL) pfd->SetFileName(filename); // Failure is not critical
263 if (!(options & FOS_PICKFOLDERS) && file_types != NULL && num_file_types > 0) {
264 CALLCOM(pfd->SetFileTypes(num_file_types, file_types), "Failed to set file types")
265 CALLCOM(pfd->SetFileTypeIndex(1), "Failed to set file type index")
266 }
267 if (default_extension != NULL) { CALLCOM(pfd->SetDefaultExtension(default_extension), "Failed to set default extension") }
268 hr = pfd->Show(parent);
269 if (hr == HRESULT_FROM_WIN32(ERROR_CANCELLED)) goto error;
270 if (FAILED(hr)) REPORTERR(hr, "Failed to show dialog")
271
272 if (save_dialog) {
273 CALLCOM(pfd->GetResult(&item), "Failed to get save dialog result");
274 CALLCOM(item->GetDisplayName(SIGDN_FILESYSPATH, &name), "Failed to get display name of save dialog result");
275 path = to_utf8(name, &name_sz);
276 CoTaskMemFree(name);
277 name = NULL;
278 if (path == NULL) return 1;
279 if (!write_bytes(pipe, SECRET_SIZE + 1, secret)) return 1;
280 if (!write_bytes(pipe, name_sz, path)) return 1;
281 } else {
282 CALLCOM(((IFileOpenDialog *)pfd)->GetResults(&items), "Failed to get dialog results");
283 CALLCOM(items->GetCount(&item_count), "Failed to get count of results");
284 if (item_count > 0) {
285 if (!write_bytes(pipe, SECRET_SIZE + 1, secret)) return 1;
286 for (DWORD i = 0; i < item_count; i++) {
287 CALLCOM(items->GetItemAt(i, &item), "Failed to get result item");
288 if (SUCCEEDED(item->GetDisplayName(SIGDN_FILESYSPATH, &name))) {
289 path = to_utf8(name, &name_sz);
290 CoTaskMemFree(name);
291 name = NULL;
292 if (path == NULL) return 1;
293 if (!write_bytes(pipe, name_sz, path)) return 1;
294 }
295 }
296 }
297 }
298
299 error:
300 if (pfd) pfd->Release();
301 CoUninitialize();
302 return ret;
303 }
304 #define READ(x, y) \
305 if (!read_bytes((x), (y))) return 1;
306 #define CHECK_KEY(x) (key_size == sizeof(x) - 1 && memcmp(buf, x, sizeof(x) - 1) == 0)
307 #define READSTR(x) \
308 READ(sizeof(unsigned short), buf); \
309 if (!read_string(*((unsigned short *)buf), &x)) return 1;
310 #define SETBINARY(x) \
311 if (_setmode(_fileno(x), _O_BINARY) == -1) { \
312 PRINTERR("Failed to set binary mode"); \
313 return 1; \
314 }
315 #define READBOOL(x) \
316 READ(1, buf); \
317 x = !!buf[0];
318
319 HANDLE
320 open_named_pipe(LPWSTR pipename) {
321 HANDLE ans = INVALID_HANDLE_VALUE;
322 while (true) {
323 ans = CreateFileW(pipename, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
324 if (ans != INVALID_HANDLE_VALUE) break;
325 if (GetLastError() != ERROR_PIPE_BUSY) {
326 fprintf(stderr, "Failed to open pipe. GetLastError()=%d\n", GetLastError());
327 fflush(stderr);
328 return ans;
329 }
330 if (!WaitNamedPipeW(pipename, 20000)) {
331 fprintf(stderr, "Failed to open pipe. 20 second wait timed out. GetLastError()=%d\n", GetLastError());
332 fflush(stderr);
333 return ans;
334 }
335 }
336 return ans;
337 }
338
339 typedef HRESULT(__stdcall *app_uid_func)(PCWSTR app_uid);
340
341 bool
342 set_app_uid(LPWSTR app_uid) {
343 // Not available on vista so we have to load the function dynamically
344 bool ok = false;
345 HINSTANCE dll = LoadLibraryW(L"Shell32.dll");
346 if (dll != NULL) {
347 app_uid_func f = (app_uid_func)GetProcAddress(dll, "SetCurrentProcessExplicitAppUserModelID");
348 if (f != NULL) ok = f(app_uid) == S_OK;
349 FreeLibrary(dll);
350 dll = NULL;
351 }
352 return ok;
353 }
354
355 int WINAPI
356 wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow) {
357 char buf[257] = {0}, secret[SECRET_SIZE + 1] = {0};
358 size_t key_size = 0;
359 HWND parent = NULL;
360 bool save_dialog = false, multiselect = false, confirm_overwrite = false, only_dirs = false, no_symlinks = false;
361 unsigned short len = 0;
362 LPWSTR title = NULL, folder = NULL, filename = NULL, save_path = NULL, echo = NULL, pipename = NULL, default_extension = NULL, app_uid = NULL;
363 COMDLG_FILTERSPEC *file_types = NULL;
364 UINT num_file_types = 0;
365 HANDLE pipe = INVALID_HANDLE_VALUE;
366
367 SETBINARY(stdout);
368 SETBINARY(stdin);
369 SETBINARY(stderr);
370 // The calibre executables call SetDllDirectory, we unset it here just in
371 // case it interferes with some idiotic shell extension or the other
372 SetDllDirectory(NULL);
373 rsbuf = (char *)calloc(65537, sizeof(char));
374 if (rsbuf == NULL) {
375 PRINTERR("Out of memory!");
376 return 1;
377 }
378
379 while (!feof(stdin)) {
380 memset(buf, 0, sizeof(buf));
381 if (!read_bytes(1, buf, true)) {
382 if (feof(stdin)) break;
383 return 1;
384 }
385 key_size = (size_t)buf[0];
386 READ(key_size, buf);
387 if CHECK_KEY ("HWND") {
388 READ(sizeof(HWND), buf);
389 #pragma warning(push)
390 #pragma warning(disable : 4312)
391 if (sizeof(HWND) == 8) parent = (HWND) * ((__int64 *)buf);
392 else if (sizeof(HWND) == 4) parent = (HWND) * ((__int32 *)buf);
393 else {
394 fprintf(stderr, "Unknown pointer size: %zd", sizeof(HWND));
395 fflush(stderr);
396 return 1;
397 }
398 #pragma warning(pop)
399 }
400
401 else if CHECK_KEY ("PIPENAME") {
402 READSTR(pipename);
403 pipe = open_named_pipe(pipename);
404 if (pipe == INVALID_HANDLE_VALUE) return 1;
405 }
406
407 else if CHECK_KEY ("SECRET") {
408 if (!read_bytes(SECRET_SIZE, secret)) return 1;
409 }
410
411 else if CHECK_KEY ("APP_UID") {
412 READSTR(app_uid)
413 }
414
415 else if CHECK_KEY ("TITLE") {
416 READSTR(title)
417 }
418
419 else if CHECK_KEY ("FOLDER") {
420 READSTR(folder)
421 }
422
423 else if CHECK_KEY ("FILENAME") {
424 READSTR(filename)
425 }
426
427 else if CHECK_KEY ("SAVE_PATH") {
428 READSTR(save_path)
429 }
430
431 else if CHECK_KEY ("SAVE_AS") {
432 READBOOL(save_dialog)
433 }
434
435 else if CHECK_KEY ("MULTISELECT") {
436 READBOOL(multiselect)
437 }
438
439 else if CHECK_KEY ("CONFIRM_OVERWRITE") {
440 READBOOL(confirm_overwrite)
441 }
442
443 else if CHECK_KEY ("ONLY_DIRS") {
444 READBOOL(only_dirs)
445 }
446
447 else if CHECK_KEY ("NO_SYMLINKS") {
448 READBOOL(no_symlinks)
449 }
450
451 else if CHECK_KEY ("FILE_TYPES") {
452 file_types = read_file_types(&num_file_types);
453 if (file_types == NULL) return 1;
454 }
455
456 else if CHECK_KEY ("DEFAULT_EXTENSION") {
457 READSTR(default_extension)
458 }
459
460 else if CHECK_KEY ("ECHO") {
461 READSTR(echo)
462 }
463
464 else {
465 PRINTERR("Unknown key");
466 return 1;
467 }
468 }
469
470 if (pipe == INVALID_HANDLE_VALUE) {
471 PRINTERR("No pipename received");
472 return 1;
473 }
474 if (secret == NULL) {
475 PRINTERR("No secret received");
476 return 1;
477 }
478
479 if (echo != NULL) {
480 int echo_sz = 0;
481 char *echo_buf = to_utf8(echo, &echo_sz);
482 if (!write_bytes(pipe, SECRET_SIZE + 1, secret)) return 1;
483 return write_bytes(pipe, echo_sz, echo_buf) ? 0 : 1;
484 }
485 if (app_uid != NULL) {
486 // don't check return status as failure is not critical
487 set_app_uid(app_uid);
488 }
489
490 set_dpi_aware();
491 return show_dialog(
492 pipe,
493 secret,
494 parent,
495 save_dialog,
496 title,
497 folder,
498 filename,
499 save_path,
500 multiselect,
501 confirm_overwrite,
502 only_dirs,
503 no_symlinks,
504 file_types,
505 num_file_types,
506 default_extension);
507 }