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.

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