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.

589 lines
20KB

  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() && selectedFile != nullptr && selectedFile != kSelectedFileCancelled)
  81. std::free(const_cast<char*>(selectedFile));
  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. if (selectedFile != nullptr && selectedFile != kSelectedFileCancelled)
  208. std::free(const_cast<char*>(selectedFile));
  209. }
  210. #endif
  211. };
  212. // --------------------------------------------------------------------------------------------------------------------
  213. #ifdef DISTRHO_FILE_BROWSER_DIALOG_EXTRA_NAMESPACE
  214. namespace DISTRHO_FILE_BROWSER_DIALOG_EXTRA_NAMESPACE {
  215. #endif
  216. // --------------------------------------------------------------------------------------------------------------------
  217. FileBrowserHandle fileBrowserCreate(const bool isEmbed,
  218. const uintptr_t windowId,
  219. const double scaleFactor,
  220. const FileBrowserOptions& options)
  221. {
  222. String startDir(options.startDir);
  223. if (startDir.isEmpty())
  224. {
  225. #ifdef DISTRHO_OS_WINDOWS
  226. if (char* const cwd = _getcwd(nullptr, 0))
  227. {
  228. startDir = cwd;
  229. std::free(cwd);
  230. }
  231. #else
  232. if (char* const cwd = getcwd(nullptr, 0))
  233. {
  234. startDir = cwd;
  235. std::free(cwd);
  236. }
  237. #endif
  238. }
  239. DISTRHO_SAFE_ASSERT_RETURN(startDir.isNotEmpty(), nullptr);
  240. if (! startDir.endsWith(DISTRHO_OS_SEP))
  241. startDir += DISTRHO_OS_SEP_STR;
  242. String windowTitle(options.title);
  243. if (windowTitle.isEmpty())
  244. windowTitle = "FileBrowser";
  245. ScopedPointer<FileBrowserData> handle(new FileBrowserData(options.saving));
  246. #ifdef DISTRHO_OS_MAC
  247. NSSavePanel* const nsBasePanel = handle->nsBasePanel;
  248. DISTRHO_SAFE_ASSERT_RETURN(nsBasePanel != nullptr, nullptr);
  249. if (! options.saving)
  250. {
  251. NSOpenPanel* const nsOpenPanel = handle->nsOpenPanel;
  252. DISTRHO_SAFE_ASSERT_RETURN(nsOpenPanel != nullptr, nullptr);
  253. [nsOpenPanel setAllowsMultipleSelection:NO];
  254. [nsOpenPanel setCanChooseDirectories:NO];
  255. [nsOpenPanel setCanChooseFiles:YES];
  256. }
  257. [nsBasePanel setDirectoryURL:[NSURL fileURLWithPath:[NSString stringWithUTF8String:startDir]]];
  258. // TODO file filter using allowedContentTypes: [UTType]
  259. if (options.buttons.listAllFiles == FileBrowserOptions::kButtonVisibleChecked)
  260. [nsBasePanel setAllowsOtherFileTypes:YES];
  261. if (options.buttons.showHidden == FileBrowserOptions::kButtonVisibleChecked)
  262. [nsBasePanel setShowsHiddenFiles:YES];
  263. NSString* const titleString = [[NSString alloc]
  264. initWithBytes:windowTitle
  265. length:strlen(windowTitle)
  266. encoding:NSUTF8StringEncoding];
  267. [nsBasePanel setTitle:titleString];
  268. FileBrowserData* const handleptr = handle.get();
  269. dispatch_async(dispatch_get_main_queue(), ^
  270. {
  271. [nsBasePanel beginSheetModalForWindow:[(NSView*)windowId window]
  272. completionHandler:^(NSModalResponse result)
  273. {
  274. if (result == NSModalResponseOK && [[nsBasePanel URL] isFileURL])
  275. {
  276. NSString* const path = [[nsBasePanel URL] path];
  277. handleptr->selectedFile = strdup([path UTF8String]);
  278. }
  279. else
  280. {
  281. handleptr->selectedFile = kSelectedFileCancelled;
  282. }
  283. }];
  284. });
  285. #endif
  286. #ifdef DISTRHO_OS_WINDOWS
  287. handle->setupAndStart(isEmbed, startDir, windowTitle, windowId, options);
  288. #endif
  289. #ifdef HAVE_DBUS
  290. // optional, can be null
  291. DBusConnection* const dbuscon = handle->dbuscon;
  292. if (dbuscon != nullptr && dbus_bus_name_has_owner(dbuscon, "org.freedesktop.portal.Desktop", nullptr))
  293. {
  294. // https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-org.freedesktop.portal.FileChooser
  295. if (DBusMessage* const message = dbus_message_new_method_call("org.freedesktop.portal.Desktop",
  296. "/org/freedesktop/portal/desktop",
  297. "org.freedesktop.portal.FileChooser",
  298. options.saving ? "SaveFile" : "OpenFile"))
  299. {
  300. char windowIdStr[32];
  301. memset(windowIdStr, 0, sizeof(windowIdStr));
  302. # ifdef HAVE_X11
  303. snprintf(windowIdStr, sizeof(windowIdStr)-1, "x11:%llx", (ulonglong)windowId);
  304. # endif
  305. const char* windowIdStrPtr = windowIdStr;
  306. dbus_message_append_args(message,
  307. DBUS_TYPE_STRING, &windowIdStrPtr,
  308. DBUS_TYPE_STRING, &windowTitle,
  309. DBUS_TYPE_INVALID);
  310. DBusMessageIter iter, array;
  311. dbus_message_iter_init_append(message, &iter);
  312. dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &array);
  313. {
  314. DBusMessageIter dict, variant, variantArray;
  315. const char* const current_folder_key = "current_folder";
  316. const char* const current_folder_val = startDir.buffer();
  317. dbus_message_iter_open_container(&array, DBUS_TYPE_DICT_ENTRY, nullptr, &dict);
  318. dbus_message_iter_append_basic(&dict, DBUS_TYPE_STRING, &current_folder_key);
  319. dbus_message_iter_open_container(&dict, DBUS_TYPE_VARIANT, "ay", &variant);
  320. dbus_message_iter_open_container(&variant, DBUS_TYPE_ARRAY, "y", &variantArray);
  321. dbus_message_iter_append_fixed_array(&variantArray, DBUS_TYPE_BYTE,
  322. &current_folder_val, startDir.length()+1);
  323. dbus_message_iter_close_container(&variant, &variantArray);
  324. dbus_message_iter_close_container(&dict, &variant);
  325. dbus_message_iter_close_container(&array, &dict);
  326. }
  327. dbus_message_iter_close_container(&iter, &array);
  328. dbus_connection_send(dbuscon, message, nullptr);
  329. dbus_message_unref(message);
  330. return handle.release();
  331. }
  332. }
  333. #endif
  334. #ifdef HAVE_X11
  335. Display* const x11display = handle->x11display;
  336. DISTRHO_SAFE_ASSERT_RETURN(x11display != nullptr, nullptr);
  337. // unsupported at the moment
  338. if (options.saving)
  339. return nullptr;
  340. DISTRHO_SAFE_ASSERT_RETURN(x_fib_configure(0, startDir) == 0, nullptr);
  341. DISTRHO_SAFE_ASSERT_RETURN(x_fib_configure(1, windowTitle) == 0, nullptr);
  342. const int button1 = options.buttons.showHidden == FileBrowserOptions::kButtonVisibleChecked ? 1
  343. : options.buttons.showHidden == FileBrowserOptions::kButtonVisibleUnchecked ? 0 : -1;
  344. const int button2 = options.buttons.showPlaces == FileBrowserOptions::kButtonVisibleChecked ? 1
  345. : options.buttons.showPlaces == FileBrowserOptions::kButtonVisibleUnchecked ? 0 : -1;
  346. const int button3 = options.buttons.listAllFiles == FileBrowserOptions::kButtonVisibleChecked ? 1
  347. : options.buttons.listAllFiles == FileBrowserOptions::kButtonVisibleUnchecked ? 0 : -1;
  348. x_fib_cfg_buttons(1, button1);
  349. x_fib_cfg_buttons(2, button2);
  350. x_fib_cfg_buttons(3, button3);
  351. if (x_fib_show(x11display, windowId, 0, 0, scaleFactor + 0.5) != 0)
  352. return nullptr;
  353. #endif
  354. return handle.release();
  355. // might be unused
  356. (void)isEmbed;
  357. (void)windowId;
  358. (void)scaleFactor;
  359. }
  360. // --------------------------------------------------------------------------------------------------------------------
  361. // returns true if dialog was closed (with or without a file selection)
  362. bool fileBrowserIdle(const FileBrowserHandle handle)
  363. {
  364. #ifdef HAVE_DBUS
  365. if (DBusConnection* dbuscon = handle->dbuscon)
  366. {
  367. while (dbus_connection_dispatch(dbuscon) == DBUS_DISPATCH_DATA_REMAINS) {}
  368. dbus_connection_read_write_dispatch(dbuscon, 0);
  369. if (DBusMessage* const message = dbus_connection_pop_message(dbuscon))
  370. {
  371. const char* const interface = dbus_message_get_interface(message);
  372. const char* const member = dbus_message_get_member(message);
  373. if (interface != nullptr && std::strcmp(interface, "org.freedesktop.portal.Request") == 0
  374. && member != nullptr && std::strcmp(member, "Response") == 0)
  375. {
  376. do {
  377. DBusMessageIter iter;
  378. dbus_message_iter_init(message, &iter);
  379. // starts with uint32 for return/exit code
  380. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&iter) == DBUS_TYPE_UINT32);
  381. uint32_t ret = 1;
  382. dbus_message_iter_get_basic(&iter, &ret);
  383. if (ret != 0)
  384. break;
  385. // next must be array
  386. dbus_message_iter_next(&iter);
  387. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&iter) == DBUS_TYPE_ARRAY);
  388. // open dict array
  389. DBusMessageIter dictArray;
  390. dbus_message_iter_recurse(&iter, &dictArray);
  391. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&dictArray) == DBUS_TYPE_DICT_ENTRY);
  392. // open containing dict
  393. DBusMessageIter dict;
  394. dbus_message_iter_recurse(&dictArray, &dict);
  395. // look for dict with string "uris"
  396. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&dict) == DBUS_TYPE_STRING);
  397. const char* key = nullptr;
  398. dbus_message_iter_get_basic(&dict, &key);
  399. DISTRHO_SAFE_ASSERT_BREAK(key != nullptr);
  400. // keep going until we find it
  401. while (std::strcmp(key, "uris") != 0)
  402. {
  403. key = nullptr;
  404. dbus_message_iter_next(&dictArray);
  405. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&dictArray) == DBUS_TYPE_DICT_ENTRY);
  406. dbus_message_iter_recurse(&dictArray, &dict);
  407. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&dict) == DBUS_TYPE_STRING);
  408. dbus_message_iter_get_basic(&dict, &key);
  409. DISTRHO_SAFE_ASSERT_BREAK(key != nullptr);
  410. }
  411. if (key == nullptr)
  412. break;
  413. // then comes variant
  414. dbus_message_iter_next(&dict);
  415. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&dict) == DBUS_TYPE_VARIANT);
  416. DBusMessageIter variant;
  417. dbus_message_iter_recurse(&dict, &variant);
  418. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&variant) == DBUS_TYPE_ARRAY);
  419. // open variant array (variant type is string)
  420. DBusMessageIter variantArray;
  421. dbus_message_iter_recurse(&variant, &variantArray);
  422. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&variantArray) == DBUS_TYPE_STRING);
  423. const char* value = nullptr;
  424. dbus_message_iter_get_basic(&variantArray, &value);
  425. // and finally we have our dear value, just make sure it is local
  426. DISTRHO_SAFE_ASSERT_BREAK(value != nullptr);
  427. if (const char* const localvalue = std::strstr(value, "file:///"))
  428. handle->selectedFile = strdup(localvalue + 7);
  429. } while(false);
  430. if (handle->selectedFile == nullptr)
  431. handle->selectedFile = kSelectedFileCancelled;
  432. }
  433. }
  434. }
  435. #endif
  436. #ifdef HAVE_X11
  437. Display* const x11display = handle->x11display;
  438. if (x11display == nullptr)
  439. return false;
  440. XEvent event;
  441. while (XPending(x11display) > 0)
  442. {
  443. XNextEvent(x11display, &event);
  444. if (x_fib_handle_events(x11display, &event) == 0)
  445. continue;
  446. if (x_fib_status() > 0)
  447. handle->selectedFile = x_fib_filename();
  448. else
  449. handle->selectedFile = kSelectedFileCancelled;
  450. x_fib_close(x11display);
  451. XCloseDisplay(x11display);
  452. handle->x11display = nullptr;
  453. break;
  454. }
  455. #endif
  456. return handle->selectedFile != nullptr;
  457. }
  458. // --------------------------------------------------------------------------------------------------------------------
  459. // close sofd file dialog
  460. void fileBrowserClose(const FileBrowserHandle handle)
  461. {
  462. #ifdef HAVE_X11
  463. if (Display* const x11display = handle->x11display)
  464. x_fib_close(x11display);
  465. #endif
  466. delete handle;
  467. }
  468. // --------------------------------------------------------------------------------------------------------------------
  469. // get path chosen via sofd file dialog
  470. const char* fileBrowserGetPath(const FileBrowserHandle handle)
  471. {
  472. return handle->selectedFile != kSelectedFileCancelled ? handle->selectedFile : nullptr;
  473. }
  474. // --------------------------------------------------------------------------------------------------------------------
  475. #ifdef DISTRHO_FILE_BROWSER_DIALOG_EXTRA_NAMESPACE
  476. }
  477. #endif
  478. END_NAMESPACE_DISTRHO