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.

543 lines
18KB

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