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.

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