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.

1603 lines
59KB

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