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.

568 lines
19KB

  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 <vector>
  28. #else
  29. # include <unistd.h>
  30. #endif
  31. #ifdef HAVE_DBUS
  32. # include <dbus/dbus.h>
  33. #endif
  34. #ifdef HAVE_X11
  35. # define DBLCLKTME 400
  36. # include "sofd/libsofd.h"
  37. # include "sofd/libsofd.c"
  38. #endif
  39. START_NAMESPACE_DISTRHO
  40. // --------------------------------------------------------------------------------------------------------------------
  41. // static pointer used for signal null/none action taken
  42. static const char* const kSelectedFileCancelled = "__dpf_cancelled__";
  43. struct FileBrowserData {
  44. const char* selectedFile;
  45. #ifdef DISTRHO_OS_MAC
  46. NSSavePanel* nsBasePanel;
  47. NSOpenPanel* nsOpenPanel;
  48. #endif
  49. #ifdef HAVE_DBUS
  50. DBusConnection* dbuscon;
  51. #endif
  52. #ifdef HAVE_X11
  53. Display* x11display;
  54. #endif
  55. #ifdef DISTRHO_OS_WINDOWS
  56. OPENFILENAMEW ofn;
  57. volatile bool threadCancelled;
  58. uintptr_t threadHandle;
  59. std::vector<WCHAR> fileNameW;
  60. std::vector<WCHAR> startDirW;
  61. std::vector<WCHAR> titleW;
  62. const bool saving;
  63. bool isEmbed;
  64. FileBrowserData(const bool save)
  65. : selectedFile(nullptr),
  66. threadCancelled(false),
  67. threadHandle(0),
  68. fileNameW(32768),
  69. saving(save),
  70. isEmbed(false)
  71. {
  72. std::memset(&ofn, 0, sizeof(ofn));
  73. ofn.lStructSize = sizeof(ofn);
  74. ofn.lpstrFile = fileNameW.data();
  75. ofn.nMaxFile = (DWORD)fileNameW.size();
  76. }
  77. ~FileBrowserData()
  78. {
  79. if (cancelAndStop() && selectedFile != nullptr && selectedFile != kSelectedFileCancelled)
  80. std::free(const_cast<char*>(selectedFile));
  81. }
  82. void setupAndStart(const bool embed,
  83. const char* const startDir,
  84. const char* const windowTitle,
  85. const uintptr_t winId,
  86. const FileBrowserOptions options)
  87. {
  88. isEmbed = embed;
  89. ofn.hwndOwner = (HWND)winId;
  90. ofn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;
  91. if (options.buttons.showHidden == FileBrowserOptions::kButtonVisibleChecked)
  92. ofn.Flags |= OFN_FORCESHOWHIDDEN;
  93. ofn.FlagsEx = 0x0;
  94. if (options.buttons.showPlaces == FileBrowserOptions::kButtonInvisible)
  95. ofn.FlagsEx |= OFN_EX_NOPLACESBAR;
  96. startDirW.resize(std::strlen(startDir) + 1);
  97. if (MultiByteToWideChar(CP_UTF8, 0, startDir, -1, startDirW.data(), static_cast<int>(startDirW.size())))
  98. ofn.lpstrInitialDir = startDirW.data();
  99. titleW.resize(std::strlen(windowTitle) + 1);
  100. if (MultiByteToWideChar(CP_UTF8, 0, windowTitle, -1, titleW.data(), static_cast<int>(titleW.size())))
  101. ofn.lpstrTitle = titleW.data();
  102. uint threadId;
  103. threadCancelled = false;
  104. threadHandle = _beginthreadex(nullptr, 0, _run, this, 0, &threadId);
  105. }
  106. bool cancelAndStop()
  107. {
  108. threadCancelled = true;
  109. if (threadHandle == 0)
  110. return true;
  111. // if previous dialog running, carefully close its window
  112. const HWND owner = isEmbed ? GetParent(ofn.hwndOwner) : ofn.hwndOwner;
  113. if (owner != nullptr && owner != INVALID_HANDLE_VALUE)
  114. {
  115. const HWND window = GetWindow(owner, GW_HWNDFIRST);
  116. if (window != nullptr && window != INVALID_HANDLE_VALUE)
  117. {
  118. SendMessage(window, WM_SYSCOMMAND, SC_CLOSE, 0);
  119. SendMessage(window, WM_CLOSE, 0, 0);
  120. WaitForSingleObject((HANDLE)threadHandle, 5000);
  121. }
  122. }
  123. if (threadHandle == 0)
  124. return true;
  125. // not good if thread still running, but let's close the handle anyway
  126. CloseHandle((HANDLE)threadHandle);
  127. threadHandle = 0;
  128. return false;
  129. }
  130. void run()
  131. {
  132. const char* nextFile = nullptr;
  133. if (saving ? GetSaveFileNameW(&ofn) : GetOpenFileNameW(&ofn))
  134. {
  135. if (threadCancelled)
  136. {
  137. threadHandle = 0;
  138. return;
  139. }
  140. // back to UTF-8
  141. std::vector<char> fileNameA(4 * 32768);
  142. if (WideCharToMultiByte(CP_UTF8, 0, fileNameW.data(), -1,
  143. fileNameA.data(), (int)fileNameA.size(),
  144. nullptr, nullptr))
  145. {
  146. nextFile = strdup(fileNameA.data());
  147. }
  148. }
  149. if (threadCancelled)
  150. {
  151. threadHandle = 0;
  152. return;
  153. }
  154. if (nextFile == nullptr)
  155. nextFile = kSelectedFileCancelled;
  156. selectedFile = nextFile;
  157. threadHandle = 0;
  158. }
  159. static unsigned __stdcall _run(void* const arg)
  160. {
  161. // CoInitializeEx(nullptr, COINIT_MULTITHREADED);
  162. static_cast<FileBrowserData*>(arg)->run();
  163. // CoUninitialize();
  164. _endthreadex(0);
  165. return 0;
  166. }
  167. #else // DISTRHO_OS_WINDOWS
  168. FileBrowserData(const bool saving)
  169. : selectedFile(nullptr)
  170. {
  171. #ifdef DISTRHO_OS_MAC
  172. if (saving)
  173. {
  174. nsOpenPanel = nullptr;
  175. nsBasePanel = [[NSSavePanel savePanel]retain];
  176. }
  177. else
  178. {
  179. nsOpenPanel = [[NSOpenPanel openPanel]retain];
  180. nsBasePanel = nsOpenPanel;
  181. }
  182. #endif
  183. #ifdef HAVE_DBUS
  184. DBusError err;
  185. dbus_error_init(&err);
  186. if ((dbuscon = dbus_bus_get(DBUS_BUS_SESSION, &err)) != nullptr)
  187. dbus_connection_set_exit_on_disconnect(dbuscon, false);
  188. dbus_error_free(&err);
  189. #endif
  190. #ifdef HAVE_X11
  191. x11display = XOpenDisplay(nullptr);
  192. #endif
  193. // maybe unused
  194. return; (void)saving;
  195. }
  196. ~FileBrowserData()
  197. {
  198. #ifdef DISTRHO_OS_MAC
  199. [nsBasePanel release];
  200. #endif
  201. #ifdef HAVE_DBUS
  202. if (dbuscon != nullptr)
  203. dbus_connection_unref(dbuscon);
  204. #endif
  205. #ifdef HAVE_X11
  206. if (x11display != nullptr)
  207. XCloseDisplay(x11display);
  208. #endif
  209. if (selectedFile != nullptr && selectedFile != kSelectedFileCancelled)
  210. std::free(const_cast<char*>(selectedFile));
  211. }
  212. #endif
  213. };
  214. // --------------------------------------------------------------------------------------------------------------------
  215. #ifdef DISTRHO_FILE_BROWSER_DIALOG_EXTRA_NAMESPACE
  216. namespace DISTRHO_FILE_BROWSER_DIALOG_EXTRA_NAMESPACE {
  217. #endif
  218. // --------------------------------------------------------------------------------------------------------------------
  219. FileBrowserHandle fileBrowserCreate(const bool isEmbed,
  220. const uintptr_t windowId,
  221. const double scaleFactor,
  222. const FileBrowserOptions& options)
  223. {
  224. String startDir(options.startDir);
  225. if (startDir.isEmpty())
  226. {
  227. #ifdef DISTRHO_OS_WINDOWS
  228. if (char* const cwd = _getcwd(nullptr, 0))
  229. {
  230. startDir = cwd;
  231. std::free(cwd);
  232. }
  233. #else
  234. if (char* const cwd = getcwd(nullptr, 0))
  235. {
  236. startDir = cwd;
  237. std::free(cwd);
  238. }
  239. #endif
  240. }
  241. DISTRHO_SAFE_ASSERT_RETURN(startDir.isNotEmpty(), nullptr);
  242. if (! startDir.endsWith(DISTRHO_OS_SEP))
  243. startDir += DISTRHO_OS_SEP_STR;
  244. String windowTitle(options.title);
  245. if (windowTitle.isEmpty())
  246. windowTitle = "FileBrowser";
  247. ScopedPointer<FileBrowserData> handle(new FileBrowserData(options.saving));
  248. #ifdef DISTRHO_OS_MAC
  249. NSSavePanel* const nsBasePanel = handle->nsBasePanel;
  250. DISTRHO_SAFE_ASSERT_RETURN(nsBasePanel != nullptr, nullptr);
  251. if (! options.saving)
  252. {
  253. NSOpenPanel* const nsOpenPanel = handle->nsOpenPanel;
  254. DISTRHO_SAFE_ASSERT_RETURN(nsOpenPanel != nullptr, nullptr);
  255. [nsOpenPanel setAllowsMultipleSelection:NO];
  256. [nsOpenPanel setCanChooseDirectories:NO];
  257. [nsOpenPanel setCanChooseFiles:YES];
  258. }
  259. [nsBasePanel setDirectoryURL:[NSURL fileURLWithPath:[NSString stringWithUTF8String:startDir]]];
  260. // TODO file filter using allowedContentTypes: [UTType]
  261. if (options.buttons.listAllFiles == FileBrowserOptions::kButtonVisibleChecked)
  262. [nsBasePanel setAllowsOtherFileTypes:YES];
  263. if (options.buttons.showHidden == FileBrowserOptions::kButtonVisibleChecked)
  264. [nsBasePanel setShowsHiddenFiles:YES];
  265. NSString* const titleString = [[NSString alloc]
  266. initWithBytes:windowTitle
  267. length:strlen(windowTitle)
  268. encoding:NSUTF8StringEncoding];
  269. [nsBasePanel setTitle:titleString];
  270. FileBrowserData* const handleptr = handle.get();
  271. dispatch_async(dispatch_get_main_queue(), ^
  272. {
  273. [nsBasePanel beginSheetModalForWindow:[(NSView*)windowId window]
  274. completionHandler:^(NSModalResponse result)
  275. {
  276. if (result == NSModalResponseOK && [[nsBasePanel URL] isFileURL])
  277. {
  278. NSString* const path = [[nsBasePanel URL] path];
  279. handleptr->selectedFile = strdup([path UTF8String]);
  280. }
  281. else
  282. {
  283. handleptr->selectedFile = kSelectedFileCancelled;
  284. }
  285. }];
  286. });
  287. #endif
  288. #ifdef DISTRHO_OS_WINDOWS
  289. handle->setupAndStart(isEmbed, startDir, windowTitle, windowId, options);
  290. #endif
  291. #ifdef HAVE_DBUS
  292. // optional, can be null
  293. if (DBusConnection* dbuscon = handle->dbuscon)
  294. {
  295. // https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-org.freedesktop.portal.FileChooser
  296. if (DBusMessage* const message = dbus_message_new_method_call("org.freedesktop.portal.Desktop",
  297. "/org/freedesktop/portal/desktop",
  298. "org.freedesktop.portal.FileChooser",
  299. options.saving ? "SaveFile" : "OpenFile"))
  300. {
  301. char windowIdStr[32];
  302. memset(windowIdStr, 0, sizeof(windowIdStr));
  303. snprintf(windowIdStr, sizeof(windowIdStr)-1, "x11:%llx", (ulonglong)windowId);
  304. const char* windowIdStrPtr = windowIdStr;
  305. dbus_message_append_args(message,
  306. DBUS_TYPE_STRING, &windowIdStrPtr,
  307. DBUS_TYPE_STRING, &windowTitle,
  308. DBUS_TYPE_INVALID);
  309. DBusMessageIter iter, array;
  310. dbus_message_iter_init_append(message, &iter);
  311. dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &array);
  312. // here merely as example, does nothing yet
  313. {
  314. DBusMessageIter dict, variant;
  315. const char* const property = "property";
  316. const char* const value = "value";
  317. dbus_message_iter_open_container(&array, DBUS_TYPE_DICT_ENTRY, nullptr, &dict);
  318. dbus_message_iter_append_basic(&dict, DBUS_TYPE_STRING, &property);
  319. dbus_message_iter_open_container(&dict, DBUS_TYPE_VARIANT, "s", &variant);
  320. dbus_message_iter_append_basic(&variant, DBUS_TYPE_STRING, &value);
  321. dbus_message_iter_close_container(&dict, &variant);
  322. dbus_message_iter_close_container(&array, &dict);
  323. }
  324. dbus_message_iter_close_container(&iter, &array);
  325. dbus_connection_send(dbuscon, message, nullptr);
  326. dbus_message_unref(message);
  327. return handle.release();
  328. }
  329. }
  330. #endif
  331. #ifdef HAVE_X11
  332. Display* const x11display = handle->x11display;
  333. DISTRHO_SAFE_ASSERT_RETURN(x11display != nullptr, nullptr);
  334. // unsupported at the moment
  335. if (options.saving)
  336. return nullptr;
  337. DISTRHO_SAFE_ASSERT_RETURN(x_fib_configure(0, startDir) == 0, nullptr);
  338. DISTRHO_SAFE_ASSERT_RETURN(x_fib_configure(1, windowTitle) == 0, nullptr);
  339. const int button1 = options.buttons.showHidden == FileBrowserOptions::kButtonVisibleChecked ? 1
  340. : options.buttons.showHidden == FileBrowserOptions::kButtonVisibleUnchecked ? 0 : -1;
  341. const int button2 = options.buttons.showPlaces == FileBrowserOptions::kButtonVisibleChecked ? 1
  342. : options.buttons.showPlaces == FileBrowserOptions::kButtonVisibleUnchecked ? 0 : -1;
  343. const int button3 = options.buttons.listAllFiles == FileBrowserOptions::kButtonVisibleChecked ? 1
  344. : options.buttons.listAllFiles == FileBrowserOptions::kButtonVisibleUnchecked ? 0 : -1;
  345. x_fib_cfg_buttons(1, button1);
  346. x_fib_cfg_buttons(2, button2);
  347. x_fib_cfg_buttons(3, button3);
  348. if (x_fib_show(x11display, windowId, 0, 0, scaleFactor + 0.5) != 0)
  349. return nullptr;
  350. #endif
  351. return handle.release();
  352. // might be unused
  353. (void)isEmbed;
  354. (void)windowId;
  355. (void)scaleFactor;
  356. }
  357. // --------------------------------------------------------------------------------------------------------------------
  358. // returns true if dialog was closed (with or without a file selection)
  359. bool fileBrowserIdle(const FileBrowserHandle handle)
  360. {
  361. #ifdef HAVE_DBUS
  362. if (DBusConnection* dbuscon = handle->dbuscon)
  363. {
  364. while (dbus_connection_dispatch(dbuscon) == DBUS_DISPATCH_DATA_REMAINS) {}
  365. dbus_connection_read_write_dispatch(dbuscon, 0);
  366. if (DBusMessage * message = dbus_connection_pop_message(dbuscon))
  367. {
  368. const char* const interface = dbus_message_get_interface(message);
  369. const char* const member = dbus_message_get_member(message);
  370. if (interface != nullptr && std::strcmp(interface, "org.freedesktop.portal.Request") == 0
  371. && member != nullptr && std::strcmp(member, "Response") == 0)
  372. {
  373. do {
  374. DBusMessageIter iter;
  375. dbus_message_iter_init(message, &iter);
  376. // starts with uint32 for return/exit code
  377. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&iter) == DBUS_TYPE_UINT32);
  378. uint32_t ret = 1;
  379. dbus_message_iter_get_basic(&iter, &ret);
  380. if (ret != 0)
  381. break;
  382. // next must be array
  383. dbus_message_iter_next(&iter);
  384. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&iter) == DBUS_TYPE_ARRAY);
  385. // open dict array
  386. DBusMessageIter dictArray;
  387. dbus_message_iter_recurse(&iter, &dictArray);
  388. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&dictArray) == DBUS_TYPE_DICT_ENTRY);
  389. // open containing dict
  390. DBusMessageIter dict;
  391. dbus_message_iter_recurse(&dictArray, &dict);
  392. // start with the string "uris"
  393. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&dict) == DBUS_TYPE_STRING);
  394. const char* key = nullptr;
  395. dbus_message_iter_get_basic(&dict, &key);
  396. DISTRHO_SAFE_ASSERT_BREAK(key != nullptr && std::strcmp(key, "uris") == 0);
  397. // then comes variant
  398. dbus_message_iter_next(&dict);
  399. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&dict) == DBUS_TYPE_VARIANT);
  400. DBusMessageIter variant;
  401. dbus_message_iter_recurse(&dict, &variant);
  402. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&variant) == DBUS_TYPE_ARRAY);
  403. // open variant array (variant type is string)
  404. DBusMessageIter variantArray;
  405. dbus_message_iter_recurse(&variant, &variantArray);
  406. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&variantArray) == DBUS_TYPE_STRING);
  407. const char* value = nullptr;
  408. dbus_message_iter_get_basic(&variantArray, &value);
  409. // and finally we have our dear value, just make sure it is local
  410. DISTRHO_SAFE_ASSERT_BREAK(value != nullptr);
  411. if (const char* const localvalue = std::strstr(value, "file:///"))
  412. handle->selectedFile = strdup(localvalue + 7);
  413. } while(false);
  414. if (handle->selectedFile == nullptr)
  415. handle->selectedFile = kSelectedFileCancelled;
  416. }
  417. }
  418. }
  419. #endif
  420. #ifdef HAVE_X11
  421. Display* const x11display = handle->x11display;
  422. if (x11display == nullptr)
  423. return false;
  424. XEvent event;
  425. while (XPending(x11display) > 0)
  426. {
  427. XNextEvent(x11display, &event);
  428. if (x_fib_handle_events(x11display, &event) == 0)
  429. continue;
  430. if (x_fib_status() > 0)
  431. handle->selectedFile = x_fib_filename();
  432. else
  433. handle->selectedFile = kSelectedFileCancelled;
  434. x_fib_close(x11display);
  435. XCloseDisplay(x11display);
  436. handle->x11display = nullptr;
  437. break;
  438. }
  439. #endif
  440. return handle->selectedFile != nullptr;
  441. }
  442. // --------------------------------------------------------------------------------------------------------------------
  443. // close sofd file dialog
  444. void fileBrowserClose(const FileBrowserHandle handle)
  445. {
  446. #ifdef HAVE_X11
  447. if (Display* const x11display = handle->x11display)
  448. x_fib_close(x11display);
  449. #endif
  450. delete handle;
  451. }
  452. // --------------------------------------------------------------------------------------------------------------------
  453. // get path chosen via sofd file dialog
  454. const char* fileBrowserGetPath(const FileBrowserHandle handle)
  455. {
  456. return handle->selectedFile != kSelectedFileCancelled ? handle->selectedFile : nullptr;
  457. }
  458. // --------------------------------------------------------------------------------------------------------------------
  459. #ifdef DISTRHO_FILE_BROWSER_DIALOG_EXTRA_NAMESPACE
  460. }
  461. #endif
  462. END_NAMESPACE_DISTRHO