Audio plugin host https://kx.studio/carla
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.

598 lines
20KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. namespace juce
  19. {
  20. // Win32NativeFileChooser needs to be a reference counted object as there
  21. // is no way for the parent to know when the dialog HWND has actually been
  22. // created without pumping the message thread (which is forbidden when modal
  23. // loops are disabled). However, the HWND pointer is the only way to cancel
  24. // the dialog box. This means that the actual native FileChooser HWND may
  25. // not have been created yet when the user deletes JUCE's FileChooser class. If this
  26. // occurs the Win32NativeFileChooser will still have a reference count of 1 and will
  27. // simply delete itself immediately once the HWND will have been created a while later.
  28. class Win32NativeFileChooser : public ReferenceCountedObject,
  29. private Thread
  30. {
  31. public:
  32. using Ptr = ReferenceCountedObjectPtr<Win32NativeFileChooser>;
  33. enum { charsAvailableForResult = 32768 };
  34. Win32NativeFileChooser (Component* parent, int flags, FilePreviewComponent* previewComp,
  35. const File& startingFile, const String& titleToUse,
  36. const String& filtersToUse)
  37. : Thread ("Native Win32 FileChooser"),
  38. owner (parent), title (titleToUse), filtersString (filtersToUse),
  39. selectsDirectories ((flags & FileBrowserComponent::canSelectDirectories) != 0),
  40. isSave ((flags & FileBrowserComponent::saveMode) != 0),
  41. warnAboutOverwrite ((flags & FileBrowserComponent::warnAboutOverwriting) != 0),
  42. selectMultiple ((flags & FileBrowserComponent::canSelectMultipleItems) != 0),
  43. nativeDialogRef (nullptr), shouldCancel (0)
  44. {
  45. auto parentDirectory = startingFile.getParentDirectory();
  46. // Handle nonexistent root directories in the same way as existing ones
  47. files.calloc (static_cast<size_t> (charsAvailableForResult) + 1);
  48. if (startingFile.isDirectory() ||startingFile.isRoot())
  49. {
  50. initialPath = startingFile.getFullPathName();
  51. }
  52. else
  53. {
  54. startingFile.getFileName().copyToUTF16 (files,
  55. static_cast<size_t> (charsAvailableForResult) * sizeof (WCHAR));
  56. initialPath = parentDirectory.getFullPathName();
  57. }
  58. if (! selectsDirectories)
  59. {
  60. if (previewComp != nullptr)
  61. customComponent.reset (new CustomComponentHolder (previewComp));
  62. setupFilters();
  63. }
  64. }
  65. ~Win32NativeFileChooser()
  66. {
  67. signalThreadShouldExit();
  68. waitForThreadToExit (-1);
  69. }
  70. void open (bool async)
  71. {
  72. results.clear();
  73. // the thread should not be running
  74. nativeDialogRef.set (nullptr);
  75. if (async)
  76. {
  77. jassert (! isThreadRunning());
  78. threadHasReference.reset();
  79. startThread();
  80. threadHasReference.wait (-1);
  81. }
  82. else
  83. {
  84. results = openDialog (false);
  85. owner->exitModalState (results.size() > 0 ? 1 : 0);
  86. }
  87. }
  88. void cancel()
  89. {
  90. ScopedLock lock (deletingDialog);
  91. customComponent = nullptr;
  92. shouldCancel.set (1);
  93. if (auto hwnd = nativeDialogRef.get())
  94. EndDialog (hwnd, 0);
  95. }
  96. Component* getCustomComponent() { return customComponent.get(); }
  97. Array<URL> results;
  98. private:
  99. //==============================================================================
  100. class CustomComponentHolder : public Component
  101. {
  102. public:
  103. CustomComponentHolder (Component* const customComp)
  104. {
  105. setVisible (true);
  106. setOpaque (true);
  107. addAndMakeVisible (customComp);
  108. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  109. }
  110. void paint (Graphics& g) override
  111. {
  112. g.fillAll (Colours::lightgrey);
  113. }
  114. void resized() override
  115. {
  116. if (Component* const c = getChildComponent(0))
  117. c->setBounds (getLocalBounds());
  118. }
  119. private:
  120. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponentHolder)
  121. };
  122. //==============================================================================
  123. Component::SafePointer<Component> owner;
  124. String title, filtersString;
  125. std::unique_ptr<CustomComponentHolder> customComponent;
  126. String initialPath, returnedString, defaultExtension;
  127. WaitableEvent threadHasReference;
  128. CriticalSection deletingDialog;
  129. bool selectsDirectories, isSave, warnAboutOverwrite, selectMultiple;
  130. HeapBlock<WCHAR> files;
  131. HeapBlock<WCHAR> filters;
  132. Atomic<HWND> nativeDialogRef;
  133. Atomic<int> shouldCancel;
  134. //==============================================================================
  135. Array<URL> openDialog (bool async)
  136. {
  137. Array<URL> selections;
  138. if (selectsDirectories)
  139. {
  140. BROWSEINFO bi = {};
  141. bi.hwndOwner = (HWND) (async ? nullptr : owner->getWindowHandle());
  142. bi.pszDisplayName = files;
  143. bi.lpszTitle = title.toWideCharPointer();
  144. bi.lParam = (LPARAM) this;
  145. bi.lpfn = browseCallbackProc;
  146. #ifdef BIF_USENEWUI
  147. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  148. #else
  149. bi.ulFlags = 0x50;
  150. #endif
  151. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  152. if (! SHGetPathFromIDListW (list, files))
  153. {
  154. files[0] = 0;
  155. returnedString.clear();
  156. }
  157. LPMALLOC al;
  158. if (list != nullptr && SUCCEEDED (SHGetMalloc (&al)))
  159. al->Free (list);
  160. if (files[0] != 0)
  161. {
  162. File result (String (files.get()));
  163. if (returnedString.isNotEmpty())
  164. result = result.getSiblingFile (returnedString);
  165. selections.add (URL (result));
  166. }
  167. }
  168. else
  169. {
  170. OPENFILENAMEW of = {};
  171. #ifdef OPENFILENAME_SIZE_VERSION_400W
  172. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  173. #else
  174. of.lStructSize = sizeof (of);
  175. #endif
  176. of.hwndOwner = (HWND) (async ? nullptr : owner->getWindowHandle());
  177. of.lpstrFilter = filters.getData();
  178. of.nFilterIndex = 1;
  179. of.lpstrFile = files;
  180. of.nMaxFile = (DWORD) charsAvailableForResult;
  181. of.lpstrInitialDir = initialPath.toWideCharPointer();
  182. of.lpstrTitle = title.toWideCharPointer();
  183. of.Flags = getOpenFilenameFlags (async);
  184. of.lCustData = (LPARAM) this;
  185. of.lpfnHook = &openCallback;
  186. if (isSave)
  187. {
  188. StringArray tokens;
  189. tokens.addTokens (filtersString, ";,", "\"'");
  190. tokens.trim();
  191. tokens.removeEmptyStrings();
  192. if (tokens.size() == 1 && tokens[0].removeCharacters ("*.").isNotEmpty())
  193. {
  194. defaultExtension = tokens[0].fromFirstOccurrenceOf (".", false, false);
  195. of.lpstrDefExt = defaultExtension.toWideCharPointer();
  196. }
  197. if (! GetSaveFileName (&of))
  198. return {};
  199. }
  200. else
  201. {
  202. if (! GetOpenFileName (&of))
  203. return {};
  204. }
  205. if (selectMultiple && of.nFileOffset > 0 && files [of.nFileOffset - 1] == 0)
  206. {
  207. const WCHAR* filename = files + of.nFileOffset;
  208. while (*filename != 0)
  209. {
  210. selections.add (URL (File (String (files.get())).getChildFile (String (filename))));
  211. filename += wcslen (filename) + 1;
  212. }
  213. }
  214. else if (files[0] != 0)
  215. {
  216. selections.add (URL (File (String (files.get()))));
  217. }
  218. }
  219. getNativeDialogList().removeValue (this);
  220. return selections;
  221. }
  222. void run() override
  223. {
  224. // as long as the thread is running, don't delete this class
  225. Ptr safeThis (this);
  226. threadHasReference.signal();
  227. Array<URL> r = openDialog (true);
  228. MessageManager::callAsync ([safeThis, r]
  229. {
  230. safeThis->results = r;
  231. if (safeThis->owner != nullptr)
  232. safeThis->owner->exitModalState (r.size() > 0 ? 1 : 0);
  233. });
  234. }
  235. static HashMap<HWND, Win32NativeFileChooser*>& getNativeDialogList()
  236. {
  237. static HashMap<HWND, Win32NativeFileChooser*> dialogs;
  238. return dialogs;
  239. }
  240. static Win32NativeFileChooser* getNativePointerForDialog (HWND hWnd)
  241. {
  242. return getNativeDialogList()[hWnd];
  243. }
  244. //==============================================================================
  245. void setupFilters()
  246. {
  247. const size_t filterSpaceNumChars = 2048;
  248. filters.calloc (filterSpaceNumChars);
  249. const size_t bytesWritten = filtersString.copyToUTF16 (filters.getData(), filterSpaceNumChars * sizeof (WCHAR));
  250. filtersString.copyToUTF16 (filters + (bytesWritten / sizeof (WCHAR)),
  251. ((filterSpaceNumChars - 1) * sizeof (WCHAR) - bytesWritten));
  252. for (size_t i = 0; i < filterSpaceNumChars; ++i)
  253. if (filters[i] == '|')
  254. filters[i] = 0;
  255. }
  256. DWORD getOpenFilenameFlags (bool async)
  257. {
  258. DWORD ofFlags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY | OFN_ENABLESIZING;
  259. if (warnAboutOverwrite)
  260. ofFlags |= OFN_OVERWRITEPROMPT;
  261. if (selectMultiple)
  262. ofFlags |= OFN_ALLOWMULTISELECT;
  263. if (async || customComponent != nullptr)
  264. ofFlags |= OFN_ENABLEHOOK;
  265. return ofFlags;
  266. }
  267. //==============================================================================
  268. void initialised (HWND hWnd)
  269. {
  270. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) initialPath.toWideCharPointer());
  271. initDialog (hWnd);
  272. }
  273. void validateFailed (const String& path)
  274. {
  275. returnedString = path;
  276. }
  277. void initDialog (HWND hdlg)
  278. {
  279. ScopedLock lock (deletingDialog);
  280. getNativeDialogList().set (hdlg, this);
  281. if (shouldCancel.get() != 0)
  282. {
  283. EndDialog (hdlg, 0);
  284. }
  285. else
  286. {
  287. nativeDialogRef.set (hdlg);
  288. if (customComponent != nullptr)
  289. {
  290. Component::SafePointer<Component> safeCustomComponent (customComponent.get());
  291. RECT dialogScreenRect, dialogClientRect;
  292. GetWindowRect (hdlg, &dialogScreenRect);
  293. GetClientRect (hdlg, &dialogClientRect);
  294. auto screenRectangle = Rectangle<int>::leftTopRightBottom (dialogScreenRect.left, dialogScreenRect.top,
  295. dialogScreenRect.right, dialogScreenRect.bottom);
  296. auto scale = Desktop::getInstance().getDisplays().findDisplayForRect (screenRectangle, true).scale;
  297. auto physicalComponentWidth = roundToInt (safeCustomComponent->getWidth() * scale);
  298. SetWindowPos (hdlg, nullptr, screenRectangle.getX(), screenRectangle.getY(),
  299. physicalComponentWidth + jmax (150, screenRectangle.getWidth()),
  300. jmax (150, screenRectangle.getHeight()),
  301. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  302. auto appendCustomComponent = [safeCustomComponent, dialogClientRect, scale, hdlg]() mutable
  303. {
  304. if (safeCustomComponent != nullptr)
  305. {
  306. auto scaledClientRectangle = Rectangle<int>::leftTopRightBottom (dialogClientRect.left, dialogClientRect.top,
  307. dialogClientRect.right, dialogClientRect.bottom) / scale;
  308. safeCustomComponent->setBounds (scaledClientRectangle.getRight(), scaledClientRectangle.getY(),
  309. safeCustomComponent->getWidth(), scaledClientRectangle.getHeight());
  310. safeCustomComponent->addToDesktop (0, hdlg);
  311. }
  312. };
  313. if (MessageManager::getInstance()->isThisTheMessageThread())
  314. appendCustomComponent();
  315. else
  316. MessageManager::callAsync (appendCustomComponent);
  317. }
  318. }
  319. }
  320. void destroyDialog (HWND hdlg)
  321. {
  322. ScopedLock exiting (deletingDialog);
  323. getNativeDialogList().remove (hdlg);
  324. nativeDialogRef.set (nullptr);
  325. if (MessageManager::getInstance()->isThisTheMessageThread())
  326. customComponent = nullptr;
  327. else
  328. MessageManager::callAsync ([this] { customComponent = nullptr; });
  329. }
  330. void selectionChanged (HWND hdlg)
  331. {
  332. ScopedLock lock (deletingDialog);
  333. if (customComponent != nullptr && shouldCancel.get() == 0)
  334. {
  335. if (FilePreviewComponent* comp = dynamic_cast<FilePreviewComponent*> (customComponent->getChildComponent(0)))
  336. {
  337. WCHAR path [MAX_PATH * 2] = { 0 };
  338. CommDlg_OpenSave_GetFilePath (hdlg, (LPARAM) &path, MAX_PATH);
  339. if (MessageManager::getInstance()->isThisTheMessageThread())
  340. {
  341. comp->selectedFileChanged (File (path));
  342. }
  343. else
  344. {
  345. Component::SafePointer<FilePreviewComponent> safeComp (comp);
  346. File selectedFile (path);
  347. MessageManager::callAsync ([safeComp, selectedFile]() mutable
  348. {
  349. safeComp->selectedFileChanged (selectedFile);
  350. });
  351. }
  352. }
  353. }
  354. }
  355. //==============================================================================
  356. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  357. {
  358. auto* self = reinterpret_cast<Win32NativeFileChooser*> (lpData);
  359. switch (msg)
  360. {
  361. case BFFM_INITIALIZED: self->initialised (hWnd); break;
  362. case BFFM_VALIDATEFAILEDW: self->validateFailed (String ((LPCWSTR) lParam)); break;
  363. case BFFM_VALIDATEFAILEDA: self->validateFailed (String ((const char*) lParam)); break;
  364. default: break;
  365. }
  366. return 0;
  367. }
  368. static UINT_PTR CALLBACK openCallback (HWND hwnd, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  369. {
  370. auto hdlg = getDialogFromHWND (hwnd);
  371. switch (uiMsg)
  372. {
  373. case WM_INITDIALOG:
  374. {
  375. if (auto* self = reinterpret_cast<Win32NativeFileChooser*> (((OPENFILENAMEW*) lParam)->lCustData))
  376. self->initDialog (hdlg);
  377. break;
  378. }
  379. case WM_DESTROY:
  380. {
  381. if (auto* self = getNativeDialogList()[hdlg])
  382. self->destroyDialog (hdlg);
  383. break;
  384. }
  385. case WM_NOTIFY:
  386. {
  387. auto ofn = reinterpret_cast<LPOFNOTIFY> (lParam);
  388. if (ofn->hdr.code == CDN_SELCHANGE)
  389. if (auto* self = reinterpret_cast<Win32NativeFileChooser*> (ofn->lpOFN->lCustData))
  390. self->selectionChanged (hdlg);
  391. break;
  392. }
  393. default:
  394. break;
  395. }
  396. return 0;
  397. }
  398. static HWND getDialogFromHWND (HWND hwnd)
  399. {
  400. if (hwnd == nullptr)
  401. return nullptr;
  402. HWND dialogH = GetParent (hwnd);
  403. if (dialogH == nullptr)
  404. dialogH = hwnd;
  405. return dialogH;
  406. }
  407. //==============================================================================
  408. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Win32NativeFileChooser)
  409. };
  410. class FileChooser::Native : public Component,
  411. public FileChooser::Pimpl
  412. {
  413. public:
  414. Native (FileChooser& fileChooser, int flags, FilePreviewComponent* previewComp)
  415. : owner (fileChooser),
  416. nativeFileChooser (new Win32NativeFileChooser (this, flags, previewComp, fileChooser.startingFile,
  417. fileChooser.title, fileChooser.filters))
  418. {
  419. auto mainMon = Desktop::getInstance().getDisplays().getMainDisplay().userArea;
  420. setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  421. mainMon.getY() + mainMon.getHeight() / 4,
  422. 0, 0);
  423. setOpaque (true);
  424. setAlwaysOnTop (juce_areThereAnyAlwaysOnTopWindows());
  425. addToDesktop (0);
  426. }
  427. ~Native()
  428. {
  429. exitModalState (0);
  430. nativeFileChooser->cancel();
  431. nativeFileChooser = nullptr;
  432. }
  433. void launch() override
  434. {
  435. SafePointer<Native> safeThis (this);
  436. enterModalState (true, ModalCallbackFunction::create (
  437. [safeThis] (int)
  438. {
  439. if (safeThis != nullptr)
  440. safeThis->owner.finished (safeThis->nativeFileChooser->results);
  441. }));
  442. nativeFileChooser->open (true);
  443. }
  444. void runModally() override
  445. {
  446. enterModalState (true);
  447. nativeFileChooser->open (false);
  448. exitModalState (nativeFileChooser->results.size() > 0 ? 1 : 0);
  449. nativeFileChooser->cancel();
  450. owner.finished (nativeFileChooser->results);
  451. }
  452. bool canModalEventBeSentToComponent (const Component* targetComponent) override
  453. {
  454. if (targetComponent == nullptr)
  455. return false;
  456. if (targetComponent == nativeFileChooser->getCustomComponent())
  457. return true;
  458. return targetComponent->findParentComponentOfClass<FilePreviewComponent>() != nullptr;
  459. }
  460. private:
  461. FileChooser& owner;
  462. Win32NativeFileChooser::Ptr nativeFileChooser;
  463. };
  464. //==============================================================================
  465. bool FileChooser::isPlatformDialogAvailable()
  466. {
  467. #if JUCE_DISABLE_NATIVE_FILECHOOSERS
  468. return false;
  469. #else
  470. return true;
  471. #endif
  472. }
  473. FileChooser::Pimpl* FileChooser::showPlatformDialog (FileChooser& owner, int flags,
  474. FilePreviewComponent* preview)
  475. {
  476. return new FileChooser::Native (owner, flags, preview);
  477. }
  478. } // namespace juce