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.

578 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 componentWidth = custom->getWidth();
  296. SetWindowPos (hdlg, 0,
  297. r.left, r.top,
  298. componentWidth + jmax (150, (int) (r.right - r.left)),
  299. jmax (150, (int) (r.bottom - r.top)),
  300. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  301. if (MessageManager::getInstance()->isThisTheMessageThread())
  302. {
  303. custom->setBounds (cr.right, cr.top, componentWidth, cr.bottom - cr.top);
  304. custom->addToDesktop (0, hdlg);
  305. }
  306. else
  307. {
  308. MessageManager::callAsync ([custom, cr, componentWidth, hdlg]() mutable
  309. {
  310. if (custom != nullptr)
  311. {
  312. custom->setBounds (cr.right, cr.top, componentWidth, cr.bottom - cr.top);
  313. custom->addToDesktop (0, hdlg);
  314. }
  315. });
  316. }
  317. }
  318. }
  319. }
  320. void destroyDialog (HWND hdlg)
  321. {
  322. ScopedLock exiting (deletingDialog);
  323. getNativeDialogList().remove (hdlg);
  324. nativeDialogRef.set (nullptr);
  325. }
  326. void selectionChanged (HWND hdlg)
  327. {
  328. ScopedLock lock (deletingDialog);
  329. if (customComponent != nullptr && shouldCancel.get() == 0)
  330. {
  331. if (FilePreviewComponent* comp = dynamic_cast<FilePreviewComponent*> (customComponent->getChildComponent(0)))
  332. {
  333. WCHAR path [MAX_PATH * 2] = { 0 };
  334. CommDlg_OpenSave_GetFilePath (hdlg, (LPARAM) &path, MAX_PATH);
  335. if (MessageManager::getInstance()->isThisTheMessageThread())
  336. {
  337. comp->selectedFileChanged (File (path));
  338. }
  339. else
  340. {
  341. Component::SafePointer<FilePreviewComponent> safeComp (comp);
  342. File selectedFile (path);
  343. MessageManager::callAsync ([safeComp, selectedFile]() mutable
  344. {
  345. safeComp->selectedFileChanged (selectedFile);
  346. });
  347. }
  348. }
  349. }
  350. }
  351. //==============================================================================
  352. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  353. {
  354. auto* self = reinterpret_cast<Win32NativeFileChooser*> (lpData);
  355. switch (msg)
  356. {
  357. case BFFM_INITIALIZED: self->initialised (hWnd); break;
  358. case BFFM_VALIDATEFAILEDW: self->validateFailed (String ((LPCWSTR) lParam)); break;
  359. case BFFM_VALIDATEFAILEDA: self->validateFailed (String ((const char*) lParam)); break;
  360. default: break;
  361. }
  362. return 0;
  363. }
  364. static UINT_PTR CALLBACK openCallback (HWND hwnd, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  365. {
  366. auto hdlg = getDialogFromHWND (hwnd);
  367. switch (uiMsg)
  368. {
  369. case WM_INITDIALOG:
  370. {
  371. if (auto* self = reinterpret_cast<Win32NativeFileChooser*> (((OPENFILENAMEW*) lParam)->lCustData))
  372. self->initDialog (hdlg);
  373. break;
  374. }
  375. case WM_DESTROY:
  376. {
  377. if (auto* self = getNativeDialogList()[hdlg])
  378. self->destroyDialog (hdlg);
  379. break;
  380. }
  381. case WM_NOTIFY:
  382. {
  383. auto ofn = reinterpret_cast<LPOFNOTIFY> (lParam);
  384. if (ofn->hdr.code == CDN_SELCHANGE)
  385. if (auto* self = reinterpret_cast<Win32NativeFileChooser*> (ofn->lpOFN->lCustData))
  386. self->selectionChanged (hdlg);
  387. break;
  388. }
  389. default:
  390. break;
  391. }
  392. return 0;
  393. }
  394. static HWND getDialogFromHWND (HWND hwnd)
  395. {
  396. if (hwnd == nullptr)
  397. return nullptr;
  398. HWND dialogH = GetParent (hwnd);
  399. if (dialogH == 0)
  400. dialogH = hwnd;
  401. return dialogH;
  402. }
  403. //==============================================================================
  404. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Win32NativeFileChooser)
  405. };
  406. class FileChooser::Native : public Component,
  407. public FileChooser::Pimpl
  408. {
  409. public:
  410. Native (FileChooser& fileChooser, int flags, FilePreviewComponent* previewComp)
  411. : owner (fileChooser),
  412. nativeFileChooser (new Win32NativeFileChooser (this, flags, previewComp, fileChooser.startingFile,
  413. fileChooser.title, fileChooser.filters))
  414. {
  415. auto mainMon = Desktop::getInstance().getDisplays().getMainDisplay().userArea;
  416. setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  417. mainMon.getY() + mainMon.getHeight() / 4,
  418. 0, 0);
  419. setOpaque (true);
  420. setAlwaysOnTop (juce_areThereAnyAlwaysOnTopWindows());
  421. addToDesktop (0);
  422. }
  423. ~Native()
  424. {
  425. exitModalState (0);
  426. nativeFileChooser->cancel();
  427. nativeFileChooser = nullptr;
  428. }
  429. void launch() override
  430. {
  431. SafePointer<Native> safeThis (this);
  432. enterModalState (true, ModalCallbackFunction::create (
  433. [safeThis] (int)
  434. {
  435. if (safeThis != nullptr)
  436. safeThis->owner.finished (safeThis->nativeFileChooser->results);
  437. }));
  438. nativeFileChooser->open (true);
  439. }
  440. void runModally() override
  441. {
  442. enterModalState (true);
  443. nativeFileChooser->open (false);
  444. exitModalState (nativeFileChooser->results.size() > 0 ? 1 : 0);
  445. nativeFileChooser->cancel();
  446. owner.finished (nativeFileChooser->results);
  447. }
  448. private:
  449. FileChooser& owner;
  450. Win32NativeFileChooser::Ptr nativeFileChooser;
  451. };
  452. //==============================================================================
  453. bool FileChooser::isPlatformDialogAvailable()
  454. {
  455. #if JUCE_DISABLE_NATIVE_FILECHOOSERS
  456. return false;
  457. #else
  458. return true;
  459. #endif
  460. }
  461. FileChooser::Pimpl* FileChooser::showPlatformDialog (FileChooser& owner, int flags,
  462. FilePreviewComponent* preview)
  463. {
  464. return new FileChooser::Native (owner, flags, preview);
  465. }
  466. } // namespace juce