The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

591 lines
19KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  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 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. namespace juce
  20. {
  21. // Win32NativeFileChooser needs to be a reference counted object as there
  22. // is no way for the parent to know when the dialog HWND has actually been
  23. // created without pumping the message thread (which is forbidden when modal
  24. // loops are disabled). However, the HWND pointer is the only way to cancel
  25. // the dialog box. This means that the actual native FileChooser HWND may
  26. // not have been created yet when the user deletes JUCE's FileChooser class. If this
  27. // occurs the Win32NativeFileChooser will still have a reference count of 1 and will
  28. // simply delete itself immedietely once the HWND will have been created a while later.
  29. class Win32NativeFileChooser : public ReferenceCountedObject,
  30. private Thread
  31. {
  32. public:
  33. using Ptr = ReferenceCountedObjectPtr<Win32NativeFileChooser>;
  34. enum { charsAvailableForResult = 32768 };
  35. Win32NativeFileChooser (Component* parent, int flags, FilePreviewComponent* previewComp,
  36. const File& startingFile, const String& titleToUse,
  37. const String& filtersToUse)
  38. : Thread ("Native Win32 FileChooser"),
  39. owner (parent), title (titleToUse), filtersString (filtersToUse),
  40. selectsDirectories ((flags & FileBrowserComponent::canSelectDirectories) != 0),
  41. selectsFiles ((flags & FileBrowserComponent::canSelectFiles) != 0),
  42. isSave ((flags & FileBrowserComponent::saveMode) != 0),
  43. warnAboutOverwrite ((flags & FileBrowserComponent::warnAboutOverwriting) != 0),
  44. selectMultiple ((flags & FileBrowserComponent::canSelectMultipleItems) != 0),
  45. nativeDialogRef (nullptr), shouldCancel (0)
  46. {
  47. auto parentDirectory = startingFile.getParentDirectory();
  48. // Handle nonexistent root directories in the same way as existing ones
  49. files.calloc (static_cast<size_t> (charsAvailableForResult) + 1);
  50. if (startingFile.isDirectory() ||startingFile.isRoot())
  51. {
  52. initialPath = startingFile.getFullPathName();
  53. }
  54. else
  55. {
  56. startingFile.getFileName().copyToUTF16 (files,
  57. static_cast<size_t> (charsAvailableForResult) * sizeof (WCHAR));
  58. initialPath = parentDirectory.getFullPathName();
  59. }
  60. if (! selectsDirectories)
  61. {
  62. if (previewComp != nullptr)
  63. customComponent.reset (new CustomComponentHolder (previewComp));
  64. setupFilters();
  65. }
  66. }
  67. ~Win32NativeFileChooser()
  68. {
  69. signalThreadShouldExit();
  70. waitForThreadToExit (-1);
  71. }
  72. void open (bool async)
  73. {
  74. results.clear();
  75. // the thread should not be running
  76. nativeDialogRef.set (nullptr);
  77. if (async)
  78. {
  79. jassert (! isThreadRunning());
  80. threadHasReference.reset();
  81. startThread();
  82. threadHasReference.wait (-1);
  83. }
  84. else
  85. {
  86. results = openDialog (false);
  87. owner->exitModalState (results.size() > 0 ? 1 : 0);
  88. }
  89. }
  90. void cancel()
  91. {
  92. ScopedLock lock (deletingDialog);
  93. customComponent = nullptr;
  94. shouldCancel.set (1);
  95. if (auto hwnd = nativeDialogRef.get())
  96. EndDialog (hwnd, 0);
  97. }
  98. Array<URL> results;
  99. private:
  100. //==============================================================================
  101. class CustomComponentHolder : public Component
  102. {
  103. public:
  104. CustomComponentHolder (Component* const customComp)
  105. {
  106. setVisible (true);
  107. setOpaque (true);
  108. addAndMakeVisible (customComp);
  109. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  110. }
  111. void paint (Graphics& g) override
  112. {
  113. g.fillAll (Colours::lightgrey);
  114. }
  115. void resized() override
  116. {
  117. if (Component* const c = getChildComponent(0))
  118. c->setBounds (getLocalBounds());
  119. }
  120. private:
  121. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponentHolder)
  122. };
  123. //==============================================================================
  124. Component::SafePointer<Component> owner;
  125. String title, filtersString;
  126. std::unique_ptr<CustomComponentHolder> customComponent;
  127. String initialPath, returnedString, defaultExtension;
  128. WaitableEvent threadHasReference;
  129. CriticalSection deletingDialog;
  130. bool selectsDirectories, selectsFiles, isSave, warnAboutOverwrite, selectMultiple;
  131. HeapBlock<WCHAR> files;
  132. HeapBlock<WCHAR> filters;
  133. Atomic<HWND> nativeDialogRef;
  134. Atomic<int> shouldCancel;
  135. //==============================================================================
  136. Array<URL> openDialog (bool async)
  137. {
  138. Array<URL> selections;
  139. if (selectsDirectories)
  140. {
  141. BROWSEINFO bi = { 0 };
  142. bi.hwndOwner = (HWND) (async ? nullptr : owner->getWindowHandle());
  143. bi.pszDisplayName = files;
  144. bi.lpszTitle = title.toWideCharPointer();
  145. bi.lParam = (LPARAM) this;
  146. bi.lpfn = browseCallbackProc;
  147. #ifdef BIF_USENEWUI
  148. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  149. #else
  150. bi.ulFlags = 0x50;
  151. #endif
  152. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  153. if (! SHGetPathFromIDListW (list, files))
  154. {
  155. files[0] = 0;
  156. returnedString.clear();
  157. }
  158. LPMALLOC al;
  159. if (list != nullptr && SUCCEEDED (SHGetMalloc (&al)))
  160. al->Free (list);
  161. if (files[0] != 0)
  162. {
  163. File result (String (files.get()));
  164. if (returnedString.isNotEmpty())
  165. result = result.getSiblingFile (returnedString);
  166. selections.add (URL (result));
  167. }
  168. }
  169. else
  170. {
  171. OPENFILENAMEW of = { 0 };
  172. #ifdef OPENFILENAME_SIZE_VERSION_400W
  173. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  174. #else
  175. of.lStructSize = sizeof (of);
  176. #endif
  177. of.hwndOwner = (HWND) (async ? nullptr : owner->getWindowHandle());
  178. of.lpstrFilter = filters.getData();
  179. of.nFilterIndex = 1;
  180. of.lpstrFile = files;
  181. of.nMaxFile = (DWORD) charsAvailableForResult;
  182. of.lpstrInitialDir = initialPath.toWideCharPointer();
  183. of.lpstrTitle = title.toWideCharPointer();
  184. of.Flags = getOpenFilenameFlags (async);
  185. of.lCustData = (LPARAM) this;
  186. of.lpfnHook = &openCallback;
  187. if (isSave)
  188. {
  189. StringArray tokens;
  190. tokens.addTokens (filtersString, ";,", "\"'");
  191. tokens.trim();
  192. tokens.removeEmptyStrings();
  193. if (tokens.size() == 1 && tokens[0].removeCharacters ("*.").isNotEmpty())
  194. {
  195. defaultExtension = tokens[0].fromFirstOccurrenceOf (".", false, false);
  196. of.lpstrDefExt = defaultExtension.toWideCharPointer();
  197. }
  198. if (! GetSaveFileName (&of))
  199. return {};
  200. }
  201. else
  202. {
  203. if (! GetOpenFileName (&of))
  204. return {};
  205. }
  206. if (selectMultiple && of.nFileOffset > 0 && files [of.nFileOffset - 1] == 0)
  207. {
  208. const WCHAR* filename = files + of.nFileOffset;
  209. while (*filename != 0)
  210. {
  211. selections.add (URL (File (String (files.get())).getChildFile (String (filename))));
  212. filename += wcslen (filename) + 1;
  213. }
  214. }
  215. else if (files[0] != 0)
  216. {
  217. selections.add (URL (File (String (files.get()))));
  218. }
  219. }
  220. getNativeDialogList().removeValue (this);
  221. return selections;
  222. }
  223. void run() override
  224. {
  225. // as long as the thread is running, don't delete this class
  226. Ptr safeThis (this);
  227. threadHasReference.signal();
  228. Array<URL> r = openDialog (true);
  229. MessageManager::callAsync ([safeThis, r]
  230. {
  231. safeThis->results = r;
  232. if (safeThis->owner != nullptr)
  233. safeThis->owner->exitModalState (r.size() > 0 ? 1 : 0);
  234. });
  235. }
  236. static HashMap<HWND, Win32NativeFileChooser*>& getNativeDialogList()
  237. {
  238. static HashMap<HWND, Win32NativeFileChooser*> dialogs;
  239. return dialogs;
  240. }
  241. static Win32NativeFileChooser* getNativePointerForDialog (HWND hWnd)
  242. {
  243. return getNativeDialogList()[hWnd];
  244. }
  245. //==============================================================================
  246. void setupFilters()
  247. {
  248. const size_t filterSpaceNumChars = 2048;
  249. filters.calloc (filterSpaceNumChars);
  250. const size_t bytesWritten = filtersString.copyToUTF16 (filters.getData(), filterSpaceNumChars * sizeof (WCHAR));
  251. filtersString.copyToUTF16 (filters + (bytesWritten / sizeof (WCHAR)),
  252. ((filterSpaceNumChars - 1) * sizeof (WCHAR) - bytesWritten));
  253. for (size_t i = 0; i < filterSpaceNumChars; ++i)
  254. if (filters[i] == '|')
  255. filters[i] = 0;
  256. }
  257. DWORD getOpenFilenameFlags (bool async)
  258. {
  259. DWORD ofFlags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY | OFN_ENABLESIZING;
  260. if (warnAboutOverwrite)
  261. ofFlags |= OFN_OVERWRITEPROMPT;
  262. if (selectMultiple)
  263. ofFlags |= OFN_ALLOWMULTISELECT;
  264. if (async || customComponent != nullptr)
  265. ofFlags |= OFN_ENABLEHOOK;
  266. return ofFlags;
  267. }
  268. //==============================================================================
  269. void initialised (HWND hWnd)
  270. {
  271. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) initialPath.toWideCharPointer());
  272. initDialog (hWnd);
  273. }
  274. void validateFailed (const String& path)
  275. {
  276. returnedString = path;
  277. }
  278. void initDialog (HWND hdlg)
  279. {
  280. ScopedLock lock (deletingDialog);
  281. getNativeDialogList().set (hdlg, this);
  282. if (shouldCancel.get() != 0)
  283. {
  284. EndDialog (hdlg, 0);
  285. }
  286. else
  287. {
  288. nativeDialogRef.set (hdlg);
  289. if (customComponent)
  290. {
  291. Component::SafePointer<Component> custom (customComponent.get());
  292. RECT r, cr;
  293. GetWindowRect (hdlg, &r);
  294. GetClientRect (hdlg, &cr);
  295. auto scale = Desktop::getInstance().getDisplays()
  296. .findDisplayForRect (Rectangle<int>::leftTopRightBottom (r.left, r.top, r.right, r.bottom), true).scale;
  297. auto componentWidth = custom->getWidth();
  298. SetWindowPos (hdlg, 0, r.left, r.top,
  299. roundToInt (componentWidth * scale) + jmax (150, (int) (r.right - r.left)),
  300. jmax (150, (int) (r.bottom - r.top)),
  301. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  302. if (MessageManager::getInstance()->isThisTheMessageThread())
  303. {
  304. custom->setBounds (roundToInt (cr.right / scale), roundToInt (cr.top / scale),
  305. componentWidth, roundToInt ((cr.bottom - cr.top) / scale));
  306. custom->addToDesktop (0, hdlg);
  307. }
  308. else
  309. {
  310. MessageManager::callAsync ([custom, cr, componentWidth, scale, hdlg]() mutable
  311. {
  312. if (custom != nullptr)
  313. {
  314. custom->setBounds (roundToInt (cr.right / scale), roundToInt (cr.top / scale),
  315. componentWidth, roundToInt ((cr.bottom - cr.top) / scale));
  316. custom->addToDesktop (0, hdlg);
  317. }
  318. });
  319. }
  320. }
  321. }
  322. }
  323. void destroyDialog (HWND hdlg)
  324. {
  325. ScopedLock exiting (deletingDialog);
  326. getNativeDialogList().remove (hdlg);
  327. nativeDialogRef.set (nullptr);
  328. 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 == 0)
  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. return targetComponent->findParentComponentOfClass<FilePreviewComponent>() != nullptr;
  457. }
  458. private:
  459. FileChooser& owner;
  460. Win32NativeFileChooser::Ptr nativeFileChooser;
  461. };
  462. //==============================================================================
  463. bool FileChooser::isPlatformDialogAvailable()
  464. {
  465. #if JUCE_DISABLE_NATIVE_FILECHOOSERS
  466. return false;
  467. #else
  468. return true;
  469. #endif
  470. }
  471. FileChooser::Pimpl* FileChooser::showPlatformDialog (FileChooser& owner, int flags,
  472. FilePreviewComponent* preview)
  473. {
  474. return new FileChooser::Native (owner, flags, preview);
  475. }
  476. } // namespace juce