fork/slippc
git clone https://git.julia.blue/fork/slippc
7abc388
testing
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{ 56cancel = -1 , 57ok , 58yes , 59no , 60abort , 61retry , 62ignore , 63}; 64 65enum class choice 66{ 67ok = 0 , 68ok_cancel , 69yes_no , 70yes_no_cancel , 71retry_cancel , 72abort_retry_ignore , 73}; 74 75enum class icon 76{ 77info = 0 , 78warning , 79error , 80question , 81}; 82 83// Additional option flags for various dialog constructors 84enum class opt :uint8_t 85{ 86none = 0 , 87// For file open, allow multiselect. 88multiselect = 0x1 , 89// For file save, force overwrite and disable the confirmation dialog. 90force_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. 94force_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 : 105static bool available (); 106 107static void verbose (bool value ); 108static void rescan (); 109 110protected : 111explicit settings (bool resync = false); 112 113bool check_program (std ::string const & program ); 114 115inline bool is_osascript ()const ; 116inline bool is_zenity ()const ; 117inline bool is_kdialog ()const ; 118 119enum class flag 120 { 121is_scanned = 0 , 122is_verbose , 123 124has_zenity , 125has_matedialog , 126has_qarma , 127has_kdialog , 128is_vista , 129 130max_flag , 131 }; 132 133// Static array of flags for internal state 134bool const & flags (flag in_flag )const ; 135 136// Non-const getter for the static array of flags 137bool & 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{ 149friend class dialog ; 150 151public : 152// High level function to get the result of a command 153std ::string result (int * exit_code = nullptr ); 154 155// High level function to abort 156bool kill (); 157 158#if _WIN32 159void start_func (std ::function < std ::string (int * )> const & fun ); 160static BOOL CALLBACK enum_windows_callback (HWND hwnd ,LPARAM lParam ); 161#elif __EMSCRIPTEN__ 162void start (int exit_code ); 163#else 164void start_process (std ::vector < std ::string > const & command ); 165#endif 166 167 ~executor (); 168 169protected : 170bool ready (int timeout = default_wait_timeout ); 171void stop (); 172 173private : 174bool m_running = false; 175std ::string m_stdout ; 176int m_exit_code = -1 ; 177#if _WIN32 178std ::future < std ::string > m_future ; 179std ::set < HWND > m_windows ; 180std ::condition_variable m_cond ; 181std ::mutex m_mutex ; 182DWORD m_tid ; 183#elif __EMSCRIPTEN__ || __NX__ 184// FIXME: do something 185#else 186pid_t m_pid = 0 ; 187int m_fd = -1 ; 188#endif 189}; 190 191class platform 192{ 193protected : 194#if _WIN32 195// Helper class around LoadLibraryA() and GetProcAddress() with some safety 196class dll 197 { 198public : 199dll (std ::string const & name ); 200 ~dll (); 201 202template < typename T > class proc 203 { 204public : 205proc (dll const & lib ,std ::string const & sym ) 206 :m_proc (reinterpret_cast < T *> (::GetProcAddress (lib .handle ,sym .c_str ()))) 207 {} 208 209operator bool ()const {return m_proc != nullptr ; } 210operator T * ()const { return m_proc; } 211 212private : 213T * m_proc; 214}; 215 216private : 217HMODULE handle; 218}; 219 220// Helper class around CoInitialize() and CoUnInitialize() 221class ole32_dll : public dll 222{ 223public : 224ole32_dll (); 225~ ole32_dll (); 226bool is_initialized (); 227 228private : 229HRESULT m_state; 230}; 231 232// Helper class around CreateActCtx() and ActivateActCtx() 233class new_style_context 234{ 235public : 236new_style_context (); 237~ new_style_context (); 238 239private : 240HANDLE create (); 241ULONG_PTR m_cookie = 0 ; 242}; 243#endif 244}; 245 246class dialog : protected settings, protected platform 247{ 248public : 249bool ready ( int timeout = default_wait_timeout) const; 250bool kill () const ; 251 252protected : 253explicit dialog (); 254 255std ::vector < std::string > desktop_helper () const; 256static std ::string buttons_to_name ( choice _choice); 257static std ::string get_icon_name ( icon _icon); 258 259std :: string powershell_quote( std :: string const & str) const ; 260std :: string osascript_quote( std :: string const & str) const ; 261std :: string shell_quote( std :: string const & str) const ; 262 263// Keep handle to executing command 264std ::shared_ptr < executor > m_async; 265}; 266 267class file_dialog : public dialog 268{ 269protected : 270enum type 271{ 272open, 273save, 274folder, 275}; 276 277file_dialog ( type in_type, 278std ::string const & title, 279std ::string const & default_path = "" , 280std::vector < std::string > const & filters = {}, 281opt options = opt::none); 282 283protected : 284std :: string string_result (); 285std ::vector < std::string > vector_result (); 286 287#if _WIN32 288static int CALLBACK bffcallback ( HWND hwnd, UINT uMsg, LPARAM , LPARAM pData); 289std :: string select_folder_vista ( IFileDialog * ifd, bool force_path); 290 291std :: wstring m_wtitle; 292std :: wstring m_wdefault_path; 293 294std ::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 : 307notify ( std :: string const & title, 308std:: string const & message, 309icon _icon = icon::info); 310}; 311 312// 313// The message widget 314// 315 316class message : public internal::dialog 317{ 318public : 319message ( std :: string const & title, 320std:: string const & text, 321choice _choice = choice::ok_cancel, 322icon _icon = icon::info); 323 324button result (); 325 326private : 327// Some extra logic to map the exit code to button number 328std ::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 : 338open_file ( std :: string const & title, 339std:: string const & default_path = "" , 340std::vector < std::string > const & filters = { "All Files" , "*" }, 341opt 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 349open_file ( std :: string const & title, 350std:: string const & default_path, 351std::vector < std::string > const & filters, 352bool allow_multiselect); 353 354std ::vector < std::string > result (); 355}; 356 357class save_file : public internal::file_dialog 358{ 359public : 360save_file ( std :: string const & title, 361std:: string const & default_path = "" , 362std::vector < std::string > const & filters = { "All Files" , "*" }, 363opt 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 371save_file ( std :: string const & title, 372std:: string const & default_path, 373std::vector < std::string > const & filters, 374bool confirm_overwrite); 375 376std :: string result (); 377}; 378 379class select_folder : public internal::file_dialog 380{ 381public : 382select_folder ( std :: string const & title, 383std:: string const & default_path = "" , 384opt options = opt::none); 385 386std :: 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{ 405int len = MultiByteToWideChar ( CP_UTF8 , 0 , str. c_str (), ( int )str. size (), nullptr , 0 ); 406std :: wstring ret( len , '\0' ); 407MultiByteToWideChar ( CP_UTF8 , 0 , str. c_str (), ( int )str. size (), ( LPWSTR )ret. data (), ( int )ret. size ()); 408return ret; 409} 410 411static inline std ::string wstr2str ( std ::wstring const & str) 412{ 413int len = WideCharToMultiByte ( CP_UTF8 , 0 , str. c_str (), ( int )str. size (), nullptr , 0 , nullptr , nullptr ); 414std :: string ret( len , '\0' ); 415WideCharToMultiByte ( CP_UTF8 , 0 , str. c_str (), ( int )str. size (), ( LPSTR )ret. data (), ( int )ret. size (), nullptr , nullptr ); 416return ret; 417} 418 419static inline bool is_vista () 420{ 421OSVERSIONINFOEXW osvi; 422memset ( & osvi, 0 , sizeof (osvi)); 423DWORDLONG const mask = VerSetConditionMask ( 424VerSetConditionMask ( 425VerSetConditionMask ( 4260 , VER_MAJORVERSION , VER_GREATER_EQUAL ), 427VER_MINORVERSION , VER_GREATER_EQUAL ), 428VER_SERVICEPACKMAJOR , VER_GREATER_EQUAL ); 429osvi. dwOSVersionInfoSize = sizeof (osvi); 430osvi. dwMajorVersion = HIBYTE (_WIN32_WINNT_VISTA); 431osvi. dwMinorVersion = LOBYTE (_WIN32_WINNT_VISTA); 432osvi. wServicePackMajor = 0 ; 433 434return 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{ 442return suffix. size () <= str. size () && 443str. 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{ 448return prefix. size () <= str. size () && 449str. compare ( 0 , prefix. size (), prefix) == 0 ; 450} 451 452} // namespace internal 453 454// settings implementation 455 456inline settings :: settings ( bool resync) 457{ 458flags( flag :: is_scanned ) &= !resync; 459 460if ( flags (flag::is_scanned)) 461return ; 462 463#if _WIN32 464flags( flag :: is_vista ) = internal:: is_vista (); 465#elif !__APPLE__ 466flags( flag :: has_zenity ) = check_program ( "zenity" ); 467flags( flag :: has_matedialog ) = check_program ( "matedialog" ); 468flags( flag :: has_qarma ) = check_program ( "qarma" ); 469flags( flag :: has_kdialog ) = check_program ( "kdialog" ); 470 471// If multiple helpers are available, try to default to the best one 472if ( flags (flag::has_zenity) && flags (flag::has_kdialog)) 473{ 474auto desktop_name = std::getenv( "XDG_SESSION_DESKTOP" ); 475if (desktop_name && desktop_name == std:: string ( "gnome" )) 476flags (flag::has_kdialog) = false; 477else if (desktop_name && desktop_name == std:: string ( "KDE" )) 478flags (flag::has_zenity) = false; 479} 480#endif 481 482flags( flag :: is_scanned ) = true; 483} 484 485inline bool settings:: available () 486{ 487#if _WIN32 488return true; 489#elif __APPLE__ 490return true; 491#else 492settings tmp; 493return tmp. flags (flag::has_zenity) || 494tmp. flags (flag::has_matedialog) || 495tmp. flags (flag::has_qarma) || 496tmp. flags (flag::has_kdialog); 497#endif 498} 499 500inline void settings:: verbose ( bool value) 501{ 502settings (). flags (flag::is_verbose) = value; 503} 504 505inline void settings:: rescan () 506{ 507settings ( /* 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; 515return false; 516#elif __EMSCRIPTEN__ 517( void )program; 518return false; 519#else 520int exit_code = -1 ; 521internal :: executor async; 522async. start_process ({ "/bin/sh" , "-c" , "which " + program}); 523async. result ( & exit_code); 524return exit_code == 0 ; 525#endif 526} 527 528inline bool settings:: is_osascript () const 529{ 530#if __APPLE__ 531return true; 532#else 533return false; 534#endif 535} 536 537inline bool settings:: is_zenity () const 538{ 539return flags( flag :: has_zenity ) || 540flags ( flag ::has_matedialog) || 541flags (flag::has_qarma); 542} 543 544inline bool settings:: is_kdialog () const 545{ 546return flags ( flag ::has_kdialog); 547} 548 549inline bool const & settings:: flags ( flag in_flag) const 550{ 551static bool flags[ size_t (flag::max_flag)]; 552return flags[ size_t (in_flag)]; 553} 554 555inline bool & settings:: flags ( flag in_flag) 556{ 557return 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{ 564stop (); 565if (exit_code) 566* exit_code = m_exit_code; 567return m_stdout; 568} 569 570inline bool internal::executor:: kill () 571{ 572#if _WIN32 573if (m_future. valid ()) 574{ 575// Close all windows that weren’t open when we started the future 576auto previous_windows = m_windows; 577EnumWindows ( & enum_windows_callback, ( LPARAM )this); 578for (auto hwnd : m_windows ) 579if ( previous_windows . find ( hwnd ) == previous_windows. end ()) 580SendMessage (hwnd, WM_CLOSE , 0 , 0 ); 581} 582#elif __EMSCRIPTEN__ || __NX__ 583// FIXME: do something 584( void )timeout; 585return false; // cannot kill 586#else 587:: kill ( m_pid , SIGKILL ); 588#endif 589stop (); 590return true; 591} 592 593#if _WIN32 594inline BOOL CALLBACK internal::executor:: enum_windows_callback ( HWND hwnd, LPARAM lParam) 595{ 596auto that = ( executor * )lParam; 597 598DWORD pid; 599auto tid = GetWindowThreadProcessId (hwnd, & pid); 600if (tid == that -> m_tid ) 601that -> m_windows . insert (hwnd); 602return TRUE; 603} 604#endif 605 606#if _WIN32 607inline void internal::executor:: start_func (std::function < std:: string (int * ) > const & fun) 608{ 609stop (); 610 611auto trampoline = [fun, this]() 612{ 613// Save our thread id so that the caller can cancel us 614m_tid = GetCurrentThreadId (); 615EnumWindows ( & enum_windows_callback, ( LPARAM )this); 616m_cond. notify_all (); 617return fun ( & m_exit_code); 618}; 619 620std ::unique_lock < std::mutex > lock (m_mutex); 621m_future = std:: async ( std :: launch ::async, trampoline); 622m_cond. wait (lock); 623m_running = true; 624} 625 626#elif __EMSCRIPTEN__ 627inline void internal::executor:: start ( int exit_code) 628{ 629m_exit_code = exit_code; 630} 631 632#else 633inline void internal::executor:: start_process ( std ::vector < std::string > const & command) 634{ 635stop (); 636m_stdout. clear (); 637m_exit_code = -1 ; 638 639int in[ 2 ], out[ 2 ]; 640if ( pipe (in) != 0 || pipe (out) != 0 ) 641return ; 642 643m_pid = fork (); 644if (m_pid < 0 ) 645return ; 646 647close (in[m_pid ? 0 : 1 ]); 648close (out[m_pid ? 1 : 0 ]); 649 650if (m_pid == 0 ) 651{ 652dup2 (in[ 0 ], STDIN_FILENO ); 653dup2 (out[ 1 ], STDOUT_FILENO ); 654 655// Ignore stderr so that it doesn’t pollute the console (e.g. GTK+ errors from zenity) 656int fd = open ( "/dev/null" , O_WRONLY ); 657dup2 (fd, STDERR_FILENO ); 658close (fd); 659 660std ::vector < char *> args; 661std :: transform (command. cbegin (), command. cend (), std:: back_inserter (args), 662[](std::string const & s) { return const_cast < char *> (s. c_str ()); }); 663args. push_back ( nullptr ); // null-terminate argv[] 664 665execvp (args[ 0 ], args. data ()); 666exit ( 1 ); 667} 668 669close (in[ 1 ]); 670m_fd = out[ 0 ]; 671auto flags = fcntl ( m_fd , F_GETFL ); 672fcntl (m_fd, F_SETFL , flags | O_NONBLOCK ); 673 674m_running = true; 675} 676#endif 677 678inline internal ::executor::~ executor () 679{ 680stop (); 681} 682 683inline bool internal::executor:: ready ( int timeout /* = default_wait_timeout */ ) 684{ 685if (!m_running) 686return true; 687 688#if _WIN32 689if (m_future. valid ()) 690{ 691auto status = m_future. wait_for (std::chrono:: milliseconds (timeout)); 692if (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. 697MSG msg; 698while ( PeekMessage ( & msg, nullptr , 0 , 0 , PM_REMOVE )) 699{ 700TranslateMessage ( & msg); 701DispatchMessage ( & msg); 702} 703return false; 704} 705 706m_stdout = m_future. get (); 707} 708#elif __EMSCRIPTEN__ || __NX__ 709// FIXME: do something 710( void )timeout; 711#else 712char buf[ BUFSIZ ]; 713ssize_t received = read (m_fd, buf, BUFSIZ ); // Flawfinder: ignore 714if (received > 0 ) 715{ 716m_stdout += std:: string (buf, received); 717return 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. 724int status; 725pid_t child = waitpid (m_pid, & status, WNOHANG ); 726if (child != m_pid && (child >= 0 || errno != ECHILD )) 727{ 728// FIXME: this happens almost always at first iteration 729std :: this_thread :: sleep_for ( std :: chrono :: milliseconds (timeout)); 730return false; 731} 732 733close (m_fd); 734m_exit_code = WEXITSTATUS (status); 735#endif 736 737m_running = false; 738return true; 739} 740 741inline void internal::executor:: stop () 742{ 743// Loop until the user closes the dialog 744while (! 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{ 757if (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 770auto coinit = proc < HRESULT WINAPI ( LPVOID , DWORD ) > ( * this, "CoInitializeEx" ); 771m_state = coinit ( nullptr , COINIT_MULTITHREADED ); 772} 773 774inline internal ::platform::ole32_dll::~ ole32_dll () 775{ 776if ( is_initialized ()) 777proc < void WINAPI () > ( * this, "CoUninitialize" )(); 778} 779 780inline bool internal::platform::ole32_dll:: is_initialized () 781{ 782return 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. 792static HANDLE hctx = create (); 793 794if (hctx != INVALID_HANDLE_VALUE ) 795ActivateActCtx (hctx, & m_cookie); 796} 797 798inline internal ::platform::new_style_context::~ new_style_context () 799{ 800DeactivateActCtx ( 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. 812dll comdlg32( "comdlg32.dll" ); 813 814// Using approach as shown here: https://stackoverflow.com/a/10444161 815UINT len = :: GetSystemDirectoryA ( nullptr , 0 ); 816std :: string sys_dir( len , '\0' ); 817:: GetSystemDirectoryA ( & sys_dir[ 0 ], len); 818 819ACTCTXA 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”. 823sizeof (act_ctx), 824ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID , 825"shell32.dll" , 0 , 0 , sys_dir. c_str (), ( LPCSTR ) 124 , 826}; 827 828return :: CreateActCtxA ( & act_ctx); 829} 830#endif // _WIN32 831 832// dialog implementation 833 834inline bool internal::dialog:: ready ( int timeout /* = default_wait_timeout */ ) const 835{ 836return m_async -> ready (timeout); 837} 838 839inline bool internal::dialog:: kill () const 840{ 841return 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__ 852return { "osascript" }; 853#else 854return { 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{ 864switch ( _choice ) 865{ 866case choice::ok_cancel: return "okcancel"; 867case choice::yes_no: return "yesno"; 868case choice::yes_no_cancel: return "yesnocancel"; 869case choice::retry_cancel: return "retrycancel"; 870case 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{ 877switch ( _icon ) 878{ 879case icon::warning: return "warning"; 880case icon::error: return "error"; 881case icon::question: return "question"; 882// Zenity wants "information" but WinForms wants "info" 883/* case icon::info: */ default : 884#if _WIN32 885return "info"; 886#else 887return " 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{ 895int not_first = 0 ; 896for ( auto & e : v) 897s << ( not_first ++ ? " " : "") << e; 898return 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{ 907return "'" + 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{ 915return "\"" + 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{ 922return "'" + std:: regex_replace (str, std:: regex ( "'" ), "'\\''" ) + "'" ; 923} 924 925// file_dialog implementation 926 927inline internal ::file_dialog:: file_dialog ( type in_type, 928std ::string const & title, 929std ::string const & default_path /* = "" */ , 930std ::vector < std::string > const & filters /* = {} */ , 931opt options /* = opt::none */ ) 932{ 933#if _WIN32 934std :: string filter_list; 935std :: regex whitespace( " *" ); 936for ( size_t i = 0 ; i + 1 < filters. size (); i += 2 ) 937{ 938filter_list += filters[i] + '\0' ; 939filter_list += std:: regex_replace (filters[i + 1 ], whitespace, ";" ) + '\0' ; 940} 941filter_list += '\0' ; 942 943m_async -> start_func ([this, in_type, title, default_path, filter_list, 944options]( int * exit_code) -> std ::string 945{ 946( void )exit_code; 947m_wtitle = internal:: str2wstr (title); 948m_wdefault_path = internal:: str2wstr (default_path); 949auto 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) 955ole32_dll ole32; 956 957// Folder selection uses a different method 958if (in_type == type::folder) 959{ 960if ( flags (flag::is_vista)) 961{ 962// On Vista and higher we should be able to use IFileDialog for folder selection 963IFileDialog * ifd; 964HRESULT 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 968if ( SUCCEEDED (hr)) 969return select_folder_vista (ifd, options & opt::force_path); 970} 971 972BROWSEINFOW bi; 973memset ( & bi, 0 , sizeof (bi)); 974 975bi. lpfn = & bffcallback; 976bi. lParam = ( LPARAM )this; 977 978if ( flags (flag::is_vista)) 979{ 980if (ole32. is_initialized ()) 981bi. ulFlags |= BIF_NEWDIALOGSTYLE ; 982bi. ulFlags |= BIF_EDITBOX ; 983bi. ulFlags |= BIF_STATUSTEXT ; 984} 985 986auto * list = SHBrowseForFolderW ( & bi); 987std :: string ret; 988if (list) 989{ 990auto buffer = new wchar_t[ MAX_PATH ]; 991SHGetPathFromIDListW (list, buffer); 992dll ::proc < void WINAPI ( LPVOID ) > (ole32, "CoTaskMemFree" )(list); 993ret = internal:: wstr2str (buffer); 994delete[] buffer; 995} 996return ret; 997} 998 999OPENFILENAMEW ofn; 1000memset ( & ofn, 0 , sizeof (ofn)); 1001ofn. lStructSize = sizeof ( OPENFILENAMEW ); 1002ofn. hwndOwner = GetActiveWindow (); 1003 1004ofn. lpstrFilter = wfilter_list. c_str (); 1005 1006auto woutput = std::wstring( MAX_PATH * 256 , L '\0' ); 1007ofn. lpstrFile = ( LPWSTR )woutput. data (); 1008ofn. nMaxFile = ( DWORD )woutput. size (); 1009if (!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. 1014auto path_attr = GetFileAttributesW (m_wdefault_path. c_str ()); 1015if (path_attr != INVALID_FILE_ATTRIBUTES && (path_attr & FILE_ATTRIBUTE_DIRECTORY )) 1016ofn. lpstrInitialDir = m_wdefault_path. c_str (); 1017else if (m_wdefault_path. size () <= woutput. size ()) 1018//second argument is size of buffer, not length of string 1019StringCchCopyW (ofn. lpstrFile , MAX_PATH * 256 + 1 , m_wdefault_path. c_str ()); 1020else 1021{ 1022ofn. lpstrFileTitle = ( LPWSTR )m_wdefault_path. data (); 1023ofn. nMaxFileTitle = ( DWORD )m_wdefault_path. size (); 1024} 1025} 1026ofn. lpstrTitle = m_wtitle. c_str (); 1027ofn. Flags = OFN_NOCHANGEDIR | OFN_EXPLORER ; 1028 1029dll comdlg32( "comdlg32.dll" ); 1030 1031// Apply new visual style (required for windows XP) 1032new_style_context ctx; 1033 1034if (in_type == type::save) 1035{ 1036if (!(options & opt::force_overwrite)) 1037ofn. Flags |= OFN_OVERWRITEPROMPT ; 1038 1039dll ::proc < BOOL WINAPI ( LPOPENFILENAMEW ) > get_save_file_name (comdlg32, "GetSaveFileNameW" ); 1040if ( get_save_file_name ( & ofn) == 0 ) 1041return "" ; 1042return internal:: wstr2str (woutput. c_str ()); 1043} 1044else 1045{ 1046if (options & opt::multiselect) 1047ofn. Flags |= OFN_ALLOWMULTISELECT ; 1048ofn. Flags |= OFN_PATHMUSTEXIST ; 1049 1050dll ::proc < BOOL WINAPI ( LPOPENFILENAMEW ) > get_open_file_name (comdlg32, "GetOpenFileNameW" ); 1051if ( get_open_file_name ( & ofn) == 0 ) 1052return "" ; 1053} 1054 1055std :: string prefix; 1056for ( wchar_t const * p = woutput. c_str (); * p; ) 1057{ 1058auto filename = internal:: wstr2str ( p ); 1059p += 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. 1063if ((options & opt::multiselect) && *++ p && prefix. empty ()) 1064{ 1065prefix = filename + "/" ; 1066continue ; 1067} 1068 1069m_vector_result. push_back (prefix + filename); 1070} 1071 1072return "" ; 1073}); 1074#else 1075auto command = desktop_helper (); 1076 1077if ( is_osascript ()) 1078{ 1079std :: string script = "set ret to choose" ; 1080switch (in_type) 1081{ 1082case type:: save : 1083script += " file name" ; 1084break ; 1085case type:: open : default : 1086script += " file" ; 1087if (options & opt::multiselect) 1088script += " with multiple selections allowed" ; 1089break ; 1090case type:: folder : 1091script += " folder" ; 1092break ; 1093} 1094 1095if (default_path. size ()) 1096script += " default location " + osascript_quote (default_path); 1097script += " with prompt " + osascript_quote (title); 1098 1099if (in_type == type::open) 1100{ 1101// Concatenate all user-provided filter patterns 1102std :: string patterns; 1103for ( size_t i = 0 ; i < filters. size () / 2 ; ++ i) 1104patterns += " " + 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. 1109std :: regex sep( "\\s+" ); 1110std :: string filter_list; 1111bool has_filter = true; 1112std:: sregex_token_iterator iter(patterns. begin (), patterns. end (), sep, -1 ); 1113std :: sregex_token_iterator end; 1114for ( ; iter != end; ++ iter) 1115{ 1116auto pat = iter -> str (); 1117if (pat == "*" || pat == "*.*" ) 1118has_filter = false; 1119else if (internal:: starts_with (pat, "*." )) 1120filter_list += (filter_list. size () == 0 ? "" : "," ) + 1121osascript_quote (pat. substr ( 2 , pat. size () - 2 )); 1122} 1123if (has_filter && filter_list. size () > 0 ) 1124script += " of type {" + filter_list + "}" ; 1125} 1126 1127if (in_type == type::open && (options & opt::multiselect)) 1128{ 1129script += "\nset s to \"\"" ; 1130script += "\nrepeat with i in ret" ; 1131script += "\n set s to s & (POSIX path of i) & \"\\n\"" ; 1132script += "\nend repeat" ; 1133script += "\ncopy s to stdout" ; 1134} 1135else 1136{ 1137script += "\nPOSIX path of ret" ; 1138} 1139 1140command. push_back ( "-e" ); 1141command. push_back (script); 1142} 1143else if ( is_zenity ()) 1144{ 1145command. push_back ( "--file-selection" ); 1146command. push_back ( "--filename=" + default_path); 1147command. push_back ( "--title" ); 1148command. push_back (title); 1149command. push_back ( "--separator=\n" ); 1150 1151for ( size_t i = 0 ; i < filters. size () / 2 ; ++ i) 1152{ 1153command. push_back ( "--file-filter" ); 1154command. push_back (filters[ 2 * i] + "|" + filters[ 2 * i + 1 ]); 1155} 1156 1157if (in_type == type::save) 1158command. push_back ( "--save" ); 1159if (in_type == type::folder) 1160command. push_back ( "--directory" ); 1161if (!(options & opt::force_overwrite)) 1162command. push_back ( "--confirm-overwrite" ); 1163if (options & opt::multiselect) 1164command. push_back ( "--multiple" ); 1165} 1166else if ( is_kdialog ()) 1167{ 1168switch (in_type) 1169{ 1170case type:: save : command. push_back ( "--getsavefilename" ); break ; 1171case type:: open : command. push_back ( "--getopenfilename" ); break ; 1172case type:: folder : command. push_back ( "--getexistingdirectory" ); break ; 1173} 1174if (options & opt::multiselect) 1175command. push_back ( " --multiple" ); 1176 1177command. push_back (default_path); 1178 1179std :: string filter; 1180for ( size_t i = 0 ; i < filters. size () / 2 ; ++ i) 1181filter += (i == 0 ? "" : " | " ) + filters[ 2 * i] + "(" + filters[ 2 * i + 1 ] + ")" ; 1182command. push_back (filter); 1183 1184command. push_back ( "--title" ); 1185command. push_back (title); 1186} 1187 1188if ( flags (flag::is_verbose)) 1189std ::cerr << "pfd: " << command << std::endl; 1190 1191m_async -> start_process (command); 1192#endif 1193} 1194 1195inline std::string internal::file_dialog::string_result() 1196{ 1197#if _WIN32 1198return m_async -> result(); 1199#else 1200auto ret = m_async -> result (); 1201// Strip potential trailing newline (zenity). Also strip trailing slash 1202// added by osascript for consistency with other backends. 1203while ( ret .back() == '\n' || ret. back () == '/' ) 1204ret = ret. substr ( 0 , ret. size () - 1 ); 1205return ret; 1206#endif 1207} 1208 1209inline std ::vector < std::string > internal::file_dialog:: vector_result () 1210{ 1211#if _WIN32 1212m_async -> result (); 1213return m_vector_result; 1214#else 1215std ::vector < std::string > ret; 1216auto result = m_async -> result (); 1217for (;;) 1218{ 1219// Split result along newline characters 1220auto i = result. find ( '\n' ); 1221if (i == 0 || i == std::string::npos) 1222break ; 1223ret. push_back (result. substr ( 0 , i)); 1224result = result. substr (i + 1 , result. size ()); 1225} 1226return 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, 1233LPARAM , LPARAM pData) 1234{ 1235auto inst = ( file_dialog * )pData; 1236switch (uMsg) 1237{ 1238case BFFM_INITIALIZED : 1239SendMessage (hwnd, BFFM_SETSELECTIONW , TRUE, ( LPARAM )inst -> m_wdefault_path . c_str ()); 1240break ; 1241} 1242return 0 ; 1243} 1244 1245inline std ::string internal :: file_dialog :: select_folder_vista (IFileDialog * ifd, bool force_path) 1246{ 1247std :: string result; 1248 1249IShellItem * folder; 1250 1251// Load library at runtime so app doesn't link it at load time (which will fail on windows XP) 1252dll shell32( "shell32.dll" ); 1253dll ::proc < HRESULT WINAPI ( PCWSTR , IBindCtx * , REFIID , void ** ) > 1254create_item (shell32, "SHCreateItemFromParsingName" ); 1255 1256if (!create_item) 1257return "" ; 1258 1259auto hr = create_item (m_wdefault_path. c_str (), 1260nullptr , 1261IID_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 1269if ( SUCCEEDED (hr)) 1270{ 1271if (force_path) 1272ifd -> SetFolder (folder); 1273else 1274ifd -> SetDefaultFolder (folder); 1275folder -> Release (); 1276} 1277 1278// Set the dialog title and option to select folders 1279ifd -> SetOptions ( FOS_PICKFOLDERS ); 1280ifd -> SetTitle (m_wtitle. c_str ()); 1281 1282hr = ifd -> Show ( GetActiveWindow ()); 1283if ( SUCCEEDED (hr)) 1284{ 1285IShellItem * item; 1286hr = ifd -> GetResult ( & item); 1287if ( SUCCEEDED (hr)) 1288{ 1289wchar_t * wselected = nullptr ; 1290item -> GetDisplayName ( SIGDN_FILESYSPATH , & wselected); 1291item -> Release (); 1292 1293if (wselected) 1294{ 1295result = internal::wstr2str( std :: wstring ( wselected )); 1296dll ::proc < void WINAPI ( LPVOID ) > ( ole32_dll (), "CoTaskMemFree" )(wselected); 1297} 1298} 1299} 1300 1301ifd -> Release (); 1302 1303return result; 1304} 1305#endif 1306 1307// notify implementation 1308 1309inline notify :: notify ( std ::string const & title, 1310std ::string const & message, 1311icon _icon /* = icon::info */ ) 1312{ 1313if (_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. 1320struct notify_icon_data : public NOTIFYICONDATAW 1321{ 1322~ notify_icon_data () { Shell_NotifyIconW ( NIM_DELETE , this); } 1323}; 1324 1325static 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. 1330nid = nullptr ; 1331nid = std::make_shared < notify_icon_data > (); 1332 1333// For XP support 1334nid -> cbSize = NOTIFYICONDATAW_V2_SIZE ; 1335nid -> hWnd = nullptr ; 1336nid -> 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. 1345nid -> 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 1354switch (_icon) 1355{ 1356case icon:: warning : nid -> dwInfoFlags = NIIF_WARNING ; break ; 1357case icon:: error : nid -> dwInfoFlags = NIIF_ERROR ; break ; 1358/* case icon::info: */ default : nid -> dwInfoFlags = NIIF_INFO ; break ; 1359} 1360 1361ENUMRESNAMEPROC icon_enum_callback = []( HMODULE , LPCTSTR , LPTSTR lpName, LONG_PTR lParam) -> BOOL 1362{ 1363(( NOTIFYICONDATAW * )lParam) -> hIcon = :: LoadIcon ( GetModuleHandle ( nullptr ), lpName); 1364return false; 1365}; 1366 1367nid -> hIcon = :: LoadIcon ( nullptr , IDI_APPLICATION ); 1368:: EnumResourceNames ( nullptr , RT_GROUP_ICON , icon_enum_callback, ( LONG_PTR )nid. get ()); 1369 1370nid -> uTimeout = 5000 ; 1371 1372StringCchCopyW (nid -> szInfoTitle , ARRAYSIZE (nid -> szInfoTitle ), internal:: str2wstr (title). c_str ()); 1373StringCchCopyW (nid -> szInfo , ARRAYSIZE (nid -> szInfo ), internal:: str2wstr (message). c_str ()); 1374 1375// Display the new icon 1376Shell_NotifyIconW ( NIM_ADD , nid. get ()); 1377#else 1378auto command = desktop_helper (); 1379 1380if ( is_osascript ()) 1381{ 1382command. push_back ( "-e" ); 1383command. push_back ( "display notification " + osascript_quote (message) + 1384" with title " + osascript_quote (title)); 1385} 1386else if ( is_zenity ()) 1387{ 1388command. push_back ( "--notification" ); 1389command. push_back ( "--window-icon" ); 1390command. push_back ( get_icon_name (_icon)); 1391command. push_back ( "--text" ); 1392command. push_back (title + "\n" + message); 1393} 1394else if ( is_kdialog ()) 1395{ 1396command. push_back ( "--icon" ); 1397command. push_back ( get_icon_name (_icon)); 1398command. push_back ( "--title" ); 1399command. push_back (title); 1400command. push_back ( "--passivepopup" ); 1401command. push_back (message); 1402command. push_back ( "5" ); 1403} 1404 1405if ( flags (flag::is_verbose)) 1406std ::cerr << "pfd: " << command << std::endl; 1407 1408m_async -> start_process (command); 1409#endif 1410} 1411 1412// message implementation 1413 1414inline message :: message ( std ::string const & title, 1415std ::string const & text, 1416choice _choice /* = choice::ok_cancel */ , 1417icon _icon /* = icon::info */ ) 1418{ 1419#if _WIN32 1420UINT style = MB_TOPMOST ; 1421switch (_icon) 1422{ 1423case icon:: warning : style |= MB_ICONWARNING ; break ; 1424case icon:: error : style |= MB_ICONERROR ; break ; 1425case icon:: question : style |= MB_ICONQUESTION ; break ; 1426/* case icon::info: */ default : style |= MB_ICONINFORMATION ; break ; 1427} 1428 1429switch (_choice) 1430{ 1431case choice:: ok_cancel : style |= MB_OKCANCEL ; break ; 1432case choice:: yes_no : style |= MB_YESNO ; break ; 1433case choice:: yes_no_cancel : style |= MB_YESNOCANCEL ; break ; 1434case choice:: retry_cancel : style |= MB_RETRYCANCEL ; break ; 1435case choice:: abort_retry_ignore : style |= MB_ABORTRETRYIGNORE ; break ; 1436/* case choice::ok: */ default : style |= MB_OK ; break ; 1437} 1438 1439m_mappings[ IDCANCEL ] = button::cancel; 1440m_mappings[ IDOK ] = button::ok; 1441m_mappings[ IDYES ] = button::yes; 1442m_mappings[ IDNO ] = button::no; 1443m_mappings[ IDABORT ] = button::abort; 1444m_mappings[ IDRETRY ] = button::retry; 1445m_mappings[ IDIGNORE ] = button::ignore; 1446 1447m_async -> start_func ([this, text, title, style]( int * exit_code) -> std ::string 1448{ 1449auto wtext = internal:: str2wstr ( text ); 1450auto wtitle = internal:: str2wstr ( title ); 1451// Apply new visual style (required for all Windows versions) 1452new_style_context ctx; 1453* exit_code = MessageBoxW ( GetActiveWindow (), wtext. c_str (), wtitle. c_str (), style); 1454return "" ; 1455}); 1456 1457#elif __EMSCRIPTEN__ 1458std :: string full_message; 1459switch (_icon) 1460{ 1461case icon:: warning : full_message = "⚠️" ; break ; 1462case icon:: error : full_message = "⛔" ; break ; 1463case icon:: question : full_message = "❓" ; break ; 1464/* case icon::info: */ default : full_message = "ℹ" ; break ; 1465} 1466 1467full_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. 1471m_async -> start ( EM_ASM_INT ( 1472{ 1473if ($1) 1474return window. confirm ( UTF8ToString ($0)) ? 0 : -1 ; 1475alert ( UTF8ToString ($0)); 1476return 0 ; 1477}, full_message. c_str (), _choice == choice::ok_cancel)); 1478#else 1479auto command = desktop_helper (); 1480 1481if ( is_osascript ()) 1482{ 1483std :: string script = "display dialog " + osascript_quote (text) + 1484" with title " + osascript_quote (title); 1485switch (_choice) 1486{ 1487case choice:: ok_cancel : 1488script += "buttons {\"OK\", \"Cancel\"}" 1489" default button \"OK\"" 1490" cancel button \"Cancel\"" ; 1491m_mappings[ 256 ] = button::cancel; 1492break ; 1493case choice:: yes_no : 1494script += "buttons {\"Yes\", \"No\"}" 1495" default button \"Yes\"" 1496" cancel button \"No\"" ; 1497m_mappings[ 256 ] = button::no; 1498break ; 1499case choice:: yes_no_cancel : 1500script += "buttons {\"Yes\", \"No\", \"Cancel\"}" 1501" default button \"Yes\"" 1502" cancel button \"Cancel\"" ; 1503m_mappings[ 256 ] = button::cancel; 1504break ; 1505case choice:: retry_cancel : 1506script += "buttons {\"Retry\", \"Cancel\"}" 1507" default button \"Retry\"" 1508" cancel button \"Cancel\"" ; 1509m_mappings[ 256 ] = button::cancel; 1510break ; 1511case choice:: abort_retry_ignore : 1512script += "buttons {\"Abort\", \"Retry\", \"Ignore\"}" 1513" default button \"Retry\"" 1514" cancel button \"Retry\"" ; 1515m_mappings[ 256 ] = button::cancel; 1516break ; 1517case choice:: ok : default : 1518script += "buttons {\"OK\"}" 1519" default button \"OK\"" 1520" cancel button \"OK\"" ; 1521m_mappings[ 256 ] = button::ok; 1522break ; 1523} 1524script += " with icon " ; 1525switch (_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\")" 1529case icon:: info : default : script += PFD_OSX_ICON ( "ToolBarInfo" ); break ; 1530case icon:: warning : script += "caution" ; break ; 1531case icon:: error : script += "stop" ; break ; 1532case icon:: question : script += PFD_OSX_ICON ( "GenericQuestionMarkIcon" ); break ; 1533#undef PFD_OSX_ICON 1534} 1535 1536command. push_back ( "-e" ); 1537command. push_back (script); 1538} 1539else if ( is_zenity ()) 1540{ 1541switch (_choice) 1542{ 1543case choice:: ok_cancel : 1544command. insert (command. end (), { "--question" , "--cancel-label=Cancel" , "--ok-label=OK" }); break ; 1545case 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. 1548command. insert (command. end (), { "--question" , "--switch" , "--extra-button=No" , "--extra-button=Yes" }); break ; 1549case choice:: yes_no_cancel : 1550command. insert (command. end (), { "--question" , "--switch" , "--extra-button=Cancel" , "--extra-button=No" , "--extra-button=Yes" }); break ; 1551case choice:: retry_cancel : 1552command. insert (command. end (), { "--question" , "--switch" , "--extra-button=Cancel" , "--extra-button=Retry" }); break ; 1553case choice:: abort_retry_ignore : 1554command. insert (command. end (), { "--question" , "--switch" , "--extra-button=Ignore" , "--extra-button=Abort" , "--extra-button=Retry" }); break ; 1555case choice:: ok : 1556default : 1557switch (_icon) 1558{ 1559case icon:: error : command. push_back ( "--error" ); break ; 1560case icon:: warning : command. push_back ( "--warning" ); break ; 1561default : command. push_back ( "--info" ); break ; 1562} 1563} 1564 1565command. insert (command. end (), { "--title" , title, 1566"--width=300" , "--height=0" , // sensible defaults 1567"--text" , text, 1568"--icon-name=dialog-" + get_icon_name (_icon) }); 1569} 1570else if ( is_kdialog ()) 1571{ 1572if (_choice == choice::ok) 1573{ 1574switch (_icon) 1575{ 1576case icon:: error : command. push_back ( "--error" ); break ; 1577case icon:: warning : command. push_back ( "--sorry" ); break ; 1578default : command. push_back ( "--msgbox" ); break ; 1579} 1580} 1581else 1582{ 1583std :: string flag = "--" ; 1584if (_icon == icon::warning || _icon == icon::error) 1585flag += "warning" ; 1586flag += "yesno" ; 1587if (_choice == choice::yes_no_cancel) 1588flag += "cancel" ; 1589command. push_back (flag); 1590if (_choice == choice::yes_no || _choice == choice::yes_no_cancel) 1591{ 1592m_mappings[ 0 ] = button::yes; 1593m_mappings[ 256 ] = button::no; 1594} 1595} 1596 1597command. push_back (text); 1598command. push_back ( "--title" ); 1599command. push_back (title); 1600 1601// Must be after the above part 1602if (_choice == choice::ok_cancel) 1603command. insert (command. end (), { "--yes-label" , "OK" , "--no-label" , "Cancel" }); 1604} 1605 1606if ( flags (flag::is_verbose)) 1607std ::cerr << "pfd: " << command << std::endl; 1608 1609m_async -> start_process (command); 1610#endif 1611} 1612 1613inline button message:: result () 1614{ 1615int exit_code; 1616auto ret = m_async -> result ( & exit_code); 1617// osascript will say "button returned:Cancel\n" 1618// and others will just say "Cancel\n" 1619if (exit_code < 0 || // this means cancel 1620internal:: ends_with (ret, "Cancel\n" )) 1621return button::cancel; 1622if (internal:: ends_with (ret, "OK\n" )) 1623return button::ok; 1624if (internal:: ends_with (ret, "Yes\n" )) 1625return button::yes; 1626if (internal:: ends_with (ret, "No\n" )) 1627return button::no; 1628if (internal:: ends_with (ret, "Abort\n" )) 1629return button::abort; 1630if (internal:: ends_with (ret, "Retry\n" )) 1631return button::retry; 1632if (internal:: ends_with (ret, "Ignore\n" )) 1633return button::ignore; 1634if (m_mappings. count (exit_code) != 0 ) 1635return m_mappings[exit_code]; 1636return exit_code == 0 ? button::ok : button::cancel; 1637} 1638 1639// open_file implementation 1640 1641inline open_file :: open_file ( std ::string const & title, 1642std ::string const & default_path /* = "" */ , 1643std ::vector < std::string > const & filters /* = { "All Files", "*" } */ , 1644opt 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, 1650std ::string const & default_path, 1651std ::vector < std::string > const & filters, 1652bool 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{ 1660return vector_result (); 1661} 1662 1663// save_file implementation 1664 1665inline save_file :: save_file ( std ::string const & title, 1666std ::string const & default_path /* = "" */ , 1667std ::vector < std::string > const & filters /* = { "All Files", "*" } */ , 1668opt 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, 1674std ::string const & default_path, 1675std ::vector < std::string > const & filters, 1676bool 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{ 1684return string_result (); 1685} 1686 1687// select_folder implementation 1688 1689inline select_folder :: select_folder ( std ::string const & title, 1690std ::string const & default_path /* = "" */ , 1691opt options /* = opt::none */ ) 1692: file_dialog (type::folder, title, default_path, {}, options) 1693{ 1694} 1695 1696inline std ::string select_folder :: result () 1697{ 1698return string_result (); 1699} 1700 1701#endif // PFD_SKIP_IMPLEMENTATION 1702 1703} // namespace pfd 1704