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.

855 lines
28KB

  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. #if JUCE_MINGW
  19. LWSTDAPI IUnknown_GetWindow (IUnknown* punk, HWND* phwnd);
  20. #endif
  21. namespace juce
  22. {
  23. // Implemented in juce_win32_Messaging.cpp
  24. bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  25. class Win32NativeFileChooser : private Thread
  26. {
  27. public:
  28. enum { charsAvailableForResult = 32768 };
  29. Win32NativeFileChooser (Component* parent, int flags, FilePreviewComponent* previewComp,
  30. const File& startingFile, const String& titleToUse,
  31. const String& filtersToUse)
  32. : Thread ("Native Win32 FileChooser"),
  33. owner (parent),
  34. title (titleToUse),
  35. filtersString (filtersToUse.replaceCharacter (',', ';')),
  36. selectsDirectories ((flags & FileBrowserComponent::canSelectDirectories) != 0),
  37. isSave ((flags & FileBrowserComponent::saveMode) != 0),
  38. warnAboutOverwrite ((flags & FileBrowserComponent::warnAboutOverwriting) != 0),
  39. selectMultiple ((flags & FileBrowserComponent::canSelectMultipleItems) != 0)
  40. {
  41. auto parentDirectory = startingFile.getParentDirectory();
  42. // Handle nonexistent root directories in the same way as existing ones
  43. files.calloc (static_cast<size_t> (charsAvailableForResult) + 1);
  44. if (startingFile.isDirectory() || startingFile.isRoot())
  45. {
  46. initialPath = startingFile.getFullPathName();
  47. }
  48. else
  49. {
  50. startingFile.getFileName().copyToUTF16 (files,
  51. static_cast<size_t> (charsAvailableForResult) * sizeof (WCHAR));
  52. initialPath = parentDirectory.getFullPathName();
  53. }
  54. if (! selectsDirectories)
  55. {
  56. if (previewComp != nullptr)
  57. customComponent.reset (new CustomComponentHolder (previewComp));
  58. setupFilters();
  59. }
  60. }
  61. ~Win32NativeFileChooser() override
  62. {
  63. signalThreadShouldExit();
  64. while (isThreadRunning())
  65. {
  66. if (! dispatchNextMessageOnSystemQueue (true))
  67. Thread::sleep (1);
  68. }
  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. startThread();
  79. }
  80. else
  81. {
  82. results = openDialog (false);
  83. owner->exitModalState (results.size() > 0 ? 1 : 0);
  84. }
  85. }
  86. void cancel()
  87. {
  88. ScopedLock lock (deletingDialog);
  89. customComponent = nullptr;
  90. shouldCancel = true;
  91. if (auto hwnd = nativeDialogRef.get())
  92. PostMessage (hwnd, WM_CLOSE, 0, 0);
  93. }
  94. Component* getCustomComponent() { return customComponent.get(); }
  95. Array<URL> results;
  96. private:
  97. //==============================================================================
  98. class CustomComponentHolder : public Component
  99. {
  100. public:
  101. CustomComponentHolder (Component* const customComp)
  102. {
  103. setVisible (true);
  104. setOpaque (true);
  105. addAndMakeVisible (customComp);
  106. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  107. }
  108. void paint (Graphics& g) override
  109. {
  110. g.fillAll (Colours::lightgrey);
  111. }
  112. void resized() override
  113. {
  114. if (Component* const c = getChildComponent(0))
  115. c->setBounds (getLocalBounds());
  116. }
  117. private:
  118. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponentHolder)
  119. };
  120. //==============================================================================
  121. const Component::SafePointer<Component> owner;
  122. String title, filtersString;
  123. std::unique_ptr<CustomComponentHolder> customComponent;
  124. String initialPath, returnedString;
  125. CriticalSection deletingDialog;
  126. bool selectsDirectories, isSave, warnAboutOverwrite, selectMultiple;
  127. HeapBlock<WCHAR> files;
  128. HeapBlock<WCHAR> filters;
  129. Atomic<HWND> nativeDialogRef { nullptr };
  130. bool shouldCancel = false;
  131. struct FreeLPWSTR
  132. {
  133. void operator() (LPWSTR ptr) const noexcept { CoTaskMemFree (ptr); }
  134. };
  135. bool showDialog (IFileDialog& dialog, bool async)
  136. {
  137. FILEOPENDIALOGOPTIONS flags = {};
  138. if (FAILED (dialog.GetOptions (&flags)))
  139. return false;
  140. const auto setBit = [] (FILEOPENDIALOGOPTIONS& field, bool value, FILEOPENDIALOGOPTIONS option)
  141. {
  142. if (value)
  143. field |= option;
  144. else
  145. field &= ~option;
  146. };
  147. setBit (flags, selectsDirectories, FOS_PICKFOLDERS);
  148. setBit (flags, warnAboutOverwrite, FOS_OVERWRITEPROMPT);
  149. setBit (flags, selectMultiple, FOS_ALLOWMULTISELECT);
  150. setBit (flags, customComponent != nullptr, FOS_FORCEPREVIEWPANEON);
  151. if (FAILED (dialog.SetOptions (flags)) || FAILED (dialog.SetTitle (title.toUTF16())))
  152. return false;
  153. PIDLIST_ABSOLUTE pidl = {};
  154. if (FAILED (SHParseDisplayName (initialPath.toWideCharPointer(), nullptr, &pidl, SFGAO_FOLDER, nullptr)))
  155. {
  156. LPWSTR ptr = nullptr;
  157. auto result = SHGetKnownFolderPath (FOLDERID_Desktop, 0, nullptr, &ptr);
  158. std::unique_ptr<WCHAR, FreeLPWSTR> desktopPath (ptr);
  159. if (FAILED (result))
  160. return false;
  161. if (FAILED (SHParseDisplayName (desktopPath.get(), nullptr, &pidl, SFGAO_FOLDER, nullptr)))
  162. return false;
  163. }
  164. const auto item = [&]
  165. {
  166. ComSmartPtr<IShellItem> ptr;
  167. SHCreateShellItem (nullptr, nullptr, pidl, ptr.resetAndGetPointerAddress());
  168. return ptr;
  169. }();
  170. if (item == nullptr || FAILED (dialog.SetDefaultFolder (item)))
  171. return false;
  172. String filename (files.getData());
  173. if (FAILED (dialog.SetFileName (filename.toWideCharPointer())))
  174. return false;
  175. auto extension = getDefaultFileExtension (filename);
  176. if (extension.isNotEmpty() && FAILED (dialog.SetDefaultExtension (extension.toWideCharPointer())))
  177. return false;
  178. const COMDLG_FILTERSPEC spec[] { { filtersString.toWideCharPointer(), filtersString.toWideCharPointer() } };
  179. if (! selectsDirectories && FAILED (dialog.SetFileTypes (numElementsInArray (spec), spec)))
  180. return false;
  181. struct Events : public ComBaseClassHelper<IFileDialogEvents>
  182. {
  183. explicit Events (Win32NativeFileChooser& o) : owner (o) {}
  184. JUCE_COMRESULT OnTypeChange (IFileDialog* d) override { return updateHwnd (d); }
  185. JUCE_COMRESULT OnFolderChanging (IFileDialog* d, IShellItem*) override { return updateHwnd (d); }
  186. JUCE_COMRESULT OnFileOk (IFileDialog* d) override { return updateHwnd (d); }
  187. JUCE_COMRESULT OnFolderChange (IFileDialog* d) override { return updateHwnd (d); }
  188. JUCE_COMRESULT OnSelectionChange (IFileDialog* d) override { return updateHwnd (d); }
  189. JUCE_COMRESULT OnShareViolation (IFileDialog* d, IShellItem*, FDE_SHAREVIOLATION_RESPONSE*) override { return updateHwnd (d); }
  190. JUCE_COMRESULT OnOverwrite (IFileDialog* d, IShellItem*, FDE_OVERWRITE_RESPONSE*) override { return updateHwnd (d); }
  191. JUCE_COMRESULT updateHwnd (IFileDialog* d)
  192. {
  193. HWND hwnd = nullptr;
  194. IUnknown_GetWindow (d, &hwnd);
  195. ScopedLock lock (owner.deletingDialog);
  196. if (owner.shouldCancel)
  197. d->Close (S_FALSE);
  198. else if (hwnd != nullptr)
  199. owner.nativeDialogRef = hwnd;
  200. return S_OK;
  201. }
  202. Win32NativeFileChooser& owner;
  203. };
  204. {
  205. ScopedLock lock (deletingDialog);
  206. if (shouldCancel)
  207. return false;
  208. }
  209. const auto result = [&]
  210. {
  211. struct ScopedAdvise
  212. {
  213. ScopedAdvise (IFileDialog& d, Events& events) : dialog (d) { dialog.Advise (&events, &cookie); }
  214. ~ScopedAdvise() { dialog.Unadvise (cookie); }
  215. IFileDialog& dialog;
  216. DWORD cookie = 0;
  217. };
  218. Events events { *this };
  219. ScopedAdvise scope { dialog, events };
  220. return dialog.Show (async ? nullptr : static_cast<HWND> (owner->getWindowHandle())) == S_OK;
  221. }();
  222. ScopedLock lock (deletingDialog);
  223. nativeDialogRef = nullptr;
  224. return result;
  225. }
  226. //==============================================================================
  227. Array<URL> openDialogVistaAndUp (bool async)
  228. {
  229. const auto getUrl = [] (IShellItem& item)
  230. {
  231. LPWSTR ptr = nullptr;
  232. if (item.GetDisplayName (SIGDN_FILESYSPATH, &ptr) != S_OK)
  233. return URL();
  234. const auto path = std::unique_ptr<WCHAR, FreeLPWSTR> { ptr };
  235. return URL (File (String (path.get())));
  236. };
  237. if (isSave)
  238. {
  239. const auto dialog = [&]
  240. {
  241. ComSmartPtr<IFileDialog> ptr;
  242. ptr.CoCreateInstance (CLSID_FileSaveDialog, CLSCTX_INPROC_SERVER);
  243. return ptr;
  244. }();
  245. if (dialog == nullptr)
  246. return {};
  247. showDialog (*dialog, async);
  248. const auto item = [&]
  249. {
  250. ComSmartPtr<IShellItem> ptr;
  251. dialog->GetResult (ptr.resetAndGetPointerAddress());
  252. return ptr;
  253. }();
  254. if (item == nullptr)
  255. return {};
  256. const auto url = getUrl (*item);
  257. if (url.isEmpty())
  258. return {};
  259. return { url };
  260. }
  261. const auto dialog = [&]
  262. {
  263. ComSmartPtr<IFileOpenDialog> ptr;
  264. ptr.CoCreateInstance (CLSID_FileOpenDialog, CLSCTX_INPROC_SERVER);
  265. return ptr;
  266. }();
  267. if (dialog == nullptr)
  268. return {};
  269. showDialog (*dialog, async);
  270. const auto items = [&]
  271. {
  272. ComSmartPtr<IShellItemArray> ptr;
  273. dialog->GetResults (ptr.resetAndGetPointerAddress());
  274. return ptr;
  275. }();
  276. if (items == nullptr)
  277. return {};
  278. Array<URL> result;
  279. DWORD numItems = 0;
  280. items->GetCount (&numItems);
  281. for (DWORD i = 0; i < numItems; ++i)
  282. {
  283. ComSmartPtr<IShellItem> scope;
  284. items->GetItemAt (i, scope.resetAndGetPointerAddress());
  285. if (scope != nullptr)
  286. {
  287. const auto url = getUrl (*scope);
  288. if (! url.isEmpty())
  289. result.add (url);
  290. }
  291. }
  292. return result;
  293. }
  294. Array<URL> openDialogPreVista (bool async)
  295. {
  296. Array<URL> selections;
  297. if (selectsDirectories)
  298. {
  299. BROWSEINFO bi = {};
  300. bi.hwndOwner = (HWND) (async ? nullptr : owner->getWindowHandle());
  301. bi.pszDisplayName = files;
  302. bi.lpszTitle = title.toWideCharPointer();
  303. bi.lParam = (LPARAM) this;
  304. bi.lpfn = browseCallbackProc;
  305. #ifdef BIF_USENEWUI
  306. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  307. #else
  308. bi.ulFlags = 0x50;
  309. #endif
  310. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  311. if (! SHGetPathFromIDListW (list, files))
  312. {
  313. files[0] = 0;
  314. returnedString.clear();
  315. }
  316. LPMALLOC al;
  317. if (list != nullptr && SUCCEEDED (SHGetMalloc (&al)))
  318. al->Free (list);
  319. if (files[0] != 0)
  320. {
  321. File result (String (files.get()));
  322. if (returnedString.isNotEmpty())
  323. result = result.getSiblingFile (returnedString);
  324. selections.add (URL (result));
  325. }
  326. }
  327. else
  328. {
  329. OPENFILENAMEW of = {};
  330. #ifdef OPENFILENAME_SIZE_VERSION_400W
  331. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  332. #else
  333. of.lStructSize = sizeof (of);
  334. #endif
  335. of.hwndOwner = (HWND) (async ? nullptr : owner->getWindowHandle());
  336. of.lpstrFilter = filters.getData();
  337. of.nFilterIndex = 1;
  338. of.lpstrFile = files;
  339. of.nMaxFile = (DWORD) charsAvailableForResult;
  340. of.lpstrInitialDir = initialPath.toWideCharPointer();
  341. of.lpstrTitle = title.toWideCharPointer();
  342. of.Flags = getOpenFilenameFlags (async);
  343. of.lCustData = (LPARAM) this;
  344. of.lpfnHook = &openCallback;
  345. if (isSave)
  346. {
  347. auto extension = getDefaultFileExtension (files.getData());
  348. if (extension.isNotEmpty())
  349. of.lpstrDefExt = extension.toWideCharPointer();
  350. if (! GetSaveFileName (&of))
  351. return {};
  352. }
  353. else
  354. {
  355. if (! GetOpenFileName (&of))
  356. return {};
  357. }
  358. if (selectMultiple && of.nFileOffset > 0 && files[of.nFileOffset - 1] == 0)
  359. {
  360. const WCHAR* filename = files + of.nFileOffset;
  361. while (*filename != 0)
  362. {
  363. selections.add (URL (File (String (files.get())).getChildFile (String (filename))));
  364. filename += wcslen (filename) + 1;
  365. }
  366. }
  367. else if (files[0] != 0)
  368. {
  369. selections.add (URL (File (String (files.get()))));
  370. }
  371. }
  372. return selections;
  373. }
  374. Array<URL> openDialog (bool async)
  375. {
  376. struct Remover
  377. {
  378. explicit Remover (Win32NativeFileChooser& chooser) : item (chooser) {}
  379. ~Remover() { getNativeDialogList().removeValue (&item); }
  380. Win32NativeFileChooser& item;
  381. };
  382. const Remover remover (*this);
  383. #if ! JUCE_MINGW
  384. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista
  385. && customComponent == nullptr)
  386. {
  387. return openDialogVistaAndUp (async);
  388. }
  389. #endif
  390. return openDialogPreVista (async);
  391. }
  392. void run() override
  393. {
  394. results = [&]
  395. {
  396. struct ScopedCoInitialize
  397. {
  398. // IUnknown_GetWindow will only succeed when instantiated in a single-thread apartment
  399. ScopedCoInitialize() { CoInitializeEx (nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); }
  400. ~ScopedCoInitialize() { CoUninitialize(); }
  401. };
  402. ScopedCoInitialize scope;
  403. return openDialog (true);
  404. }();
  405. auto safeOwner = owner;
  406. auto resultCode = results.size() > 0 ? 1 : 0;
  407. MessageManager::callAsync ([resultCode, safeOwner]
  408. {
  409. if (safeOwner != nullptr)
  410. safeOwner->exitModalState (resultCode);
  411. });
  412. }
  413. static HashMap<HWND, Win32NativeFileChooser*>& getNativeDialogList()
  414. {
  415. static HashMap<HWND, Win32NativeFileChooser*> dialogs;
  416. return dialogs;
  417. }
  418. static Win32NativeFileChooser* getNativePointerForDialog (HWND hwnd)
  419. {
  420. return getNativeDialogList()[hwnd];
  421. }
  422. //==============================================================================
  423. void setupFilters()
  424. {
  425. const size_t filterSpaceNumChars = 2048;
  426. filters.calloc (filterSpaceNumChars);
  427. const size_t bytesWritten = filtersString.copyToUTF16 (filters.getData(), filterSpaceNumChars * sizeof (WCHAR));
  428. filtersString.copyToUTF16 (filters + (bytesWritten / sizeof (WCHAR)),
  429. ((filterSpaceNumChars - 1) * sizeof (WCHAR) - bytesWritten));
  430. for (size_t i = 0; i < filterSpaceNumChars; ++i)
  431. if (filters[i] == '|')
  432. filters[i] = 0;
  433. }
  434. DWORD getOpenFilenameFlags (bool async)
  435. {
  436. DWORD ofFlags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY | OFN_ENABLESIZING;
  437. if (warnAboutOverwrite)
  438. ofFlags |= OFN_OVERWRITEPROMPT;
  439. if (selectMultiple)
  440. ofFlags |= OFN_ALLOWMULTISELECT;
  441. if (async || customComponent != nullptr)
  442. ofFlags |= OFN_ENABLEHOOK;
  443. return ofFlags;
  444. }
  445. String getDefaultFileExtension (const String& filename) const
  446. {
  447. auto extension = filename.fromLastOccurrenceOf (".", false, false);
  448. if (extension.isEmpty())
  449. {
  450. auto tokens = StringArray::fromTokens (filtersString, ";,", "\"'");
  451. tokens.trim();
  452. tokens.removeEmptyStrings();
  453. if (tokens.size() == 1 && tokens[0].removeCharacters ("*.").isNotEmpty())
  454. extension = tokens[0].fromFirstOccurrenceOf (".", false, false);
  455. }
  456. return extension;
  457. }
  458. //==============================================================================
  459. void initialised (HWND hWnd)
  460. {
  461. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) initialPath.toWideCharPointer());
  462. initDialog (hWnd);
  463. }
  464. void validateFailed (const String& path)
  465. {
  466. returnedString = path;
  467. }
  468. void initDialog (HWND hdlg)
  469. {
  470. ScopedLock lock (deletingDialog);
  471. getNativeDialogList().set (hdlg, this);
  472. if (shouldCancel)
  473. {
  474. EndDialog (hdlg, 0);
  475. }
  476. else
  477. {
  478. nativeDialogRef.set (hdlg);
  479. if (customComponent != nullptr)
  480. {
  481. Component::SafePointer<Component> safeCustomComponent (customComponent.get());
  482. RECT dialogScreenRect, dialogClientRect;
  483. GetWindowRect (hdlg, &dialogScreenRect);
  484. GetClientRect (hdlg, &dialogClientRect);
  485. auto screenRectangle = Rectangle<int>::leftTopRightBottom (dialogScreenRect.left, dialogScreenRect.top,
  486. dialogScreenRect.right, dialogScreenRect.bottom);
  487. auto scale = Desktop::getInstance().getDisplays().getDisplayForRect (screenRectangle, true)->scale;
  488. auto physicalComponentWidth = roundToInt (safeCustomComponent->getWidth() * scale);
  489. SetWindowPos (hdlg, nullptr, screenRectangle.getX(), screenRectangle.getY(),
  490. physicalComponentWidth + jmax (150, screenRectangle.getWidth()),
  491. jmax (150, screenRectangle.getHeight()),
  492. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  493. auto appendCustomComponent = [safeCustomComponent, dialogClientRect, scale, hdlg]() mutable
  494. {
  495. if (safeCustomComponent != nullptr)
  496. {
  497. auto scaledClientRectangle = Rectangle<int>::leftTopRightBottom (dialogClientRect.left, dialogClientRect.top,
  498. dialogClientRect.right, dialogClientRect.bottom) / scale;
  499. safeCustomComponent->setBounds (scaledClientRectangle.getRight(), scaledClientRectangle.getY(),
  500. safeCustomComponent->getWidth(), scaledClientRectangle.getHeight());
  501. safeCustomComponent->addToDesktop (0, hdlg);
  502. }
  503. };
  504. if (MessageManager::getInstance()->isThisTheMessageThread())
  505. appendCustomComponent();
  506. else
  507. MessageManager::callAsync (appendCustomComponent);
  508. }
  509. }
  510. }
  511. void destroyDialog (HWND hdlg)
  512. {
  513. ScopedLock exiting (deletingDialog);
  514. getNativeDialogList().remove (hdlg);
  515. nativeDialogRef.set (nullptr);
  516. if (MessageManager::getInstance()->isThisTheMessageThread())
  517. customComponent = nullptr;
  518. else
  519. MessageManager::callAsync ([this] { customComponent = nullptr; });
  520. }
  521. void selectionChanged (HWND hdlg)
  522. {
  523. ScopedLock lock (deletingDialog);
  524. if (customComponent != nullptr && ! shouldCancel)
  525. {
  526. if (FilePreviewComponent* comp = dynamic_cast<FilePreviewComponent*> (customComponent->getChildComponent (0)))
  527. {
  528. WCHAR path [MAX_PATH * 2] = { 0 };
  529. CommDlg_OpenSave_GetFilePath (hdlg, (LPARAM) &path, MAX_PATH);
  530. if (MessageManager::getInstance()->isThisTheMessageThread())
  531. {
  532. comp->selectedFileChanged (File (path));
  533. }
  534. else
  535. {
  536. Component::SafePointer<FilePreviewComponent> safeComp (comp);
  537. File selectedFile (path);
  538. MessageManager::callAsync ([safeComp, selectedFile]() mutable
  539. {
  540. safeComp->selectedFileChanged (selectedFile);
  541. });
  542. }
  543. }
  544. }
  545. }
  546. //==============================================================================
  547. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  548. {
  549. auto* self = reinterpret_cast<Win32NativeFileChooser*> (lpData);
  550. switch (msg)
  551. {
  552. case BFFM_INITIALIZED: self->initialised (hWnd); break;
  553. case BFFM_VALIDATEFAILEDW: self->validateFailed (String ((LPCWSTR) lParam)); break;
  554. case BFFM_VALIDATEFAILEDA: self->validateFailed (String ((const char*) lParam)); break;
  555. default: break;
  556. }
  557. return 0;
  558. }
  559. static UINT_PTR CALLBACK openCallback (HWND hwnd, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  560. {
  561. auto hdlg = getDialogFromHWND (hwnd);
  562. switch (uiMsg)
  563. {
  564. case WM_INITDIALOG:
  565. {
  566. if (auto* self = reinterpret_cast<Win32NativeFileChooser*> (((OPENFILENAMEW*) lParam)->lCustData))
  567. self->initDialog (hdlg);
  568. break;
  569. }
  570. case WM_DESTROY:
  571. {
  572. if (auto* self = getNativeDialogList()[hdlg])
  573. self->destroyDialog (hdlg);
  574. break;
  575. }
  576. case WM_NOTIFY:
  577. {
  578. auto ofn = reinterpret_cast<LPOFNOTIFY> (lParam);
  579. if (ofn->hdr.code == CDN_SELCHANGE)
  580. if (auto* self = reinterpret_cast<Win32NativeFileChooser*> (ofn->lpOFN->lCustData))
  581. self->selectionChanged (hdlg);
  582. break;
  583. }
  584. default:
  585. break;
  586. }
  587. return 0;
  588. }
  589. static HWND getDialogFromHWND (HWND hwnd)
  590. {
  591. if (hwnd == nullptr)
  592. return nullptr;
  593. HWND dialogH = GetParent (hwnd);
  594. if (dialogH == nullptr)
  595. dialogH = hwnd;
  596. return dialogH;
  597. }
  598. //==============================================================================
  599. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Win32NativeFileChooser)
  600. };
  601. class FileChooser::Native : public std::enable_shared_from_this<Native>,
  602. public Component,
  603. public FileChooser::Pimpl
  604. {
  605. public:
  606. Native (FileChooser& fileChooser, int flags, FilePreviewComponent* previewComp)
  607. : owner (fileChooser),
  608. nativeFileChooser (std::make_unique<Win32NativeFileChooser> (this, flags, previewComp, fileChooser.startingFile,
  609. fileChooser.title, fileChooser.filters))
  610. {
  611. auto mainMon = Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  612. setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  613. mainMon.getY() + mainMon.getHeight() / 4,
  614. 0, 0);
  615. setOpaque (true);
  616. setAlwaysOnTop (juce_areThereAnyAlwaysOnTopWindows());
  617. addToDesktop (0);
  618. }
  619. ~Native() override
  620. {
  621. exitModalState (0);
  622. nativeFileChooser->cancel();
  623. }
  624. void launch() override
  625. {
  626. std::weak_ptr<Native> safeThis = shared_from_this();
  627. enterModalState (true, ModalCallbackFunction::create ([safeThis] (int)
  628. {
  629. if (auto locked = safeThis.lock())
  630. locked->owner.finished (locked->nativeFileChooser->results);
  631. }));
  632. nativeFileChooser->open (true);
  633. }
  634. void runModally() override
  635. {
  636. #if JUCE_MODAL_LOOPS_PERMITTED
  637. enterModalState (true);
  638. nativeFileChooser->open (false);
  639. exitModalState (nativeFileChooser->results.size() > 0 ? 1 : 0);
  640. nativeFileChooser->cancel();
  641. owner.finished (nativeFileChooser->results);
  642. #else
  643. jassertfalse;
  644. #endif
  645. }
  646. bool canModalEventBeSentToComponent (const Component* targetComponent) override
  647. {
  648. if (targetComponent == nullptr)
  649. return false;
  650. if (targetComponent == nativeFileChooser->getCustomComponent())
  651. return true;
  652. return targetComponent->findParentComponentOfClass<FilePreviewComponent>() != nullptr;
  653. }
  654. private:
  655. FileChooser& owner;
  656. std::shared_ptr<Win32NativeFileChooser> nativeFileChooser;
  657. };
  658. //==============================================================================
  659. bool FileChooser::isPlatformDialogAvailable()
  660. {
  661. #if JUCE_DISABLE_NATIVE_FILECHOOSERS
  662. return false;
  663. #else
  664. return true;
  665. #endif
  666. }
  667. std::shared_ptr<FileChooser::Pimpl> FileChooser::showPlatformDialog (FileChooser& owner, int flags,
  668. FilePreviewComponent* preview)
  669. {
  670. return std::make_shared<FileChooser::Native> (owner, flags, preview);
  671. }
  672. } // namespace juce