Audio plugin host https://kx.studio/carla
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.

juce_win32_FileChooser.cpp 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - 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 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-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. // Implemented in juce_win32_Messaging.cpp
  21. bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  22. class Win32NativeFileChooser : private Thread
  23. {
  24. public:
  25. enum { charsAvailableForResult = 32768 };
  26. Win32NativeFileChooser (Component* parent, int flags, FilePreviewComponent* previewComp,
  27. const File& startingFile, const String& titleToUse,
  28. const String& filtersToUse)
  29. : Thread ("Native Win32 FileChooser"),
  30. owner (parent),
  31. title (titleToUse),
  32. filtersString (filtersToUse.replaceCharacter (',', ';')),
  33. selectsDirectories ((flags & FileBrowserComponent::canSelectDirectories) != 0),
  34. isSave ((flags & FileBrowserComponent::saveMode) != 0),
  35. warnAboutOverwrite ((flags & FileBrowserComponent::warnAboutOverwriting) != 0),
  36. selectMultiple ((flags & FileBrowserComponent::canSelectMultipleItems) != 0)
  37. {
  38. auto parentDirectory = startingFile.getParentDirectory();
  39. // Handle nonexistent root directories in the same way as existing ones
  40. files.calloc (static_cast<size_t> (charsAvailableForResult) + 1);
  41. if (startingFile.isDirectory() || startingFile.isRoot())
  42. {
  43. initialPath = startingFile.getFullPathName();
  44. }
  45. else
  46. {
  47. startingFile.getFileName().copyToUTF16 (files,
  48. static_cast<size_t> (charsAvailableForResult) * sizeof (WCHAR));
  49. initialPath = parentDirectory.getFullPathName();
  50. }
  51. if (! selectsDirectories)
  52. {
  53. if (previewComp != nullptr)
  54. customComponent.reset (new CustomComponentHolder (previewComp));
  55. setupFilters();
  56. }
  57. }
  58. ~Win32NativeFileChooser() override
  59. {
  60. signalThreadShouldExit();
  61. while (isThreadRunning())
  62. {
  63. if (! dispatchNextMessageOnSystemQueue (true))
  64. Thread::sleep (1);
  65. }
  66. }
  67. void open (bool async)
  68. {
  69. results.clear();
  70. // the thread should not be running
  71. nativeDialogRef.set (nullptr);
  72. if (async)
  73. {
  74. jassert (! isThreadRunning());
  75. startThread();
  76. }
  77. else
  78. {
  79. results = openDialog (false);
  80. owner->exitModalState (results.size() > 0 ? 1 : 0);
  81. }
  82. }
  83. void cancel()
  84. {
  85. ScopedLock lock (deletingDialog);
  86. customComponent = nullptr;
  87. shouldCancel = true;
  88. if (auto hwnd = nativeDialogRef.get())
  89. PostMessage (hwnd, WM_CLOSE, 0, 0);
  90. }
  91. Component* getCustomComponent() { return customComponent.get(); }
  92. Array<URL> results;
  93. private:
  94. //==============================================================================
  95. class CustomComponentHolder : public Component
  96. {
  97. public:
  98. CustomComponentHolder (Component* const customComp)
  99. {
  100. setVisible (true);
  101. setOpaque (true);
  102. addAndMakeVisible (customComp);
  103. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  104. }
  105. void paint (Graphics& g) override
  106. {
  107. g.fillAll (Colours::lightgrey);
  108. }
  109. void resized() override
  110. {
  111. if (Component* const c = getChildComponent(0))
  112. c->setBounds (getLocalBounds());
  113. }
  114. private:
  115. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponentHolder)
  116. };
  117. //==============================================================================
  118. const Component::SafePointer<Component> owner;
  119. String title, filtersString;
  120. std::unique_ptr<CustomComponentHolder> customComponent;
  121. String initialPath, returnedString;
  122. CriticalSection deletingDialog;
  123. bool selectsDirectories, isSave, warnAboutOverwrite, selectMultiple;
  124. HeapBlock<WCHAR> files;
  125. HeapBlock<WCHAR> filters;
  126. Atomic<HWND> nativeDialogRef { nullptr };
  127. bool shouldCancel = false;
  128. struct FreeLPWSTR
  129. {
  130. void operator() (LPWSTR ptr) const noexcept { CoTaskMemFree (ptr); }
  131. };
  132. #if JUCE_MSVC
  133. bool showDialog (IFileDialog& dialog, bool async)
  134. {
  135. FILEOPENDIALOGOPTIONS flags = {};
  136. if (FAILED (dialog.GetOptions (&flags)))
  137. return false;
  138. const auto setBit = [] (FILEOPENDIALOGOPTIONS& field, bool value, FILEOPENDIALOGOPTIONS option)
  139. {
  140. if (value)
  141. field |= option;
  142. else
  143. field &= ~option;
  144. };
  145. setBit (flags, selectsDirectories, FOS_PICKFOLDERS);
  146. setBit (flags, warnAboutOverwrite, FOS_OVERWRITEPROMPT);
  147. setBit (flags, selectMultiple, FOS_ALLOWMULTISELECT);
  148. setBit (flags, customComponent != nullptr, FOS_FORCEPREVIEWPANEON);
  149. if (FAILED (dialog.SetOptions (flags)) || FAILED (dialog.SetTitle (title.toUTF16())))
  150. return false;
  151. PIDLIST_ABSOLUTE pidl = {};
  152. if (FAILED (SHParseDisplayName (initialPath.toWideCharPointer(), nullptr, &pidl, SFGAO_FOLDER, nullptr)))
  153. {
  154. LPWSTR ptr = nullptr;
  155. auto result = SHGetKnownFolderPath (FOLDERID_Desktop, 0, nullptr, &ptr);
  156. std::unique_ptr<WCHAR, FreeLPWSTR> desktopPath (ptr);
  157. if (FAILED (result))
  158. return false;
  159. if (FAILED (SHParseDisplayName (desktopPath.get(), nullptr, &pidl, SFGAO_FOLDER, nullptr)))
  160. return false;
  161. }
  162. const auto item = [&]
  163. {
  164. ComSmartPtr<IShellItem> ptr;
  165. SHCreateShellItem (nullptr, nullptr, pidl, ptr.resetAndGetPointerAddress());
  166. return ptr;
  167. }();
  168. if (item != nullptr)
  169. {
  170. dialog.SetDefaultFolder (item);
  171. if (! initialPath.isEmpty())
  172. dialog.SetFolder (item);
  173. }
  174. String filename (files.getData());
  175. if (FAILED (dialog.SetFileName (filename.toWideCharPointer())))
  176. return false;
  177. auto extension = getDefaultFileExtension (filename);
  178. if (extension.isNotEmpty() && FAILED (dialog.SetDefaultExtension (extension.toWideCharPointer())))
  179. return false;
  180. const COMDLG_FILTERSPEC spec[] { { filtersString.toWideCharPointer(), filtersString.toWideCharPointer() } };
  181. if (! selectsDirectories && FAILED (dialog.SetFileTypes (numElementsInArray (spec), spec)))
  182. return false;
  183. struct Events : public ComBaseClassHelper<IFileDialogEvents>
  184. {
  185. explicit Events (Win32NativeFileChooser& o) : owner (o) {}
  186. JUCE_COMRESULT OnTypeChange (IFileDialog* d) override { return updateHwnd (d); }
  187. JUCE_COMRESULT OnFolderChanging (IFileDialog* d, IShellItem*) override { return updateHwnd (d); }
  188. JUCE_COMRESULT OnFileOk (IFileDialog* d) override { return updateHwnd (d); }
  189. JUCE_COMRESULT OnFolderChange (IFileDialog* d) override { return updateHwnd (d); }
  190. JUCE_COMRESULT OnSelectionChange (IFileDialog* d) override { return updateHwnd (d); }
  191. JUCE_COMRESULT OnShareViolation (IFileDialog* d, IShellItem*, FDE_SHAREVIOLATION_RESPONSE*) override { return updateHwnd (d); }
  192. JUCE_COMRESULT OnOverwrite (IFileDialog* d, IShellItem*, FDE_OVERWRITE_RESPONSE*) override { return updateHwnd (d); }
  193. JUCE_COMRESULT updateHwnd (IFileDialog* d)
  194. {
  195. HWND hwnd = nullptr;
  196. if (auto window = ComSmartPtr<IFileDialog> { d }.getInterface<IOleWindow>())
  197. window->GetWindow (&hwnd);
  198. ScopedLock lock (owner.deletingDialog);
  199. if (owner.shouldCancel)
  200. d->Close (S_FALSE);
  201. else if (hwnd != nullptr)
  202. owner.nativeDialogRef = hwnd;
  203. return S_OK;
  204. }
  205. Win32NativeFileChooser& owner;
  206. };
  207. {
  208. ScopedLock lock (deletingDialog);
  209. if (shouldCancel)
  210. return false;
  211. }
  212. const auto result = [&]
  213. {
  214. struct ScopedAdvise
  215. {
  216. ScopedAdvise (IFileDialog& d, Events& events) : dialog (d) { dialog.Advise (&events, &cookie); }
  217. ~ScopedAdvise() { dialog.Unadvise (cookie); }
  218. IFileDialog& dialog;
  219. DWORD cookie = 0;
  220. };
  221. Events events { *this };
  222. ScopedAdvise scope { dialog, events };
  223. return dialog.Show (async ? nullptr : static_cast<HWND> (owner->getWindowHandle())) == S_OK;
  224. }();
  225. ScopedLock lock (deletingDialog);
  226. nativeDialogRef = nullptr;
  227. return result;
  228. }
  229. //==============================================================================
  230. Array<URL> openDialogVistaAndUp (bool async)
  231. {
  232. const auto getUrl = [] (IShellItem& item)
  233. {
  234. LPWSTR ptr = nullptr;
  235. if (item.GetDisplayName (SIGDN_FILESYSPATH, &ptr) != S_OK)
  236. return URL();
  237. const auto path = std::unique_ptr<WCHAR, FreeLPWSTR> { ptr };
  238. return URL (File (String (path.get())));
  239. };
  240. if (isSave)
  241. {
  242. const auto dialog = [&]
  243. {
  244. ComSmartPtr<IFileDialog> ptr;
  245. ptr.CoCreateInstance (CLSID_FileSaveDialog, CLSCTX_INPROC_SERVER);
  246. return ptr;
  247. }();
  248. if (dialog == nullptr)
  249. return {};
  250. showDialog (*dialog, async);
  251. const auto item = [&]
  252. {
  253. ComSmartPtr<IShellItem> ptr;
  254. dialog->GetResult (ptr.resetAndGetPointerAddress());
  255. return ptr;
  256. }();
  257. if (item == nullptr)
  258. return {};
  259. const auto url = getUrl (*item);
  260. if (url.isEmpty())
  261. return {};
  262. return { url };
  263. }
  264. const auto dialog = [&]
  265. {
  266. ComSmartPtr<IFileOpenDialog> ptr;
  267. ptr.CoCreateInstance (CLSID_FileOpenDialog, CLSCTX_INPROC_SERVER);
  268. return ptr;
  269. }();
  270. if (dialog == nullptr)
  271. return {};
  272. showDialog (*dialog, async);
  273. const auto items = [&]
  274. {
  275. ComSmartPtr<IShellItemArray> ptr;
  276. dialog->GetResults (ptr.resetAndGetPointerAddress());
  277. return ptr;
  278. }();
  279. if (items == nullptr)
  280. return {};
  281. Array<URL> result;
  282. DWORD numItems = 0;
  283. items->GetCount (&numItems);
  284. for (DWORD i = 0; i < numItems; ++i)
  285. {
  286. ComSmartPtr<IShellItem> scope;
  287. items->GetItemAt (i, scope.resetAndGetPointerAddress());
  288. if (scope != nullptr)
  289. {
  290. const auto url = getUrl (*scope);
  291. if (! url.isEmpty())
  292. result.add (url);
  293. }
  294. }
  295. return result;
  296. }
  297. #endif
  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_MSVC
  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 flagsIn, FilePreviewComponent* previewComp)
  616. : owner (fileChooser),
  617. nativeFileChooser (std::make_unique<Win32NativeFileChooser> (this, flagsIn, 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