The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

866 lines
28KB

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