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.

792 lines
26KB

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