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.

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