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.

1575 lines
60KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE examples.
  4. Copyright (c) 2020 - 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: WidgetsDemo
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: Showcases various widgets.
  24. dependencies: juce_core, juce_data_structures, juce_events, juce_graphics,
  25. juce_gui_basics, juce_gui_extra
  26. exporters: xcode_mac, vs2019, linux_make, androidstudio, xcode_iphone
  27. moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1
  28. type: Component
  29. mainClass: WidgetsDemo
  30. useLocalCopy: 1
  31. END_JUCE_PIP_METADATA
  32. *******************************************************************************/
  33. #pragma once
  34. #include "../Assets/DemoUtilities.h"
  35. //==============================================================================
  36. static void showBubbleMessage (Component& targetComponent, const String& textToShow,
  37. std::unique_ptr<BubbleMessageComponent>& bmc,
  38. bool isRunningComponentTransformDemo);
  39. //==============================================================================
  40. /** To demonstrate how sliders can have custom snapping applied to their values,
  41. this simple class snaps the value to 50 if it comes near.
  42. */
  43. struct SnappingSlider : public Slider
  44. {
  45. double snapValue (double attemptedValue, DragMode dragMode) override
  46. {
  47. if (dragMode == notDragging)
  48. return attemptedValue; // if they're entering the value in the text-box, don't mess with it.
  49. if (attemptedValue > 40 && attemptedValue < 60)
  50. return 50.0;
  51. return attemptedValue;
  52. }
  53. };
  54. /** A TextButton that pops up a colour chooser to change its colours. */
  55. class ColourChangeButton : public TextButton,
  56. public ChangeListener
  57. {
  58. public:
  59. ColourChangeButton()
  60. : TextButton ("Click to change colour...")
  61. {
  62. setSize (10, 24);
  63. changeWidthToFitText();
  64. }
  65. void clicked() override
  66. {
  67. auto colourSelector = std::make_unique<ColourSelector> (ColourSelector::showAlphaChannel
  68. | ColourSelector::showColourAtTop
  69. | ColourSelector::editableColour
  70. | ColourSelector::showSliders
  71. | ColourSelector::showColourspace);
  72. colourSelector->setName ("background");
  73. colourSelector->setCurrentColour (findColour (TextButton::buttonColourId));
  74. colourSelector->addChangeListener (this);
  75. colourSelector->setColour (ColourSelector::backgroundColourId, Colours::transparentBlack);
  76. colourSelector->setSize (300, 400);
  77. CallOutBox::launchAsynchronously (std::move (colourSelector), getScreenBounds(), nullptr);
  78. }
  79. using TextButton::clicked;
  80. void changeListenerCallback (ChangeBroadcaster* source) override
  81. {
  82. if (auto* cs = dynamic_cast<ColourSelector*> (source))
  83. setColour (TextButton::buttonColourId, cs->getCurrentColour());
  84. }
  85. };
  86. //==============================================================================
  87. struct SlidersPage : public Component
  88. {
  89. SlidersPage()
  90. {
  91. Rectangle<int> layoutArea { 20, 20, 580, 430 };
  92. auto sliderArea = layoutArea.removeFromTop (320);
  93. auto* s = createSlider (false);
  94. s->setSliderStyle (Slider::LinearVertical);
  95. s->setTextBoxStyle (Slider::TextBoxBelow, false, 100, 20);
  96. s->setBounds (sliderArea.removeFromLeft (70));
  97. s->setDoubleClickReturnValue (true, 50.0); // double-clicking this slider will set it to 50.0
  98. s->setTextValueSuffix (" units");
  99. s = createSlider (false);
  100. s->setSliderStyle (Slider::LinearVertical);
  101. s->setVelocityBasedMode (true);
  102. s->setSkewFactor (0.5);
  103. s->setTextBoxStyle (Slider::TextBoxAbove, true, 100, 20);
  104. s->setBounds (sliderArea.removeFromLeft (70));
  105. s->setTextValueSuffix (" rels");
  106. sliderArea.removeFromLeft (20);
  107. auto horizonalSliderArea = sliderArea.removeFromLeft (180);
  108. s = createSlider (true);
  109. s->setSliderStyle (Slider::LinearHorizontal);
  110. s->setTextBoxStyle (Slider::TextBoxLeft, false, 80, 20);
  111. s->setBounds (horizonalSliderArea.removeFromTop (20));
  112. s = createSlider (false);
  113. s->setSliderStyle (Slider::LinearHorizontal);
  114. s->setTextBoxStyle (Slider::NoTextBox, false, 0, 0);
  115. horizonalSliderArea.removeFromTop (20);
  116. s->setBounds (horizonalSliderArea.removeFromTop (20));
  117. s->setPopupDisplayEnabled (true, false, this);
  118. s->setTextValueSuffix (" nuns required to change a lightbulb");
  119. s = createSlider (false);
  120. s->setSliderStyle (Slider::LinearHorizontal);
  121. s->setTextBoxStyle (Slider::TextEntryBoxPosition::TextBoxAbove, false, 70, 20);
  122. horizonalSliderArea.removeFromTop (20);
  123. s->setBounds (horizonalSliderArea.removeFromTop (50));
  124. s->setPopupDisplayEnabled (true, false, this);
  125. s = createSlider (false);
  126. s->setSliderStyle (Slider::IncDecButtons);
  127. s->setTextBoxStyle (Slider::TextBoxLeft, false, 50, 20);
  128. horizonalSliderArea.removeFromTop (20);
  129. s->setBounds (horizonalSliderArea.removeFromTop (20));
  130. s->setIncDecButtonsMode (Slider::incDecButtonsDraggable_Vertical);
  131. s = createSlider (false);
  132. s->setSliderStyle (Slider::Rotary);
  133. s->setRotaryParameters (MathConstants<float>::pi * 1.2f, MathConstants<float>::pi * 2.8f, false);
  134. s->setTextBoxStyle (Slider::TextBoxRight, false, 70, 20);
  135. horizonalSliderArea.removeFromTop (15);
  136. s->setBounds (horizonalSliderArea.removeFromTop (70));
  137. s->setTextValueSuffix (" mm");
  138. s = createSlider (false);
  139. s->setSliderStyle (Slider::LinearBar);
  140. horizonalSliderArea.removeFromTop (10);
  141. s->setBounds (horizonalSliderArea.removeFromTop (30));
  142. s->setTextValueSuffix (" gallons");
  143. sliderArea.removeFromLeft (20);
  144. auto twoValueSliderArea = sliderArea.removeFromLeft (180);
  145. s = createSlider (false);
  146. s->setSliderStyle (Slider::TwoValueHorizontal);
  147. s->setBounds (twoValueSliderArea.removeFromTop (40));
  148. s = createSlider (false);
  149. s->setSliderStyle (Slider::ThreeValueHorizontal);
  150. s->setPopupDisplayEnabled (true, false, this);
  151. twoValueSliderArea.removeFromTop (10);
  152. s->setBounds (twoValueSliderArea.removeFromTop (40));
  153. s = createSlider (false);
  154. s->setSliderStyle (Slider::TwoValueVertical);
  155. twoValueSliderArea.removeFromLeft (30);
  156. s->setBounds (twoValueSliderArea.removeFromLeft (40));
  157. s = createSlider (false);
  158. s->setSliderStyle (Slider::ThreeValueVertical);
  159. s->setPopupDisplayEnabled (true, false, this);
  160. twoValueSliderArea.removeFromLeft (30);
  161. s->setBounds (twoValueSliderArea.removeFromLeft (40));
  162. s = createSlider (false);
  163. s->setSliderStyle (Slider::LinearBarVertical);
  164. s->setTextBoxStyle (Slider::NoTextBox, false, 0, 0);
  165. sliderArea.removeFromLeft (20);
  166. s->setBounds (sliderArea.removeFromLeft (20));
  167. s->setPopupDisplayEnabled (true, true, this);
  168. s->setTextValueSuffix (" mickles in a muckle");
  169. /* Here, we'll create a Value object, and tell a bunch of our sliders to use it as their
  170. value source. By telling them all to share the same Value, they'll stay in sync with
  171. each other.
  172. We could also optionally keep a copy of this Value elsewhere, and by changing it,
  173. cause all the sliders to automatically update.
  174. */
  175. Value sharedValue;
  176. sharedValue = Random::getSystemRandom().nextDouble() * 100;
  177. for (int i = 0; i < 8; ++i)
  178. sliders.getUnchecked (i)->getValueObject().referTo (sharedValue);
  179. // ..and now we'll do the same for all our min/max slider values..
  180. Value sharedValueMin, sharedValueMax;
  181. sharedValueMin = Random::getSystemRandom().nextDouble() * 40.0;
  182. sharedValueMax = Random::getSystemRandom().nextDouble() * 40.0 + 60.0;
  183. for (int i = 8; i <= 11; ++i)
  184. {
  185. auto* selectedSlider = sliders.getUnchecked(i);
  186. selectedSlider->setTextBoxStyle (Slider::NoTextBox, false, 0, 0);
  187. selectedSlider->getMaxValueObject().referTo (sharedValueMax);
  188. selectedSlider->getMinValueObject().referTo (sharedValueMin);
  189. }
  190. hintLabel.setBounds (layoutArea);
  191. addAndMakeVisible (hintLabel);
  192. }
  193. private:
  194. OwnedArray<Slider> sliders;
  195. Label hintLabel { "hint", "Try right-clicking on a slider for an options menu. \n\n"
  196. "Also, holding down CTRL while dragging will turn on a slider's velocity-sensitive mode" };
  197. Slider* createSlider (bool isSnapping)
  198. {
  199. auto* s = isSnapping ? new SnappingSlider()
  200. : new Slider();
  201. sliders.add (s);
  202. addAndMakeVisible (s);
  203. s->setRange (0.0, 100.0, 0.1);
  204. s->setPopupMenuEnabled (true);
  205. s->setValue (Random::getSystemRandom().nextDouble() * 100.0, dontSendNotification);
  206. return s;
  207. }
  208. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SlidersPage)
  209. };
  210. //==============================================================================
  211. struct ButtonsPage : public Component
  212. {
  213. ButtonsPage (bool isRunningComponentTransformDemo)
  214. {
  215. {
  216. auto* group = addToList (new GroupComponent ("group", "Radio buttons"));
  217. group->setBounds (20, 20, 220, 140);
  218. }
  219. for (int i = 0; i < 4; ++i)
  220. {
  221. auto* tb = addToList (new ToggleButton ("Radio Button #" + String (i + 1)));
  222. tb->setRadioGroupId (1234);
  223. tb->setBounds (45, 46 + i * 22, 180, 22);
  224. tb->setTooltip ("A set of mutually-exclusive radio buttons");
  225. if (i == 0)
  226. tb->setToggleState (true, dontSendNotification);
  227. }
  228. for (int i = 0; i < 4; ++i)
  229. {
  230. DrawablePath normal, over;
  231. Path p;
  232. p.addStar ({}, i + 5, 20.0f, 50.0f, -0.2f);
  233. normal.setPath (p);
  234. normal.setFill (Colours::lightblue);
  235. normal.setStrokeFill (Colours::black);
  236. normal.setStrokeThickness (4.0f);
  237. over.setPath (p);
  238. over.setFill (Colours::blue);
  239. over.setStrokeFill (Colours::black);
  240. over.setStrokeThickness (4.0f);
  241. auto* db = addToList (new DrawableButton (String (i + 5) + " points", DrawableButton::ImageAboveTextLabel));
  242. db->setImages (&normal, &over, nullptr);
  243. db->setClickingTogglesState (true);
  244. db->setRadioGroupId (23456);
  245. int buttonSize = 50;
  246. db->setBounds (25 + i * buttonSize, 180, buttonSize, buttonSize);
  247. if (i == 0)
  248. db->setToggleState (true, dontSendNotification);
  249. }
  250. for (int i = 0; i < 4; ++i)
  251. {
  252. auto* tb = addToList (new TextButton ("Button " + String (i + 1)));
  253. tb->setClickingTogglesState (true);
  254. tb->setRadioGroupId (34567);
  255. tb->setColour (TextButton::textColourOffId, Colours::black);
  256. tb->setColour (TextButton::textColourOnId, Colours::black);
  257. tb->setColour (TextButton::buttonColourId, Colours::white);
  258. tb->setColour (TextButton::buttonOnColourId, Colours::blueviolet.brighter());
  259. tb->setBounds (20 + i * 55, 260, 55, 24);
  260. tb->setConnectedEdges (((i != 0) ? Button::ConnectedOnLeft : 0)
  261. | ((i != 3) ? Button::ConnectedOnRight : 0));
  262. if (i == 0)
  263. tb->setToggleState (true, dontSendNotification);
  264. }
  265. {
  266. auto* colourChangeButton = new ColourChangeButton();
  267. components.add (colourChangeButton);
  268. addAndMakeVisible (colourChangeButton);
  269. colourChangeButton->setTopLeftPosition (20, 320);
  270. }
  271. {
  272. auto* hyperlink = addToList (new HyperlinkButton ("This is a HyperlinkButton",
  273. { "http://www.juce.com" }));
  274. hyperlink->setBounds (260, 20, 200, 24);
  275. }
  276. // create some drawables to use for our drawable buttons...
  277. DrawablePath normal, over;
  278. {
  279. Path p;
  280. p.addStar ({}, 5, 20.0f, 50.0f, 0.2f);
  281. normal.setPath (p);
  282. normal.setFill (getRandomDarkColour());
  283. }
  284. {
  285. Path p;
  286. p.addStar ({}, 9, 25.0f, 50.0f, 0.0f);
  287. over.setPath (p);
  288. over.setFill (getRandomBrightColour());
  289. over.setStrokeFill (getRandomDarkColour());
  290. over.setStrokeThickness (5.0f);
  291. }
  292. DrawableImage down;
  293. down.setImage (getImageFromAssets ("juce_icon.png"));
  294. down.setOverlayColour (Colours::black.withAlpha (0.3f));
  295. auto popupMessageCallback = [this, isRunningComponentTransformDemo]
  296. {
  297. if (auto* focused = Component::getCurrentlyFocusedComponent())
  298. showBubbleMessage (*focused,
  299. "This is a demo of the BubbleMessageComponent, which lets you pop up a message pointing "
  300. "at a component or somewhere on the screen.\n\n"
  301. "The message bubbles will disappear after a timeout period, or when the mouse is clicked.",
  302. this->bubbleMessage,
  303. isRunningComponentTransformDemo);
  304. };
  305. {
  306. // create an image-above-text button from these drawables..
  307. auto db = addToList (new DrawableButton ("Button 1", DrawableButton::ImageAboveTextLabel));
  308. db->setImages (&normal, &over, &down);
  309. db->setBounds (260, 60, 80, 80);
  310. db->setTooltip ("This is a DrawableButton with a label");
  311. db->onClick = popupMessageCallback;
  312. }
  313. {
  314. // create an image-only button from these drawables..
  315. auto db = addToList (new DrawableButton ("Button 2", DrawableButton::ImageFitted));
  316. db->setImages (&normal, &over, &down);
  317. db->setClickingTogglesState (true);
  318. db->setBounds (370, 60, 80, 80);
  319. db->setTooltip ("This is an image-only DrawableButton");
  320. db->onClick = popupMessageCallback;
  321. }
  322. {
  323. // create an image-on-button-shape button from the same drawables..
  324. auto db = addToList (new DrawableButton ("Button 3", DrawableButton::ImageOnButtonBackground));
  325. db->setImages (&normal, nullptr, nullptr);
  326. db->setBounds (260, 160, 110, 25);
  327. db->setTooltip ("This is a DrawableButton on a standard button background");
  328. db->onClick = popupMessageCallback;
  329. }
  330. {
  331. auto db = addToList (new DrawableButton ("Button 4", DrawableButton::ImageOnButtonBackground));
  332. db->setImages (&normal, &over, &down);
  333. db->setClickingTogglesState (true);
  334. db->setColour (DrawableButton::backgroundColourId, Colours::white);
  335. db->setColour (DrawableButton::backgroundOnColourId, Colours::yellow);
  336. db->setBounds (400, 150, 50, 50);
  337. db->setTooltip ("This is a DrawableButton on a standard button background");
  338. db->onClick = popupMessageCallback;
  339. }
  340. {
  341. auto sb = addToList (new ShapeButton ("ShapeButton",
  342. getRandomDarkColour(),
  343. getRandomDarkColour(),
  344. getRandomDarkColour()));
  345. sb->setShape (getJUCELogoPath(), false, true, false);
  346. sb->setBounds (260, 220, 200, 120);
  347. }
  348. {
  349. auto ib = addToList (new ImageButton ("ImageButton"));
  350. auto juceImage = getImageFromAssets ("juce_icon.png");
  351. ib->setImages (true, true, true,
  352. juceImage, 0.7f, Colours::transparentBlack,
  353. juceImage, 1.0f, Colours::transparentBlack,
  354. juceImage, 1.0f, getRandomBrightColour().withAlpha (0.8f),
  355. 0.5f);
  356. ib->setBounds (45, 380, 100, 100);
  357. ib->setTooltip ("ImageButton - showing alpha-channel hit-testing and colour overlay when clicked");
  358. }
  359. }
  360. private:
  361. OwnedArray<Component> components;
  362. std::unique_ptr<BubbleMessageComponent> bubbleMessage;
  363. TooltipWindow tooltipWindow;
  364. // This little function avoids a bit of code-duplication by adding a component to
  365. // our list as well as calling addAndMakeVisible on it..
  366. template <typename ComponentType>
  367. ComponentType* addToList (ComponentType* newComp)
  368. {
  369. components.add (newComp);
  370. addAndMakeVisible (newComp);
  371. return newComp;
  372. }
  373. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonsPage)
  374. };
  375. //==============================================================================
  376. struct MiscPage : public Component
  377. {
  378. MiscPage()
  379. {
  380. addAndMakeVisible (textEditor1);
  381. textEditor1.setBounds (10, 25, 200, 24);
  382. textEditor1.setText ("Single-line text box");
  383. addAndMakeVisible (textEditor2);
  384. textEditor2.setBounds (10, 55, 200, 24);
  385. textEditor2.setText ("Password");
  386. addAndMakeVisible (comboBox);
  387. comboBox.setBounds (10, 85, 200, 24);
  388. comboBox.setEditableText (true);
  389. comboBox.setJustificationType (Justification::centred);
  390. for (int i = 1; i < 100; ++i)
  391. comboBox.addItem ("combo box item " + String (i), i);
  392. comboBox.setSelectedId (1);
  393. }
  394. void lookAndFeelChanged() override
  395. {
  396. textEditor1.applyFontToAllText (textEditor1.getFont());
  397. textEditor2.applyFontToAllText (textEditor2.getFont());
  398. }
  399. TextEditor textEditor1,
  400. textEditor2 { "Password", (juce_wchar) 0x2022 };
  401. ComboBox comboBox { "Combo" };
  402. };
  403. //==============================================================================
  404. struct MenuPage : public Component
  405. {
  406. MenuPage()
  407. {
  408. addAndMakeVisible (shortMenuButton);
  409. shortMenuButton.onClick = [&]
  410. {
  411. PopupMenu menu;
  412. menu.addItem ("Single Item", nullptr);
  413. menu.showMenuAsync (PopupMenu::Options{}.withTargetComponent (shortMenuButton));
  414. };
  415. addAndMakeVisible (longMenuButton);
  416. longMenuButton.onClick = [&]
  417. {
  418. PopupMenu menu;
  419. for (int i = 0; i < 40; ++i)
  420. menu.addItem ("Item " + String (i), nullptr);
  421. menu.showMenuAsync (PopupMenu::Options{}.withTargetComponent (longMenuButton));
  422. };
  423. addAndMakeVisible (nestedMenusButton);
  424. nestedMenusButton.onClick = [&]
  425. {
  426. PopupMenu menu;
  427. for (int i = 0; i < 15; ++i)
  428. {
  429. PopupMenu subMenu;
  430. for (int j = 0; j < 10; ++j)
  431. {
  432. if (j % 2 == 0)
  433. {
  434. PopupMenu subSubMenu;
  435. for (int z = 0; z < 5; ++z)
  436. subSubMenu.addItem ("Sub-sub-item " + String (z), nullptr);
  437. subMenu.addSubMenu ("Sub-item " + String (j), subSubMenu);
  438. }
  439. else
  440. {
  441. subMenu.addItem ("Sub-item " + String (j), nullptr);
  442. }
  443. }
  444. menu.addSubMenu ("Item " + String (i), subMenu);
  445. }
  446. menu.showMenuAsync (PopupMenu::Options{}.withTargetComponent (nestedMenusButton));
  447. };
  448. addAndMakeVisible (multiColumnMenuButton);
  449. multiColumnMenuButton.onClick = [&]
  450. {
  451. PopupMenu menu;
  452. for (int i = 0; i < 200; ++i)
  453. menu.addItem ("Item " + String (i), nullptr);
  454. menu.showMenuAsync (PopupMenu::Options{}.withTargetComponent (multiColumnMenuButton)
  455. .withMinimumNumColumns (2)
  456. .withMaximumNumColumns (4));
  457. };
  458. addAndMakeVisible (customItemButton);
  459. customItemButton.onClick = [&]
  460. {
  461. struct CustomComponent : public PopupMenu::CustomComponent
  462. {
  463. CustomComponent (int widthIn, int heightIn, Colour backgroundIn)
  464. : idealWidth (widthIn), idealHeight (heightIn), background (backgroundIn)
  465. {}
  466. void getIdealSize (int& width, int& height) override
  467. {
  468. width = idealWidth;
  469. height = idealHeight;
  470. }
  471. void paint (Graphics& g) override { g.fillAll (background); }
  472. int idealWidth = 0;
  473. int idealHeight = 0;
  474. Colour background;
  475. };
  476. PopupMenu menu;
  477. menu.addCustomItem (-1, std::make_unique<CustomComponent> (100, 20, Colours::darkred));
  478. menu.addCustomItem (-1, std::make_unique<CustomComponent> (20, 100, Colours::darkgreen));
  479. menu.addCustomItem (-1, std::make_unique<CustomComponent> (100, 100, Colours::darkblue));
  480. menu.addCustomItem (-1, std::make_unique<CustomComponent> (100, 50, Colours::darkcyan));
  481. menu.addCustomItem (-1, std::make_unique<CustomComponent> (50, 100, Colours::darkmagenta));
  482. menu.showMenuAsync (PopupMenu::Options{}.withTargetComponent (customItemButton)
  483. .withMinimumNumColumns (5));
  484. };
  485. addAndMakeVisible (fancyThemeButton);
  486. fancyThemeButton.setLookAndFeel (&popupLookAndFeel);
  487. fancyThemeButton.onClick = [&]
  488. {
  489. const auto colour = Colour::fromHSL (randomColourGenerator.nextFloat(), 0.5f, 0.5f, 1.0f);
  490. fancyThemeButton.setColour (TextButton::buttonColourId, colour);
  491. PopupMenu menu;
  492. menu.setLookAndFeel (&popupLookAndFeel);
  493. for (auto length : { 5, 10, 7, 3 })
  494. {
  495. for (int i = 0; i < length; ++i)
  496. menu.addItem ("Item " + String (i), nullptr);
  497. menu.addColumnBreak();
  498. }
  499. menu.showMenuAsync (PopupMenu::Options{}.withTargetComponent (&fancyThemeButton));
  500. };
  501. }
  502. void resized() override
  503. {
  504. const auto makeItem = [] (Component& comp)
  505. {
  506. return FlexItem { comp }.withWidth (200).withHeight (24).withMargin ({ 4 });
  507. };
  508. FlexBox box;
  509. box.flexDirection = FlexBox::Direction::column;
  510. box.items = { makeItem (shortMenuButton),
  511. makeItem (longMenuButton),
  512. makeItem (nestedMenusButton),
  513. makeItem (multiColumnMenuButton),
  514. makeItem (customItemButton),
  515. makeItem (fancyThemeButton) };
  516. box.performLayout (getLocalBounds());
  517. }
  518. struct PopupMenuLookAndFeel : public LookAndFeel_V4
  519. {
  520. void drawPopupMenuColumnSeparatorWithOptions (Graphics& g,
  521. const Rectangle<int>& bounds,
  522. const PopupMenu::Options& opt)
  523. {
  524. if (auto* target = opt.getTargetComponent())
  525. {
  526. const auto baseColour = target->findColour (TextButton::buttonColourId);
  527. g.setColour (baseColour.brighter (0.4f));
  528. const float dashes[] { 5.0f, 5.0f };
  529. const auto centre = bounds.toFloat().getCentre();
  530. g.drawDashedLine ({ centre.withY ((float) bounds.getY()),
  531. centre.withY ((float) bounds.getBottom()) },
  532. dashes,
  533. numElementsInArray (dashes),
  534. 3.0f);
  535. }
  536. }
  537. void drawPopupMenuBackgroundWithOptions (Graphics& g, int, int, const PopupMenu::Options& opt)
  538. {
  539. if (auto* target = opt.getTargetComponent())
  540. {
  541. g.fillAll (target->findColour (TextButton::buttonColourId));
  542. }
  543. }
  544. // Return the amount of space that should be left between popup menu columns.
  545. int getPopupMenuColumnSeparatorWidthWithOptions (const PopupMenu::Options&)
  546. {
  547. return 10;
  548. }
  549. };
  550. Random randomColourGenerator;
  551. PopupMenuLookAndFeel popupLookAndFeel;
  552. TextButton shortMenuButton { "Short" },
  553. longMenuButton { "Long" },
  554. nestedMenusButton { "Nested Sub-Menus" },
  555. multiColumnMenuButton { "Multi Column" },
  556. customItemButton { "Custom Items" },
  557. fancyThemeButton { "Fancy Theme with Column Breaks" };
  558. };
  559. //==============================================================================
  560. class ToolbarDemoComp : public Component,
  561. private Slider::Listener
  562. {
  563. public:
  564. ToolbarDemoComp()
  565. {
  566. // Create and add the toolbar...
  567. addAndMakeVisible (toolbar);
  568. // And use our item factory to add a set of default icons to it...
  569. toolbar.addDefaultItems (factory);
  570. // Now we'll just create the other sliders and buttons on the demo page, which adjust
  571. // the toolbar's properties...
  572. addAndMakeVisible (infoLabel);
  573. infoLabel.setJustificationType (Justification::topLeft);
  574. infoLabel.setBounds (80, 80, 450, 100);
  575. infoLabel.setInterceptsMouseClicks (false, false);
  576. addAndMakeVisible (depthSlider);
  577. depthSlider.setRange (10.0, 200.0, 1.0);
  578. depthSlider.setValue (50, dontSendNotification);
  579. depthSlider.addListener (this);
  580. depthSlider.setBounds (80, 210, 300, 22);
  581. depthLabel.attachToComponent (&depthSlider, false);
  582. addAndMakeVisible (orientationButton);
  583. orientationButton.onClick = [this] { toolbar.setVertical (! toolbar.isVertical()); resized(); };
  584. orientationButton.changeWidthToFitText (22);
  585. orientationButton.setTopLeftPosition (depthSlider.getX(), depthSlider.getBottom() + 20);
  586. addAndMakeVisible (customiseButton);
  587. customiseButton.onClick = [this] { toolbar.showCustomisationDialog (factory); };
  588. customiseButton.changeWidthToFitText (22);
  589. customiseButton.setTopLeftPosition (orientationButton.getRight() + 20, orientationButton.getY());
  590. }
  591. void resized() override
  592. {
  593. auto toolbarThickness = (int) depthSlider.getValue();
  594. if (toolbar.isVertical())
  595. toolbar.setBounds (getLocalBounds().removeFromLeft (toolbarThickness));
  596. else
  597. toolbar.setBounds (getLocalBounds().removeFromTop (toolbarThickness));
  598. }
  599. void sliderValueChanged (Slider*) override
  600. {
  601. resized();
  602. }
  603. private:
  604. Toolbar toolbar;
  605. Slider depthSlider { Slider::LinearHorizontal, Slider::TextBoxLeft };
  606. Label depthLabel { {}, "Toolbar depth:" },
  607. infoLabel { {}, "As well as showing off toolbars, this demo illustrates how to store "
  608. "a set of SVG files in a Zip file, embed that in your application, and read "
  609. "them back in at runtime.\n\nThe icon images here are taken from the open-source "
  610. "Tango icon project."};
  611. TextButton orientationButton { "Vertical/Horizontal" },
  612. customiseButton { "Customise..." };
  613. //==============================================================================
  614. class DemoToolbarItemFactory : public ToolbarItemFactory
  615. {
  616. public:
  617. DemoToolbarItemFactory() {}
  618. //==============================================================================
  619. // Each type of item a toolbar can contain must be given a unique ID. These
  620. // are the ones we'll use in this demo.
  621. enum DemoToolbarItemIds
  622. {
  623. doc_new = 1,
  624. doc_open = 2,
  625. doc_save = 3,
  626. doc_saveAs = 4,
  627. edit_copy = 5,
  628. edit_cut = 6,
  629. edit_paste = 7,
  630. juceLogoButton = 8,
  631. customComboBox = 9
  632. };
  633. void getAllToolbarItemIds (Array<int>& ids) override
  634. {
  635. // This returns the complete list of all item IDs that are allowed to
  636. // go in our toolbar. Any items you might want to add must be listed here. The
  637. // order in which they are listed will be used by the toolbar customisation panel.
  638. ids.add (doc_new);
  639. ids.add (doc_open);
  640. ids.add (doc_save);
  641. ids.add (doc_saveAs);
  642. ids.add (edit_copy);
  643. ids.add (edit_cut);
  644. ids.add (edit_paste);
  645. ids.add (juceLogoButton);
  646. ids.add (customComboBox);
  647. // If you're going to use separators, then they must also be added explicitly
  648. // to the list.
  649. ids.add (separatorBarId);
  650. ids.add (spacerId);
  651. ids.add (flexibleSpacerId);
  652. }
  653. void getDefaultItemSet (Array<int>& ids) override
  654. {
  655. // This returns an ordered list of the set of items that make up a
  656. // toolbar's default set. Not all items need to be on this list, and
  657. // items can appear multiple times (e.g. the separators used here).
  658. ids.add (doc_new);
  659. ids.add (doc_open);
  660. ids.add (doc_save);
  661. ids.add (doc_saveAs);
  662. ids.add (spacerId);
  663. ids.add (separatorBarId);
  664. ids.add (edit_copy);
  665. ids.add (edit_cut);
  666. ids.add (edit_paste);
  667. ids.add (separatorBarId);
  668. ids.add (flexibleSpacerId);
  669. ids.add (customComboBox);
  670. ids.add (flexibleSpacerId);
  671. ids.add (separatorBarId);
  672. ids.add (juceLogoButton);
  673. }
  674. ToolbarItemComponent* createItem (int itemId) override
  675. {
  676. switch (itemId)
  677. {
  678. case doc_new: return createButtonFromZipFileSVG (itemId, "new", "document-new.svg");
  679. case doc_open: return createButtonFromZipFileSVG (itemId, "open", "document-open.svg");
  680. case doc_save: return createButtonFromZipFileSVG (itemId, "save", "document-save.svg");
  681. case doc_saveAs: return createButtonFromZipFileSVG (itemId, "save as", "document-save-as.svg");
  682. case edit_copy: return createButtonFromZipFileSVG (itemId, "copy", "edit-copy.svg");
  683. case edit_cut: return createButtonFromZipFileSVG (itemId, "cut", "edit-cut.svg");
  684. case edit_paste: return createButtonFromZipFileSVG (itemId, "paste", "edit-paste.svg");
  685. case juceLogoButton:
  686. {
  687. auto drawable = std::make_unique<DrawableImage>();
  688. drawable->setImage (getImageFromAssets ("juce_icon.png"));
  689. return new ToolbarButton (itemId, "juce!", std::move (drawable), {});
  690. }
  691. case customComboBox: return new CustomToolbarComboBox (itemId);
  692. default: break;
  693. }
  694. return nullptr;
  695. }
  696. private:
  697. StringArray iconNames;
  698. OwnedArray<Drawable> iconsFromZipFile;
  699. // This is a little utility to create a button with one of the SVG images in
  700. // our embedded ZIP file "icons.zip"
  701. ToolbarButton* createButtonFromZipFileSVG (const int itemId, const String& text, const String& filename)
  702. {
  703. if (iconsFromZipFile.size() == 0)
  704. {
  705. // If we've not already done so, load all the images from the zip file..
  706. ZipFile icons (createAssetInputStream ("icons.zip").release(), true);
  707. for (int i = 0; i < icons.getNumEntries(); ++i)
  708. {
  709. std::unique_ptr<InputStream> svgFileStream (icons.createStreamForEntry (i));
  710. if (svgFileStream.get() != nullptr)
  711. {
  712. iconNames.add (icons.getEntry (i)->filename);
  713. iconsFromZipFile.add (Drawable::createFromImageDataStream (*svgFileStream));
  714. }
  715. }
  716. }
  717. auto* image = iconsFromZipFile[iconNames.indexOf (filename)];
  718. return new ToolbarButton (itemId, text, image->createCopy(), {});
  719. }
  720. // Demonstrates how to put a custom component into a toolbar - this one contains
  721. // a ComboBox.
  722. class CustomToolbarComboBox : public ToolbarItemComponent
  723. {
  724. public:
  725. CustomToolbarComboBox (const int toolbarItemId)
  726. : ToolbarItemComponent (toolbarItemId, "Custom Toolbar Item", false)
  727. {
  728. addAndMakeVisible (comboBox);
  729. for (int i = 1; i < 20; ++i)
  730. comboBox.addItem ("Toolbar ComboBox item " + String (i), i);
  731. comboBox.setSelectedId (1);
  732. comboBox.setEditableText (true);
  733. }
  734. bool getToolbarItemSizes (int /*toolbarDepth*/, bool isVertical,
  735. int& preferredSize, int& minSize, int& maxSize) override
  736. {
  737. if (isVertical)
  738. return false;
  739. preferredSize = 250;
  740. minSize = 80;
  741. maxSize = 300;
  742. return true;
  743. }
  744. void paintButtonArea (Graphics&, int, int, bool, bool) override
  745. {
  746. }
  747. void contentAreaChanged (const Rectangle<int>& newArea) override
  748. {
  749. comboBox.setSize (newArea.getWidth() - 2,
  750. jmin (newArea.getHeight() - 2, 22));
  751. comboBox.setCentrePosition (newArea.getCentreX(), newArea.getCentreY());
  752. }
  753. private:
  754. ComboBox comboBox { "demo toolbar combo box" };
  755. };
  756. };
  757. DemoToolbarItemFactory factory;
  758. };
  759. //==============================================================================
  760. /**
  761. This class shows how to implement a TableListBoxModel to show in a TableListBox.
  762. */
  763. class TableDemoComponent : public Component,
  764. public TableListBoxModel
  765. {
  766. public:
  767. TableDemoComponent()
  768. {
  769. // Load some data from an embedded XML file..
  770. loadData();
  771. // Create our table component and add it to this component..
  772. addAndMakeVisible (table);
  773. table.setModel (this);
  774. // give it a border
  775. table.setColour (ListBox::outlineColourId, Colours::grey);
  776. table.setOutlineThickness (1);
  777. // Add some columns to the table header, based on the column list in our database..
  778. for (auto* columnXml : columnList->getChildIterator())
  779. {
  780. table.getHeader().addColumn (columnXml->getStringAttribute ("name"),
  781. columnXml->getIntAttribute ("columnId"),
  782. columnXml->getIntAttribute ("width"),
  783. 50, 400,
  784. TableHeaderComponent::defaultFlags);
  785. }
  786. // we could now change some initial settings..
  787. table.getHeader().setSortColumnId (1, true); // sort forwards by the ID column
  788. table.getHeader().setColumnVisible (7, false); // hide the "length" column until the user shows it
  789. // un-comment this line to have a go of stretch-to-fit mode
  790. // table.getHeader().setStretchToFitActive (true);
  791. table.setMultipleSelectionEnabled (true);
  792. }
  793. // This is overloaded from TableListBoxModel, and must return the total number of rows in our table
  794. int getNumRows() override
  795. {
  796. return numRows;
  797. }
  798. // This is overloaded from TableListBoxModel, and should fill in the background of the whole row
  799. void paintRowBackground (Graphics& g, int rowNumber, int /*width*/, int /*height*/, bool rowIsSelected) override
  800. {
  801. auto alternateColour = getLookAndFeel().findColour (ListBox::backgroundColourId)
  802. .interpolatedWith (getLookAndFeel().findColour (ListBox::textColourId), 0.03f);
  803. if (rowIsSelected)
  804. g.fillAll (Colours::lightblue);
  805. else if (rowNumber % 2)
  806. g.fillAll (alternateColour);
  807. }
  808. // This is overloaded from TableListBoxModel, and must paint any cells that aren't using custom
  809. // components.
  810. void paintCell (Graphics& g, int rowNumber, int columnId,
  811. int width, int height, bool /*rowIsSelected*/) override
  812. {
  813. g.setColour (getLookAndFeel().findColour (ListBox::textColourId));
  814. g.setFont (font);
  815. if (auto* rowElement = dataList->getChildElement (rowNumber))
  816. {
  817. auto text = rowElement->getStringAttribute (getAttributeNameForColumnId (columnId));
  818. g.drawText (text, 2, 0, width - 4, height, Justification::centredLeft, true);
  819. }
  820. g.setColour (getLookAndFeel().findColour (ListBox::backgroundColourId));
  821. g.fillRect (width - 1, 0, 1, height);
  822. }
  823. // This is overloaded from TableListBoxModel, and tells us that the user has clicked a table header
  824. // to change the sort order.
  825. void sortOrderChanged (int newSortColumnId, bool isForwards) override
  826. {
  827. if (newSortColumnId != 0)
  828. {
  829. DemoDataSorter sorter (getAttributeNameForColumnId (newSortColumnId), isForwards);
  830. dataList->sortChildElements (sorter);
  831. table.updateContent();
  832. }
  833. }
  834. // This is overloaded from TableListBoxModel, and must update any custom components that we're using
  835. Component* refreshComponentForCell (int rowNumber, int columnId, bool /*isRowSelected*/,
  836. Component* existingComponentToUpdate) override
  837. {
  838. if (columnId == 1 || columnId == 7) // The ID and Length columns do not have a custom component
  839. {
  840. jassert (existingComponentToUpdate == nullptr);
  841. return nullptr;
  842. }
  843. if (columnId == 5) // For the ratings column, we return the custom combobox component
  844. {
  845. auto* ratingsBox = static_cast<RatingColumnCustomComponent*> (existingComponentToUpdate);
  846. // If an existing component is being passed-in for updating, we'll re-use it, but
  847. // if not, we'll have to create one.
  848. if (ratingsBox == nullptr)
  849. ratingsBox = new RatingColumnCustomComponent (*this);
  850. ratingsBox->setRowAndColumn (rowNumber, columnId);
  851. return ratingsBox;
  852. }
  853. // The other columns are editable text columns, for which we use the custom Label component
  854. auto* textLabel = static_cast<EditableTextCustomComponent*> (existingComponentToUpdate);
  855. // same as above...
  856. if (textLabel == nullptr)
  857. textLabel = new EditableTextCustomComponent (*this);
  858. textLabel->setRowAndColumn (rowNumber, columnId);
  859. return textLabel;
  860. }
  861. // This is overloaded from TableListBoxModel, and should choose the best width for the specified
  862. // column.
  863. int getColumnAutoSizeWidth (int columnId) override
  864. {
  865. if (columnId == 5)
  866. return 100; // (this is the ratings column, containing a custom combobox component)
  867. int widest = 32;
  868. // find the widest bit of text in this column..
  869. for (int i = getNumRows(); --i >= 0;)
  870. {
  871. if (auto* rowElement = dataList->getChildElement (i))
  872. {
  873. auto text = rowElement->getStringAttribute (getAttributeNameForColumnId (columnId));
  874. widest = jmax (widest, font.getStringWidth (text));
  875. }
  876. }
  877. return widest + 8;
  878. }
  879. // A couple of quick methods to set and get cell values when the user changes them
  880. int getRating (const int rowNumber) const
  881. {
  882. return dataList->getChildElement (rowNumber)->getIntAttribute ("Rating");
  883. }
  884. void setRating (const int rowNumber, const int newRating)
  885. {
  886. dataList->getChildElement (rowNumber)->setAttribute ("Rating", newRating);
  887. }
  888. String getText (const int columnNumber, const int rowNumber) const
  889. {
  890. return dataList->getChildElement (rowNumber)->getStringAttribute ( getAttributeNameForColumnId(columnNumber));
  891. }
  892. void setText (const int columnNumber, const int rowNumber, const String& newText)
  893. {
  894. auto columnName = table.getHeader().getColumnName (columnNumber);
  895. dataList->getChildElement (rowNumber)->setAttribute (columnName, newText);
  896. }
  897. //==============================================================================
  898. void resized() override
  899. {
  900. // position our table with a gap around its edge
  901. table.setBoundsInset (BorderSize<int> (8));
  902. }
  903. private:
  904. TableListBox table; // the table component itself
  905. Font font { 14.0f };
  906. std::unique_ptr<XmlElement> demoData; // This is the XML document loaded from the embedded file "demo table data.xml"
  907. XmlElement* columnList = nullptr; // A pointer to the sub-node of demoData that contains the list of columns
  908. XmlElement* dataList = nullptr; // A pointer to the sub-node of demoData that contains the list of data rows
  909. int numRows; // The number of rows of data we've got
  910. //==============================================================================
  911. // This is a custom Label component, which we use for the table's editable text columns.
  912. class EditableTextCustomComponent : public Label
  913. {
  914. public:
  915. EditableTextCustomComponent (TableDemoComponent& td) : owner (td)
  916. {
  917. // double click to edit the label text; single click handled below
  918. setEditable (false, true, false);
  919. }
  920. void mouseDown (const MouseEvent& event) override
  921. {
  922. // single click on the label should simply select the row
  923. owner.table.selectRowsBasedOnModifierKeys (row, event.mods, false);
  924. Label::mouseDown (event);
  925. }
  926. void textWasEdited() override
  927. {
  928. owner.setText (columnId, row, getText());
  929. }
  930. // Our demo code will call this when we may need to update our contents
  931. void setRowAndColumn (const int newRow, const int newColumn)
  932. {
  933. row = newRow;
  934. columnId = newColumn;
  935. setText (owner.getText(columnId, row), dontSendNotification);
  936. }
  937. void paint (Graphics& g) override
  938. {
  939. auto& lf = getLookAndFeel();
  940. if (! dynamic_cast<LookAndFeel_V4*> (&lf))
  941. lf.setColour (textColourId, Colours::black);
  942. Label::paint (g);
  943. }
  944. private:
  945. TableDemoComponent& owner;
  946. int row, columnId;
  947. Colour textColour;
  948. };
  949. //==============================================================================
  950. // This is a custom component containing a combo box, which we're going to put inside
  951. // our table's "rating" column.
  952. class RatingColumnCustomComponent : public Component
  953. {
  954. public:
  955. RatingColumnCustomComponent (TableDemoComponent& td) : owner (td)
  956. {
  957. // just put a combo box inside this component
  958. addAndMakeVisible (comboBox);
  959. comboBox.addItem ("fab", 1);
  960. comboBox.addItem ("groovy", 2);
  961. comboBox.addItem ("hep", 3);
  962. comboBox.addItem ("mad for it", 4);
  963. comboBox.addItem ("neat", 5);
  964. comboBox.addItem ("swingin", 6);
  965. comboBox.addItem ("wild", 7);
  966. comboBox.onChange = [this] { owner.setRating (row, comboBox.getSelectedId()); };
  967. comboBox.setWantsKeyboardFocus (false);
  968. }
  969. void resized() override
  970. {
  971. comboBox.setBoundsInset (BorderSize<int> (2));
  972. }
  973. // Our demo code will call this when we may need to update our contents
  974. void setRowAndColumn (int newRow, int newColumn)
  975. {
  976. row = newRow;
  977. columnId = newColumn;
  978. comboBox.setSelectedId (owner.getRating (row), dontSendNotification);
  979. }
  980. private:
  981. TableDemoComponent& owner;
  982. ComboBox comboBox;
  983. int row, columnId;
  984. };
  985. //==============================================================================
  986. // A comparator used to sort our data when the user clicks a column header
  987. class DemoDataSorter
  988. {
  989. public:
  990. DemoDataSorter (const String& attributeToSortBy, bool forwards)
  991. : attributeToSort (attributeToSortBy),
  992. direction (forwards ? 1 : -1)
  993. {
  994. }
  995. int compareElements (XmlElement* first, XmlElement* second) const
  996. {
  997. auto result = first->getStringAttribute (attributeToSort)
  998. .compareNatural (second->getStringAttribute (attributeToSort));
  999. if (result == 0)
  1000. result = first->getStringAttribute ("ID")
  1001. .compareNatural (second->getStringAttribute ("ID"));
  1002. return direction * result;
  1003. }
  1004. private:
  1005. String attributeToSort;
  1006. int direction;
  1007. };
  1008. //==============================================================================
  1009. // this loads the embedded database XML file into memory
  1010. void loadData()
  1011. {
  1012. demoData = parseXML (loadEntireAssetIntoString ("demo table data.xml"));
  1013. dataList = demoData->getChildByName ("DATA");
  1014. columnList = demoData->getChildByName ("COLUMNS");
  1015. numRows = dataList->getNumChildElements();
  1016. }
  1017. // (a utility method to search our XML for the attribute that matches a column ID)
  1018. String getAttributeNameForColumnId (const int columnId) const
  1019. {
  1020. for (auto* columnXml : columnList->getChildIterator())
  1021. {
  1022. if (columnXml->getIntAttribute ("columnId") == columnId)
  1023. return columnXml->getStringAttribute ("name");
  1024. }
  1025. return {};
  1026. }
  1027. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableDemoComponent)
  1028. };
  1029. //==============================================================================
  1030. class DragAndDropDemo : public Component,
  1031. public DragAndDropContainer
  1032. {
  1033. public:
  1034. DragAndDropDemo()
  1035. {
  1036. setName ("Drag-and-Drop");
  1037. sourceListBox.setModel (&sourceModel);
  1038. sourceListBox.setMultipleSelectionEnabled (true);
  1039. addAndMakeVisible (sourceListBox);
  1040. addAndMakeVisible (target);
  1041. }
  1042. void resized() override
  1043. {
  1044. auto r = getLocalBounds().reduced (8);
  1045. sourceListBox.setBounds (r.withSize (250, 180));
  1046. target .setBounds (r.removeFromBottom (150).removeFromRight (250));
  1047. }
  1048. private:
  1049. //==============================================================================
  1050. struct SourceItemListboxContents : public ListBoxModel
  1051. {
  1052. // The following methods implement the necessary virtual functions from ListBoxModel,
  1053. // telling the listbox how many rows there are, painting them, etc.
  1054. int getNumRows() override
  1055. {
  1056. return 30;
  1057. }
  1058. void paintListBoxItem (int rowNumber, Graphics& g,
  1059. int width, int height, bool rowIsSelected) override
  1060. {
  1061. if (rowIsSelected)
  1062. g.fillAll (Colours::lightblue);
  1063. g.setColour (LookAndFeel::getDefaultLookAndFeel().findColour (Label::textColourId));
  1064. g.setFont ((float) height * 0.7f);
  1065. g.drawText ("Draggable Thing #" + String (rowNumber + 1),
  1066. 5, 0, width, height,
  1067. Justification::centredLeft, true);
  1068. }
  1069. var getDragSourceDescription (const SparseSet<int>& selectedRows) override
  1070. {
  1071. // for our drag description, we'll just make a comma-separated list of the selected row
  1072. // numbers - this will be picked up by the drag target and displayed in its box.
  1073. StringArray rows;
  1074. for (int i = 0; i < selectedRows.size(); ++i)
  1075. rows.add (String (selectedRows[i] + 1));
  1076. return rows.joinIntoString (", ");
  1077. }
  1078. };
  1079. //==============================================================================
  1080. // and this is a component that can have things dropped onto it..
  1081. class DragAndDropDemoTarget : public Component,
  1082. public DragAndDropTarget,
  1083. public FileDragAndDropTarget,
  1084. public TextDragAndDropTarget
  1085. {
  1086. public:
  1087. DragAndDropDemoTarget() {}
  1088. void paint (Graphics& g) override
  1089. {
  1090. g.fillAll (Colours::green.withAlpha (0.2f));
  1091. // draw a red line around the comp if the user's currently dragging something over it..
  1092. if (somethingIsBeingDraggedOver)
  1093. {
  1094. g.setColour (Colours::red);
  1095. g.drawRect (getLocalBounds(), 3);
  1096. }
  1097. g.setColour (getLookAndFeel().findColour (Label::textColourId));
  1098. g.setFont (14.0f);
  1099. g.drawFittedText (message, getLocalBounds().reduced (10, 0), Justification::centred, 4);
  1100. }
  1101. //==============================================================================
  1102. // These methods implement the DragAndDropTarget interface, and allow our component
  1103. // to accept drag-and-drop of objects from other JUCE components..
  1104. bool isInterestedInDragSource (const SourceDetails& /*dragSourceDetails*/) override
  1105. {
  1106. // normally you'd check the sourceDescription value to see if it's the
  1107. // sort of object that you're interested in before returning true, but for
  1108. // the demo, we'll say yes to anything..
  1109. return true;
  1110. }
  1111. void itemDragEnter (const SourceDetails& /*dragSourceDetails*/) override
  1112. {
  1113. somethingIsBeingDraggedOver = true;
  1114. repaint();
  1115. }
  1116. void itemDragMove (const SourceDetails& /*dragSourceDetails*/) override
  1117. {
  1118. }
  1119. void itemDragExit (const SourceDetails& /*dragSourceDetails*/) override
  1120. {
  1121. somethingIsBeingDraggedOver = false;
  1122. repaint();
  1123. }
  1124. void itemDropped (const SourceDetails& dragSourceDetails) override
  1125. {
  1126. message = "Items dropped: " + dragSourceDetails.description.toString();
  1127. somethingIsBeingDraggedOver = false;
  1128. repaint();
  1129. }
  1130. //==============================================================================
  1131. // These methods implement the FileDragAndDropTarget interface, and allow our component
  1132. // to accept drag-and-drop of files..
  1133. bool isInterestedInFileDrag (const StringArray& /*files*/) override
  1134. {
  1135. // normally you'd check these files to see if they're something that you're
  1136. // interested in before returning true, but for the demo, we'll say yes to anything..
  1137. return true;
  1138. }
  1139. void fileDragEnter (const StringArray& /*files*/, int /*x*/, int /*y*/) override
  1140. {
  1141. somethingIsBeingDraggedOver = true;
  1142. repaint();
  1143. }
  1144. void fileDragMove (const StringArray& /*files*/, int /*x*/, int /*y*/) override
  1145. {
  1146. }
  1147. void fileDragExit (const StringArray& /*files*/) override
  1148. {
  1149. somethingIsBeingDraggedOver = false;
  1150. repaint();
  1151. }
  1152. void filesDropped (const StringArray& files, int /*x*/, int /*y*/) override
  1153. {
  1154. message = "Files dropped: " + files.joinIntoString ("\n");
  1155. somethingIsBeingDraggedOver = false;
  1156. repaint();
  1157. }
  1158. //==============================================================================
  1159. // These methods implement the TextDragAndDropTarget interface, and allow our component
  1160. // to accept drag-and-drop of text..
  1161. bool isInterestedInTextDrag (const String& /*text*/) override
  1162. {
  1163. return true;
  1164. }
  1165. void textDragEnter (const String& /*text*/, int /*x*/, int /*y*/) override
  1166. {
  1167. somethingIsBeingDraggedOver = true;
  1168. repaint();
  1169. }
  1170. void textDragMove (const String& /*text*/, int /*x*/, int /*y*/) override
  1171. {
  1172. }
  1173. void textDragExit (const String& /*text*/) override
  1174. {
  1175. somethingIsBeingDraggedOver = false;
  1176. repaint();
  1177. }
  1178. void textDropped (const String& text, int /*x*/, int /*y*/) override
  1179. {
  1180. message = "Text dropped:\n" + text;
  1181. somethingIsBeingDraggedOver = false;
  1182. repaint();
  1183. }
  1184. private:
  1185. String message { "Drag-and-drop some rows from the top-left box onto this component!\n\n"
  1186. "You can also drag-and-drop files and text from other apps"};
  1187. bool somethingIsBeingDraggedOver = false;
  1188. };
  1189. //==============================================================================
  1190. ListBox sourceListBox { "D+D source", nullptr };
  1191. SourceItemListboxContents sourceModel;
  1192. DragAndDropDemoTarget target;
  1193. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DragAndDropDemo)
  1194. };
  1195. //==============================================================================
  1196. struct DemoTabbedComponent : public TabbedComponent
  1197. {
  1198. DemoTabbedComponent (bool isRunningComponenTransformsDemo)
  1199. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  1200. {
  1201. auto colour = findColour (ResizableWindow::backgroundColourId);
  1202. addTab ("Buttons", colour, new ButtonsPage (isRunningComponenTransformsDemo), true);
  1203. addTab ("Sliders", colour, new SlidersPage(), true);
  1204. addTab ("Toolbars", colour, new ToolbarDemoComp(), true);
  1205. addTab ("Misc", colour, new MiscPage(), true);
  1206. addTab ("Menus", colour, new MenuPage(), true);
  1207. addTab ("Tables", colour, new TableDemoComponent(), true);
  1208. addTab ("Drag & Drop", colour, new DragAndDropDemo(), true);
  1209. getTabbedButtonBar().getTabButton (5)->setExtraComponent (new CustomTabButton (isRunningComponenTransformsDemo),
  1210. TabBarButton::afterText);
  1211. }
  1212. // This is a small star button that is put inside one of the tabs. You can
  1213. // use this technique to create things like "close tab" buttons, etc.
  1214. class CustomTabButton : public Component
  1215. {
  1216. public:
  1217. CustomTabButton (bool isRunningComponenTransformsDemo)
  1218. : runningComponenTransformsDemo (isRunningComponenTransformsDemo)
  1219. {
  1220. setSize (20, 20);
  1221. }
  1222. void paint (Graphics& g) override
  1223. {
  1224. Path star;
  1225. star.addStar ({}, 7, 1.0f, 2.0f);
  1226. g.setColour (Colours::green);
  1227. g.fillPath (star, star.getTransformToScaleToFit (getLocalBounds().reduced (2).toFloat(), true));
  1228. }
  1229. void mouseDown (const MouseEvent&) override
  1230. {
  1231. showBubbleMessage (*this,
  1232. "This is a custom tab component\n"
  1233. "\n"
  1234. "You can use these to implement things like close-buttons "
  1235. "or status displays for your tabs.",
  1236. bubbleMessage,
  1237. runningComponenTransformsDemo);
  1238. }
  1239. private:
  1240. bool runningComponenTransformsDemo;
  1241. std::unique_ptr<BubbleMessageComponent> bubbleMessage;
  1242. };
  1243. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DemoTabbedComponent)
  1244. };
  1245. //==============================================================================
  1246. struct WidgetsDemo : public Component
  1247. {
  1248. WidgetsDemo (bool isRunningComponenTransformsDemo = false)
  1249. : tabs (isRunningComponenTransformsDemo)
  1250. {
  1251. setOpaque (true);
  1252. addAndMakeVisible (tabs);
  1253. setSize (700, 500);
  1254. }
  1255. void paint (Graphics& g) override
  1256. {
  1257. g.fillAll (Colours::lightgrey);
  1258. }
  1259. void resized() override
  1260. {
  1261. tabs.setBounds (getLocalBounds().reduced (4));
  1262. }
  1263. DemoTabbedComponent tabs;
  1264. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WidgetsDemo)
  1265. };
  1266. //==============================================================================
  1267. void showBubbleMessage (Component& targetComponent, const String& textToShow,
  1268. std::unique_ptr<BubbleMessageComponent>& bmc,
  1269. bool isRunningComponentTransformDemo)
  1270. {
  1271. bmc.reset (new BubbleMessageComponent());
  1272. if (isRunningComponentTransformDemo)
  1273. {
  1274. targetComponent.findParentComponentOfClass<WidgetsDemo>()->addChildComponent (bmc.get());
  1275. }
  1276. else if (Desktop::canUseSemiTransparentWindows())
  1277. {
  1278. bmc->setAlwaysOnTop (true);
  1279. bmc->addToDesktop (0);
  1280. }
  1281. else
  1282. {
  1283. targetComponent.getTopLevelComponent()->addChildComponent (bmc.get());
  1284. }
  1285. AttributedString text (textToShow);
  1286. text.setJustification (Justification::centred);
  1287. text.setColour (targetComponent.findColour (TextButton::textColourOffId));
  1288. bmc->showAt (&targetComponent, text, 2000, true, false);
  1289. }