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.

565 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 (dbuscon != nullptr)
  203. dbus_connection_unref(dbuscon);
  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. if (DBusConnection* dbuscon = handle->dbuscon)
  292. {
  293. if (DBusMessage* const message = dbus_message_new_method_call("org.freedesktop.portal.Desktop",
  294. "/org/freedesktop/portal/desktop",
  295. "org.freedesktop.portal.FileChooser",
  296. options.saving ? "SaveFile" : "OpenFile"))
  297. {
  298. char windowIdStr[32];
  299. memset(windowIdStr, 0, sizeof(windowIdStr));
  300. snprintf(windowIdStr, sizeof(windowIdStr)-1, "x11:%llx", (ulonglong)windowId);
  301. const char* windowIdStrPtr = windowIdStr;
  302. dbus_message_append_args(message,
  303. DBUS_TYPE_STRING, &windowIdStrPtr,
  304. DBUS_TYPE_STRING, &windowTitle,
  305. DBUS_TYPE_INVALID);
  306. DBusMessageIter iter, array;
  307. dbus_message_iter_init_append(message, &iter);
  308. dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &array);
  309. // here merely as example, does nothing yet
  310. {
  311. DBusMessageIter dict, variant;
  312. const char* const property = "property";
  313. const char* const value = "value";
  314. dbus_message_iter_open_container(&array, DBUS_TYPE_DICT_ENTRY, nullptr, &dict);
  315. dbus_message_iter_append_basic(&dict, DBUS_TYPE_STRING, &property);
  316. dbus_message_iter_open_container(&dict, DBUS_TYPE_VARIANT, "s", &variant);
  317. dbus_message_iter_append_basic(&variant, DBUS_TYPE_STRING, &value);
  318. dbus_message_iter_close_container(&dict, &variant);
  319. dbus_message_iter_close_container(&array, &dict);
  320. }
  321. dbus_message_iter_close_container(&iter, &array);
  322. dbus_connection_send(dbuscon, message, nullptr);
  323. dbus_message_unref(message);
  324. return handle.release();
  325. }
  326. }
  327. #endif
  328. #ifdef HAVE_X11
  329. Display* const x11display = handle->x11display;
  330. DISTRHO_SAFE_ASSERT_RETURN(x11display != nullptr, nullptr);
  331. // unsupported at the moment
  332. if (options.saving)
  333. return nullptr;
  334. DISTRHO_SAFE_ASSERT_RETURN(x_fib_configure(0, startDir) == 0, nullptr);
  335. DISTRHO_SAFE_ASSERT_RETURN(x_fib_configure(1, windowTitle) == 0, nullptr);
  336. const int button1 = options.buttons.showHidden == FileBrowserOptions::kButtonVisibleChecked ? 1
  337. : options.buttons.showHidden == FileBrowserOptions::kButtonVisibleUnchecked ? 0 : -1;
  338. const int button2 = options.buttons.showPlaces == FileBrowserOptions::kButtonVisibleChecked ? 1
  339. : options.buttons.showPlaces == FileBrowserOptions::kButtonVisibleUnchecked ? 0 : -1;
  340. const int button3 = options.buttons.listAllFiles == FileBrowserOptions::kButtonVisibleChecked ? 1
  341. : options.buttons.listAllFiles == FileBrowserOptions::kButtonVisibleUnchecked ? 0 : -1;
  342. x_fib_cfg_buttons(1, button1);
  343. x_fib_cfg_buttons(2, button2);
  344. x_fib_cfg_buttons(3, button3);
  345. if (x_fib_show(x11display, windowId, 0, 0, scaleFactor + 0.5) != 0)
  346. return nullptr;
  347. #endif
  348. return handle.release();
  349. // might be unused
  350. (void)isEmbed;
  351. (void)windowId;
  352. (void)scaleFactor;
  353. }
  354. // --------------------------------------------------------------------------------------------------------------------
  355. // returns true if dialog was closed (with or without a file selection)
  356. bool fileBrowserIdle(const FileBrowserHandle handle)
  357. {
  358. #ifdef HAVE_DBUS
  359. if (DBusConnection* dbuscon = handle->dbuscon)
  360. {
  361. while (dbus_connection_dispatch(dbuscon) == DBUS_DISPATCH_DATA_REMAINS) {}
  362. dbus_connection_read_write_dispatch(dbuscon, 0);
  363. if (DBusMessage * message = dbus_connection_pop_message(dbuscon))
  364. {
  365. const char* const interface = dbus_message_get_interface(message);
  366. const char* const member = dbus_message_get_member(message);
  367. if (interface != nullptr && std::strcmp(interface, "org.freedesktop.portal.Request") == 0
  368. && member != nullptr && std::strcmp(member, "Response") == 0)
  369. {
  370. do {
  371. DBusMessageIter iter;
  372. dbus_message_iter_init(message, &iter);
  373. // starts with uint32 for return/exit code
  374. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&iter) == DBUS_TYPE_UINT32);
  375. uint32_t ret = 1;
  376. dbus_message_iter_get_basic(&iter, &ret);
  377. if (ret != 0)
  378. break;
  379. // next must be array
  380. dbus_message_iter_next(&iter);
  381. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&iter) == DBUS_TYPE_ARRAY);
  382. // open dict array
  383. DBusMessageIter dictArray;
  384. dbus_message_iter_recurse(&iter, &dictArray);
  385. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&dictArray) == DBUS_TYPE_DICT_ENTRY);
  386. // open containing dict
  387. DBusMessageIter dict;
  388. dbus_message_iter_recurse(&dictArray, &dict);
  389. // start with the string "uris"
  390. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&dict) == DBUS_TYPE_STRING);
  391. const char* key = nullptr;
  392. dbus_message_iter_get_basic(&dict, &key);
  393. DISTRHO_SAFE_ASSERT_BREAK(key != nullptr && std::strcmp(key, "uris") == 0);
  394. // then comes variant
  395. dbus_message_iter_next(&dict);
  396. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&dict) == DBUS_TYPE_VARIANT);
  397. DBusMessageIter variant;
  398. dbus_message_iter_recurse(&dict, &variant);
  399. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&variant) == DBUS_TYPE_ARRAY);
  400. // open variant array (variant type is string)
  401. DBusMessageIter variantArray;
  402. dbus_message_iter_recurse(&variant, &variantArray);
  403. DISTRHO_SAFE_ASSERT_BREAK(dbus_message_iter_get_arg_type(&variantArray) == DBUS_TYPE_STRING);
  404. const char* value = nullptr;
  405. dbus_message_iter_get_basic(&variantArray, &value);
  406. // and finally we have our dear value, just make sure it is local
  407. DISTRHO_SAFE_ASSERT_BREAK(value != nullptr);
  408. if (const char* const localvalue = std::strstr(value, "file:///"))
  409. handle->selectedFile = strdup(localvalue + 7);
  410. } while(false);
  411. if (handle->selectedFile == nullptr)
  412. handle->selectedFile = kSelectedFileCancelled;
  413. }
  414. }
  415. }
  416. #endif
  417. #ifdef HAVE_X11
  418. Display* const x11display = handle->x11display;
  419. if (x11display == nullptr)
  420. return false;
  421. XEvent event;
  422. while (XPending(x11display) > 0)
  423. {
  424. XNextEvent(x11display, &event);
  425. if (x_fib_handle_events(x11display, &event) == 0)
  426. continue;
  427. if (x_fib_status() > 0)
  428. handle->selectedFile = x_fib_filename();
  429. else
  430. handle->selectedFile = kSelectedFileCancelled;
  431. x_fib_close(x11display);
  432. XCloseDisplay(x11display);
  433. handle->x11display = nullptr;
  434. break;
  435. }
  436. #endif
  437. return handle->selectedFile != nullptr;
  438. }
  439. // --------------------------------------------------------------------------------------------------------------------
  440. // close sofd file dialog
  441. void fileBrowserClose(const FileBrowserHandle handle)
  442. {
  443. #ifdef HAVE_X11
  444. if (Display* const x11display = handle->x11display)
  445. x_fib_close(x11display);
  446. #endif
  447. delete handle;
  448. }
  449. // --------------------------------------------------------------------------------------------------------------------
  450. // get path chosen via sofd file dialog
  451. const char* fileBrowserGetPath(const FileBrowserHandle handle)
  452. {
  453. return handle->selectedFile != kSelectedFileCancelled ? handle->selectedFile : nullptr;
  454. }
  455. // --------------------------------------------------------------------------------------------------------------------
  456. #ifdef DISTRHO_FILE_BROWSER_DIALOG_EXTRA_NAMESPACE
  457. }
  458. #endif
  459. END_NAMESPACE_DISTRHO