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.

866 lines
28KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - 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 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-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. // Implemented in juce_win32_Messaging.cpp
  21. namespace detail
  22. {
  23. bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  24. } // namespace detail
  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 (! detail::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)
  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)
  171. {
  172. dialog.SetDefaultFolder (item);
  173. if (! initialPath.isEmpty())
  174. dialog.SetFolder (item);
  175. }
  176. String filename (files.getData());
  177. if (FAILED (dialog.SetFileName (filename.toWideCharPointer())))
  178. return false;
  179. auto extension = getDefaultFileExtension (filename);
  180. if (extension.isNotEmpty() && FAILED (dialog.SetDefaultExtension (extension.toWideCharPointer())))
  181. return false;
  182. const COMDLG_FILTERSPEC spec[] { { filtersString.toWideCharPointer(), filtersString.toWideCharPointer() } };
  183. if (! selectsDirectories && FAILED (dialog.SetFileTypes (numElementsInArray (spec), spec)))
  184. return false;
  185. struct Events : public ComBaseClassHelper<IFileDialogEvents>
  186. {
  187. explicit Events (Win32NativeFileChooser& o) : owner (o) {}
  188. JUCE_COMRESULT OnTypeChange (IFileDialog* d) override { return updateHwnd (d); }
  189. JUCE_COMRESULT OnFolderChanging (IFileDialog* d, IShellItem*) override { return updateHwnd (d); }
  190. JUCE_COMRESULT OnFileOk (IFileDialog* d) override { return updateHwnd (d); }
  191. JUCE_COMRESULT OnFolderChange (IFileDialog* d) override { return updateHwnd (d); }
  192. JUCE_COMRESULT OnSelectionChange (IFileDialog* d) override { return updateHwnd (d); }
  193. JUCE_COMRESULT OnShareViolation (IFileDialog* d, IShellItem*, FDE_SHAREVIOLATION_RESPONSE*) override { return updateHwnd (d); }
  194. JUCE_COMRESULT OnOverwrite (IFileDialog* d, IShellItem*, FDE_OVERWRITE_RESPONSE*) override { return updateHwnd (d); }
  195. JUCE_COMRESULT updateHwnd (IFileDialog* d)
  196. {
  197. HWND hwnd = nullptr;
  198. if (auto window = ComSmartPtr<IFileDialog> { d }.getInterface<IOleWindow>())
  199. window->GetWindow (&hwnd);
  200. ScopedLock lock (owner.deletingDialog);
  201. if (owner.shouldCancel)
  202. d->Close (S_FALSE);
  203. else if (hwnd != nullptr)
  204. owner.nativeDialogRef = hwnd;
  205. return S_OK;
  206. }
  207. Win32NativeFileChooser& owner;
  208. };
  209. {
  210. ScopedLock lock (deletingDialog);
  211. if (shouldCancel)
  212. return false;
  213. }
  214. const auto result = [&]
  215. {
  216. struct ScopedAdvise
  217. {
  218. ScopedAdvise (IFileDialog& d, Events& events) : dialog (d) { dialog.Advise (&events, &cookie); }
  219. ~ScopedAdvise() { dialog.Unadvise (cookie); }
  220. IFileDialog& dialog;
  221. DWORD cookie = 0;
  222. };
  223. Events events { *this };
  224. ScopedAdvise scope { dialog, events };
  225. return dialog.Show (GetActiveWindow()) == S_OK;
  226. }();
  227. ScopedLock lock (deletingDialog);
  228. nativeDialogRef = nullptr;
  229. return result;
  230. }
  231. //==============================================================================
  232. Array<URL> openDialogVistaAndUp()
  233. {
  234. const auto getUrl = [] (IShellItem& item)
  235. {
  236. LPWSTR ptr = nullptr;
  237. if (item.GetDisplayName (SIGDN_FILESYSPATH, &ptr) != S_OK)
  238. return URL();
  239. const auto path = std::unique_ptr<WCHAR, FreeLPWSTR> { ptr };
  240. return URL (File (String (path.get())));
  241. };
  242. if (isSave)
  243. {
  244. const auto dialog = [&]
  245. {
  246. ComSmartPtr<IFileDialog> ptr;
  247. ptr.CoCreateInstance (CLSID_FileSaveDialog, CLSCTX_INPROC_SERVER);
  248. return ptr;
  249. }();
  250. if (dialog == nullptr)
  251. return {};
  252. showDialog (*dialog);
  253. const auto item = [&]
  254. {
  255. ComSmartPtr<IShellItem> ptr;
  256. dialog->GetResult (ptr.resetAndGetPointerAddress());
  257. return ptr;
  258. }();
  259. if (item == nullptr)
  260. return {};
  261. const auto url = getUrl (*item);
  262. if (url.isEmpty())
  263. return {};
  264. return { url };
  265. }
  266. const auto dialog = [&]
  267. {
  268. ComSmartPtr<IFileOpenDialog> ptr;
  269. ptr.CoCreateInstance (CLSID_FileOpenDialog, CLSCTX_INPROC_SERVER);
  270. return ptr;
  271. }();
  272. if (dialog == nullptr)
  273. return {};
  274. showDialog (*dialog);
  275. const auto items = [&]
  276. {
  277. ComSmartPtr<IShellItemArray> ptr;
  278. dialog->GetResults (ptr.resetAndGetPointerAddress());
  279. return ptr;
  280. }();
  281. if (items == nullptr)
  282. return {};
  283. Array<URL> result;
  284. DWORD numItems = 0;
  285. items->GetCount (&numItems);
  286. for (DWORD i = 0; i < numItems; ++i)
  287. {
  288. ComSmartPtr<IShellItem> scope;
  289. items->GetItemAt (i, scope.resetAndGetPointerAddress());
  290. if (scope != nullptr)
  291. {
  292. const auto url = getUrl (*scope);
  293. if (! url.isEmpty())
  294. result.add (url);
  295. }
  296. }
  297. return result;
  298. }
  299. Array<URL> openDialogPreVista (bool async)
  300. {
  301. Array<URL> selections;
  302. if (selectsDirectories)
  303. {
  304. BROWSEINFO bi = {};
  305. bi.hwndOwner = GetActiveWindow();
  306. bi.pszDisplayName = files;
  307. bi.lpszTitle = title.toWideCharPointer();
  308. bi.lParam = (LPARAM) this;
  309. bi.lpfn = browseCallbackProc;
  310. #ifdef BIF_USENEWUI
  311. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  312. #else
  313. bi.ulFlags = 0x50;
  314. #endif
  315. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  316. if (! SHGetPathFromIDListW (list, files))
  317. {
  318. files[0] = 0;
  319. returnedString.clear();
  320. }
  321. LPMALLOC al;
  322. if (list != nullptr && SUCCEEDED (SHGetMalloc (&al)))
  323. al->Free (list);
  324. if (files[0] != 0)
  325. {
  326. File result (String (files.get()));
  327. if (returnedString.isNotEmpty())
  328. result = result.getSiblingFile (returnedString);
  329. selections.add (URL (result));
  330. }
  331. }
  332. else
  333. {
  334. OPENFILENAMEW of = {};
  335. #ifdef OPENFILENAME_SIZE_VERSION_400W
  336. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  337. #else
  338. of.lStructSize = sizeof (of);
  339. #endif
  340. if (files[0] != 0)
  341. {
  342. auto startingFile = File (initialPath).getChildFile (String (files.get()));
  343. startingFile.getFullPathName().copyToUTF16 (files, charsAvailableForResult * sizeof (WCHAR));
  344. }
  345. of.hwndOwner = GetActiveWindow();
  346. of.lpstrFilter = filters.getData();
  347. of.nFilterIndex = 1;
  348. of.lpstrFile = files;
  349. of.nMaxFile = (DWORD) charsAvailableForResult;
  350. of.lpstrInitialDir = initialPath.toWideCharPointer();
  351. of.lpstrTitle = title.toWideCharPointer();
  352. of.Flags = getOpenFilenameFlags (async);
  353. of.lCustData = (LPARAM) this;
  354. of.lpfnHook = &openCallback;
  355. if (isSave)
  356. {
  357. auto extension = getDefaultFileExtension (files.getData());
  358. if (extension.isNotEmpty())
  359. of.lpstrDefExt = extension.toWideCharPointer();
  360. if (! GetSaveFileName (&of))
  361. return {};
  362. }
  363. else
  364. {
  365. if (! GetOpenFileName (&of))
  366. return {};
  367. }
  368. if (selectMultiple && of.nFileOffset > 0 && files[of.nFileOffset - 1] == 0)
  369. {
  370. const WCHAR* filename = files + of.nFileOffset;
  371. while (*filename != 0)
  372. {
  373. selections.add (URL (File (String (files.get())).getChildFile (String (filename))));
  374. filename += wcslen (filename) + 1;
  375. }
  376. }
  377. else if (files[0] != 0)
  378. {
  379. selections.add (URL (File (String (files.get()))));
  380. }
  381. }
  382. return selections;
  383. }
  384. Array<URL> openDialog (bool async)
  385. {
  386. struct Remover
  387. {
  388. explicit Remover (Win32NativeFileChooser& chooser) : item (chooser) {}
  389. ~Remover() { getNativeDialogList().removeValue (&item); }
  390. Win32NativeFileChooser& item;
  391. };
  392. const Remover remover (*this);
  393. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista
  394. && customComponent == nullptr)
  395. {
  396. return openDialogVistaAndUp();
  397. }
  398. return openDialogPreVista (async);
  399. }
  400. void run() override
  401. {
  402. results = [&]
  403. {
  404. struct ScopedCoInitialize
  405. {
  406. // IUnknown_GetWindow will only succeed when instantiated in a single-thread apartment
  407. ScopedCoInitialize() { [[maybe_unused]] const auto result = CoInitializeEx (nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); }
  408. ~ScopedCoInitialize() { CoUninitialize(); }
  409. };
  410. ScopedCoInitialize scope;
  411. return openDialog (true);
  412. }();
  413. auto safeOwner = owner;
  414. auto resultCode = results.size() > 0 ? 1 : 0;
  415. MessageManager::callAsync ([resultCode, safeOwner]
  416. {
  417. if (safeOwner != nullptr)
  418. safeOwner->exitModalState (resultCode);
  419. });
  420. }
  421. static HashMap<HWND, Win32NativeFileChooser*>& getNativeDialogList()
  422. {
  423. static HashMap<HWND, Win32NativeFileChooser*> dialogs;
  424. return dialogs;
  425. }
  426. static Win32NativeFileChooser* getNativePointerForDialog (HWND hwnd)
  427. {
  428. return getNativeDialogList()[hwnd];
  429. }
  430. //==============================================================================
  431. void setupFilters()
  432. {
  433. const size_t filterSpaceNumChars = 2048;
  434. filters.calloc (filterSpaceNumChars);
  435. const size_t bytesWritten = filtersString.copyToUTF16 (filters.getData(), filterSpaceNumChars * sizeof (WCHAR));
  436. filtersString.copyToUTF16 (filters + (bytesWritten / sizeof (WCHAR)),
  437. ((filterSpaceNumChars - 1) * sizeof (WCHAR) - bytesWritten));
  438. for (size_t i = 0; i < filterSpaceNumChars; ++i)
  439. if (filters[i] == '|')
  440. filters[i] = 0;
  441. }
  442. DWORD getOpenFilenameFlags (bool async)
  443. {
  444. DWORD ofFlags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY | OFN_ENABLESIZING;
  445. if (warnAboutOverwrite)
  446. ofFlags |= OFN_OVERWRITEPROMPT;
  447. if (selectMultiple)
  448. ofFlags |= OFN_ALLOWMULTISELECT;
  449. if (async || customComponent != nullptr)
  450. ofFlags |= OFN_ENABLEHOOK;
  451. return ofFlags;
  452. }
  453. String getDefaultFileExtension (const String& filename) const
  454. {
  455. const auto extension = filename.contains (".") ? filename.fromLastOccurrenceOf (".", false, false)
  456. : String();
  457. if (! extension.isEmpty())
  458. return extension;
  459. auto tokens = StringArray::fromTokens (filtersString, ";,", "\"'");
  460. tokens.trim();
  461. tokens.removeEmptyStrings();
  462. if (tokens.size() == 1 && tokens[0].removeCharacters ("*.").isNotEmpty())
  463. return tokens[0].fromFirstOccurrenceOf (".", false, false);
  464. return {};
  465. }
  466. //==============================================================================
  467. void initialised (HWND hWnd)
  468. {
  469. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) initialPath.toWideCharPointer());
  470. initDialog (hWnd);
  471. }
  472. void validateFailed (const String& path)
  473. {
  474. returnedString = path;
  475. }
  476. void initDialog (HWND hdlg)
  477. {
  478. ScopedLock lock (deletingDialog);
  479. getNativeDialogList().set (hdlg, this);
  480. if (shouldCancel)
  481. {
  482. EndDialog (hdlg, 0);
  483. }
  484. else
  485. {
  486. nativeDialogRef.set (hdlg);
  487. if (customComponent != nullptr)
  488. {
  489. Component::SafePointer<Component> safeCustomComponent (customComponent.get());
  490. RECT dialogScreenRect, dialogClientRect;
  491. GetWindowRect (hdlg, &dialogScreenRect);
  492. GetClientRect (hdlg, &dialogClientRect);
  493. auto screenRectangle = Rectangle<int>::leftTopRightBottom (dialogScreenRect.left, dialogScreenRect.top,
  494. dialogScreenRect.right, dialogScreenRect.bottom);
  495. auto scale = Desktop::getInstance().getDisplays().getDisplayForRect (screenRectangle, true)->scale;
  496. auto physicalComponentWidth = roundToInt (safeCustomComponent->getWidth() * scale);
  497. SetWindowPos (hdlg, nullptr, screenRectangle.getX(), screenRectangle.getY(),
  498. physicalComponentWidth + jmax (150, screenRectangle.getWidth()),
  499. jmax (150, screenRectangle.getHeight()),
  500. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  501. auto appendCustomComponent = [safeCustomComponent, dialogClientRect, scale, hdlg]() mutable
  502. {
  503. if (safeCustomComponent != nullptr)
  504. {
  505. auto scaledClientRectangle = Rectangle<int>::leftTopRightBottom (dialogClientRect.left, dialogClientRect.top,
  506. dialogClientRect.right, dialogClientRect.bottom) / scale;
  507. safeCustomComponent->setBounds (scaledClientRectangle.getRight(), scaledClientRectangle.getY(),
  508. safeCustomComponent->getWidth(), scaledClientRectangle.getHeight());
  509. safeCustomComponent->addToDesktop (0, hdlg);
  510. }
  511. };
  512. if (MessageManager::getInstance()->isThisTheMessageThread())
  513. appendCustomComponent();
  514. else
  515. MessageManager::callAsync (appendCustomComponent);
  516. }
  517. }
  518. }
  519. void destroyDialog (HWND hdlg)
  520. {
  521. ScopedLock exiting (deletingDialog);
  522. getNativeDialogList().remove (hdlg);
  523. nativeDialogRef.set (nullptr);
  524. if (MessageManager::getInstance()->isThisTheMessageThread())
  525. customComponent = nullptr;
  526. else
  527. MessageManager::callAsync ([this] { customComponent = nullptr; });
  528. }
  529. void selectionChanged (HWND hdlg)
  530. {
  531. ScopedLock lock (deletingDialog);
  532. if (customComponent != nullptr && ! shouldCancel)
  533. {
  534. if (FilePreviewComponent* comp = dynamic_cast<FilePreviewComponent*> (customComponent->getChildComponent (0)))
  535. {
  536. WCHAR path [MAX_PATH * 2] = { 0 };
  537. CommDlg_OpenSave_GetFilePath (hdlg, (LPARAM) &path, MAX_PATH);
  538. if (MessageManager::getInstance()->isThisTheMessageThread())
  539. {
  540. comp->selectedFileChanged (File (path));
  541. }
  542. else
  543. {
  544. MessageManager::callAsync ([safeComp = Component::SafePointer<FilePreviewComponent> { comp },
  545. selectedFile = File { path }]() mutable
  546. {
  547. if (safeComp != nullptr)
  548. safeComp->selectedFileChanged (selectedFile);
  549. });
  550. }
  551. }
  552. }
  553. }
  554. //==============================================================================
  555. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  556. {
  557. auto* self = reinterpret_cast<Win32NativeFileChooser*> (lpData);
  558. switch (msg)
  559. {
  560. case BFFM_INITIALIZED: self->initialised (hWnd); break;
  561. case BFFM_VALIDATEFAILEDW: self->validateFailed (String ((LPCWSTR) lParam)); break;
  562. case BFFM_VALIDATEFAILEDA: self->validateFailed (String ((const char*) lParam)); break;
  563. default: break;
  564. }
  565. return 0;
  566. }
  567. static UINT_PTR CALLBACK openCallback (HWND hwnd, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  568. {
  569. auto hdlg = getDialogFromHWND (hwnd);
  570. switch (uiMsg)
  571. {
  572. case WM_INITDIALOG:
  573. {
  574. if (auto* self = reinterpret_cast<Win32NativeFileChooser*> (((OPENFILENAMEW*) lParam)->lCustData))
  575. self->initDialog (hdlg);
  576. break;
  577. }
  578. case WM_DESTROY:
  579. {
  580. if (auto* self = getNativeDialogList()[hdlg])
  581. self->destroyDialog (hdlg);
  582. break;
  583. }
  584. case WM_NOTIFY:
  585. {
  586. auto ofn = reinterpret_cast<LPOFNOTIFY> (lParam);
  587. if (ofn->hdr.code == CDN_SELCHANGE)
  588. if (auto* self = reinterpret_cast<Win32NativeFileChooser*> (ofn->lpOFN->lCustData))
  589. self->selectionChanged (hdlg);
  590. break;
  591. }
  592. default:
  593. break;
  594. }
  595. return 0;
  596. }
  597. static HWND getDialogFromHWND (HWND hwnd)
  598. {
  599. if (hwnd == nullptr)
  600. return nullptr;
  601. HWND dialogH = GetParent (hwnd);
  602. if (dialogH == nullptr)
  603. dialogH = hwnd;
  604. return dialogH;
  605. }
  606. //==============================================================================
  607. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Win32NativeFileChooser)
  608. };
  609. class FileChooser::Native : public std::enable_shared_from_this<Native>,
  610. public Component,
  611. public FileChooser::Pimpl
  612. {
  613. public:
  614. Native (FileChooser& fileChooser, int flagsIn, FilePreviewComponent* previewComp)
  615. : owner (fileChooser),
  616. nativeFileChooser (std::make_unique<Win32NativeFileChooser> (this, flagsIn, previewComp, fileChooser.startingFile,
  617. fileChooser.title, fileChooser.filters))
  618. {
  619. auto mainMon = Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  620. setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  621. mainMon.getY() + mainMon.getHeight() / 4,
  622. 0, 0);
  623. setOpaque (true);
  624. setAlwaysOnTop (juce_areThereAnyAlwaysOnTopWindows());
  625. addToDesktop (0);
  626. }
  627. ~Native() override
  628. {
  629. exitModalState (0);
  630. nativeFileChooser->cancel();
  631. }
  632. void launch() override
  633. {
  634. std::weak_ptr<Native> safeThis = shared_from_this();
  635. enterModalState (true, ModalCallbackFunction::create ([safeThis] (int)
  636. {
  637. if (auto locked = safeThis.lock())
  638. locked->owner.finished (locked->nativeFileChooser->results);
  639. }));
  640. nativeFileChooser->open (true);
  641. }
  642. void runModally() override
  643. {
  644. #if JUCE_MODAL_LOOPS_PERMITTED
  645. enterModalState (true);
  646. nativeFileChooser->open (false);
  647. exitModalState (nativeFileChooser->results.size() > 0 ? 1 : 0);
  648. nativeFileChooser->cancel();
  649. owner.finished (nativeFileChooser->results);
  650. #else
  651. jassertfalse;
  652. #endif
  653. }
  654. bool canModalEventBeSentToComponent (const Component* targetComponent) override
  655. {
  656. if (targetComponent == nullptr)
  657. return false;
  658. if (targetComponent == nativeFileChooser->getCustomComponent())
  659. return true;
  660. return targetComponent->findParentComponentOfClass<FilePreviewComponent>() != nullptr;
  661. }
  662. private:
  663. FileChooser& owner;
  664. std::shared_ptr<Win32NativeFileChooser> nativeFileChooser;
  665. };
  666. //==============================================================================
  667. bool FileChooser::isPlatformDialogAvailable()
  668. {
  669. #if JUCE_DISABLE_NATIVE_FILECHOOSERS
  670. return false;
  671. #else
  672. return true;
  673. #endif
  674. }
  675. std::shared_ptr<FileChooser::Pimpl> FileChooser::showPlatformDialog (FileChooser& owner, int flags,
  676. FilePreviewComponent* preview)
  677. {
  678. return std::make_shared<FileChooser::Native> (owner, flags, preview);
  679. }
  680. } // namespace juce