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.

829 lines
27KB

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