-
Notifications
You must be signed in to change notification settings - Fork 99
/
portable-file-dialogs.h
1887 lines (1634 loc) · 56.1 KB
/
portable-file-dialogs.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
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
//
// Portable File Dialogs
//
// Copyright © 2018–2022 Sam Hocevar <[email protected]>
//
// This library is free software. It comes without any warranty, to
// the extent permitted by applicable law. You can redistribute it
// and/or modify it under the terms of the Do What the Fuck You Want
// to Public License, Version 2, as published by the WTFPL Task Force.
// See http://www.wtfpl.net/ for more details.
//
#pragma once
#if _WIN32
#ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN 1
#endif
#include <windows.h>
#include <commdlg.h>
#include <shlobj.h>
#include <shobjidl.h> // IFileDialog
#include <shellapi.h>
#include <strsafe.h>
#include <future> // std::async
#include <userenv.h> // GetUserProfileDirectory()
#elif __EMSCRIPTEN__
#include <emscripten.h>
#else
#ifndef _POSIX_C_SOURCE
# define _POSIX_C_SOURCE 2 // for popen()
#endif
#ifdef __APPLE__
# ifndef _DARWIN_C_SOURCE
# define _DARWIN_C_SOURCE
# endif
#endif
#include <cstdio> // popen()
#include <cstdlib> // std::getenv()
#include <fcntl.h> // fcntl()
#include <unistd.h> // read(), pipe(), dup2(), getuid()
#include <csignal> // ::kill, std::signal
#include <sys/stat.h> // stat()
#include <sys/wait.h> // waitpid()
#include <pwd.h> // getpwnam()
#endif
#include <string> // std::string
#include <memory> // std::shared_ptr
#include <iostream> // std::ostream
#include <map> // std::map
#include <set> // std::set
#include <regex> // std::regex
#include <thread> // std::mutex, std::this_thread
#include <chrono> // std::chrono
// Versions of mingw64 g++ up to 9.3.0 do not have a complete IFileDialog
#ifndef PFD_HAS_IFILEDIALOG
# define PFD_HAS_IFILEDIALOG 1
# if (defined __MINGW64__ || defined __MINGW32__) && defined __GXX_ABI_VERSION
# if __GXX_ABI_VERSION <= 1013
# undef PFD_HAS_IFILEDIALOG
# define PFD_HAS_IFILEDIALOG 0
# endif
# endif
#endif
namespace pfd
{
enum class button
{
cancel = -1,
ok,
yes,
no,
abort,
retry,
ignore,
};
enum class choice
{
ok = 0,
ok_cancel,
yes_no,
yes_no_cancel,
retry_cancel,
abort_retry_ignore,
};
enum class icon
{
info = 0,
warning,
error,
question,
};
// Additional option flags for various dialog constructors
enum class opt : uint8_t
{
none = 0,
// For file open, allow multiselect.
multiselect = 0x1,
// For file save, force overwrite and disable the confirmation dialog.
force_overwrite = 0x2,
// For folder select, force path to be the provided argument instead
// of the last opened directory, which is the Microsoft-recommended,
// user-friendly behaviour.
force_path = 0x4,
};
inline opt operator |(opt a, opt b) { return opt(uint8_t(a) | uint8_t(b)); }
inline bool operator &(opt a, opt b) { return bool(uint8_t(a) & uint8_t(b)); }
// The settings class, only exposing to the user a way to set verbose mode
// and to force a rescan of installed desktop helpers (zenity, kdialog…).
class settings
{
public:
static bool available();
static void verbose(bool value);
static void rescan();
protected:
explicit settings(bool resync = false);
bool check_program(std::string const &program);
inline bool is_osascript() const;
inline bool is_zenity() const;
inline bool is_kdialog() const;
enum class flag
{
is_scanned = 0,
is_verbose,
has_zenity,
has_matedialog,
has_qarma,
has_kdialog,
is_vista,
max_flag,
};
// Static array of flags for internal state
bool const &flags(flag in_flag) const;
// Non-const getter for the static array of flags
bool &flags(flag in_flag);
};
// Internal classes, not to be used by client applications
namespace internal
{
// Process wait timeout, in milliseconds
static int const default_wait_timeout = 20;
class executor
{
friend class dialog;
public:
// High level function to get the result of a command
std::string result(int *exit_code = nullptr);
// High level function to abort
bool kill();
#if _WIN32
void start_func(std::function<std::string(int *)> const &fun);
static BOOL CALLBACK enum_windows_callback(HWND hwnd, LPARAM lParam);
#elif __EMSCRIPTEN__
void start(int exit_code);
#else
void start_process(std::vector<std::string> const &command);
#endif
~executor();
protected:
bool ready(int timeout = default_wait_timeout);
void stop();
private:
bool m_running = false;
std::string m_stdout;
int m_exit_code = -1;
#if _WIN32
std::future<std::string> m_future;
std::set<HWND> m_windows;
std::condition_variable m_cond;
std::mutex m_mutex;
DWORD m_tid;
#elif __EMSCRIPTEN__ || __NX__
// FIXME: do something
#else
pid_t m_pid = 0;
int m_fd = -1;
#endif
};
class platform
{
protected:
#if _WIN32
// Helper class around LoadLibraryA() and GetProcAddress() with some safety
class dll
{
public:
dll(std::string const &name);
~dll();
template<typename T> class proc
{
public:
proc(dll const &lib, std::string const &sym)
: m_proc(reinterpret_cast<T *>((void *)::GetProcAddress(lib.handle, sym.c_str())))
{}
operator bool() const { return m_proc != nullptr; }
operator T *() const { return m_proc; }
private:
T *m_proc;
};
private:
HMODULE handle;
};
// Helper class around CoInitialize() and CoUnInitialize()
class ole32_dll : public dll
{
public:
ole32_dll();
~ole32_dll();
bool is_initialized();
private:
HRESULT m_state;
};
// Helper class around CreateActCtx() and ActivateActCtx()
class new_style_context
{
public:
new_style_context();
~new_style_context();
private:
HANDLE create();
ULONG_PTR m_cookie = 0;
};
#endif
};
class dialog : protected settings, protected platform
{
public:
bool ready(int timeout = default_wait_timeout) const;
bool kill() const;
protected:
explicit dialog();
std::vector<std::string> desktop_helper() const;
static std::string buttons_to_name(choice _choice);
static std::string get_icon_name(icon _icon);
std::string powershell_quote(std::string const &str) const;
std::string osascript_quote(std::string const &str) const;
std::string shell_quote(std::string const &str) const;
// Keep handle to executing command
std::shared_ptr<executor> m_async;
};
class file_dialog : public dialog
{
protected:
enum type
{
open,
save,
folder,
};
file_dialog(type in_type,
std::string const &title,
std::string const &default_path = "",
std::vector<std::string> const &filters = {},
opt options = opt::none);
protected:
std::string string_result();
std::vector<std::string> vector_result();
#if _WIN32
static int CALLBACK bffcallback(HWND hwnd, UINT uMsg, LPARAM, LPARAM pData);
#if PFD_HAS_IFILEDIALOG
std::string select_folder_vista(IFileDialog *ifd, bool force_path);
#endif
std::wstring m_wtitle;
std::wstring m_wdefault_path;
std::vector<std::string> m_vector_result;
#endif
};
} // namespace internal
//
// The path class provides some platform-specific path constants
//
class path : protected internal::platform
{
public:
static std::string home();
static std::string separator();
};
//
// The notify widget
//
class notify : public internal::dialog
{
public:
notify(std::string const &title,
std::string const &message,
icon _icon = icon::info);
};
//
// The message widget
//
class message : public internal::dialog
{
public:
message(std::string const &title,
std::string const &text,
choice _choice = choice::ok_cancel,
icon _icon = icon::info);
button result();
private:
// Some extra logic to map the exit code to button number
std::map<int, button> m_mappings;
};
//
// The open_file, save_file, and open_folder widgets
//
class open_file : public internal::file_dialog
{
public:
open_file(std::string const &title,
std::string const &default_path = "",
std::vector<std::string> const &filters = { "All Files", "*" },
opt options = opt::none);
#if defined(__has_cpp_attribute)
#if __has_cpp_attribute(deprecated)
// Backwards compatibility
[[deprecated("Use pfd::opt::multiselect instead of allow_multiselect")]]
#endif
#endif
open_file(std::string const &title,
std::string const &default_path,
std::vector<std::string> const &filters,
bool allow_multiselect);
std::vector<std::string> result();
};
class save_file : public internal::file_dialog
{
public:
save_file(std::string const &title,
std::string const &default_path = "",
std::vector<std::string> const &filters = { "All Files", "*" },
opt options = opt::none);
#if defined(__has_cpp_attribute)
#if __has_cpp_attribute(deprecated)
// Backwards compatibility
[[deprecated("Use pfd::opt::force_overwrite instead of confirm_overwrite")]]
#endif
#endif
save_file(std::string const &title,
std::string const &default_path,
std::vector<std::string> const &filters,
bool confirm_overwrite);
std::string result();
};
class select_folder : public internal::file_dialog
{
public:
select_folder(std::string const &title,
std::string const &default_path = "",
opt options = opt::none);
std::string result();
};
//
// Below this are all the method implementations. You may choose to define the
// macro PFD_SKIP_IMPLEMENTATION everywhere before including this header except
// in one place. This may reduce compilation times.
//
#if !defined PFD_SKIP_IMPLEMENTATION
// internal free functions implementations
namespace internal
{
#if _WIN32
static inline std::wstring str2wstr(std::string const &str)
{
int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), nullptr, 0);
std::wstring ret(len, '\0');
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), (LPWSTR)ret.data(), (int)ret.size());
return ret;
}
static inline std::string wstr2str(std::wstring const &str)
{
int len = WideCharToMultiByte(CP_UTF8, 0, str.c_str(), (int)str.size(), nullptr, 0, nullptr, nullptr);
std::string ret(len, '\0');
WideCharToMultiByte(CP_UTF8, 0, str.c_str(), (int)str.size(), (LPSTR)ret.data(), (int)ret.size(), nullptr, nullptr);
return ret;
}
static inline bool is_vista()
{
OSVERSIONINFOEXW osvi;
memset(&osvi, 0, sizeof(osvi));
DWORDLONG const mask = VerSetConditionMask(
VerSetConditionMask(
VerSetConditionMask(
0, VER_MAJORVERSION, VER_GREATER_EQUAL),
VER_MINORVERSION, VER_GREATER_EQUAL),
VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);
osvi.dwOSVersionInfoSize = sizeof(osvi);
osvi.dwMajorVersion = HIBYTE(_WIN32_WINNT_VISTA);
osvi.dwMinorVersion = LOBYTE(_WIN32_WINNT_VISTA);
osvi.wServicePackMajor = 0;
return VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, mask) != FALSE;
}
#endif
// This is necessary until C++20 which will have std::string::ends_with() etc.
static inline bool ends_with(std::string const &str, std::string const &suffix)
{
return suffix.size() <= str.size() &&
str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
}
static inline bool starts_with(std::string const &str, std::string const &prefix)
{
return prefix.size() <= str.size() &&
str.compare(0, prefix.size(), prefix) == 0;
}
// This is necessary until C++17 which will have std::filesystem::is_directory
static inline bool is_directory(std::string const &path)
{
#if _WIN32
auto attr = GetFileAttributesA(path.c_str());
return attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY);
#elif __EMSCRIPTEN__
// TODO
return false;
#else
struct stat s;
return stat(path.c_str(), &s) == 0 && S_ISDIR(s.st_mode);
#endif
}
// This is necessary because getenv is not thread-safe
static inline std::string getenv(std::string const &str)
{
#if _MSC_VER
char *buf = nullptr;
size_t size = 0;
if (_dupenv_s(&buf, &size, str.c_str()) == 0 && buf)
{
std::string ret(buf);
free(buf);
return ret;
}
return "";
#else
auto buf = std::getenv(str.c_str());
return buf ? buf : "";
#endif
}
} // namespace internal
// settings implementation
inline settings::settings(bool resync)
{
flags(flag::is_scanned) &= !resync;
if (flags(flag::is_scanned))
return;
auto pfd_verbose = internal::getenv("PFD_VERBOSE");
auto match_no = std::regex("(|0|no|false)", std::regex_constants::icase);
if (!std::regex_match(pfd_verbose, match_no))
flags(flag::is_verbose) = true;
#if _WIN32
flags(flag::is_vista) = internal::is_vista();
#elif !__APPLE__
flags(flag::has_zenity) = check_program("zenity");
flags(flag::has_matedialog) = check_program("matedialog");
flags(flag::has_qarma) = check_program("qarma");
flags(flag::has_kdialog) = check_program("kdialog");
// If multiple helpers are available, try to default to the best one
if (flags(flag::has_zenity) && flags(flag::has_kdialog))
{
auto desktop_name = internal::getenv("XDG_SESSION_DESKTOP");
if (desktop_name == std::string("gnome"))
flags(flag::has_kdialog) = false;
else if (desktop_name == std::string("KDE"))
flags(flag::has_zenity) = false;
}
#endif
flags(flag::is_scanned) = true;
}
inline bool settings::available()
{
#if _WIN32
return true;
#elif __APPLE__
return true;
#elif __EMSCRIPTEN__
// FIXME: Return true after implementation is complete.
return false;
#else
settings tmp;
return tmp.flags(flag::has_zenity) ||
tmp.flags(flag::has_matedialog) ||
tmp.flags(flag::has_qarma) ||
tmp.flags(flag::has_kdialog);
#endif
}
inline void settings::verbose(bool value)
{
settings().flags(flag::is_verbose) = value;
}
inline void settings::rescan()
{
settings(/* resync = */ true);
}
// Check whether a program is present using “which”.
inline bool settings::check_program(std::string const &program)
{
#if _WIN32
(void)program;
return false;
#elif __EMSCRIPTEN__
(void)program;
return false;
#else
int exit_code = -1;
internal::executor async;
async.start_process({"/bin/sh", "-c", "which " + program});
async.result(&exit_code);
return exit_code == 0;
#endif
}
inline bool settings::is_osascript() const
{
#if __APPLE__
return true;
#else
return false;
#endif
}
inline bool settings::is_zenity() const
{
return flags(flag::has_zenity) ||
flags(flag::has_matedialog) ||
flags(flag::has_qarma);
}
inline bool settings::is_kdialog() const
{
return flags(flag::has_kdialog);
}
inline bool const &settings::flags(flag in_flag) const
{
static bool flags[size_t(flag::max_flag)];
return flags[size_t(in_flag)];
}
inline bool &settings::flags(flag in_flag)
{
return const_cast<bool &>(static_cast<settings const *>(this)->flags(in_flag));
}
// path implementation
inline std::string path::home()
{
#if _WIN32
// First try the USERPROFILE environment variable
auto user_profile = internal::getenv("USERPROFILE");
if (user_profile.size() > 0)
return user_profile;
// Otherwise, try GetUserProfileDirectory()
HANDLE token = nullptr;
DWORD len = MAX_PATH;
char buf[MAX_PATH] = { '\0' };
if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))
{
dll userenv("userenv.dll");
dll::proc<BOOL WINAPI (HANDLE, LPSTR, LPDWORD)> get_user_profile_directory(userenv, "GetUserProfileDirectoryA");
get_user_profile_directory(token, buf, &len);
CloseHandle(token);
if (*buf)
return buf;
}
#elif __EMSCRIPTEN__
return "/";
#else
// First try the HOME environment variable
auto home = internal::getenv("HOME");
if (home.size() > 0)
return home;
// Otherwise, try getpwuid_r()
size_t len = 4096;
#if defined(_SC_GETPW_R_SIZE_MAX)
auto size_max = sysconf(_SC_GETPW_R_SIZE_MAX);
if (size_max != -1)
len = size_t(size_max);
#endif
std::vector<char> buf(len);
struct passwd pwd, *result;
if (getpwuid_r(getuid(), &pwd, buf.data(), buf.size(), &result) == 0)
return result->pw_dir;
#endif
return "/";
}
inline std::string path::separator()
{
#if _WIN32
return "\\";
#else
return "/";
#endif
}
// executor implementation
inline std::string internal::executor::result(int *exit_code /* = nullptr */)
{
stop();
if (exit_code)
*exit_code = m_exit_code;
return m_stdout;
}
inline bool internal::executor::kill()
{
#if _WIN32
if (m_future.valid())
{
// Close all windows that weren’t open when we started the future
auto previous_windows = m_windows;
EnumWindows(&enum_windows_callback, (LPARAM)this);
for (auto hwnd : m_windows)
if (previous_windows.find(hwnd) == previous_windows.end())
{
SendMessage(hwnd, WM_CLOSE, 0, 0);
// Also send IDNO in case of a Yes/No or Abort/Retry/Ignore messagebox
SendMessage(hwnd, WM_COMMAND, IDNO, 0);
}
}
#elif __EMSCRIPTEN__ || __NX__
// FIXME: do something
return false; // cannot kill
#else
::kill(m_pid, SIGKILL);
#endif
stop();
return true;
}
#if _WIN32
inline BOOL CALLBACK internal::executor::enum_windows_callback(HWND hwnd, LPARAM lParam)
{
auto that = (executor *)lParam;
DWORD pid;
auto tid = GetWindowThreadProcessId(hwnd, &pid);
if (tid == that->m_tid)
that->m_windows.insert(hwnd);
return TRUE;
}
#endif
#if _WIN32
inline void internal::executor::start_func(std::function<std::string(int *)> const &fun)
{
stop();
auto trampoline = [fun, this]()
{
// Save our thread id so that the caller can cancel us
m_tid = GetCurrentThreadId();
EnumWindows(&enum_windows_callback, (LPARAM)this);
m_cond.notify_all();
return fun(&m_exit_code);
};
std::unique_lock<std::mutex> lock(m_mutex);
m_future = std::async(std::launch::async, trampoline);
m_cond.wait(lock);
m_running = true;
}
#elif __EMSCRIPTEN__
inline void internal::executor::start(int exit_code)
{
m_exit_code = exit_code;
}
#else
inline void internal::executor::start_process(std::vector<std::string> const &command)
{
stop();
m_stdout.clear();
m_exit_code = -1;
int in[2], out[2];
if (pipe(in) != 0 || pipe(out) != 0)
return;
m_pid = fork();
if (m_pid < 0)
return;
close(in[m_pid ? 0 : 1]);
close(out[m_pid ? 1 : 0]);
if (m_pid == 0)
{
dup2(in[0], STDIN_FILENO);
dup2(out[1], STDOUT_FILENO);
// Ignore stderr so that it doesn’t pollute the console (e.g. GTK+ errors from zenity)
int fd = open("/dev/null", O_WRONLY);
dup2(fd, STDERR_FILENO);
close(fd);
std::vector<char *> args;
std::transform(command.cbegin(), command.cend(), std::back_inserter(args),
[](std::string const &s) { return const_cast<char *>(s.c_str()); });
args.push_back(nullptr); // null-terminate argv[]
execvp(args[0], args.data());
exit(1);
}
close(in[1]);
m_fd = out[0];
auto flags = fcntl(m_fd, F_GETFL);
fcntl(m_fd, F_SETFL, flags | O_NONBLOCK);
m_running = true;
}
#endif
inline internal::executor::~executor()
{
stop();
}
inline bool internal::executor::ready(int timeout /* = default_wait_timeout */)
{
if (!m_running)
return true;
#if _WIN32
if (m_future.valid())
{
auto status = m_future.wait_for(std::chrono::milliseconds(timeout));
if (status != std::future_status::ready)
{
// On Windows, we need to run the message pump. If the async
// thread uses a Windows API dialog, it may be attached to the
// main thread and waiting for messages that only we can dispatch.
MSG msg;
while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return false;
}
m_stdout = m_future.get();
}
#elif __EMSCRIPTEN__ || __NX__
// FIXME: do something
(void)timeout;
#else
char buf[BUFSIZ];
ssize_t received = read(m_fd, buf, BUFSIZ); // Flawfinder: ignore
if (received > 0)
{
m_stdout += std::string(buf, received);
return false;
}
// Reap child process if it is dead. It is possible that the system has already reaped it
// (this happens when the calling application handles or ignores SIG_CHLD) and results in
// waitpid() failing with ECHILD. Otherwise we assume the child is running and we sleep for
// a little while.
int status;
pid_t child = waitpid(m_pid, &status, WNOHANG);
if (child != m_pid && (child >= 0 || errno != ECHILD))
{
// FIXME: this happens almost always at first iteration
std::this_thread::sleep_for(std::chrono::milliseconds(timeout));
return false;
}
close(m_fd);
m_exit_code = WEXITSTATUS(status);
#endif
m_running = false;
return true;
}
inline void internal::executor::stop()
{
// Loop until the user closes the dialog
while (!ready())
;
}
// dll implementation
#if _WIN32
inline internal::platform::dll::dll(std::string const &name)
: handle(::LoadLibraryA(name.c_str()))
{}
inline internal::platform::dll::~dll()
{
if (handle)
::FreeLibrary(handle);
}
#endif // _WIN32
// ole32_dll implementation
#if _WIN32
inline internal::platform::ole32_dll::ole32_dll()
: dll("ole32.dll")
{
// Use COINIT_MULTITHREADED because COINIT_APARTMENTTHREADED causes crashes.
// See https://github.com/samhocevar/portable-file-dialogs/issues/51
auto coinit = proc<HRESULT WINAPI (LPVOID, DWORD)>(*this, "CoInitializeEx");
m_state = coinit(nullptr, COINIT_MULTITHREADED);
}
inline internal::platform::ole32_dll::~ole32_dll()
{
if (is_initialized())
proc<void WINAPI ()>(*this, "CoUninitialize")();
}
inline bool internal::platform::ole32_dll::is_initialized()
{
return m_state == S_OK || m_state == S_FALSE;
}
#endif
// new_style_context implementation
#if _WIN32
inline internal::platform::new_style_context::new_style_context()
{
// Only create one activation context for the whole app lifetime.
static HANDLE hctx = create();
if (hctx != INVALID_HANDLE_VALUE)
ActivateActCtx(hctx, &m_cookie);
}
inline internal::platform::new_style_context::~new_style_context()
{
DeactivateActCtx(0, m_cookie);
}
inline HANDLE internal::platform::new_style_context::create()
{
// This “hack” seems to be necessary for this code to work on windows XP.
// Without it, dialogs do not show and close immediately. GetError()
// returns 0 so I don’t know what causes this. I was not able to reproduce
// this behavior on Windows 7 and 10 but just in case, let it be here for
// those versions too.
// This hack is not required if other dialogs are used (they load comdlg32
// automatically), only if message boxes are used.
dll comdlg32("comdlg32.dll");
// Using approach as shown here: https://stackoverflow.com/a/10444161
UINT len = ::GetSystemDirectoryA(nullptr, 0);
std::string sys_dir(len, '\0');
::GetSystemDirectoryA(&sys_dir[0], len);
ACTCTXA act_ctx =
{
// Do not set flag ACTCTX_FLAG_SET_PROCESS_DEFAULT, since it causes a
// crash with error “default context is already set”.
sizeof(act_ctx),
ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID,
"shell32.dll", 0, 0, sys_dir.c_str(), (LPCSTR)124, nullptr, 0,
};
return ::CreateActCtxA(&act_ctx);
}
#endif // _WIN32
// dialog implementation
inline bool internal::dialog::ready(int timeout /* = default_wait_timeout */) const
{
return m_async->ready(timeout);
}
inline bool internal::dialog::kill() const
{
return m_async->kill();
}
inline internal::dialog::dialog()
: m_async(std::make_shared<executor>())
{
}
inline std::vector<std::string> internal::dialog::desktop_helper() const
{
#if __APPLE__
return { "osascript" };
#else
return { flags(flag::has_zenity) ? "zenity"
: flags(flag::has_matedialog) ? "matedialog"
: flags(flag::has_qarma) ? "qarma"
: flags(flag::has_kdialog) ? "kdialog"
: "echo" };
#endif
}
inline std::string internal::dialog::buttons_to_name(choice _choice)
{
switch (_choice)
{
case choice::ok_cancel: return "okcancel";
case choice::yes_no: return "yesno";
case choice::yes_no_cancel: return "yesnocancel";
case choice::retry_cancel: return "retrycancel";