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.

1636 lines
61KB

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