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.

520 lines
24KB

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