fork/slippc

git clone https://git.julia.blue/fork/slippc

Patrick CrainAdded portable-file-dialogs and tentative GUI solution for slippc output7abc388

testing
50.6 KiB1704 linesraw
1//
2//  Portable File Dialogs
3//
4//  Copyright © 2018—2020 Sam Hocevar <sam@hocevar.net>
5//
6//  This library is free software. It comes without any warranty, to
7//  the extent permitted by applicable law. You can redistribute it
8//  and/or modify it under the terms of the Do What the Fuck You Want
9//  to Public License, Version 2, as published by the WTFPL Task Force.
10//  See http://www.wtfpl.net/ for more details.
11//
12
13#pragma once
14
15#if _WIN32
16#ifndef WIN32_LEAN_AND_MEAN
17#   define WIN32_LEAN_AND_MEAN 1
18#endif
19#include <Windows.h>
20#include <commdlg.h>
21#include <ShlObj.h>
22#include <ShObjIdl.h> // IFileDialog
23#include <shellapi.h>
24#include <strsafe.h>
25#include <future>     // std::async
26
27#elif __EMSCRIPTEN__
28#include <emscripten.h>
29
30#else
31#ifndef _POSIX_C_SOURCE
32#   define _POSIX_C_SOURCE 2 // for popen()
33#endif
34#include <cstdio>     // popen()
35#include <cstdlib>    // std::getenv()
36#include <fcntl.h>    // fcntl()
37#include <unistd.h>   // read(), pipe(), dup2()
38#include <csignal>    // ::kill, std::signal
39#include <sys/wait.h> // waitpid()
40#endif
41
42#include <string>   // std::string
43#include <memory>   // std::shared_ptr
44#include <iostream> // std::ostream
45#include <map>      // std::map
46#include <set>      // std::set
47#include <regex>    // std::regex
48#include <thread>   // std::mutex, std::this_thread
49#include <chrono>   // std::chrono
50
51namespace pfd
52{
53
54enum class button
55{
56    cancel = -1,
57    ok,
58    yes,
59    no,
60    abort,
61    retry,
62    ignore,
63};
64
65enum class choice
66{
67    ok = 0,
68    ok_cancel,
69    yes_no,
70    yes_no_cancel,
71    retry_cancel,
72    abort_retry_ignore,
73};
74
75enum class icon
76{
77    info = 0,
78    warning,
79    error,
80    question,
81};
82
83// Additional option flags for various dialog constructors
84enum class opt : uint8_t
85{
86    none = 0,
87    // For file open, allow multiselect.
88    multiselect     = 0x1,
89    // For file save, force overwrite and disable the confirmation dialog.
90    force_overwrite = 0x2,
91    // For folder select, force path to be the provided argument instead
92    // of the last opened directory, which is the Microsoft-recommended,
93    // user-friendly behaviour.
94    force_path      = 0x4,
95};
96
97inline opt operator |(opt a, opt b) { return opt(uint8_t(a) | uint8_t(b)); }
98inline bool operator &(opt a, opt b) { return bool(uint8_t(a) & uint8_t(b)); }
99
100// The settings class, only exposing to the user a way to set verbose mode
101// and to force a rescan of installed desktop helpers (zenity, kdialog…).
102class settings
103{
104public:
105    static bool available();
106
107    static void verbose(bool value);
108    static void rescan();
109
110protected:
111    explicit settings(bool resync = false);
112
113    bool check_program(std::string const &program);
114
115    inline bool is_osascript() const;
116    inline bool is_zenity() const;
117    inline bool is_kdialog() const;
118
119    enum class flag
120    {
121        is_scanned = 0,
122        is_verbose,
123
124        has_zenity,
125        has_matedialog,
126        has_qarma,
127        has_kdialog,
128        is_vista,
129
130        max_flag,
131    };
132
133    // Static array of flags for internal state
134    bool const &flags(flag in_flag) const;
135
136    // Non-const getter for the static array of flags
137    bool &flags(flag in_flag);
138};
139
140// Internal classes, not to be used by client applications
141namespace internal
142{
143
144// Process wait timeout, in milliseconds
145static int const default_wait_timeout = 20;
146
147class executor
148{
149    friend class dialog;
150
151public:
152    // High level function to get the result of a command
153    std::string result(int *exit_code = nullptr);
154
155    // High level function to abort
156    bool kill();
157
158#if _WIN32
159    void start_func(std::function<std::string(int *)> const &fun);
160    static BOOL CALLBACK enum_windows_callback(HWND hwnd, LPARAM lParam);
161#elif __EMSCRIPTEN__
162    void start(int exit_code);
163#else
164    void start_process(std::vector<std::string> const &command);
165#endif
166
167    ~executor();
168
169protected:
170    bool ready(int timeout = default_wait_timeout);
171    void stop();
172
173private:
174    bool m_running = false;
175    std::string m_stdout;
176    int m_exit_code = -1;
177#if _WIN32
178    std::future<std::string> m_future;
179    std::set<HWND> m_windows;
180    std::condition_variable m_cond;
181    std::mutex m_mutex;
182    DWORD m_tid;
183#elif __EMSCRIPTEN__ || __NX__
184    // FIXME: do something
185#else
186    pid_t m_pid = 0;
187    int m_fd = -1;
188#endif
189};
190
191class platform
192{
193protected:
194#if _WIN32
195    // Helper class around LoadLibraryA() and GetProcAddress() with some safety
196    class dll
197    {
198    public:
199        dll(std::string const &name);
200        ~dll();
201
202        template<typename T> class proc
203        {
204        public:
205            proc(dll const &lib, std::string const &sym)
206              : m_proc(reinterpret_cast<T *>(::GetProcAddress(lib.handle, sym.c_str())))
207            {}
208
209            operator bool() const { return m_proc != nullptr; }
210            operator T *() const { return m_proc; }
211
212        private:
213            T *m_proc;
214        };
215
216    private:
217        HMODULE handle;
218    };
219
220    // Helper class around CoInitialize() and CoUnInitialize()
221    class ole32_dll : public dll
222    {
223    public:
224        ole32_dll();
225        ~ole32_dll();
226        bool is_initialized();
227
228    private:
229        HRESULT m_state;
230    };
231
232    // Helper class around CreateActCtx() and ActivateActCtx()
233    class new_style_context
234    {
235    public:
236        new_style_context();
237        ~new_style_context();
238
239    private:
240        HANDLE create();
241        ULONG_PTR m_cookie = 0;
242    };
243#endif
244};
245
246class dialog : protected settings, protected platform
247{
248public:
249    bool ready(int timeout = default_wait_timeout) const;
250    bool kill() const;
251
252protected:
253    explicit dialog();
254
255    std::vector<std::string> desktop_helper() const;
256    static std::string buttons_to_name(choice _choice);
257    static std::string get_icon_name(icon _icon);
258
259    std::string powershell_quote(std::string const &str) const;
260    std::string osascript_quote(std::string const &str) const;
261    std::string shell_quote(std::string const &str) const;
262
263    // Keep handle to executing command
264    std::shared_ptr<executor> m_async;
265};
266
267class file_dialog : public dialog
268{
269protected:
270    enum type
271    {
272        open,
273        save,
274        folder,
275    };
276
277    file_dialog(type in_type,
278                std::string const &title,
279                std::string const &default_path = "",
280                std::vector<std::string> const &filters = {},
281                opt options = opt::none);
282
283protected:
284    std::string string_result();
285    std::vector<std::string> vector_result();
286
287#if _WIN32
288    static int CALLBACK bffcallback(HWND hwnd, UINT uMsg, LPARAM, LPARAM pData);
289    std::string select_folder_vista(IFileDialog *ifd, bool force_path);
290
291    std::wstring m_wtitle;
292    std::wstring m_wdefault_path;
293
294    std::vector<std::string> m_vector_result;
295#endif
296};
297
298} // namespace internal
299
300//
301// The notify widget
302//
303
304class notify : public internal::dialog
305{
306public:
307    notify(std::string const &title,
308           std::string const &message,
309           icon _icon = icon::info);
310};
311
312//
313// The message widget
314//
315
316class message : public internal::dialog
317{
318public:
319    message(std::string const &title,
320            std::string const &text,
321            choice _choice = choice::ok_cancel,
322            icon _icon = icon::info);
323
324    button result();
325
326private:
327    // Some extra logic to map the exit code to button number
328    std::map<int, button> m_mappings;
329};
330
331//
332// The open_file, save_file, and open_folder widgets
333//
334
335class open_file : public internal::file_dialog
336{
337public:
338    open_file(std::string const &title,
339              std::string const &default_path = "",
340              std::vector<std::string> const &filters = { "All Files", "*" },
341              opt options = opt::none);
342
343#if defined(__has_cpp_attribute)
344#if __has_cpp_attribute(deprecated)
345    // Backwards compatibility
346    [[deprecated("Use pfd::opt::multiselect instead of allow_multiselect")]]
347#endif
348#endif
349    open_file(std::string const &title,
350              std::string const &default_path,
351              std::vector<std::string> const &filters,
352              bool allow_multiselect);
353
354    std::vector<std::string> result();
355};
356
357class save_file : public internal::file_dialog
358{
359public:
360    save_file(std::string const &title,
361              std::string const &default_path = "",
362              std::vector<std::string> const &filters = { "All Files", "*" },
363              opt options = opt::none);
364
365#if defined(__has_cpp_attribute)
366#if __has_cpp_attribute(deprecated)
367    // Backwards compatibility
368    [[deprecated("Use pfd::opt::force_overwrite instead of confirm_overwrite")]]
369#endif
370#endif
371    save_file(std::string const &title,
372              std::string const &default_path,
373              std::vector<std::string> const &filters,
374              bool confirm_overwrite);
375
376    std::string result();
377};
378
379class select_folder : public internal::file_dialog
380{
381public:
382    select_folder(std::string const &title,
383                  std::string const &default_path = "",
384                  opt options = opt::none);
385
386    std::string result();
387};
388
389//
390// Below this are all the method implementations. You may choose to define the
391// macro PFD_SKIP_IMPLEMENTATION everywhere before including this header except
392// in one place. This may reduce compilation times.
393//
394
395#if !defined PFD_SKIP_IMPLEMENTATION
396
397// internal free functions implementations
398
399namespace internal
400{
401
402#if _WIN32
403static inline std::wstring str2wstr(std::string const &str)
404{
405    int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), nullptr, 0);
406    std::wstring ret(len, '\0');
407    MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), (LPWSTR)ret.data(), (int)ret.size());
408    return ret;
409}
410
411static inline std::string wstr2str(std::wstring const &str)
412{
413    int len = WideCharToMultiByte(CP_UTF8, 0, str.c_str(), (int)str.size(), nullptr, 0, nullptr, nullptr);
414    std::string ret(len, '\0');
415    WideCharToMultiByte(CP_UTF8, 0, str.c_str(), (int)str.size(), (LPSTR)ret.data(), (int)ret.size(), nullptr, nullptr);
416    return ret;
417}
418
419static inline bool is_vista()
420{
421    OSVERSIONINFOEXW osvi;
422    memset(&osvi, 0, sizeof(osvi));
423    DWORDLONG const mask = VerSetConditionMask(
424            VerSetConditionMask(
425                    VerSetConditionMask(
426                            0, VER_MAJORVERSION, VER_GREATER_EQUAL),
427                    VER_MINORVERSION, VER_GREATER_EQUAL),
428            VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);
429    osvi.dwOSVersionInfoSize = sizeof(osvi);
430    osvi.dwMajorVersion = HIBYTE(_WIN32_WINNT_VISTA);
431    osvi.dwMinorVersion = LOBYTE(_WIN32_WINNT_VISTA);
432    osvi.wServicePackMajor = 0;
433
434    return VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, mask) != FALSE;
435}
436#endif
437
438// This is necessary until C++20 which will have std::string::ends_with() etc.
439
440static inline bool ends_with(std::string const &str, std::string const &suffix)
441{
442    return suffix.size() <= str.size() &&
443        str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
444}
445
446static inline bool starts_with(std::string const &str, std::string const &prefix)
447{
448    return prefix.size() <= str.size() &&
449        str.compare(0, prefix.size(), prefix) == 0;
450}
451
452} // namespace internal
453
454// settings implementation
455
456inline settings::settings(bool resync)
457{
458    flags(flag::is_scanned) &= !resync;
459
460    if (flags(flag::is_scanned))
461        return;
462
463#if _WIN32
464    flags(flag::is_vista) = internal::is_vista();
465#elif !__APPLE__
466    flags(flag::has_zenity) = check_program("zenity");
467    flags(flag::has_matedialog) = check_program("matedialog");
468    flags(flag::has_qarma) = check_program("qarma");
469    flags(flag::has_kdialog) = check_program("kdialog");
470
471    // If multiple helpers are available, try to default to the best one
472    if (flags(flag::has_zenity) && flags(flag::has_kdialog))
473    {
474        auto desktop_name = std::getenv("XDG_SESSION_DESKTOP");
475        if (desktop_name && desktop_name == std::string("gnome"))
476            flags(flag::has_kdialog) = false;
477        else if (desktop_name && desktop_name == std::string("KDE"))
478            flags(flag::has_zenity) = false;
479    }
480#endif
481
482    flags(flag::is_scanned) = true;
483}
484
485inline bool settings::available()
486{
487#if _WIN32
488    return true;
489#elif __APPLE__
490    return true;
491#else
492    settings tmp;
493    return tmp.flags(flag::has_zenity) ||
494           tmp.flags(flag::has_matedialog) ||
495           tmp.flags(flag::has_qarma) ||
496           tmp.flags(flag::has_kdialog);
497#endif
498}
499
500inline void settings::verbose(bool value)
501{
502    settings().flags(flag::is_verbose) = value;
503}
504
505inline void settings::rescan()
506{
507    settings(/* resync = */ true);
508}
509
510// Check whether a program is present using “which”.
511inline bool settings::check_program(std::string const &program)
512{
513#if _WIN32
514    (void)program;
515    return false;
516#elif __EMSCRIPTEN__
517    (void)program;
518    return false;
519#else
520    int exit_code = -1;
521    internal::executor async;
522    async.start_process({"/bin/sh", "-c", "which " + program});
523    async.result(&exit_code);
524    return exit_code == 0;
525#endif
526}
527
528inline bool settings::is_osascript() const
529{
530#if __APPLE__
531    return true;
532#else
533    return false;
534#endif
535}
536
537inline bool settings::is_zenity() const
538{
539    return flags(flag::has_zenity) ||
540           flags(flag::has_matedialog) ||
541           flags(flag::has_qarma);
542}
543
544inline bool settings::is_kdialog() const
545{
546    return flags(flag::has_kdialog);
547}
548
549inline bool const &settings::flags(flag in_flag) const
550{
551    static bool flags[size_t(flag::max_flag)];
552    return flags[size_t(in_flag)];
553}
554
555inline bool &settings::flags(flag in_flag)
556{
557    return const_cast<bool &>(static_cast<settings const *>(this)->flags(in_flag));
558}
559
560// executor implementation
561
562inline std::string internal::executor::result(int *exit_code /* = nullptr */)
563{
564    stop();
565    if (exit_code)
566        *exit_code = m_exit_code;
567    return m_stdout;
568}
569
570inline bool internal::executor::kill()
571{
572#if _WIN32
573    if (m_future.valid())
574    {
575        // Close all windows that weren’t open when we started the future
576        auto previous_windows = m_windows;
577        EnumWindows(&enum_windows_callback, (LPARAM)this);
578        for (auto hwnd : m_windows)
579            if (previous_windows.find(hwnd) == previous_windows.end())
580                SendMessage(hwnd, WM_CLOSE, 0, 0);
581    }
582#elif __EMSCRIPTEN__ || __NX__
583    // FIXME: do something
584    (void)timeout;
585    return false; // cannot kill
586#else
587    ::kill(m_pid, SIGKILL);
588#endif
589    stop();
590    return true;
591}
592
593#if _WIN32
594inline BOOL CALLBACK internal::executor::enum_windows_callback(HWND hwnd, LPARAM lParam)
595{
596    auto that = (executor *)lParam;
597
598    DWORD pid;
599    auto tid = GetWindowThreadProcessId(hwnd, &pid);
600    if (tid == that->m_tid)
601        that->m_windows.insert(hwnd);
602    return TRUE;
603}
604#endif
605
606#if _WIN32
607inline void internal::executor::start_func(std::function<std::string(int *)> const &fun)
608{
609    stop();
610
611    auto trampoline = [fun, this]()
612    {
613        // Save our thread id so that the caller can cancel us
614        m_tid = GetCurrentThreadId();
615        EnumWindows(&enum_windows_callback, (LPARAM)this);
616        m_cond.notify_all();
617        return fun(&m_exit_code);
618    };
619
620    std::unique_lock<std::mutex> lock(m_mutex);
621    m_future = std::async(std::launch::async, trampoline);
622    m_cond.wait(lock);
623    m_running = true;
624}
625
626#elif __EMSCRIPTEN__
627inline void internal::executor::start(int exit_code)
628{
629    m_exit_code = exit_code;
630}
631
632#else
633inline void internal::executor::start_process(std::vector<std::string> const &command)
634{
635    stop();
636    m_stdout.clear();
637    m_exit_code = -1;
638
639    int in[2], out[2];
640    if (pipe(in) != 0 || pipe(out) != 0)
641        return;
642
643    m_pid = fork();
644    if (m_pid < 0)
645        return;
646
647    close(in[m_pid ? 0 : 1]);
648    close(out[m_pid ? 1 : 0]);
649
650    if (m_pid == 0)
651    {
652        dup2(in[0], STDIN_FILENO);
653        dup2(out[1], STDOUT_FILENO);
654
655        // Ignore stderr so that it doesn’t pollute the console (e.g. GTK+ errors from zenity)
656        int fd = open("/dev/null", O_WRONLY);
657        dup2(fd, STDERR_FILENO);
658        close(fd);
659
660        std::vector<char *> args;
661        std::transform(command.cbegin(), command.cend(), std::back_inserter(args),
662                       [](std::string const &s) { return const_cast<char *>(s.c_str()); });
663        args.push_back(nullptr); // null-terminate argv[]
664
665        execvp(args[0], args.data());
666        exit(1);
667    }
668
669    close(in[1]);
670    m_fd = out[0];
671    auto flags = fcntl(m_fd, F_GETFL);
672    fcntl(m_fd, F_SETFL, flags | O_NONBLOCK);
673
674    m_running = true;
675}
676#endif
677
678inline internal::executor::~executor()
679{
680    stop();
681}
682
683inline bool internal::executor::ready(int timeout /* = default_wait_timeout */)
684{
685    if (!m_running)
686        return true;
687
688#if _WIN32
689    if (m_future.valid())
690    {
691        auto status = m_future.wait_for(std::chrono::milliseconds(timeout));
692        if (status != std::future_status::ready)
693        {
694            // On Windows, we need to run the message pump. If the async
695            // thread uses a Windows API dialog, it may be attached to the
696            // main thread and waiting for messages that only we can dispatch.
697            MSG msg;
698            while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
699            {
700                TranslateMessage(&msg);
701                DispatchMessage(&msg);
702            }
703            return false;
704        }
705
706        m_stdout = m_future.get();
707    }
708#elif __EMSCRIPTEN__ || __NX__
709    // FIXME: do something
710    (void)timeout;
711#else
712    char buf[BUFSIZ];
713    ssize_t received = read(m_fd, buf, BUFSIZ); // Flawfinder: ignore
714    if (received > 0)
715    {
716        m_stdout += std::string(buf, received);
717        return false;
718    }
719
720    // Reap child process if it is dead. It is possible that the system has already reaped it
721    // (this happens when the calling application handles or ignores SIG_CHLD) and results in
722    // waitpid() failing with ECHILD. Otherwise we assume the child is running and we sleep for
723    // a little while.
724    int status;
725    pid_t child = waitpid(m_pid, &status, WNOHANG);
726    if (child != m_pid && (child >= 0 || errno != ECHILD))
727    {
728        // FIXME: this happens almost always at first iteration
729        std::this_thread::sleep_for(std::chrono::milliseconds(timeout));
730        return false;
731    }
732
733    close(m_fd);
734    m_exit_code = WEXITSTATUS(status);
735#endif
736
737    m_running = false;
738    return true;
739}
740
741inline void internal::executor::stop()
742{
743    // Loop until the user closes the dialog
744    while (!ready())
745        ;
746}
747
748// dll implementation
749
750#if _WIN32
751inline internal::platform::dll::dll(std::string const &name)
752  : handle(::LoadLibraryA(name.c_str()))
753{}
754
755inline internal::platform::dll::~dll()
756{
757    if (handle)
758        ::FreeLibrary(handle);
759}
760#endif // _WIN32
761
762// ole32_dll implementation
763
764#if _WIN32
765inline internal::platform::ole32_dll::ole32_dll()
766    : dll("ole32.dll")
767{
768    // Use COINIT_MULTITHREADED because COINIT_APARTMENTTHREADED causes crashes.
769    // See https://github.com/samhocevar/portable-file-dialogs/issues/51
770    auto coinit = proc<HRESULT WINAPI (LPVOID, DWORD)>(*this, "CoInitializeEx");
771    m_state = coinit(nullptr, COINIT_MULTITHREADED);
772}
773
774inline internal::platform::ole32_dll::~ole32_dll()
775{
776    if (is_initialized())
777        proc<void WINAPI ()>(*this, "CoUninitialize")();
778}
779
780inline bool internal::platform::ole32_dll::is_initialized()
781{
782    return m_state == S_OK || m_state == S_FALSE;
783}
784#endif
785
786// new_style_context implementation
787
788#if _WIN32
789inline internal::platform::new_style_context::new_style_context()
790{
791    // Only create one activation context for the whole app lifetime.
792    static HANDLE hctx = create();
793
794    if (hctx != INVALID_HANDLE_VALUE)
795        ActivateActCtx(hctx, &m_cookie);
796}
797
798inline internal::platform::new_style_context::~new_style_context()
799{
800    DeactivateActCtx(0, m_cookie);
801}
802
803inline HANDLE internal::platform::new_style_context::create()
804{
805    // This “hack” seems to be necessary for this code to work on windows XP.
806    // Without it, dialogs do not show and close immediately. GetError()
807    // returns 0 so I don’t know what causes this. I was not able to reproduce
808    // this behavior on Windows 7 and 10 but just in case, let it be here for
809    // those versions too.
810    // This hack is not required if other dialogs are used (they load comdlg32
811    // automatically), only if message boxes are used.
812    dll comdlg32("comdlg32.dll");
813
814    // Using approach as shown here: https://stackoverflow.com/a/10444161
815    UINT len = ::GetSystemDirectoryA(nullptr, 0);
816    std::string sys_dir(len, '\0');
817    ::GetSystemDirectoryA(&sys_dir[0], len);
818
819    ACTCTXA act_ctx =
820    {
821        // Do not set flag ACTCTX_FLAG_SET_PROCESS_DEFAULT, since it causes a
822        // crash with error “default context is already set”.
823        sizeof(act_ctx),
824        ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID,
825        "shell32.dll", 0, 0, sys_dir.c_str(), (LPCSTR)124,
826    };
827
828    return ::CreateActCtxA(&act_ctx);
829}
830#endif // _WIN32
831
832// dialog implementation
833
834inline bool internal::dialog::ready(int timeout /* = default_wait_timeout */) const
835{
836    return m_async->ready(timeout);
837}
838
839inline bool internal::dialog::kill() const
840{
841    return m_async->kill();
842}
843
844inline internal::dialog::dialog()
845  : m_async(std::make_shared<executor>())
846{
847}
848
849inline std::vector<std::string> internal::dialog::desktop_helper() const
850{
851#if __APPLE__
852    return { "osascript" };
853#else
854    return { flags(flag::has_zenity) ? "zenity"
855           : flags(flag::has_matedialog) ? "matedialog"
856           : flags(flag::has_qarma) ? "qarma"
857           : flags(flag::has_kdialog) ? "kdialog"
858           : "echo" };
859#endif
860}
861
862inline std::string internal::dialog::buttons_to_name(choice _choice)
863{
864    switch (_choice)
865    {
866        case choice::ok_cancel: return "okcancel";
867        case choice::yes_no: return "yesno";
868        case choice::yes_no_cancel: return "yesnocancel";
869        case choice::retry_cancel: return "retrycancel";
870        case choice::abort_retry_ignore: return "abortretryignore";
871        /* case choice::ok: */ default: return "ok";
872    }
873}
874
875inline std::string internal::dialog::get_icon_name(icon _icon)
876{
877    switch (_icon)
878    {
879        case icon::warning: return "warning";
880        case icon::error: return "error";
881        case icon::question: return "question";
882        // Zenity wants "information" but WinForms wants "info"
883        /* case icon::info: */ default:
884#if _WIN32
885            return "info";
886#else
887            return "information";
888#endif
889    }
890}
891
892// THis is only used for debugging purposes
893inline std::ostream& operator <<(std::ostream &s, std::vector<std::string> const &v)
894{
895    int not_first = 0;
896    for (auto &e : v)
897        s << (not_first++ ? " " : "") << e;
898    return s;
899}
900
901// Properly quote a string for Powershell: replace ' or " with '' or ""
902// FIXME: we should probably get rid of newlines!
903// FIXME: the \" sequence seems unsafe, too!
904// XXX: this is no longer used but I would like to keep it around just in case
905inline std::string internal::dialog::powershell_quote(std::string const &str) const
906{
907    return "'" + std::regex_replace(str, std::regex("['\"]"), "$&$&") + "'";
908}
909
910// Properly quote a string for osascript: replace \ or " with \\ or \"
911// XXX: this also used to replace ' with \' when popen was used, but it would be
912// smarter to do shell_quote(osascript_quote(...)) if this is needed again.
913inline std::string internal::dialog::osascript_quote(std::string const &str) const
914{
915    return "\"" + std::regex_replace(str, std::regex("[\\\\\"]"), "\\$&") + "\"";
916}
917
918// Properly quote a string for the shell: just replace ' with '\''
919// XXX: this is no longer used but I would like to keep it around just in case
920inline std::string internal::dialog::shell_quote(std::string const &str) const
921{
922    return "'" + std::regex_replace(str, std::regex("'"), "'\\''") + "'";
923}
924
925// file_dialog implementation
926
927inline internal::file_dialog::file_dialog(type in_type,
928            std::string const &title,
929            std::string const &default_path /* = "" */,
930            std::vector<std::string> const &filters /* = {} */,
931            opt options /* = opt::none */)
932{
933#if _WIN32
934    std::string filter_list;
935    std::regex whitespace("  *");
936    for (size_t i = 0; i + 1 < filters.size(); i += 2)
937    {
938        filter_list += filters[i] + '\0';
939        filter_list += std::regex_replace(filters[i + 1], whitespace, ";") + '\0';
940    }
941    filter_list += '\0';
942
943    m_async->start_func([this, in_type, title, default_path, filter_list,
944                         options](int *exit_code) -> std::string
945    {
946        (void)exit_code;
947        m_wtitle = internal::str2wstr(title);
948        m_wdefault_path = internal::str2wstr(default_path);
949        auto wfilter_list = internal::str2wstr(filter_list);
950
951        // Initialise COM. This is required for the new folder selection window,
952        // (see https://github.com/samhocevar/portable-file-dialogs/pull/21)
953        // and to avoid random crashes with GetOpenFileNameW() (see
954        // https://github.com/samhocevar/portable-file-dialogs/issues/51)
955        ole32_dll ole32;
956
957        // Folder selection uses a different method
958        if (in_type == type::folder)
959        {
960            if (flags(flag::is_vista))
961            {
962                // On Vista and higher we should be able to use IFileDialog for folder selection
963                IFileDialog *ifd;
964                HRESULT hr = dll::proc<HRESULT WINAPI (REFCLSID, LPUNKNOWN, DWORD, REFIID, LPVOID *)>(ole32, "CoCreateInstance")
965                                 (CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&ifd));
966
967                // In case CoCreateInstance fails (which it should not), try legacy approach
968                if (SUCCEEDED(hr))
969                    return select_folder_vista(ifd, options & opt::force_path);
970            }
971
972            BROWSEINFOW bi;
973            memset(&bi, 0, sizeof(bi));
974
975            bi.lpfn = &bffcallback;
976            bi.lParam = (LPARAM)this;
977
978            if (flags(flag::is_vista))
979            {
980                if (ole32.is_initialized())
981                    bi.ulFlags |= BIF_NEWDIALOGSTYLE;
982                bi.ulFlags |= BIF_EDITBOX;
983                bi.ulFlags |= BIF_STATUSTEXT;
984            }
985
986            auto *list = SHBrowseForFolderW(&bi);
987            std::string ret;
988            if (list)
989            {
990                auto buffer = new wchar_t[MAX_PATH];
991                SHGetPathFromIDListW(list, buffer);
992                dll::proc<void WINAPI (LPVOID)>(ole32, "CoTaskMemFree")(list);
993                ret = internal::wstr2str(buffer);
994                delete[] buffer;
995            }
996            return ret;
997        }
998
999        OPENFILENAMEW ofn;
1000        memset(&ofn, 0, sizeof(ofn));
1001        ofn.lStructSize = sizeof(OPENFILENAMEW);
1002        ofn.hwndOwner = GetActiveWindow();
1003
1004        ofn.lpstrFilter = wfilter_list.c_str();
1005
1006        auto woutput = std::wstring(MAX_PATH * 256, L'\0');
1007        ofn.lpstrFile = (LPWSTR)woutput.data();
1008        ofn.nMaxFile = (DWORD)woutput.size();
1009        if (!m_wdefault_path.empty())
1010        {
1011            // If a directory was provided, use it as the initial directory. If
1012            // a valid path was provided, use it as the initial file. Otherwise,
1013            // let the Windows API decide.
1014            auto path_attr = GetFileAttributesW(m_wdefault_path.c_str());
1015            if (path_attr != INVALID_FILE_ATTRIBUTES && (path_attr & FILE_ATTRIBUTE_DIRECTORY))
1016                ofn.lpstrInitialDir = m_wdefault_path.c_str();
1017            else if (m_wdefault_path.size() <= woutput.size())
1018                //second argument is size of buffer, not length of string
1019                StringCchCopyW(ofn.lpstrFile, MAX_PATH*256+1, m_wdefault_path.c_str());
1020            else
1021            {
1022                ofn.lpstrFileTitle = (LPWSTR)m_wdefault_path.data();
1023                ofn.nMaxFileTitle = (DWORD)m_wdefault_path.size();
1024            }
1025        }
1026        ofn.lpstrTitle = m_wtitle.c_str();
1027        ofn.Flags = OFN_NOCHANGEDIR | OFN_EXPLORER;
1028
1029        dll comdlg32("comdlg32.dll");
1030
1031        // Apply new visual style (required for windows XP)
1032        new_style_context ctx;
1033
1034        if (in_type == type::save)
1035        {
1036            if (!(options & opt::force_overwrite))
1037                ofn.Flags |= OFN_OVERWRITEPROMPT;
1038
1039            dll::proc<BOOL WINAPI (LPOPENFILENAMEW)> get_save_file_name(comdlg32, "GetSaveFileNameW");
1040            if (get_save_file_name(&ofn) == 0)
1041                return "";
1042            return internal::wstr2str(woutput.c_str());
1043        }
1044        else
1045        {
1046            if (options & opt::multiselect)
1047                ofn.Flags |= OFN_ALLOWMULTISELECT;
1048            ofn.Flags |= OFN_PATHMUSTEXIST;
1049
1050            dll::proc<BOOL WINAPI (LPOPENFILENAMEW)> get_open_file_name(comdlg32, "GetOpenFileNameW");
1051            if (get_open_file_name(&ofn) == 0)
1052                return "";
1053        }
1054
1055        std::string prefix;
1056        for (wchar_t const *p = woutput.c_str(); *p; )
1057        {
1058            auto filename = internal::wstr2str(p);
1059            p += wcslen(p);
1060            // In multiselect mode, we advance p one wchar further and
1061            // check for another filename. If there is one and the
1062            // prefix is empty, it means we just read the prefix.
1063            if ((options & opt::multiselect) && *++p && prefix.empty())
1064            {
1065                prefix = filename + "/";
1066                continue;
1067            }
1068
1069            m_vector_result.push_back(prefix + filename);
1070        }
1071
1072        return "";
1073    });
1074#else
1075    auto command = desktop_helper();
1076
1077    if (is_osascript())
1078    {
1079        std::string script = "set ret to choose";
1080        switch (in_type)
1081        {
1082            case type::save:
1083                script += " file name";
1084                break;
1085            case type::open: default:
1086                script += " file";
1087                if (options & opt::multiselect)
1088                    script += " with multiple selections allowed";
1089                break;
1090            case type::folder:
1091                script += " folder";
1092                break;
1093        }
1094
1095        if (default_path.size())
1096            script += " default location " + osascript_quote(default_path);
1097        script += " with prompt " + osascript_quote(title);
1098
1099        if (in_type == type::open)
1100        {
1101            // Concatenate all user-provided filter patterns
1102            std::string patterns;
1103            for (size_t i = 0; i < filters.size() / 2; ++i)
1104                patterns += " " + filters[2 * i + 1];
1105
1106            // Split the pattern list to check whether "*" is in there; if it
1107            // is, we have to disable filters because there is no mechanism in
1108            // OS X for the user to override the filter.
1109            std::regex sep("\\s+");
1110            std::string filter_list;
1111            bool has_filter = true;
1112            std::sregex_token_iterator iter(patterns.begin(), patterns.end(), sep, -1);
1113            std::sregex_token_iterator end;
1114            for ( ; iter != end; ++iter)
1115            {
1116                auto pat = iter->str();
1117                if (pat == "*" || pat == "*.*")
1118                    has_filter = false;
1119                else if (internal::starts_with(pat, "*."))
1120                    filter_list += (filter_list.size() == 0 ? "" : ",") +
1121                                   osascript_quote(pat.substr(2, pat.size() - 2));
1122            }
1123            if (has_filter && filter_list.size() > 0)
1124                script += " of type {" + filter_list + "}";
1125        }
1126
1127        if (in_type == type::open && (options & opt::multiselect))
1128        {
1129            script += "\nset s to \"\"";
1130            script += "\nrepeat with i in ret";
1131            script += "\n  set s to s & (POSIX path of i) & \"\\n\"";
1132            script += "\nend repeat";
1133            script += "\ncopy s to stdout";
1134        }
1135        else
1136        {
1137            script += "\nPOSIX path of ret";
1138        }
1139
1140        command.push_back("-e");
1141        command.push_back(script);
1142    }
1143    else if (is_zenity())
1144    {
1145        command.push_back("--file-selection");
1146        command.push_back("--filename=" + default_path);
1147        command.push_back("--title");
1148        command.push_back(title);
1149        command.push_back("--separator=\n");
1150
1151        for (size_t i = 0; i < filters.size() / 2; ++i)
1152        {
1153            command.push_back("--file-filter");
1154            command.push_back(filters[2 * i] + "|" + filters[2 * i + 1]);
1155        }
1156
1157        if (in_type == type::save)
1158            command.push_back("--save");
1159        if (in_type == type::folder)
1160            command.push_back("--directory");
1161        if (!(options & opt::force_overwrite))
1162            command.push_back("--confirm-overwrite");
1163        if (options & opt::multiselect)
1164            command.push_back("--multiple");
1165    }
1166    else if (is_kdialog())
1167    {
1168        switch (in_type)
1169        {
1170            case type::save: command.push_back("--getsavefilename"); break;
1171            case type::open: command.push_back("--getopenfilename"); break;
1172            case type::folder: command.push_back("--getexistingdirectory"); break;
1173        }
1174        if (options & opt::multiselect)
1175            command.push_back(" --multiple");
1176
1177        command.push_back(default_path);
1178
1179        std::string filter;
1180        for (size_t i = 0; i < filters.size() / 2; ++i)
1181            filter += (i == 0 ? "" : " | ") + filters[2 * i] + "(" + filters[2 * i + 1] + ")";
1182        command.push_back(filter);
1183
1184        command.push_back("--title");
1185        command.push_back(title);
1186    }
1187
1188    if (flags(flag::is_verbose))
1189        std::cerr << "pfd: " << command << std::endl;
1190
1191    m_async->start_process(command);
1192#endif
1193}
1194
1195inline std::string internal::file_dialog::string_result()
1196{
1197#if _WIN32
1198    return m_async->result();
1199#else
1200    auto ret = m_async->result();
1201    // Strip potential trailing newline (zenity). Also strip trailing slash
1202    // added by osascript for consistency with other backends.
1203    while (ret.back() == '\n' || ret.back() == '/')
1204        ret = ret.substr(0, ret.size() - 1);
1205    return ret;
1206#endif
1207}
1208
1209inline std::vector<std::string> internal::file_dialog::vector_result()
1210{
1211#if _WIN32
1212    m_async->result();
1213    return m_vector_result;
1214#else
1215    std::vector<std::string> ret;
1216    auto result = m_async->result();
1217    for (;;)
1218    {
1219        // Split result along newline characters
1220        auto i = result.find('\n');
1221        if (i == 0 || i == std::string::npos)
1222            break;
1223        ret.push_back(result.substr(0, i));
1224        result = result.substr(i + 1, result.size());
1225    }
1226    return ret;
1227#endif
1228}
1229
1230#if _WIN32
1231// Use a static function to pass as BFFCALLBACK for legacy folder select
1232inline int CALLBACK internal::file_dialog::bffcallback(HWND hwnd, UINT uMsg,
1233                                                       LPARAM, LPARAM pData)
1234{
1235    auto inst = (file_dialog *)pData;
1236    switch (uMsg)
1237    {
1238        case BFFM_INITIALIZED:
1239            SendMessage(hwnd, BFFM_SETSELECTIONW, TRUE, (LPARAM)inst->m_wdefault_path.c_str());
1240            break;
1241    }
1242    return 0;
1243}
1244
1245inline std::string internal::file_dialog::select_folder_vista(IFileDialog *ifd, bool force_path)
1246{
1247    std::string result;
1248
1249    IShellItem *folder;
1250
1251    // Load library at runtime so app doesn't link it at load time (which will fail on windows XP)
1252    dll shell32("shell32.dll");
1253    dll::proc<HRESULT WINAPI (PCWSTR, IBindCtx*, REFIID, void**)>
1254        create_item(shell32, "SHCreateItemFromParsingName");
1255
1256    if (!create_item)
1257        return "";
1258
1259    auto hr = create_item(m_wdefault_path.c_str(),
1260                          nullptr,
1261                          IID_PPV_ARGS(&folder));
1262
1263    // Set default folder if found. This only sets the default folder. If
1264    // Windows has any info about the most recently selected folder, it
1265    // will display it instead. Generally, calling SetFolder() to set the
1266    // current directory “is not a good or expected user experience and
1267    // should therefore be avoided”:
1268    // https://docs.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifiledialog-setfolder
1269    if (SUCCEEDED(hr))
1270    {
1271        if (force_path)
1272            ifd->SetFolder(folder);
1273        else
1274            ifd->SetDefaultFolder(folder);
1275        folder->Release();
1276    }
1277
1278    // Set the dialog title and option to select folders
1279    ifd->SetOptions(FOS_PICKFOLDERS);
1280    ifd->SetTitle(m_wtitle.c_str());
1281
1282    hr = ifd->Show(GetActiveWindow());
1283    if (SUCCEEDED(hr))
1284    {
1285        IShellItem* item;
1286        hr = ifd->GetResult(&item);
1287        if (SUCCEEDED(hr))
1288        {
1289            wchar_t* wselected = nullptr;
1290            item->GetDisplayName(SIGDN_FILESYSPATH, &wselected);
1291            item->Release();
1292
1293            if (wselected)
1294            {
1295                result = internal::wstr2str(std::wstring(wselected));
1296                dll::proc<void WINAPI (LPVOID)>(ole32_dll(), "CoTaskMemFree")(wselected);
1297            }
1298        }
1299    }
1300
1301    ifd->Release();
1302
1303    return result;
1304}
1305#endif
1306
1307// notify implementation
1308
1309inline notify::notify(std::string const &title,
1310                      std::string const &message,
1311                      icon _icon /* = icon::info */)
1312{
1313    if (_icon == icon::question) // Not supported by notifications
1314        _icon = icon::info;
1315
1316#if _WIN32
1317    // Use a static shared pointer for notify_icon so that we can delete
1318    // it whenever we need to display a new one, and we can also wait
1319    // until the program has finished running.
1320    struct notify_icon_data : public NOTIFYICONDATAW
1321    {
1322        ~notify_icon_data() { Shell_NotifyIconW(NIM_DELETE, this); }
1323    };
1324
1325    static std::shared_ptr<notify_icon_data> nid;
1326
1327    // Release the previous notification icon, if any, and allocate a new
1328    // one. Note that std::make_shared() does value initialization, so there
1329    // is no need to memset the structure.
1330    nid = nullptr;
1331    nid = std::make_shared<notify_icon_data>();
1332
1333    // For XP support
1334    nid->cbSize = NOTIFYICONDATAW_V2_SIZE;
1335    nid->hWnd = nullptr;
1336    nid->uID = 0;
1337
1338    // Flag Description:
1339    // - NIF_ICON    The hIcon member is valid.
1340    // - NIF_MESSAGE The uCallbackMessage member is valid.
1341    // - NIF_TIP     The szTip member is valid.
1342    // - NIF_STATE   The dwState and dwStateMask members are valid.
1343    // - NIF_INFO    Use a balloon ToolTip instead of a standard ToolTip. The szInfo, uTimeout, szInfoTitle, and dwInfoFlags members are valid.
1344    // - NIF_GUID    Reserved.
1345    nid->uFlags = NIF_MESSAGE | NIF_ICON | NIF_INFO;
1346
1347    // Flag Description
1348    // - NIIF_ERROR     An error icon.
1349    // - NIIF_INFO      An information icon.
1350    // - NIIF_NONE      No icon.
1351    // - NIIF_WARNING   A warning icon.
1352    // - NIIF_ICON_MASK Version 6.0. Reserved.
1353    // - NIIF_NOSOUND   Version 6.0. Do not play the associated sound. Applies only to balloon ToolTips
1354    switch (_icon)
1355    {
1356        case icon::warning: nid->dwInfoFlags = NIIF_WARNING; break;
1357        case icon::error: nid->dwInfoFlags = NIIF_ERROR; break;
1358        /* case icon::info: */ default: nid->dwInfoFlags = NIIF_INFO; break;
1359    }
1360
1361    ENUMRESNAMEPROC icon_enum_callback = [](HMODULE, LPCTSTR, LPTSTR lpName, LONG_PTR lParam) -> BOOL
1362    {
1363        ((NOTIFYICONDATAW *)lParam)->hIcon = ::LoadIcon(GetModuleHandle(nullptr), lpName);
1364        return false;
1365    };
1366
1367    nid->hIcon = ::LoadIcon(nullptr, IDI_APPLICATION);
1368    ::EnumResourceNames(nullptr, RT_GROUP_ICON, icon_enum_callback, (LONG_PTR)nid.get());
1369
1370    nid->uTimeout = 5000;
1371
1372    StringCchCopyW(nid->szInfoTitle, ARRAYSIZE(nid->szInfoTitle), internal::str2wstr(title).c_str());
1373    StringCchCopyW(nid->szInfo, ARRAYSIZE(nid->szInfo), internal::str2wstr(message).c_str());
1374
1375    // Display the new icon
1376    Shell_NotifyIconW(NIM_ADD, nid.get());
1377#else
1378    auto command = desktop_helper();
1379
1380    if (is_osascript())
1381    {
1382        command.push_back("-e");
1383        command.push_back("display notification " + osascript_quote(message) +
1384                          " with title " + osascript_quote(title));
1385    }
1386    else if (is_zenity())
1387    {
1388        command.push_back("--notification");
1389        command.push_back("--window-icon");
1390        command.push_back(get_icon_name(_icon));
1391        command.push_back("--text");
1392        command.push_back(title + "\n" + message);
1393    }
1394    else if (is_kdialog())
1395    {
1396        command.push_back("--icon");
1397        command.push_back(get_icon_name(_icon));
1398        command.push_back("--title");
1399        command.push_back(title);
1400        command.push_back("--passivepopup");
1401        command.push_back(message);
1402        command.push_back("5");
1403    }
1404
1405    if (flags(flag::is_verbose))
1406        std::cerr << "pfd: " << command << std::endl;
1407
1408    m_async->start_process(command);
1409#endif
1410}
1411
1412// message implementation
1413
1414inline message::message(std::string const &title,
1415                        std::string const &text,
1416                        choice _choice /* = choice::ok_cancel */,
1417                        icon _icon /* = icon::info */)
1418{
1419#if _WIN32
1420    UINT style = MB_TOPMOST;
1421    switch (_icon)
1422    {
1423        case icon::warning: style |= MB_ICONWARNING; break;
1424        case icon::error: style |= MB_ICONERROR; break;
1425        case icon::question: style |= MB_ICONQUESTION; break;
1426        /* case icon::info: */ default: style |= MB_ICONINFORMATION; break;
1427    }
1428
1429    switch (_choice)
1430    {
1431        case choice::ok_cancel: style |= MB_OKCANCEL; break;
1432        case choice::yes_no: style |= MB_YESNO; break;
1433        case choice::yes_no_cancel: style |= MB_YESNOCANCEL; break;
1434        case choice::retry_cancel: style |= MB_RETRYCANCEL; break;
1435        case choice::abort_retry_ignore: style |= MB_ABORTRETRYIGNORE; break;
1436        /* case choice::ok: */ default: style |= MB_OK; break;
1437    }
1438
1439    m_mappings[IDCANCEL] = button::cancel;
1440    m_mappings[IDOK] = button::ok;
1441    m_mappings[IDYES] = button::yes;
1442    m_mappings[IDNO] = button::no;
1443    m_mappings[IDABORT] = button::abort;
1444    m_mappings[IDRETRY] = button::retry;
1445    m_mappings[IDIGNORE] = button::ignore;
1446
1447    m_async->start_func([this, text, title, style](int* exit_code) -> std::string
1448    {
1449        auto wtext = internal::str2wstr(text);
1450        auto wtitle = internal::str2wstr(title);
1451        // Apply new visual style (required for all Windows versions)
1452        new_style_context ctx;
1453        *exit_code = MessageBoxW(GetActiveWindow(), wtext.c_str(), wtitle.c_str(), style);
1454        return "";
1455    });
1456
1457#elif __EMSCRIPTEN__
1458    std::string full_message;
1459    switch (_icon)
1460    {
1461        case icon::warning: full_message = "⚠️"; break;
1462        case icon::error: full_message = "⛔"; break;
1463        case icon::question: full_message = "❓"; break;
1464        /* case icon::info: */ default: full_message = "ℹ"; break;
1465    }
1466
1467    full_message += ' ' + title + "\n\n" + text;
1468
1469    // This does not really start an async task; it just passes the
1470    // EM_ASM_INT return value to a fake start() function.
1471    m_async->start(EM_ASM_INT(
1472    {
1473        if ($1)
1474            return window.confirm(UTF8ToString($0)) ? 0 : -1;
1475        alert(UTF8ToString($0));
1476        return 0;
1477    }, full_message.c_str(), _choice == choice::ok_cancel));
1478#else
1479    auto command = desktop_helper();
1480
1481    if (is_osascript())
1482    {
1483        std::string script = "display dialog " + osascript_quote(text) +
1484                             " with title " + osascript_quote(title);
1485        switch (_choice)
1486        {
1487            case choice::ok_cancel:
1488                script += "buttons {\"OK\", \"Cancel\"}"
1489                          " default button \"OK\""
1490                          " cancel button \"Cancel\"";
1491                m_mappings[256] = button::cancel;
1492                break;
1493            case choice::yes_no:
1494                script += "buttons {\"Yes\", \"No\"}"
1495                          " default button \"Yes\""
1496                          " cancel button \"No\"";
1497                m_mappings[256] = button::no;
1498                break;
1499            case choice::yes_no_cancel:
1500                script += "buttons {\"Yes\", \"No\", \"Cancel\"}"
1501                          " default button \"Yes\""
1502                          " cancel button \"Cancel\"";
1503                m_mappings[256] = button::cancel;
1504                break;
1505            case choice::retry_cancel:
1506                script += "buttons {\"Retry\", \"Cancel\"}"
1507                          " default button \"Retry\""
1508                          " cancel button \"Cancel\"";
1509                m_mappings[256] = button::cancel;
1510                break;
1511            case choice::abort_retry_ignore:
1512                script += "buttons {\"Abort\", \"Retry\", \"Ignore\"}"
1513                          " default button \"Retry\""
1514                          " cancel button \"Retry\"";
1515                m_mappings[256] = button::cancel;
1516                break;
1517            case choice::ok: default:
1518                script += "buttons {\"OK\"}"
1519                          " default button \"OK\""
1520                          " cancel button \"OK\"";
1521                m_mappings[256] = button::ok;
1522                break;
1523        }
1524        script += " with icon ";
1525        switch (_icon)
1526        {
1527            #define PFD_OSX_ICON(n) "alias ((path to library folder from system domain) as text " \
1528                "& \"CoreServices:CoreTypes.bundle:Contents:Resources:" n ".icns\")"
1529            case icon::info: default: script += PFD_OSX_ICON("ToolBarInfo"); break;
1530            case icon::warning: script += "caution"; break;
1531            case icon::error: script += "stop"; break;
1532            case icon::question: script += PFD_OSX_ICON("GenericQuestionMarkIcon"); break;
1533            #undef PFD_OSX_ICON
1534        }
1535
1536        command.push_back("-e");
1537        command.push_back(script);
1538    }
1539    else if (is_zenity())
1540    {
1541        switch (_choice)
1542        {
1543            case choice::ok_cancel:
1544                command.insert(command.end(), { "--question", "--cancel-label=Cancel", "--ok-label=OK" }); break;
1545            case choice::yes_no:
1546                // Do not use standard --question because it causes “No” to return -1,
1547                // which is inconsistent with the “Yes/No/Cancel” mode below.
1548                command.insert(command.end(), { "--question", "--switch", "--extra-button=No", "--extra-button=Yes" }); break;
1549            case choice::yes_no_cancel:
1550                command.insert(command.end(), { "--question", "--switch", "--extra-button=Cancel", "--extra-button=No", "--extra-button=Yes" }); break;
1551            case choice::retry_cancel:
1552                command.insert(command.end(), { "--question", "--switch", "--extra-button=Cancel", "--extra-button=Retry" }); break;
1553            case choice::abort_retry_ignore:
1554                command.insert(command.end(), { "--question", "--switch", "--extra-button=Ignore", "--extra-button=Abort", "--extra-button=Retry" }); break;
1555            case choice::ok:
1556            default:
1557                switch (_icon)
1558                {
1559                    case icon::error: command.push_back("--error"); break;
1560                    case icon::warning: command.push_back("--warning"); break;
1561                    default: command.push_back("--info"); break;
1562                }
1563        }
1564
1565        command.insert(command.end(), { "--title", title,
1566                                        "--width=300", "--height=0", // sensible defaults
1567                                        "--text", text,
1568                                        "--icon-name=dialog-" + get_icon_name(_icon) });
1569    }
1570    else if (is_kdialog())
1571    {
1572        if (_choice == choice::ok)
1573        {
1574            switch (_icon)
1575            {
1576                case icon::error: command.push_back("--error"); break;
1577                case icon::warning: command.push_back("--sorry"); break;
1578                default: command.push_back("--msgbox"); break;
1579            }
1580        }
1581        else
1582        {
1583            std::string flag = "--";
1584            if (_icon == icon::warning || _icon == icon::error)
1585                flag += "warning";
1586            flag += "yesno";
1587            if (_choice == choice::yes_no_cancel)
1588                flag += "cancel";
1589            command.push_back(flag);
1590            if (_choice == choice::yes_no || _choice == choice::yes_no_cancel)
1591            {
1592                m_mappings[0] = button::yes;
1593                m_mappings[256] = button::no;
1594            }
1595        }
1596
1597        command.push_back(text);
1598        command.push_back("--title");
1599        command.push_back(title);
1600
1601        // Must be after the above part
1602        if (_choice == choice::ok_cancel)
1603            command.insert(command.end(), { "--yes-label", "OK", "--no-label", "Cancel" });
1604    }
1605
1606    if (flags(flag::is_verbose))
1607        std::cerr << "pfd: " << command << std::endl;
1608
1609    m_async->start_process(command);
1610#endif
1611}
1612
1613inline button message::result()
1614{
1615    int exit_code;
1616    auto ret = m_async->result(&exit_code);
1617    // osascript will say "button returned:Cancel\n"
1618    // and others will just say "Cancel\n"
1619    if (exit_code < 0 || // this means cancel
1620        internal::ends_with(ret, "Cancel\n"))
1621        return button::cancel;
1622    if (internal::ends_with(ret, "OK\n"))
1623        return button::ok;
1624    if (internal::ends_with(ret, "Yes\n"))
1625        return button::yes;
1626    if (internal::ends_with(ret, "No\n"))
1627        return button::no;
1628    if (internal::ends_with(ret, "Abort\n"))
1629        return button::abort;
1630    if (internal::ends_with(ret, "Retry\n"))
1631        return button::retry;
1632    if (internal::ends_with(ret, "Ignore\n"))
1633        return button::ignore;
1634    if (m_mappings.count(exit_code) != 0)
1635        return m_mappings[exit_code];
1636    return exit_code == 0 ? button::ok : button::cancel;
1637}
1638
1639// open_file implementation
1640
1641inline open_file::open_file(std::string const &title,
1642                            std::string const &default_path /* = "" */,
1643                            std::vector<std::string> const &filters /* = { "All Files", "*" } */,
1644                            opt options /* = opt::none */)
1645  : file_dialog(type::open, title, default_path, filters, options)
1646{
1647}
1648
1649inline open_file::open_file(std::string const &title,
1650                            std::string const &default_path,
1651                            std::vector<std::string> const &filters,
1652                            bool allow_multiselect)
1653  : open_file(title, default_path, filters,
1654              (allow_multiselect ? opt::multiselect : opt::none))
1655{
1656}
1657
1658inline std::vector<std::string> open_file::result()
1659{
1660    return vector_result();
1661}
1662
1663// save_file implementation
1664
1665inline save_file::save_file(std::string const &title,
1666                            std::string const &default_path /* = "" */,
1667                            std::vector<std::string> const &filters /* = { "All Files", "*" } */,
1668                            opt options /* = opt::none */)
1669  : file_dialog(type::save, title, default_path, filters, options)
1670{
1671}
1672
1673inline save_file::save_file(std::string const &title,
1674                            std::string const &default_path,
1675                            std::vector<std::string> const &filters,
1676                            bool confirm_overwrite)
1677  : save_file(title, default_path, filters,
1678              (confirm_overwrite ? opt::none : opt::force_overwrite))
1679{
1680}
1681
1682inline std::string save_file::result()
1683{
1684    return string_result();
1685}
1686
1687// select_folder implementation
1688
1689inline select_folder::select_folder(std::string const &title,
1690                                    std::string const &default_path /* = "" */,
1691                                    opt options /* = opt::none */)
1692  : file_dialog(type::folder, title, default_path, {}, options)
1693{
1694}
1695
1696inline std::string select_folder::result()
1697{
1698    return string_result();
1699}
1700
1701#endif // PFD_SKIP_IMPLEMENTATION
1702
1703} // namespace pfd
1704