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.

546 lines
26KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE examples.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. The code included in this file is provided under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  7. To use, copy, modify, and/or distribute this software for any purpose with or
  8. without fee is hereby granted provided that the above copyright notice and
  9. this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES,
  11. WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR
  12. PURPOSE, ARE DISCLAIMED.
  13. ==============================================================================
  14. */
  15. /*******************************************************************************
  16. The block below describes the properties of this PIP. A PIP is a short snippet
  17. of code that can be read by the Projucer and used to generate a JUCE project.
  18. BEGIN_JUCE_PIP_METADATA
  19. name: DialogsDemo
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: Displays different types of dialog windows.
  24. dependencies: juce_core, juce_data_structures, juce_events, juce_graphics,
  25. juce_gui_basics, juce_gui_extra
  26. exporters: xcode_mac, vs2022, linux_make, androidstudio, xcode_iphone
  27. moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1
  28. type: Component
  29. mainClass: DialogsDemo
  30. useLocalCopy: 1
  31. END_JUCE_PIP_METADATA
  32. *******************************************************************************/
  33. #pragma once
  34. #include "../Assets/DemoUtilities.h"
  35. //==============================================================================
  36. struct MessageBoxOwnerComponent : public Component
  37. {
  38. ScopedMessageBox messageBox;
  39. };
  40. //==============================================================================
  41. class DemoBackgroundThread final : public ThreadWithProgressWindow
  42. {
  43. public:
  44. explicit DemoBackgroundThread (MessageBoxOwnerComponent& comp)
  45. : ThreadWithProgressWindow ("busy doing some important things...", true, true),
  46. owner (&comp)
  47. {
  48. setStatusMessage ("Getting ready...");
  49. }
  50. void run() override
  51. {
  52. setProgress (-1.0); // setting a value beyond the range 0 -> 1 will show a spinning bar..
  53. setStatusMessage ("Preparing to do some stuff...");
  54. wait (2000);
  55. int thingsToDo = 10;
  56. for (int i = 0; i < thingsToDo; ++i)
  57. {
  58. // must check this as often as possible, because this is
  59. // how we know if the user's pressed 'cancel'
  60. if (threadShouldExit())
  61. return;
  62. // this will update the progress bar on the dialog box
  63. setProgress (i / (double) thingsToDo);
  64. setStatusMessage (String (thingsToDo - i) + " things left to do...");
  65. wait (500);
  66. }
  67. setProgress (-1.0); // setting a value beyond the range 0 -> 1 will show a spinning bar..
  68. setStatusMessage ("Finishing off the last few bits and pieces!");
  69. wait (2000);
  70. }
  71. // This method gets called on the message thread once our thread has finished..
  72. void threadComplete (bool userPressedCancel) override
  73. {
  74. const String messageString (userPressedCancel ? "You pressed cancel!" : "Thread finished ok!");
  75. if (owner != nullptr)
  76. {
  77. owner->messageBox = AlertWindow::showScopedAsync (MessageBoxOptions()
  78. .withIconType (MessageBoxIconType::InfoIcon)
  79. .withTitle ("Progress window")
  80. .withMessage (messageString)
  81. .withButton ("OK"),
  82. nullptr);
  83. }
  84. // ..and clean up by deleting our thread object..
  85. delete this;
  86. }
  87. Component::SafePointer<MessageBoxOwnerComponent> owner;
  88. };
  89. //==============================================================================
  90. class DialogsDemo final : public MessageBoxOwnerComponent
  91. {
  92. public:
  93. enum DialogType
  94. {
  95. plainAlertWindow,
  96. warningAlertWindow,
  97. infoAlertWindow,
  98. questionAlertWindow,
  99. yesNoCancelAlertWindow,
  100. extraComponentsAlertWindow,
  101. calloutBoxWindow,
  102. progressWindow,
  103. loadChooser,
  104. loadWithPreviewChooser,
  105. directoryChooser,
  106. saveChooser,
  107. shareText,
  108. shareFile,
  109. shareImage,
  110. numDialogs
  111. };
  112. DialogsDemo()
  113. {
  114. setOpaque (true);
  115. addAndMakeVisible (nativeButton);
  116. nativeButton.setButtonText ("Use Native Windows");
  117. nativeButton.onClick = [this] { getLookAndFeel().setUsingNativeAlertWindows (nativeButton.getToggleState()); };
  118. StringArray windowNames { "Plain Alert Window",
  119. "Alert Window With Warning Icon",
  120. "Alert Window With Info Icon",
  121. "Alert Window With Question Icon",
  122. "Yes No Cancel Alert Window",
  123. "Alert Window With Extra Components",
  124. "CalloutBox",
  125. "Thread With Progress Window",
  126. "'Load' File Browser",
  127. "'Load' File Browser With Image Preview",
  128. "'Choose Directory' File Browser",
  129. "'Save' File Browser",
  130. "Share Text",
  131. "Share Files",
  132. "Share Images" };
  133. // warn in case we add any windows
  134. jassert (windowNames.size() == numDialogs);
  135. for (auto windowName : windowNames)
  136. {
  137. auto* newButton = new TextButton();
  138. addAndMakeVisible (windowButtons.add (newButton));
  139. newButton->setButtonText (windowName);
  140. auto index = windowNames.indexOf (windowName);
  141. newButton->onClick = [this, index, newButton] { showWindow (*newButton, static_cast<DialogType> (index)); };
  142. }
  143. setSize (500, 500);
  144. RuntimePermissions::request (RuntimePermissions::readExternalStorage, [ptr = Component::SafePointer (this)] (bool granted)
  145. {
  146. if (granted || ptr == nullptr)
  147. return;
  148. ptr->messageBox = AlertWindow::showScopedAsync (MessageBoxOptions()
  149. .withIconType (MessageBoxIconType::WarningIcon)
  150. .withTitle ("Permissions warning")
  151. .withMessage ("External storage access permission not granted, some files"
  152. " may be inaccessible.")
  153. .withButton ("OK"),
  154. nullptr);
  155. });
  156. }
  157. //==============================================================================
  158. void paint (Graphics& g) override
  159. {
  160. g.fillAll (getUIColourIfAvailable (LookAndFeel_V4::ColourScheme::UIColour::windowBackground));
  161. }
  162. void resized() override
  163. {
  164. auto area = getLocalBounds().reduced (5, 15);
  165. Rectangle<int> topRow;
  166. for (auto* b : windowButtons)
  167. {
  168. auto index = windowButtons.indexOf (b);
  169. if (topRow.getWidth() < 10 || index == loadChooser)
  170. topRow = area.removeFromTop (26);
  171. if (index == progressWindow)
  172. area.removeFromTop (20);
  173. b->setBounds (topRow.removeFromLeft (area.getWidth() / 2).reduced (4, 2));
  174. }
  175. area.removeFromTop (15);
  176. nativeButton.setBounds (area.removeFromTop (24));
  177. }
  178. private:
  179. OwnedArray<TextButton> windowButtons;
  180. ToggleButton nativeButton;
  181. auto getAlertBoxResultChosen()
  182. {
  183. return [ptr = Component::SafePointer (this)] (int result)
  184. {
  185. if (ptr != nullptr)
  186. ptr->messageBox = AlertWindow::showScopedAsync (MessageBoxOptions()
  187. .withIconType (MessageBoxIconType::InfoIcon)
  188. .withTitle ("Alert Box")
  189. .withMessage ("Result code: " + String (result))
  190. .withButton ("OK"),
  191. nullptr);
  192. };
  193. }
  194. auto getAsyncAlertBoxResultChosen()
  195. {
  196. return [ptr = Component::SafePointer (this)] (int result)
  197. {
  198. if (ptr == nullptr)
  199. return;
  200. auto& aw = *ptr->asyncAlertWindow;
  201. aw.exitModalState (result);
  202. aw.setVisible (false);
  203. if (result == 0)
  204. {
  205. ptr->getAlertBoxResultChosen() (result);
  206. return;
  207. }
  208. auto optionIndexChosen = aw.getComboBoxComponent ("option")->getSelectedItemIndex();
  209. auto text = aw.getTextEditorContents ("text");
  210. ptr->messageBox = AlertWindow::showScopedAsync (MessageBoxOptions()
  211. .withIconType (MessageBoxIconType::InfoIcon)
  212. .withTitle ("Alert Box")
  213. .withMessage ("Result code: " + String (result) + newLine
  214. + "Option index chosen: " + String (optionIndexChosen) + newLine
  215. + "Text: " + text)
  216. .withButton ("OK"),
  217. nullptr);
  218. };
  219. }
  220. void showWindow (Component& button, DialogType type)
  221. {
  222. if (type >= plainAlertWindow && type <= questionAlertWindow)
  223. {
  224. MessageBoxIconType icon = MessageBoxIconType::NoIcon;
  225. if (type == warningAlertWindow) icon = MessageBoxIconType::WarningIcon;
  226. if (type == infoAlertWindow) icon = MessageBoxIconType::InfoIcon;
  227. if (type == questionAlertWindow) icon = MessageBoxIconType::QuestionIcon;
  228. auto options = MessageBoxOptions::makeOptionsOk (icon,
  229. "This is an AlertWindow",
  230. "And this is the AlertWindow's message. "
  231. "Blah blah blah blah blah blah blah blah blah blah blah blah blah.");
  232. messageBox = AlertWindow::showScopedAsync (options, nullptr);
  233. }
  234. else if (type == yesNoCancelAlertWindow)
  235. {
  236. auto options = MessageBoxOptions::makeOptionsYesNoCancel (MessageBoxIconType::QuestionIcon,
  237. "This is a yes/no/cancel AlertWindow",
  238. "And this is the AlertWindow's message. "
  239. "Blah blah blah blah blah blah blah blah blah blah blah blah blah.");
  240. messageBox = AlertWindow::showScopedAsync (options, getAlertBoxResultChosen());
  241. }
  242. else if (type == calloutBoxWindow)
  243. {
  244. auto colourSelector = std::make_unique<ColourSelector>();
  245. colourSelector->setName ("background");
  246. colourSelector->setCurrentColour (findColour (TextButton::buttonColourId));
  247. colourSelector->setColour (ColourSelector::backgroundColourId, Colours::transparentBlack);
  248. colourSelector->setSize (300, 400);
  249. CallOutBox::launchAsynchronously (std::move (colourSelector), button.getScreenBounds(), nullptr);
  250. }
  251. else if (type == extraComponentsAlertWindow)
  252. {
  253. asyncAlertWindow = std::make_unique<AlertWindow> ("AlertWindow demo..",
  254. "This AlertWindow has a couple of extra components added to show how to add drop-down lists and text entry boxes.",
  255. MessageBoxIconType::QuestionIcon);
  256. asyncAlertWindow->addTextEditor ("text", "enter some text here", "text field:");
  257. asyncAlertWindow->addComboBox ("option", { "option 1", "option 2", "option 3", "option 4" }, "some options");
  258. asyncAlertWindow->addButton ("OK", 1, KeyPress (KeyPress::returnKey, 0, 0));
  259. asyncAlertWindow->addButton ("Cancel", 0, KeyPress (KeyPress::escapeKey, 0, 0));
  260. asyncAlertWindow->enterModalState (true, ModalCallbackFunction::create (getAsyncAlertBoxResultChosen()));
  261. }
  262. else if (type == progressWindow)
  263. {
  264. // This will launch our ThreadWithProgressWindow in a modal state. (Our subclass
  265. // will take care of deleting the object when the task has finished)
  266. (new DemoBackgroundThread (*this))->launchThread();
  267. }
  268. else if (type >= loadChooser && type <= saveChooser)
  269. {
  270. auto useNativeVersion = nativeButton.getToggleState();
  271. if (type == loadChooser)
  272. {
  273. fc.reset (new FileChooser ("Choose a file to open...", File::getCurrentWorkingDirectory(),
  274. "*", useNativeVersion));
  275. fc->launchAsync (FileBrowserComponent::canSelectMultipleItems
  276. | FileBrowserComponent::openMode
  277. | FileBrowserComponent::canSelectFiles,
  278. [this] (const FileChooser& chooser)
  279. {
  280. String chosen;
  281. auto results = chooser.getURLResults();
  282. for (auto result : results)
  283. chosen << (result.isLocalFile() ? result.getLocalFile().getFullPathName()
  284. : result.toString (false)) << "\n";
  285. messageBox = AlertWindow::showScopedAsync (MessageBoxOptions()
  286. .withIconType (MessageBoxIconType::InfoIcon)
  287. .withTitle ("File Chooser...")
  288. .withMessage ("You picked: " + chosen)
  289. .withButton ("OK"),
  290. nullptr);
  291. });
  292. }
  293. else if (type == loadWithPreviewChooser)
  294. {
  295. imagePreview.setSize (200, 200);
  296. fc.reset (new FileChooser ("Choose an image to open...", File::getCurrentWorkingDirectory(),
  297. "*.jpg;*.jpeg;*.png;*.gif", useNativeVersion));
  298. fc->launchAsync (FileBrowserComponent::openMode
  299. | FileBrowserComponent::canSelectFiles
  300. | FileBrowserComponent::canSelectMultipleItems,
  301. [this] (const FileChooser& chooser)
  302. {
  303. String chosen;
  304. auto results = chooser.getURLResults();
  305. for (auto result : results)
  306. chosen << (result.isLocalFile() ? result.getLocalFile().getFullPathName()
  307. : result.toString (false)) << "\n";
  308. messageBox = AlertWindow::showScopedAsync (MessageBoxOptions()
  309. .withIconType (MessageBoxIconType::InfoIcon)
  310. .withTitle ("File Chooser...")
  311. .withMessage ("You picked: " + chosen)
  312. .withButton ("OK"),
  313. nullptr);
  314. },
  315. &imagePreview);
  316. }
  317. else if (type == saveChooser)
  318. {
  319. auto fileToSave = File::createTempFile ("saveChooserDemo");
  320. if (fileToSave.createDirectory().wasOk())
  321. {
  322. fileToSave = fileToSave.getChildFile ("JUCE.png");
  323. fileToSave.deleteFile();
  324. FileOutputStream outStream (fileToSave);
  325. if (outStream.openedOk())
  326. if (auto inStream = createAssetInputStream ("juce_icon.png"))
  327. outStream.writeFromInputStream (*inStream, -1);
  328. }
  329. fc.reset (new FileChooser ("Choose a file to save...",
  330. File::getCurrentWorkingDirectory().getChildFile (fileToSave.getFileName()),
  331. "*", useNativeVersion));
  332. fc->launchAsync (FileBrowserComponent::saveMode | FileBrowserComponent::canSelectFiles,
  333. [this, fileToSave] (const FileChooser& chooser)
  334. {
  335. auto result = chooser.getURLResult();
  336. auto name = result.isEmpty() ? String()
  337. : (result.isLocalFile() ? result.getLocalFile().getFullPathName()
  338. : result.toString (true));
  339. // Android and iOS file choosers will create placeholder files for chosen
  340. // paths, so we may as well write into those files.
  341. #if JUCE_ANDROID || JUCE_IOS
  342. if (! result.isEmpty())
  343. {
  344. std::unique_ptr<InputStream> wi (fileToSave.createInputStream());
  345. std::unique_ptr<OutputStream> wo (result.createOutputStream());
  346. if (wi.get() != nullptr && wo.get() != nullptr)
  347. {
  348. [[maybe_unused]] auto numWritten = wo->writeFromInputStream (*wi, -1);
  349. jassert (numWritten > 0);
  350. wo->flush();
  351. }
  352. }
  353. #endif
  354. messageBox = AlertWindow::showScopedAsync (MessageBoxOptions()
  355. .withIconType (MessageBoxIconType::InfoIcon)
  356. .withTitle ("File Chooser...")
  357. .withMessage ("You picked: " + name)
  358. .withButton ("OK"),
  359. nullptr);
  360. });
  361. }
  362. else if (type == directoryChooser)
  363. {
  364. fc.reset (new FileChooser ("Choose a directory...",
  365. File::getCurrentWorkingDirectory(),
  366. "*",
  367. useNativeVersion));
  368. fc->launchAsync (FileBrowserComponent::openMode | FileBrowserComponent::canSelectDirectories,
  369. [this] (const FileChooser& chooser)
  370. {
  371. auto result = chooser.getURLResult();
  372. auto name = result.isLocalFile() ? result.getLocalFile().getFullPathName()
  373. : result.toString (true);
  374. messageBox = AlertWindow::showScopedAsync (MessageBoxOptions()
  375. .withIconType (MessageBoxIconType::InfoIcon)
  376. .withTitle ("File Chooser...")
  377. .withMessage ("You picked: " + name)
  378. .withButton ("OK"),
  379. nullptr);
  380. });
  381. }
  382. }
  383. else if (type == shareText)
  384. {
  385. messageBox = ContentSharer::shareTextScoped ("I love JUCE!", [ptr = Component::SafePointer (this)] (bool success, const String& error)
  386. {
  387. if (ptr == nullptr)
  388. return;
  389. auto resultString = success ? String ("success") : ("failure\n (error: " + error + ")");
  390. ptr->messageBox = AlertWindow::showScopedAsync (MessageBoxOptions()
  391. .withIconType (MessageBoxIconType::InfoIcon)
  392. .withTitle ("Sharing Text Result")
  393. .withMessage ("Sharing text finished\nwith " + resultString)
  394. .withButton ("OK"),
  395. nullptr);
  396. });
  397. }
  398. else if (type == shareFile)
  399. {
  400. File fileToSave = File::createTempFile ("DialogsDemoSharingTest");
  401. if (fileToSave.createDirectory().wasOk())
  402. {
  403. fileToSave = fileToSave.getChildFile ("SharingDemoFile.txt");
  404. fileToSave.replaceWithText ("Make it fast!");
  405. Array<URL> urls;
  406. urls.add (URL (fileToSave));
  407. messageBox = ContentSharer::shareFilesScoped (urls, [ptr = Component::SafePointer (this)] (bool success, const String& error)
  408. {
  409. if (ptr == nullptr)
  410. return;
  411. auto resultString = success ? String ("success") : ("failure\n (error: " + error + ")");
  412. ptr->messageBox = AlertWindow::showScopedAsync (MessageBoxOptions()
  413. .withIconType (MessageBoxIconType::InfoIcon)
  414. .withTitle ("Sharing Files Result")
  415. .withMessage ("Sharing files finished\nwith " + resultString)
  416. .withButton ("OK"),
  417. nullptr);
  418. });
  419. }
  420. }
  421. else if (type == shareImage)
  422. {
  423. auto myImage = getImageFromAssets ("juce_icon.png");
  424. Image myImage2 (Image::RGB, 500, 500, true);
  425. Graphics g (myImage2);
  426. g.setColour (Colours::green);
  427. ColourGradient gradient (Colours::yellow, 170, 170, Colours::cyan, 170, 20, true);
  428. g.setGradientFill (gradient);
  429. g.fillEllipse (20, 20, 300, 300);
  430. Array<Image> images { myImage, myImage2 };
  431. messageBox = ContentSharer::shareImagesScoped (images, nullptr, [ptr = Component::SafePointer (this)] (bool success, const String& error)
  432. {
  433. if (ptr == nullptr)
  434. return;
  435. String resultString = success ? String ("success")
  436. : ("failure\n (error: " + error + ")");
  437. ptr->messageBox = AlertWindow::showScopedAsync (MessageBoxOptions()
  438. .withIconType (MessageBoxIconType::InfoIcon)
  439. .withTitle ("Sharing Images Result")
  440. .withMessage ("Sharing images finished\nwith " + resultString)
  441. .withButton ("OK"),
  442. nullptr);
  443. });
  444. }
  445. }
  446. ImagePreviewComponent imagePreview;
  447. std::unique_ptr<FileChooser> fc;
  448. std::unique_ptr<AlertWindow> asyncAlertWindow;
  449. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DialogsDemo)
  450. };