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.

1614 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. void lookAndFeelChanged() override
  370. {
  371. textEditor1.applyFontToAllText (textEditor1.getFont());
  372. textEditor2.applyFontToAllText (textEditor2.getFont());
  373. }
  374. TextEditor textEditor1, textEditor2;
  375. ComboBox comboBox;
  376. };
  377. //==============================================================================
  378. class ToolbarDemoComp : public Component,
  379. public SliderListener,
  380. public ButtonListener
  381. {
  382. public:
  383. ToolbarDemoComp()
  384. : depthLabel (String(), "Toolbar depth:"),
  385. infoLabel (String(), "As well as showing off toolbars, this demo illustrates how to store "
  386. "a set of SVG files in a Zip file, embed that in your application, and read "
  387. "them back in at runtime.\n\nThe icon images here are taken from the open-source "
  388. "Tango icon project."),
  389. orientationButton ("Vertical/Horizontal"),
  390. customiseButton ("Customise...")
  391. {
  392. // Create and add the toolbar...
  393. addAndMakeVisible (toolbar);
  394. // And use our item factory to add a set of default icons to it...
  395. toolbar.addDefaultItems (factory);
  396. // Now we'll just create the other sliders and buttons on the demo page, which adjust
  397. // the toolbar's properties...
  398. addAndMakeVisible (infoLabel);
  399. infoLabel.setJustificationType (Justification::topLeft);
  400. infoLabel.setBounds (80, 80, 450, 100);
  401. infoLabel.setInterceptsMouseClicks (false, false);
  402. addAndMakeVisible (depthSlider);
  403. depthSlider.setRange (10.0, 200.0, 1.0);
  404. depthSlider.setValue (50, dontSendNotification);
  405. depthSlider.setSliderStyle (Slider::LinearHorizontal);
  406. depthSlider.setTextBoxStyle (Slider::TextBoxLeft, false, 80, 20);
  407. depthSlider.addListener (this);
  408. depthSlider.setBounds (80, 210, 300, 22);
  409. depthLabel.attachToComponent (&depthSlider, false);
  410. addAndMakeVisible (orientationButton);
  411. orientationButton.addListener (this);
  412. orientationButton.changeWidthToFitText (22);
  413. orientationButton.setTopLeftPosition (depthSlider.getX(), depthSlider.getBottom() + 20);
  414. addAndMakeVisible (customiseButton);
  415. customiseButton.addListener (this);
  416. customiseButton.changeWidthToFitText (22);
  417. customiseButton.setTopLeftPosition (orientationButton.getRight() + 20, orientationButton.getY());
  418. }
  419. void resized() override
  420. {
  421. int toolbarThickness = (int) depthSlider.getValue();
  422. if (toolbar.isVertical())
  423. toolbar.setBounds (getLocalBounds().removeFromLeft (toolbarThickness));
  424. else
  425. toolbar.setBounds (getLocalBounds().removeFromTop (toolbarThickness));
  426. }
  427. void sliderValueChanged (Slider*) override
  428. {
  429. resized();
  430. }
  431. void buttonClicked (Button* button) override
  432. {
  433. if (button == &orientationButton)
  434. {
  435. toolbar.setVertical (! toolbar.isVertical());
  436. resized();
  437. }
  438. else if (button == &customiseButton)
  439. {
  440. toolbar.showCustomisationDialog (factory);
  441. }
  442. }
  443. private:
  444. Toolbar toolbar;
  445. Slider depthSlider;
  446. Label depthLabel, infoLabel;
  447. TextButton orientationButton, customiseButton;
  448. //==============================================================================
  449. class DemoToolbarItemFactory : public ToolbarItemFactory
  450. {
  451. public:
  452. DemoToolbarItemFactory() {}
  453. //==============================================================================
  454. // Each type of item a toolbar can contain must be given a unique ID. These
  455. // are the ones we'll use in this demo.
  456. enum DemoToolbarItemIds
  457. {
  458. doc_new = 1,
  459. doc_open = 2,
  460. doc_save = 3,
  461. doc_saveAs = 4,
  462. edit_copy = 5,
  463. edit_cut = 6,
  464. edit_paste = 7,
  465. juceLogoButton = 8,
  466. customComboBox = 9
  467. };
  468. void getAllToolbarItemIds (Array<int>& ids) override
  469. {
  470. // This returns the complete list of all item IDs that are allowed to
  471. // go in our toolbar. Any items you might want to add must be listed here. The
  472. // order in which they are listed will be used by the toolbar customisation panel.
  473. ids.add (doc_new);
  474. ids.add (doc_open);
  475. ids.add (doc_save);
  476. ids.add (doc_saveAs);
  477. ids.add (edit_copy);
  478. ids.add (edit_cut);
  479. ids.add (edit_paste);
  480. ids.add (juceLogoButton);
  481. ids.add (customComboBox);
  482. // If you're going to use separators, then they must also be added explicitly
  483. // to the list.
  484. ids.add (separatorBarId);
  485. ids.add (spacerId);
  486. ids.add (flexibleSpacerId);
  487. }
  488. void getDefaultItemSet (Array<int>& ids) override
  489. {
  490. // This returns an ordered list of the set of items that make up a
  491. // toolbar's default set. Not all items need to be on this list, and
  492. // items can appear multiple times (e.g. the separators used here).
  493. ids.add (doc_new);
  494. ids.add (doc_open);
  495. ids.add (doc_save);
  496. ids.add (doc_saveAs);
  497. ids.add (spacerId);
  498. ids.add (separatorBarId);
  499. ids.add (edit_copy);
  500. ids.add (edit_cut);
  501. ids.add (edit_paste);
  502. ids.add (separatorBarId);
  503. ids.add (flexibleSpacerId);
  504. ids.add (customComboBox);
  505. ids.add (flexibleSpacerId);
  506. ids.add (separatorBarId);
  507. ids.add (juceLogoButton);
  508. }
  509. ToolbarItemComponent* createItem (int itemId) override
  510. {
  511. switch (itemId)
  512. {
  513. case doc_new: return createButtonFromZipFileSVG (itemId, "new", "document-new.svg");
  514. case doc_open: return createButtonFromZipFileSVG (itemId, "open", "document-open.svg");
  515. case doc_save: return createButtonFromZipFileSVG (itemId, "save", "document-save.svg");
  516. case doc_saveAs: return createButtonFromZipFileSVG (itemId, "save as", "document-save-as.svg");
  517. case edit_copy: return createButtonFromZipFileSVG (itemId, "copy", "edit-copy.svg");
  518. case edit_cut: return createButtonFromZipFileSVG (itemId, "cut", "edit-cut.svg");
  519. case edit_paste: return createButtonFromZipFileSVG (itemId, "paste", "edit-paste.svg");
  520. case juceLogoButton: return new ToolbarButton (itemId, "juce!", Drawable::createFromImageData (BinaryData::juce_icon_png, BinaryData::juce_icon_pngSize), 0);
  521. case customComboBox: return new CustomToolbarComboBox (itemId);
  522. default: break;
  523. }
  524. return nullptr;
  525. }
  526. private:
  527. StringArray iconNames;
  528. OwnedArray<Drawable> iconsFromZipFile;
  529. // This is a little utility to create a button with one of the SVG images in
  530. // our embedded ZIP file "icons.zip"
  531. ToolbarButton* createButtonFromZipFileSVG (const int itemId, const String& text, const String& filename)
  532. {
  533. if (iconsFromZipFile.size() == 0)
  534. {
  535. // If we've not already done so, load all the images from the zip file..
  536. MemoryInputStream iconsFileStream (BinaryData::icons_zip, BinaryData::icons_zipSize, false);
  537. ZipFile icons (&iconsFileStream, false);
  538. for (int i = 0; i < icons.getNumEntries(); ++i)
  539. {
  540. ScopedPointer<InputStream> svgFileStream (icons.createStreamForEntry (i));
  541. if (svgFileStream != nullptr)
  542. {
  543. iconNames.add (icons.getEntry(i)->filename);
  544. iconsFromZipFile.add (Drawable::createFromImageDataStream (*svgFileStream));
  545. }
  546. }
  547. }
  548. Drawable* image = iconsFromZipFile [iconNames.indexOf (filename)]->createCopy();
  549. return new ToolbarButton (itemId, text, image, 0);
  550. }
  551. // Demonstrates how to put a custom component into a toolbar - this one contains
  552. // a ComboBox.
  553. class CustomToolbarComboBox : public ToolbarItemComponent
  554. {
  555. public:
  556. CustomToolbarComboBox (const int toolbarItemId)
  557. : ToolbarItemComponent (toolbarItemId, "Custom Toolbar Item", false),
  558. comboBox ("demo toolbar combo box")
  559. {
  560. addAndMakeVisible (comboBox);
  561. for (int i = 1; i < 20; ++i)
  562. comboBox.addItem ("Toolbar ComboBox item " + String (i), i);
  563. comboBox.setSelectedId (1);
  564. comboBox.setEditableText (true);
  565. }
  566. bool getToolbarItemSizes (int /*toolbarDepth*/, bool isVertical,
  567. int& preferredSize, int& minSize, int& maxSize) override
  568. {
  569. if (isVertical)
  570. return false;
  571. preferredSize = 250;
  572. minSize = 80;
  573. maxSize = 300;
  574. return true;
  575. }
  576. void paintButtonArea (Graphics&, int, int, bool, bool) override
  577. {
  578. }
  579. void contentAreaChanged (const Rectangle<int>& newArea) override
  580. {
  581. comboBox.setSize (newArea.getWidth() - 2,
  582. jmin (newArea.getHeight() - 2, 22));
  583. comboBox.setCentrePosition (newArea.getCentreX(), newArea.getCentreY());
  584. }
  585. private:
  586. ComboBox comboBox;
  587. };
  588. };
  589. DemoToolbarItemFactory factory;
  590. };
  591. //==============================================================================
  592. /**
  593. This class shows how to implement a TableListBoxModel to show in a TableListBox.
  594. */
  595. class TableDemoComponent : public Component,
  596. public TableListBoxModel
  597. {
  598. public:
  599. TableDemoComponent() : font (14.0f)
  600. {
  601. // Load some data from an embedded XML file..
  602. loadData();
  603. // Create our table component and add it to this component..
  604. addAndMakeVisible (table);
  605. table.setModel (this);
  606. // give it a border
  607. table.setColour (ListBox::outlineColourId, Colours::grey);
  608. table.setOutlineThickness (1);
  609. // Add some columns to the table header, based on the column list in our database..
  610. forEachXmlChildElement (*columnList, columnXml)
  611. {
  612. table.getHeader().addColumn (columnXml->getStringAttribute ("name"),
  613. columnXml->getIntAttribute ("columnId"),
  614. columnXml->getIntAttribute ("width"),
  615. 50, 400,
  616. TableHeaderComponent::defaultFlags);
  617. }
  618. // we could now change some initial settings..
  619. table.getHeader().setSortColumnId (1, true); // sort forwards by the ID column
  620. table.getHeader().setColumnVisible (7, false); // hide the "length" column until the user shows it
  621. // un-comment this line to have a go of stretch-to-fit mode
  622. // table.getHeader().setStretchToFitActive (true);
  623. table.setMultipleSelectionEnabled (true);
  624. }
  625. // This is overloaded from TableListBoxModel, and must return the total number of rows in our table
  626. int getNumRows() override
  627. {
  628. return numRows;
  629. }
  630. // This is overloaded from TableListBoxModel, and should fill in the background of the whole row
  631. void paintRowBackground (Graphics& g, int rowNumber, int /*width*/, int /*height*/, bool rowIsSelected) override
  632. {
  633. const Colour alternateColour (getLookAndFeel().findColour (ListBox::backgroundColourId)
  634. .interpolatedWith (getLookAndFeel().findColour (ListBox::textColourId), 0.03f));
  635. if (rowIsSelected)
  636. g.fillAll (Colours::lightblue);
  637. else if (rowNumber % 2)
  638. g.fillAll (alternateColour);
  639. }
  640. // This is overloaded from TableListBoxModel, and must paint any cells that aren't using custom
  641. // components.
  642. void paintCell (Graphics& g, int rowNumber, int columnId,
  643. int width, int height, bool /*rowIsSelected*/) override
  644. {
  645. g.setColour (getLookAndFeel().findColour (ListBox::textColourId));
  646. g.setFont (font);
  647. if (const XmlElement* rowElement = dataList->getChildElement (rowNumber))
  648. {
  649. const String text (rowElement->getStringAttribute (getAttributeNameForColumnId (columnId)));
  650. g.drawText (text, 2, 0, width - 4, height, Justification::centredLeft, true);
  651. }
  652. g.setColour (getLookAndFeel().findColour (ListBox::backgroundColourId));
  653. g.fillRect (width - 1, 0, 1, height);
  654. }
  655. // This is overloaded from TableListBoxModel, and tells us that the user has clicked a table header
  656. // to change the sort order.
  657. void sortOrderChanged (int newSortColumnId, bool isForwards) override
  658. {
  659. if (newSortColumnId != 0)
  660. {
  661. DemoDataSorter sorter (getAttributeNameForColumnId (newSortColumnId), isForwards);
  662. dataList->sortChildElements (sorter);
  663. table.updateContent();
  664. }
  665. }
  666. // This is overloaded from TableListBoxModel, and must update any custom components that we're using
  667. Component* refreshComponentForCell (int rowNumber, int columnId, bool /*isRowSelected*/,
  668. Component* existingComponentToUpdate) override
  669. {
  670. if (columnId == 1 || columnId == 7) // The ID and Length columns do not have a custom component
  671. {
  672. jassert (existingComponentToUpdate == nullptr);
  673. return nullptr;
  674. }
  675. if (columnId == 5) // For the ratings column, we return the custom combobox component
  676. {
  677. RatingColumnCustomComponent* ratingsBox = static_cast<RatingColumnCustomComponent*> (existingComponentToUpdate);
  678. // If an existing component is being passed-in for updating, we'll re-use it, but
  679. // if not, we'll have to create one.
  680. if (ratingsBox == nullptr)
  681. ratingsBox = new RatingColumnCustomComponent (*this);
  682. ratingsBox->setRowAndColumn (rowNumber, columnId);
  683. return ratingsBox;
  684. }
  685. // The other columns are editable text columns, for which we use the custom Label component
  686. EditableTextCustomComponent* textLabel = static_cast<EditableTextCustomComponent*> (existingComponentToUpdate);
  687. // same as above...
  688. if (textLabel == nullptr)
  689. textLabel = new EditableTextCustomComponent (*this);
  690. textLabel->setRowAndColumn (rowNumber, columnId);
  691. return textLabel;
  692. }
  693. // This is overloaded from TableListBoxModel, and should choose the best width for the specified
  694. // column.
  695. int getColumnAutoSizeWidth (int columnId) override
  696. {
  697. if (columnId == 5)
  698. return 100; // (this is the ratings column, containing a custom combobox component)
  699. int widest = 32;
  700. // find the widest bit of text in this column..
  701. for (int i = getNumRows(); --i >= 0;)
  702. {
  703. if (const XmlElement* rowElement = dataList->getChildElement (i))
  704. {
  705. const String text (rowElement->getStringAttribute (getAttributeNameForColumnId (columnId)));
  706. widest = jmax (widest, font.getStringWidth (text));
  707. }
  708. }
  709. return widest + 8;
  710. }
  711. // A couple of quick methods to set and get cell values when the user changes them
  712. int getRating (const int rowNumber) const
  713. {
  714. return dataList->getChildElement (rowNumber)->getIntAttribute ("Rating");
  715. }
  716. void setRating (const int rowNumber, const int newRating)
  717. {
  718. dataList->getChildElement (rowNumber)->setAttribute ("Rating", newRating);
  719. }
  720. String getText (const int columnNumber, const int rowNumber) const
  721. {
  722. return dataList->getChildElement (rowNumber)->getStringAttribute ( getAttributeNameForColumnId(columnNumber));
  723. }
  724. void setText (const int columnNumber, const int rowNumber, const String& newText)
  725. {
  726. const String& columnName = table.getHeader().getColumnName (columnNumber);
  727. dataList->getChildElement (rowNumber)->setAttribute (columnName, newText);
  728. }
  729. //==============================================================================
  730. void resized() override
  731. {
  732. // position our table with a gap around its edge
  733. table.setBoundsInset (BorderSize<int> (8));
  734. }
  735. private:
  736. TableListBox table; // the table component itself
  737. Font font;
  738. ScopedPointer<XmlElement> demoData; // This is the XML document loaded from the embedded file "demo table data.xml"
  739. XmlElement* columnList; // A pointer to the sub-node of demoData that contains the list of columns
  740. XmlElement* dataList; // A pointer to the sub-node of demoData that contains the list of data rows
  741. int numRows; // The number of rows of data we've got
  742. //==============================================================================
  743. // This is a custom Label component, which we use for the table's editable text columns.
  744. class EditableTextCustomComponent : public Label
  745. {
  746. public:
  747. EditableTextCustomComponent (TableDemoComponent& td) : owner (td)
  748. {
  749. // double click to edit the label text; single click handled below
  750. setEditable (false, true, false);
  751. }
  752. void mouseDown (const MouseEvent& event) override
  753. {
  754. // single click on the label should simply select the row
  755. owner.table.selectRowsBasedOnModifierKeys (row, event.mods, false);
  756. Label::mouseDown (event);
  757. }
  758. void textWasEdited() override
  759. {
  760. owner.setText (columnId, row, getText());
  761. }
  762. // Our demo code will call this when we may need to update our contents
  763. void setRowAndColumn (const int newRow, const int newColumn)
  764. {
  765. row = newRow;
  766. columnId = newColumn;
  767. setText (owner.getText(columnId, row), dontSendNotification);
  768. }
  769. void paint (Graphics& g) override
  770. {
  771. auto& lf = getLookAndFeel();
  772. if (! dynamic_cast<LookAndFeel_V4*> (&lf))
  773. lf.setColour (textColourId, Colours::black);
  774. Label::paint (g);
  775. }
  776. private:
  777. TableDemoComponent& owner;
  778. int row, columnId;
  779. Colour textColour;
  780. };
  781. //==============================================================================
  782. // This is a custom component containing a combo box, which we're going to put inside
  783. // our table's "rating" column.
  784. class RatingColumnCustomComponent : public Component,
  785. private ComboBoxListener
  786. {
  787. public:
  788. RatingColumnCustomComponent (TableDemoComponent& td) : owner (td)
  789. {
  790. // just put a combo box inside this component
  791. addAndMakeVisible (comboBox);
  792. comboBox.addItem ("fab", 1);
  793. comboBox.addItem ("groovy", 2);
  794. comboBox.addItem ("hep", 3);
  795. comboBox.addItem ("mad for it", 4);
  796. comboBox.addItem ("neat", 5);
  797. comboBox.addItem ("swingin", 6);
  798. comboBox.addItem ("wild", 7);
  799. // when the combo is changed, we'll get a callback.
  800. comboBox.addListener (this);
  801. comboBox.setWantsKeyboardFocus (false);
  802. }
  803. void resized() override
  804. {
  805. comboBox.setBoundsInset (BorderSize<int> (2));
  806. }
  807. // Our demo code will call this when we may need to update our contents
  808. void setRowAndColumn (int newRow, int newColumn)
  809. {
  810. row = newRow;
  811. columnId = newColumn;
  812. comboBox.setSelectedId (owner.getRating (row), dontSendNotification);
  813. }
  814. void comboBoxChanged (ComboBox*) override
  815. {
  816. owner.setRating (row, comboBox.getSelectedId());
  817. }
  818. private:
  819. TableDemoComponent& owner;
  820. ComboBox comboBox;
  821. int row, columnId;
  822. };
  823. //==============================================================================
  824. // A comparator used to sort our data when the user clicks a column header
  825. class DemoDataSorter
  826. {
  827. public:
  828. DemoDataSorter (const String& attributeToSortBy, bool forwards)
  829. : attributeToSort (attributeToSortBy),
  830. direction (forwards ? 1 : -1)
  831. {
  832. }
  833. int compareElements (XmlElement* first, XmlElement* second) const
  834. {
  835. int result = first->getStringAttribute (attributeToSort)
  836. .compareNatural (second->getStringAttribute (attributeToSort));
  837. if (result == 0)
  838. result = first->getStringAttribute ("ID")
  839. .compareNatural (second->getStringAttribute ("ID"));
  840. return direction * result;
  841. }
  842. private:
  843. String attributeToSort;
  844. int direction;
  845. };
  846. //==============================================================================
  847. // this loads the embedded database XML file into memory
  848. void loadData()
  849. {
  850. demoData = XmlDocument::parse (BinaryData::demo_table_data_xml);
  851. dataList = demoData->getChildByName ("DATA");
  852. columnList = demoData->getChildByName ("COLUMNS");
  853. numRows = dataList->getNumChildElements();
  854. }
  855. // (a utility method to search our XML for the attribute that matches a column ID)
  856. String getAttributeNameForColumnId (const int columnId) const
  857. {
  858. forEachXmlChildElement (*columnList, columnXml)
  859. {
  860. if (columnXml->getIntAttribute ("columnId") == columnId)
  861. return columnXml->getStringAttribute ("name");
  862. }
  863. return String();
  864. }
  865. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableDemoComponent)
  866. };
  867. //==============================================================================
  868. class DragAndDropDemo : public Component,
  869. public DragAndDropContainer
  870. {
  871. public:
  872. DragAndDropDemo()
  873. : sourceListBox ("D+D source", nullptr)
  874. {
  875. setName ("Drag-and-Drop");
  876. sourceListBox.setModel (&sourceModel);
  877. sourceListBox.setMultipleSelectionEnabled (true);
  878. addAndMakeVisible (sourceListBox);
  879. addAndMakeVisible (target);
  880. }
  881. void resized() override
  882. {
  883. Rectangle<int> r (getLocalBounds().reduced (8));
  884. sourceListBox.setBounds (r.withSize (250, 180));
  885. target.setBounds (r.removeFromBottom (150).removeFromRight (250));
  886. }
  887. private:
  888. //==============================================================================
  889. struct SourceItemListboxContents : public ListBoxModel
  890. {
  891. // The following methods implement the necessary virtual functions from ListBoxModel,
  892. // telling the listbox how many rows there are, painting them, etc.
  893. int getNumRows() override
  894. {
  895. return 30;
  896. }
  897. void paintListBoxItem (int rowNumber, Graphics& g,
  898. int width, int height, bool rowIsSelected) override
  899. {
  900. if (rowIsSelected)
  901. g.fillAll (Colours::lightblue);
  902. g.setColour (LookAndFeel::getDefaultLookAndFeel().findColour (Label::textColourId));
  903. g.setFont (height * 0.7f);
  904. g.drawText ("Draggable Thing #" + String (rowNumber + 1),
  905. 5, 0, width, height,
  906. Justification::centredLeft, true);
  907. }
  908. var getDragSourceDescription (const SparseSet<int>& selectedRows) override
  909. {
  910. // for our drag description, we'll just make a comma-separated list of the selected row
  911. // numbers - this will be picked up by the drag target and displayed in its box.
  912. StringArray rows;
  913. for (int i = 0; i < selectedRows.size(); ++i)
  914. rows.add (String (selectedRows[i] + 1));
  915. return rows.joinIntoString (", ");
  916. }
  917. };
  918. //==============================================================================
  919. // and this is a component that can have things dropped onto it..
  920. class DragAndDropDemoTarget : public Component,
  921. public DragAndDropTarget,
  922. public FileDragAndDropTarget,
  923. public TextDragAndDropTarget
  924. {
  925. public:
  926. DragAndDropDemoTarget()
  927. : message ("Drag-and-drop some rows from the top-left box onto this component!\n\n"
  928. "You can also drag-and-drop files and text from other apps"),
  929. somethingIsBeingDraggedOver (false)
  930. {
  931. }
  932. void paint (Graphics& g) override
  933. {
  934. g.fillAll (Colours::green.withAlpha (0.2f));
  935. // draw a red line around the comp if the user's currently dragging something over it..
  936. if (somethingIsBeingDraggedOver)
  937. {
  938. g.setColour (Colours::red);
  939. g.drawRect (getLocalBounds(), 3);
  940. }
  941. g.setColour (getLookAndFeel().findColour (Label::textColourId));
  942. g.setFont (14.0f);
  943. g.drawFittedText (message, getLocalBounds().reduced (10, 0), Justification::centred, 4);
  944. }
  945. //==============================================================================
  946. // These methods implement the DragAndDropTarget interface, and allow our component
  947. // to accept drag-and-drop of objects from other Juce components..
  948. bool isInterestedInDragSource (const SourceDetails& /*dragSourceDetails*/) override
  949. {
  950. // normally you'd check the sourceDescription value to see if it's the
  951. // sort of object that you're interested in before returning true, but for
  952. // the demo, we'll say yes to anything..
  953. return true;
  954. }
  955. void itemDragEnter (const SourceDetails& /*dragSourceDetails*/) override
  956. {
  957. somethingIsBeingDraggedOver = true;
  958. repaint();
  959. }
  960. void itemDragMove (const SourceDetails& /*dragSourceDetails*/) override
  961. {
  962. }
  963. void itemDragExit (const SourceDetails& /*dragSourceDetails*/) override
  964. {
  965. somethingIsBeingDraggedOver = false;
  966. repaint();
  967. }
  968. void itemDropped (const SourceDetails& dragSourceDetails) override
  969. {
  970. message = "Items dropped: " + dragSourceDetails.description.toString();
  971. somethingIsBeingDraggedOver = false;
  972. repaint();
  973. }
  974. //==============================================================================
  975. // These methods implement the FileDragAndDropTarget interface, and allow our component
  976. // to accept drag-and-drop of files..
  977. bool isInterestedInFileDrag (const StringArray& /*files*/) override
  978. {
  979. // normally you'd check these files to see if they're something that you're
  980. // interested in before returning true, but for the demo, we'll say yes to anything..
  981. return true;
  982. }
  983. void fileDragEnter (const StringArray& /*files*/, int /*x*/, int /*y*/) override
  984. {
  985. somethingIsBeingDraggedOver = true;
  986. repaint();
  987. }
  988. void fileDragMove (const StringArray& /*files*/, int /*x*/, int /*y*/) override
  989. {
  990. }
  991. void fileDragExit (const StringArray& /*files*/) override
  992. {
  993. somethingIsBeingDraggedOver = false;
  994. repaint();
  995. }
  996. void filesDropped (const StringArray& files, int /*x*/, int /*y*/) override
  997. {
  998. message = "Files dropped: " + files.joinIntoString ("\n");
  999. somethingIsBeingDraggedOver = false;
  1000. repaint();
  1001. }
  1002. //==============================================================================
  1003. // These methods implement the TextDragAndDropTarget interface, and allow our component
  1004. // to accept drag-and-drop of text..
  1005. bool isInterestedInTextDrag (const String& /*text*/) override
  1006. {
  1007. return true;
  1008. }
  1009. void textDragEnter (const String& /*text*/, int /*x*/, int /*y*/) override
  1010. {
  1011. somethingIsBeingDraggedOver = true;
  1012. repaint();
  1013. }
  1014. void textDragMove (const String& /*text*/, int /*x*/, int /*y*/) override
  1015. {
  1016. }
  1017. void textDragExit (const String& /*text*/) override
  1018. {
  1019. somethingIsBeingDraggedOver = false;
  1020. repaint();
  1021. }
  1022. void textDropped (const String& text, int /*x*/, int /*y*/) override
  1023. {
  1024. message = "Text dropped:\n" + text;
  1025. somethingIsBeingDraggedOver = false;
  1026. repaint();
  1027. }
  1028. private:
  1029. String message;
  1030. bool somethingIsBeingDraggedOver;
  1031. };
  1032. //==============================================================================
  1033. ListBox sourceListBox;
  1034. SourceItemListboxContents sourceModel;
  1035. DragAndDropDemoTarget target;
  1036. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DragAndDropDemo)
  1037. };
  1038. //==============================================================================
  1039. class MenusDemo : public Component,
  1040. public MenuBarModel,
  1041. public ChangeBroadcaster,
  1042. private Button::Listener
  1043. {
  1044. public:
  1045. MenusDemo()
  1046. {
  1047. addAndMakeVisible (menuBar = new MenuBarComponent (this));
  1048. popupButton.setButtonText ("Show Popup Menu");
  1049. popupButton.setTriggeredOnMouseDown (true);
  1050. popupButton.addListener (this);
  1051. addAndMakeVisible (popupButton);
  1052. setApplicationCommandManagerToWatch (&MainAppWindow::getApplicationCommandManager());
  1053. }
  1054. ~MenusDemo()
  1055. {
  1056. #if JUCE_MAC
  1057. MenuBarModel::setMacMainMenu (nullptr);
  1058. #endif
  1059. PopupMenu::dismissAllActiveMenus();
  1060. popupButton.removeListener (this);
  1061. }
  1062. void resized() override
  1063. {
  1064. Rectangle<int> area (getLocalBounds());
  1065. menuBar->setBounds (area.removeFromTop (LookAndFeel::getDefaultLookAndFeel().getDefaultMenuBarHeight()));
  1066. area.removeFromTop (20);
  1067. area = area.removeFromTop (33);
  1068. popupButton.setBounds (area.removeFromLeft (200).reduced (5));
  1069. }
  1070. //==============================================================================
  1071. StringArray getMenuBarNames() override
  1072. {
  1073. const char* const names[] = { "Demo", "Look-and-feel", "Tabs", "Misc", nullptr };
  1074. return StringArray (names);
  1075. }
  1076. PopupMenu getMenuForIndex (int menuIndex, const String& /*menuName*/) override
  1077. {
  1078. ApplicationCommandManager* commandManager = &MainAppWindow::getApplicationCommandManager();
  1079. PopupMenu menu;
  1080. if (menuIndex == 0)
  1081. {
  1082. menu.addCommandItem (commandManager, MainAppWindow::showPreviousDemo);
  1083. menu.addCommandItem (commandManager, MainAppWindow::showNextDemo);
  1084. menu.addSeparator();
  1085. menu.addCommandItem (commandManager, StandardApplicationCommandIDs::quit);
  1086. }
  1087. else if (menuIndex == 1)
  1088. {
  1089. menu.addCommandItem (commandManager, MainAppWindow::useLookAndFeelV1);
  1090. menu.addCommandItem (commandManager, MainAppWindow::useLookAndFeelV2);
  1091. menu.addCommandItem (commandManager, MainAppWindow::useLookAndFeelV3);
  1092. PopupMenu v4SubMenu;
  1093. v4SubMenu.addCommandItem (commandManager, MainAppWindow::useLookAndFeelV4Dark);
  1094. v4SubMenu.addCommandItem (commandManager, MainAppWindow::useLookAndFeelV4Midnight);
  1095. v4SubMenu.addCommandItem (commandManager, MainAppWindow::useLookAndFeelV4Grey);
  1096. v4SubMenu.addCommandItem (commandManager, MainAppWindow::useLookAndFeelV4Light);
  1097. menu.addSubMenu ("Use LookAndFeel_V4", v4SubMenu);
  1098. menu.addSeparator();
  1099. menu.addCommandItem (commandManager, MainAppWindow::useNativeTitleBar);
  1100. #if JUCE_MAC
  1101. menu.addItem (6000, "Use Native Menu Bar");
  1102. #endif
  1103. #if ! JUCE_LINUX
  1104. menu.addCommandItem (commandManager, MainAppWindow::goToKioskMode);
  1105. #endif
  1106. if (MainAppWindow* mainWindow = MainAppWindow::getMainAppWindow())
  1107. {
  1108. StringArray engines (mainWindow->getRenderingEngines());
  1109. if (engines.size() > 1)
  1110. {
  1111. menu.addSeparator();
  1112. for (int i = 0; i < engines.size(); ++i)
  1113. menu.addCommandItem (commandManager, MainAppWindow::renderingEngineOne + i);
  1114. }
  1115. }
  1116. }
  1117. else if (menuIndex == 2)
  1118. {
  1119. if (TabbedComponent* tabs = findParentComponentOfClass<TabbedComponent>())
  1120. {
  1121. menu.addItem (3000, "Tabs at Top", true, tabs->getOrientation() == TabbedButtonBar::TabsAtTop);
  1122. menu.addItem (3001, "Tabs at Bottom", true, tabs->getOrientation() == TabbedButtonBar::TabsAtBottom);
  1123. menu.addItem (3002, "Tabs on Left", true, tabs->getOrientation() == TabbedButtonBar::TabsAtLeft);
  1124. menu.addItem (3003, "Tabs on Right", true, tabs->getOrientation() == TabbedButtonBar::TabsAtRight);
  1125. }
  1126. }
  1127. else if (menuIndex == 3)
  1128. {
  1129. return getDummyPopupMenu();
  1130. }
  1131. return menu;
  1132. }
  1133. void menuItemSelected (int menuItemID, int /*topLevelMenuIndex*/) override
  1134. {
  1135. // most of our menu items are invoked automatically as commands, but we can handle the
  1136. // other special cases here..
  1137. if (menuItemID == 6000)
  1138. {
  1139. #if JUCE_MAC
  1140. if (MenuBarModel::getMacMainMenu() != nullptr)
  1141. {
  1142. MenuBarModel::setMacMainMenu (nullptr);
  1143. menuBar->setModel (this);
  1144. }
  1145. else
  1146. {
  1147. menuBar->setModel (nullptr);
  1148. MenuBarModel::setMacMainMenu (this);
  1149. }
  1150. #endif
  1151. }
  1152. else if (menuItemID >= 3000 && menuItemID <= 3003)
  1153. {
  1154. if (TabbedComponent* tabs = findParentComponentOfClass<TabbedComponent>())
  1155. {
  1156. TabbedButtonBar::Orientation o = TabbedButtonBar::TabsAtTop;
  1157. if (menuItemID == 3001) o = TabbedButtonBar::TabsAtBottom;
  1158. if (menuItemID == 3002) o = TabbedButtonBar::TabsAtLeft;
  1159. if (menuItemID == 3003) o = TabbedButtonBar::TabsAtRight;
  1160. tabs->setOrientation (o);
  1161. }
  1162. }
  1163. else if (menuItemID >= 12298 && menuItemID <= 12305)
  1164. {
  1165. sendChangeMessage();
  1166. }
  1167. }
  1168. private:
  1169. TextButton popupButton;
  1170. ScopedPointer<MenuBarComponent> menuBar;
  1171. PopupMenu getDummyPopupMenu()
  1172. {
  1173. PopupMenu m;
  1174. m.addItem (1, "Normal item");
  1175. m.addItem (2, "Disabled item", false);
  1176. m.addItem (3, "Ticked item", true, true);
  1177. m.addColouredItem (4, "Coloured item", Colours::green);
  1178. m.addSeparator();
  1179. m.addCustomItem (5, new CustomMenuComponent());
  1180. m.addSeparator();
  1181. for (int i = 0; i < 8; ++i)
  1182. {
  1183. PopupMenu subMenu;
  1184. for (int s = 0; s < 8; ++s)
  1185. {
  1186. PopupMenu subSubMenu;
  1187. for (int item = 0; item < 8; ++item)
  1188. subSubMenu.addItem (1000 + (i * s * item), "Item " + String (item + 1));
  1189. subMenu.addSubMenu ("Sub-sub menu " + String (s + 1), subSubMenu);
  1190. }
  1191. m.addSubMenu ("Sub menu " + String (i + 1), subMenu);
  1192. }
  1193. return m;
  1194. }
  1195. //==============================================================================
  1196. void buttonClicked (Button* button) override
  1197. {
  1198. if (button == &popupButton)
  1199. getDummyPopupMenu().showMenuAsync (PopupMenu::Options().withTargetComponent (&popupButton), nullptr);
  1200. }
  1201. //==============================================================================
  1202. class CustomMenuComponent : public PopupMenu::CustomComponent,
  1203. private Timer
  1204. {
  1205. public:
  1206. CustomMenuComponent()
  1207. {
  1208. // set off a timer to move a blob around on this component every
  1209. // 300 milliseconds - see the timerCallback() method.
  1210. startTimer (300);
  1211. }
  1212. void getIdealSize (int& idealWidth, int& idealHeight) override
  1213. {
  1214. // tells the menu how big we'd like to be..
  1215. idealWidth = 200;
  1216. idealHeight = 60;
  1217. }
  1218. void paint (Graphics& g) override
  1219. {
  1220. g.fillAll (Colours::yellow.withAlpha (0.3f));
  1221. g.setColour (Colours::pink);
  1222. g.fillEllipse (blobPosition);
  1223. g.setFont (Font (14.0f, Font::italic));
  1224. g.setColour (Colours::black);
  1225. g.drawFittedText ("This is a customised menu item (also demonstrating the Timer class)...",
  1226. getLocalBounds().reduced (4, 0),
  1227. Justification::centred, 3);
  1228. }
  1229. private:
  1230. void timerCallback() override
  1231. {
  1232. Random random;
  1233. blobPosition.setBounds ((float) random.nextInt (getWidth()),
  1234. (float) random.nextInt (getHeight()),
  1235. 40.0f, 30.0f);
  1236. repaint();
  1237. }
  1238. Rectangle<float> blobPosition;
  1239. };
  1240. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenusDemo)
  1241. };
  1242. //==============================================================================
  1243. class DemoTabbedComponent : public TabbedComponent,
  1244. private ChangeListener
  1245. {
  1246. public:
  1247. DemoTabbedComponent()
  1248. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  1249. {
  1250. // Register this class as a ChangeListener to the menus demo so we can update the tab colours when the LookAndFeel is changed
  1251. menusDemo = new MenusDemo();
  1252. menusDemo->addChangeListener (this);
  1253. const Colour c;
  1254. addTab ("Menus", c, menusDemo, true);
  1255. addTab ("Buttons", c, new ButtonsPage(), true);
  1256. addTab ("Sliders", c, new SlidersPage(), true);
  1257. addTab ("Toolbars", c, new ToolbarDemoComp(), true);
  1258. addTab ("Misc", c, new MiscPage(), true);
  1259. addTab ("Tables", c, new TableDemoComponent(), true);
  1260. addTab ("Drag & Drop", c, new DragAndDropDemo(), true);
  1261. updateTabColours();
  1262. getTabbedButtonBar().getTabButton (5)->setExtraComponent (new CustomTabButton(), TabBarButton::afterText);
  1263. }
  1264. void changeListenerCallback (ChangeBroadcaster* source) override
  1265. {
  1266. if (dynamic_cast<MenusDemo*> (source) != nullptr)
  1267. updateTabColours();
  1268. }
  1269. // This is a small star button that is put inside one of the tabs. You can
  1270. // use this technique to create things like "close tab" buttons, etc.
  1271. class CustomTabButton : public Component
  1272. {
  1273. public:
  1274. CustomTabButton()
  1275. {
  1276. setSize (20, 20);
  1277. }
  1278. void paint (Graphics& g) override
  1279. {
  1280. Path star;
  1281. star.addStar (Point<float>(), 7, 1.0f, 2.0f);
  1282. g.setColour (Colours::green);
  1283. g.fillPath (star, star.getTransformToScaleToFit (getLocalBounds().reduced (2).toFloat(), true));
  1284. }
  1285. void mouseDown (const MouseEvent&) override
  1286. {
  1287. showBubbleMessage (this,
  1288. "This is a custom tab component\n"
  1289. "\n"
  1290. "You can use these to implement things like close-buttons "
  1291. "or status displays for your tabs.",
  1292. bubbleMessage);
  1293. }
  1294. private:
  1295. ScopedPointer<BubbleMessageComponent> bubbleMessage;
  1296. };
  1297. private:
  1298. ScopedPointer<MenusDemo> menusDemo; //need to have keep a pointer around to register this class as a ChangeListener
  1299. void updateTabColours()
  1300. {
  1301. bool randomiseColours = ! dynamic_cast<LookAndFeel_V4*> (&LookAndFeel::getDefaultLookAndFeel());
  1302. for (int i = 0; i < getNumTabs(); ++i)
  1303. {
  1304. if (randomiseColours)
  1305. setTabBackgroundColour (i, Colour (Random::getSystemRandom().nextFloat(), 0.1f, 0.97f, 1.0f));
  1306. else
  1307. setTabBackgroundColour (i, getLookAndFeel().findColour (ResizableWindow::backgroundColourId));
  1308. }
  1309. }
  1310. void lookAndFeelChanged() override
  1311. {
  1312. updateTabColours();
  1313. }
  1314. };
  1315. //==============================================================================
  1316. struct WidgetsDemo : public Component
  1317. {
  1318. WidgetsDemo()
  1319. {
  1320. setOpaque (true);
  1321. addAndMakeVisible (tabs);
  1322. }
  1323. void paint (Graphics& g) override
  1324. {
  1325. g.fillAll (Colours::white);
  1326. }
  1327. void resized() override
  1328. {
  1329. tabs.setBounds (getLocalBounds().reduced (4));
  1330. }
  1331. DemoTabbedComponent tabs;
  1332. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WidgetsDemo)
  1333. };
  1334. // This static object will register this demo type in a global list of demos..
  1335. static JuceDemoType<WidgetsDemo> demo ("09 Components: Tabs & Widgets");