DISTRHO Plugin Framework
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

632 lines
21KB

  1. /*
  2. * DISTRHO Plugin Framework (DPF)
  3. * Copyright (C) 2012-2021 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * Permission to use, copy, modify, and/or distribute this software for any purpose with
  6. * or without fee is hereby granted, provided that the above copyright notice and this
  7. * permission notice appear in all copies.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  10. * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
  11. * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  12. * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  13. * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  14. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. #include "FileBrowserDialog.hpp"
  17. #include "ScopedPointer.hpp"
  18. #include "String.hpp"
  19. #ifdef DISTRHO_OS_MAC
  20. # import <Cocoa/Cocoa.h>
  21. #endif
  22. #ifdef DISTRHO_OS_WINDOWS
  23. # include <direct.h>
  24. # include <process.h>
  25. # include <winsock2.h>
  26. # include <windows.h>
  27. # include <commdlg.h>
  28. # include <vector>
  29. #else
  30. # include <unistd.h>
  31. #endif
  32. #ifdef HAVE_DBUS
  33. # include <dbus/dbus.h>
  34. #endif
  35. #ifdef HAVE_X11
  36. # define DBLCLKTME 400
  37. # include "sofd/libsofd.h"
  38. # include "sofd/libsofd.c"
  39. #endif
  40. START_NAMESPACE_DISTRHO
  41. // --------------------------------------------------------------------------------------------------------------------
  42. // static pointer used for signal null/none action taken
  43. static const char* const kSelectedFileCancelled = "__dpf_cancelled__";
  44. struct FileBrowserData {
  45. const char* selectedFile;
  46. #ifdef DISTRHO_OS_MAC
  47. NSSavePanel* nsBasePanel;
  48. NSOpenPanel* nsOpenPanel;
  49. #endif
  50. #ifdef HAVE_DBUS
  51. DBusConnection* dbuscon;
  52. #endif
  53. #ifdef HAVE_X11
  54. Display* x11display;
  55. #endif
  56. #ifdef DISTRHO_OS_WINDOWS
  57. OPENFILENAMEW ofn;
  58. volatile bool threadCancelled;
  59. uintptr_t threadHandle;
  60. std::vector<WCHAR> fileNameW;
  61. std::vector<WCHAR> startDirW;
  62. std::vector<WCHAR> titleW;
  63. const bool saving;
  64. bool isEmbed;
  65. FileBrowserData(const bool save)
  66. : selectedFile(nullptr),
  67. threadCancelled(false),
  68. threadHandle(0),
  69. fileNameW(32768),
  70. saving(save),
  71. isEmbed(false)
  72. {
  73. std::memset(&ofn, 0, sizeof(ofn));
  74. ofn.lStructSize = sizeof(ofn);
  75. ofn.lpstrFile = fileNameW.data();
  76. ofn.nMaxFile = (DWORD)fileNameW.size();
  77. }
  78. ~FileBrowserData()
  79. {
  80. if (cancelAndStop())
  81. free();
  82. }
  83. void setupAndStart(const bool embed,
  84. const char* const startDir,
  85. const char* const windowTitle,
  86. const uintptr_t winId,
  87. const FileBrowserOptions options)
  88. {
  89. isEmbed = embed;
  90. ofn.hwndOwner = (HWND)winId;
  91. ofn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;
  92. if (options.buttons.showHidden == FileBrowserOptions::kButtonVisibleChecked)
  93. ofn.Flags |= OFN_FORCESHOWHIDDEN;
  94. ofn.FlagsEx = 0x0;
  95. if (options.buttons.showPlaces == FileBrowserOptions::kButtonInvisible)
  96. ofn.FlagsEx |= OFN_EX_NOPLACESBAR;
  97. startDirW.resize(std::strlen(startDir) + 1);
  98. if (MultiByteToWideChar(CP_UTF8, 0, startDir, -1, startDirW.data(), static_cast<int>(startDirW.size())))
  99. ofn.lpstrInitialDir = startDirW.data();
  100. titleW.resize(std::strlen(windowTitle) + 1);
  101. if (MultiByteToWideChar(CP_UTF8, 0, windowTitle, -1, titleW.data(), static_cast<int>(titleW.size())))
  102. ofn.lpstrTitle = titleW.data();
  103. uint threadId;
  104. threadCancelled = false;
  105. threadHandle = _beginthreadex(nullptr, 0, _run, this, 0, &threadId);
  106. }
  107. bool cancelAndStop()
  108. {
  109. threadCancelled = true;
  110. if (threadHandle == 0)
  111. return true;
  112. // if previous dialog running, carefully close its window
  113. const HWND owner = isEmbed ? GetParent(ofn.hwndOwner) : ofn.hwndOwner;
  114. if (owner != nullptr && owner != INVALID_HANDLE_VALUE)
  115. {
  116. const HWND window = GetWindow(owner, GW_HWNDFIRST);
  117. if (window != nullptr && window != INVALID_HANDLE_VALUE)
  118. {
  119. SendMessage(window, WM_SYSCOMMAND, SC_CLOSE, 0);
  120. SendMessage(window, WM_CLOSE, 0, 0);
  121. WaitForSingleObject((HANDLE)threadHandle, 5000);
  122. }
  123. }
  124. if (threadHandle == 0)
  125. return true;
  126. // not good if thread still running, but let's close the handle anyway
  127. CloseHandle((HANDLE)threadHandle);
  128. threadHandle = 0;
  129. return false;
  130. }
  131. void run()
  132. {
  133. const char* nextFile = nullptr;
  134. if (saving ? GetSaveFileNameW(&ofn) : GetOpenFileNameW(&ofn))
  135. {
  136. if (threadCancelled)
  137. {
  138. threadHandle = 0;
  139. return;
  140. }
  141. // back to UTF-8
  142. std::vector<char> fileNameA(4 * 32768);
  143. if (WideCharToMultiByte(CP_UTF8, 0, fileNameW.data(), -1,
  144. fileNameA.data(), (int)fileNameA.size(),
  145. nullptr, nullptr))
  146. {
  147. nextFile = strdup(fileNameA.data());
  148. }
  149. }
  150. if (threadCancelled)
  151. {
  152. threadHandle = 0;
  153. return;
  154. }
  155. if (nextFile == nullptr)
  156. nextFile = kSelectedFileCancelled;
  157. selectedFile = nextFile;
  158. threadHandle = 0;
  159. }
  160. static unsigned __stdcall _run(void* const arg)
  161. {
  162. // CoInitializeEx(nullptr, COINIT_MULTITHREADED);
  163. static_cast<FileBrowserData*>(arg)->run();
  164. // CoUninitialize();
  165. _endthreadex(0);
  166. return 0;
  167. }
  168. #else // DISTRHO_OS_WINDOWS
  169. FileBrowserData(const bool saving)
  170. : selectedFile(nullptr)
  171. {
  172. #ifdef DISTRHO_OS_MAC
  173. if (saving)
  174. {
  175. nsOpenPanel = nullptr;
  176. nsBasePanel = [[NSSavePanel savePanel]retain];
  177. }
  178. else
  179. {
  180. nsOpenPanel = [[NSOpenPanel openPanel]retain];
  181. nsBasePanel = nsOpenPanel;
  182. }
  183. #endif
  184. #ifdef HAVE_DBUS
  185. if ((dbuscon = dbus_bus_get(DBUS_BUS_SESSION, nullptr)) != nullptr)
  186. dbus_connection_set_exit_on_disconnect(dbuscon, false);
  187. #endif
  188. #ifdef HAVE_X11
  189. x11display = XOpenDisplay(nullptr);
  190. #endif
  191. // maybe unused
  192. return; (void)saving;
  193. }
  194. ~FileBrowserData()
  195. {
  196. #ifdef DISTRHO_OS_MAC
  197. [nsBasePanel release];
  198. #endif
  199. #ifdef HAVE_DBUS
  200. if (dbuscon != nullptr)
  201. dbus_connection_unref(dbuscon);
  202. #endif
  203. #ifdef HAVE_X11
  204. if (x11display != nullptr)
  205. XCloseDisplay(x11display);
  206. #endif
  207. free();
  208. }
  209. #endif
  210. void free()
  211. {
  212. if (selectedFile == nullptr)
  213. return;
  214. if (selectedFile == kSelectedFileCancelled || std::strcmp(selectedFile, kSelectedFileCancelled) == 0)
  215. {
  216. selectedFile = nullptr;
  217. return;
  218. }
  219. std::free(const_cast<char*>(selectedFile));
  220. selectedFile = nullptr;
  221. }
  222. };
  223. // --------------------------------------------------------------------------------------------------------------------
  224. #ifdef DISTRHO_FILE_BROWSER_DIALOG_EXTRA_NAMESPACE
  225. namespace DISTRHO_FILE_BROWSER_DIALOG_EXTRA_NAMESPACE {
  226. #endif
  227. // --------------------------------------------------------------------------------------------------------------------
  228. FileBrowserHandle fileBrowserCreate(const bool isEmbed,
  229. const uintptr_t windowId,
  230. const double scaleFactor,
  231. const FileBrowserOptions& options)
  232. {
  233. String startDir(options.startDir);
  234. if (startDir.isEmpty())
  235. {
  236. #ifdef DISTRHO_OS_WINDOWS
  237. if (char* const cwd = _getcwd(nullptr, 0))
  238. {
  239. startDir = cwd;
  240. std::free(cwd);
  241. }
  242. #else
  243. if (char* const cwd = getcwd(nullptr, 0))
  244. {
  245. startDir = cwd;
  246. std::free(cwd);
  247. }
  248. #endif
  249. }
  250. DISTRHO_SAFE_ASSERT_RETURN(startDir.isNotEmpty(), nullptr);
  251. if (! startDir.endsWith(DISTRHO_OS_SEP))
  252. startDir += DISTRHO_OS_SEP_STR;
  253. String windowTitle(options.title);
  254. if (windowTitle.isEmpty())
  255. windowTitle = "FileBrowser";
  256. ScopedPointer<FileBrowserData> handle(new FileBrowserData(options.saving));
  257. #ifdef DISTRHO_OS_MAC
  258. NSSavePanel* const nsBasePanel = handle->nsBasePanel;
  259. DISTRHO_SAFE_ASSERT_RETURN(nsBasePanel != nullptr, nullptr);
  260. if (! options.saving)
  261. {
  262. NSOpenPanel* const nsOpenPanel = handle->nsOpenPanel;
  263. DISTRHO_SAFE_ASSERT_RETURN(nsOpenPanel != nullptr, nullptr);
  264. [nsOpenPanel setAllowsMultipleSelection:NO];
  265. [nsOpenPanel setCanChooseDirectories:NO];
  266. [nsOpenPanel setCanChooseFiles:YES];
  267. }
  268. [nsBasePanel setDirectoryURL:[NSURL fileURLWithPath:[NSString stringWithUTF8String:startDir]]];
  269. // TODO file filter using allowedContentTypes: [UTType]
  270. if (options.buttons.listAllFiles == FileBrowserOptions::kButtonVisibleChecked)
  271. [nsBasePanel setAllowsOtherFileTypes:YES];
  272. if (options.buttons.showHidden == FileBrowserOptions::kButtonVisibleChecked)
  273. [nsBasePanel setShowsHiddenFiles:YES];
  274. NSString* const titleString = [[NSString alloc]
  275. initWithBytes:windowTitle
  276. length:strlen(windowTitle)
  277. encoding:NSUTF8StringEncoding];
  278. [nsBasePanel setTitle:titleString];
  279. FileBrowserData* const handleptr = handle.get();
  280. dispatch_async(dispatch_get_main_queue(), ^
  281. {
  282. [nsBasePanel beginSheetModalForWindow:[(NSView*)windowId window]
  283. completionHandler:^(NSModalResponse result)
  284. {
  285. if (result == NSModalResponseOK && [[nsBasePanel URL] isFileURL])
  286. {
  287. NSString* const path = [[nsBasePanel URL] path];
  288. handleptr->selectedFile = strdup([path UTF8String]);
  289. }
  290. else
  291. {
  292. handleptr->selectedFile = kSelectedFileCancelled;
  293. }
  294. }];
  295. });
  296. #endif
  297. #ifdef DISTRHO_OS_WINDOWS
  298. handle->setupAndStart(isEmbed, startDir, windowTitle, windowId, options);
  299. #endif
  300. #ifdef HAVE_DBUS
  301. // optional, can be null
  302. DBusConnection* const dbuscon = handle->dbuscon;
  303. // https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-org.freedesktop.portal.FileChooser
  304. if (dbuscon != nullptr)
  305. {
  306. // if this is the first time we are calling into DBus, check if things are working
  307. static bool firstTry = true;
  308. if (firstTry)
  309. {
  310. firstTry = false;
  311. if (DBusMessage* const msg = dbus_message_new_method_call("org.freedesktop.portal.Desktop",
  312. "/org/freedesktop/portal/desktop",
  313. "org.freedesktop.portal.FileChooser",
  314. "version"))
  315. {
  316. if (DBusMessage* const reply = dbus_connection_send_with_reply_and_block(dbuscon, msg, 250, nullptr))
  317. dbus_message_unref(reply);
  318. dbus_message_unref(msg);
  319. }
  320. }
  321. // Any subsquent calls should have this DBus service active
  322. if (dbus_bus_name_has_owner(dbuscon, "org.freedesktop.portal.Desktop", nullptr))
  323. {
  324. if (DBusMessage* const msg = dbus_message_new_method_call("org.freedesktop.portal.Desktop",
  325. "/org/freedesktop/portal/desktop",
  326. "org.freedesktop.portal.FileChooser",
  327. options.saving ? "SaveFile" : "OpenFile"))
  328. {
  329. #ifdef HAVE_X11
  330. char windowIdStr[32];
  331. memset(windowIdStr, 0, sizeof(windowIdStr));
  332. snprintf(windowIdStr, sizeof(windowIdStr)-1, "x11:%llx", (ulonglong)windowId);
  333. const char* windowIdStrPtr = windowIdStr;
  334. #endif
  335. dbus_message_append_args(msg,
  336. #ifdef HAVE_X11
  337. DBUS_TYPE_STRING, &windowIdStrPtr,
  338. #endif
  339. DBUS_TYPE_STRING, &windowTitle,
  340. DBUS_TYPE_INVALID);
  341. DBusMessageIter iter, array;
  342. dbus_message_iter_init_append(msg, &iter);
  343. dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &array);
  344. {
  345. DBusMessageIter dict, variant, variantArray;
  346. const char* const current_folder_key = "current_folder";
  347. const char* const current_folder_val = startDir.buffer();
  348. dbus_message_iter_open_container(&array, DBUS_TYPE_DICT_ENTRY, nullptr, &dict);
  349. dbus_message_iter_append_basic(&dict, DBUS_TYPE_STRING, &current_folder_key);
  350. dbus_message_iter_open_container(&dict, DBUS_TYPE_VARIANT, "ay", &variant);
  351. dbus_message_iter_open_container(&variant, DBUS_TYPE_ARRAY, "y", &variantArray);
  352. dbus_message_iter_append_fixed_array(&variantArray, DBUS_TYPE_BYTE,
  353. &current_folder_val, startDir.length()+1);
  354. dbus_message_iter_close_container(&variant, &variantArray);
  355. dbus_message_iter_close_container(&dict, &variant);
  356. dbus_message_iter_close_container(&array, &dict);
  357. }
  358. dbus_message_iter_close_container(&iter, &array);
  359. dbus_connection_send(dbuscon, msg, nullptr);
  360. dbus_message_unref(msg);
  361. return handle.release();
  362. }
  363. }
  364. }
  365. #endif
  366. #ifdef HAVE_X11
  367. Display* const x11display = handle->x11display;
  368. DISTRHO_SAFE_ASSERT_RETURN(x11display != nullptr, nullptr);
  369. // unsupported at the moment
  370. if (options.saving)
  371. return nullptr;
  372. DISTRHO_SAFE_ASSERT_RETURN(x_fib_configure(0, startDir) == 0, nullptr);
  373. DISTRHO_SAFE_ASSERT_RETURN(x_fib_configure(1, windowTitle) == 0, nullptr);
  374. const int button1 = options.buttons.showHidden == FileBrowserOptions::kButtonVisibleChecked ? 1
  375. : options.buttons.showHidden == FileBrowserOptions::kButtonVisibleUnchecked ? 0 : -1;
  376. const int button2 = options.buttons.showPlaces == FileBrowserOptions::kButtonVisibleChecked ? 1
  377. : options.buttons.showPlaces == FileBrowserOptions::kButtonVisibleUnchecked ? 0 : -1;
  378. const int button3 = options.buttons.listAllFiles == FileBrowserOptions::kButtonVisibleChecked ? 1
  379. : options.buttons.listAllFiles == FileBrowserOptions::kButtonVisibleUnchecked ? 0 : -1;
  380. x_fib_cfg_buttons(1, button1);
  381. x_fib_cfg_buttons(2, button2);
  382. x_fib_cfg_buttons(3, button3);
  383. if (x_fib_show(x11display, windowId, 0, 0, scaleFactor + 0.5) != 0)
  384. return nullptr;
  385. #endif
  386. return handle.release();
  387. // might be unused
  388. (void)isEmbed;
  389. (void)windowId;
  390. (void)scaleFactor;
  391. }
  392. // --------------------------------------------------------------------------------------------------------------------
  393. // returns true if dialog was closed (with or without a file selection)
  394. bool fileBrowserIdle(const FileBrowserHandle handle)
  395. {
  396. #ifdef HAVE_DBUS
  397. if (DBusConnection* dbuscon = handle->dbuscon)
  398. {
  399. while (dbus_connection_dispatch(dbuscon) == DBUS_DISPATCH_DATA_REMAINS) {}
  400. dbus_connection_read_write_dispatch(dbuscon, 0);
  401. if (DBusMessage* const message = dbus_connection_pop_message(dbuscon))
  402. {
  403. const char* const interface = dbus_message_get_interface(message);
  404. const char* const member = dbus_message_get_member(message);
  405. if (interface != nullptr && std::strcmp(interface, "org.freedesktop.portal.Request") == 0
  406. && member != nullptr && std::strcmp(member, "Response") == 0)
  407. {
  408. do {
  409. DBusMessageIter iter;
  410. dbus_message_iter_init(message, &iter);
  411. // starts with uint32 for return/exit code
  412. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&iter) == DBUS_TYPE_UINT32);
  413. uint32_t ret = 1;
  414. dbus_message_iter_get_basic(&iter, &ret);
  415. if (ret != 0)
  416. break;
  417. // next must be array
  418. dbus_message_iter_next(&iter);
  419. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&iter) == DBUS_TYPE_ARRAY);
  420. // open dict array
  421. DBusMessageIter dictArray;
  422. dbus_message_iter_recurse(&iter, &dictArray);
  423. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&dictArray) == DBUS_TYPE_DICT_ENTRY);
  424. // open containing dict
  425. DBusMessageIter dict;
  426. dbus_message_iter_recurse(&dictArray, &dict);
  427. // look for dict with string "uris"
  428. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&dict) == DBUS_TYPE_STRING);
  429. const char* key = nullptr;
  430. dbus_message_iter_get_basic(&dict, &key);
  431. DISTRHO_SAFE_ASSERT_BREAK(key != nullptr);
  432. // keep going until we find it
  433. while (std::strcmp(key, "uris") != 0)
  434. {
  435. key = nullptr;
  436. dbus_message_iter_next(&dictArray);
  437. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&dictArray) == DBUS_TYPE_DICT_ENTRY);
  438. dbus_message_iter_recurse(&dictArray, &dict);
  439. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&dict) == DBUS_TYPE_STRING);
  440. dbus_message_iter_get_basic(&dict, &key);
  441. DISTRHO_SAFE_ASSERT_BREAK(key != nullptr);
  442. }
  443. if (key == nullptr)
  444. break;
  445. // then comes variant
  446. dbus_message_iter_next(&dict);
  447. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&dict) == DBUS_TYPE_VARIANT);
  448. DBusMessageIter variant;
  449. dbus_message_iter_recurse(&dict, &variant);
  450. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&variant) == DBUS_TYPE_ARRAY);
  451. // open variant array (variant type is string)
  452. DBusMessageIter variantArray;
  453. dbus_message_iter_recurse(&variant, &variantArray);
  454. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&variantArray) == DBUS_TYPE_STRING);
  455. const char* value = nullptr;
  456. dbus_message_iter_get_basic(&variantArray, &value);
  457. // and finally we have our dear value, just make sure it is local
  458. DISTRHO_SAFE_ASSERT_BREAK(value != nullptr);
  459. if (const char* const localvalue = std::strstr(value, "file:///"))
  460. handle->selectedFile = strdup(localvalue + 7);
  461. } while(false);
  462. if (handle->selectedFile == nullptr)
  463. handle->selectedFile = kSelectedFileCancelled;
  464. }
  465. }
  466. }
  467. #endif
  468. #ifdef HAVE_X11
  469. Display* const x11display = handle->x11display;
  470. if (x11display == nullptr)
  471. return false;
  472. XEvent event;
  473. while (XPending(x11display) > 0)
  474. {
  475. XNextEvent(x11display, &event);
  476. if (x_fib_handle_events(x11display, &event) == 0)
  477. continue;
  478. if (x_fib_status() > 0)
  479. handle->selectedFile = x_fib_filename();
  480. else
  481. handle->selectedFile = kSelectedFileCancelled;
  482. x_fib_close(x11display);
  483. XCloseDisplay(x11display);
  484. handle->x11display = nullptr;
  485. break;
  486. }
  487. #endif
  488. return handle->selectedFile != nullptr;
  489. }
  490. // --------------------------------------------------------------------------------------------------------------------
  491. // close sofd file dialog
  492. void fileBrowserClose(const FileBrowserHandle handle)
  493. {
  494. #ifdef HAVE_X11
  495. if (Display* const x11display = handle->x11display)
  496. x_fib_close(x11display);
  497. #endif
  498. delete handle;
  499. }
  500. // --------------------------------------------------------------------------------------------------------------------
  501. // get path chosen via sofd file dialog
  502. const char* fileBrowserGetPath(const FileBrowserHandle handle)
  503. {
  504. if (const char* const selectedFile = handle->selectedFile)
  505. if (selectedFile != kSelectedFileCancelled && std::strcmp(selectedFile, kSelectedFileCancelled) != 0)
  506. return selectedFile;
  507. return nullptr;
  508. }
  509. // --------------------------------------------------------------------------------------------------------------------
  510. #ifdef DISTRHO_FILE_BROWSER_DIALOG_EXTRA_NAMESPACE
  511. }
  512. #endif
  513. END_NAMESPACE_DISTRHO