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.

2163 lines
74KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  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 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. namespace juce
  19. {
  20. namespace PopupMenuSettings
  21. {
  22. const int scrollZone = 24;
  23. const int dismissCommandId = 0x6287345f;
  24. static bool menuWasHiddenBecauseOfAppChange = false;
  25. }
  26. //==============================================================================
  27. struct PopupMenu::HelperClasses
  28. {
  29. class MouseSourceState;
  30. struct MenuWindow;
  31. static bool canBeTriggered (const PopupMenu::Item& item) noexcept { return item.isEnabled && item.itemID != 0 && ! item.isSectionHeader; }
  32. static bool hasActiveSubMenu (const PopupMenu::Item& item) noexcept { return item.isEnabled && item.subMenu != nullptr && item.subMenu->items.size() > 0; }
  33. //==============================================================================
  34. struct HeaderItemComponent : public PopupMenu::CustomComponent
  35. {
  36. HeaderItemComponent (const String& name, const Options& opts)
  37. : CustomComponent (false), options (opts)
  38. {
  39. setName (name);
  40. }
  41. void paint (Graphics& g) override
  42. {
  43. getLookAndFeel().drawPopupMenuSectionHeaderWithOptions (g,
  44. getLocalBounds(),
  45. getName(),
  46. options);
  47. }
  48. void getIdealSize (int& idealWidth, int& idealHeight) override
  49. {
  50. getLookAndFeel().getIdealPopupMenuItemSizeWithOptions (getName(),
  51. false,
  52. -1,
  53. idealWidth,
  54. idealHeight,
  55. options);
  56. idealHeight += idealHeight / 2;
  57. idealWidth += idealWidth / 4;
  58. }
  59. const Options& options;
  60. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HeaderItemComponent)
  61. };
  62. //==============================================================================
  63. struct ItemComponent : public Component
  64. {
  65. ItemComponent (const PopupMenu::Item& i,
  66. const PopupMenu::Options& o,
  67. MenuWindow& parent)
  68. : item (i), options (o), customComp (i.customComponent)
  69. {
  70. if (item.isSectionHeader)
  71. customComp = *new HeaderItemComponent (item.text, options);
  72. if (customComp != nullptr)
  73. {
  74. setItem (*customComp, &item);
  75. addAndMakeVisible (*customComp);
  76. }
  77. parent.addAndMakeVisible (this);
  78. updateShortcutKeyDescription();
  79. int itemW = 80;
  80. int itemH = 16;
  81. getIdealSize (itemW, itemH, options.getStandardItemHeight());
  82. setSize (itemW, jlimit (1, 600, itemH));
  83. addMouseListener (&parent, false);
  84. }
  85. ~ItemComponent() override
  86. {
  87. if (customComp != nullptr)
  88. setItem (*customComp, nullptr);
  89. removeChildComponent (customComp.get());
  90. }
  91. void getIdealSize (int& idealWidth, int& idealHeight, const int standardItemHeight)
  92. {
  93. if (customComp != nullptr)
  94. customComp->getIdealSize (idealWidth, idealHeight);
  95. else
  96. getLookAndFeel().getIdealPopupMenuItemSizeWithOptions (getTextForMeasurement(),
  97. item.isSeparator,
  98. standardItemHeight,
  99. idealWidth, idealHeight,
  100. options);
  101. }
  102. void paint (Graphics& g) override
  103. {
  104. if (customComp == nullptr)
  105. getLookAndFeel().drawPopupMenuItemWithOptions (g, getLocalBounds(),
  106. isHighlighted,
  107. item,
  108. options);
  109. }
  110. void resized() override
  111. {
  112. if (auto* child = getChildComponent (0))
  113. {
  114. const auto border = getLookAndFeel().getPopupMenuBorderSizeWithOptions (options);
  115. child->setBounds (getLocalBounds().reduced (border, 0));
  116. }
  117. }
  118. void setHighlighted (bool shouldBeHighlighted)
  119. {
  120. shouldBeHighlighted = shouldBeHighlighted && item.isEnabled;
  121. if (isHighlighted != shouldBeHighlighted)
  122. {
  123. isHighlighted = shouldBeHighlighted;
  124. if (customComp != nullptr)
  125. customComp->setHighlighted (shouldBeHighlighted);
  126. repaint();
  127. }
  128. }
  129. PopupMenu::Item item;
  130. private:
  131. const PopupMenu::Options& options;
  132. // NB: we use a copy of the one from the item info in case we're using our own section comp
  133. ReferenceCountedObjectPtr<CustomComponent> customComp;
  134. bool isHighlighted = false;
  135. void updateShortcutKeyDescription()
  136. {
  137. if (item.commandManager != nullptr
  138. && item.itemID != 0
  139. && item.shortcutKeyDescription.isEmpty())
  140. {
  141. String shortcutKey;
  142. for (auto& keypress : item.commandManager->getKeyMappings()
  143. ->getKeyPressesAssignedToCommand (item.itemID))
  144. {
  145. auto key = keypress.getTextDescriptionWithIcons();
  146. if (shortcutKey.isNotEmpty())
  147. shortcutKey << ", ";
  148. if (key.length() == 1 && key[0] < 128)
  149. shortcutKey << "shortcut: '" << key << '\'';
  150. else
  151. shortcutKey << key;
  152. }
  153. item.shortcutKeyDescription = shortcutKey.trim();
  154. }
  155. }
  156. String getTextForMeasurement() const
  157. {
  158. return item.shortcutKeyDescription.isNotEmpty() ? item.text + " " + item.shortcutKeyDescription
  159. : item.text;
  160. }
  161. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent)
  162. };
  163. //==============================================================================
  164. struct MenuWindow : public Component
  165. {
  166. MenuWindow (const PopupMenu& menu, MenuWindow* parentWindow,
  167. Options opts, bool alignToRectangle, bool shouldDismissOnMouseUp,
  168. ApplicationCommandManager** manager, float parentScaleFactor = 1.0f)
  169. : Component ("menu"),
  170. parent (parentWindow),
  171. options (std::move (opts)),
  172. managerOfChosenCommand (manager),
  173. componentAttachedTo (options.getTargetComponent()),
  174. dismissOnMouseUp (shouldDismissOnMouseUp),
  175. windowCreationTime (Time::getMillisecondCounter()),
  176. lastFocusedTime (windowCreationTime),
  177. timeEnteredCurrentChildComp (windowCreationTime),
  178. scaleFactor (parentWindow != nullptr ? parentScaleFactor : 1.0f)
  179. {
  180. setWantsKeyboardFocus (false);
  181. setMouseClickGrabsKeyboardFocus (false);
  182. setAlwaysOnTop (true);
  183. setLookAndFeel (parent != nullptr ? &(parent->getLookAndFeel())
  184. : menu.lookAndFeel.get());
  185. auto& lf = getLookAndFeel();
  186. parentComponent = lf.getParentComponentForMenuOptions (options);
  187. const_cast<Options&>(options) = options.withParentComponent (parentComponent);
  188. if (parentComponent != nullptr)
  189. {
  190. parentComponent->addChildComponent (this);
  191. }
  192. else
  193. {
  194. addToDesktop (ComponentPeer::windowIsTemporary
  195. | ComponentPeer::windowIgnoresKeyPresses
  196. | lf.getMenuWindowFlags());
  197. Desktop::getInstance().addGlobalMouseListener (this);
  198. }
  199. if (parentComponent == nullptr && parentWindow == nullptr && lf.shouldPopupMenuScaleWithTargetComponent (options))
  200. if (auto* targetComponent = options.getTargetComponent())
  201. scaleFactor = Component::getApproximateScaleFactorForComponent (targetComponent);
  202. setOpaque (lf.findColour (PopupMenu::backgroundColourId).isOpaque()
  203. || ! Desktop::canUseSemiTransparentWindows());
  204. for (int i = 0; i < menu.items.size(); ++i)
  205. {
  206. auto& item = menu.items.getReference (i);
  207. if (i + 1 < menu.items.size() || ! item.isSeparator)
  208. items.add (new ItemComponent (item, options, *this));
  209. }
  210. auto targetArea = options.getTargetScreenArea() / scaleFactor;
  211. calculateWindowPos (targetArea, alignToRectangle);
  212. setTopLeftPosition (windowPos.getPosition());
  213. updateYPositions();
  214. if (auto visibleID = options.getItemThatMustBeVisible())
  215. {
  216. auto targetPosition = parentComponent != nullptr ? parentComponent->getLocalPoint (nullptr, targetArea.getTopLeft())
  217. : targetArea.getTopLeft();
  218. auto y = targetPosition.getY() - windowPos.getY();
  219. ensureItemIsVisible (visibleID, isPositiveAndBelow (y, windowPos.getHeight()) ? y : -1);
  220. }
  221. resizeToBestWindowPos();
  222. getActiveWindows().add (this);
  223. lf.preparePopupMenuWindow (*this);
  224. getMouseState (Desktop::getInstance().getMainMouseSource()); // forces creation of a mouse source watcher for the main mouse
  225. }
  226. ~MenuWindow() override
  227. {
  228. getActiveWindows().removeFirstMatchingValue (this);
  229. Desktop::getInstance().removeGlobalMouseListener (this);
  230. activeSubMenu.reset();
  231. items.clear();
  232. }
  233. //==============================================================================
  234. void paint (Graphics& g) override
  235. {
  236. if (isOpaque())
  237. g.fillAll (Colours::white);
  238. auto& theme = getLookAndFeel();
  239. theme.drawPopupMenuBackgroundWithOptions (g, getWidth(), getHeight(), options);
  240. if (columnWidths.isEmpty())
  241. return;
  242. const auto separatorWidth = theme.getPopupMenuColumnSeparatorWidthWithOptions (options);
  243. const auto border = theme.getPopupMenuBorderSizeWithOptions (options);
  244. auto currentX = 0;
  245. std::for_each (columnWidths.begin(), std::prev (columnWidths.end()), [&] (int width)
  246. {
  247. const Rectangle<int> separator (currentX + width,
  248. border,
  249. separatorWidth,
  250. getHeight() - border * 2);
  251. theme.drawPopupMenuColumnSeparatorWithOptions (g, separator, options);
  252. currentX += width + separatorWidth;
  253. });
  254. }
  255. void paintOverChildren (Graphics& g) override
  256. {
  257. auto& lf = getLookAndFeel();
  258. if (parentComponent != nullptr)
  259. lf.drawResizableFrame (g, getWidth(), getHeight(),
  260. BorderSize<int> (getLookAndFeel().getPopupMenuBorderSizeWithOptions (options)));
  261. if (canScroll())
  262. {
  263. if (isTopScrollZoneActive())
  264. {
  265. lf.drawPopupMenuUpDownArrowWithOptions (g,
  266. getWidth(),
  267. PopupMenuSettings::scrollZone,
  268. true,
  269. options);
  270. }
  271. if (isBottomScrollZoneActive())
  272. {
  273. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  274. lf.drawPopupMenuUpDownArrowWithOptions (g,
  275. getWidth(),
  276. PopupMenuSettings::scrollZone,
  277. false,
  278. options);
  279. }
  280. }
  281. }
  282. //==============================================================================
  283. // hide this and all sub-comps
  284. void hide (const PopupMenu::Item* item, bool makeInvisible)
  285. {
  286. if (isVisible())
  287. {
  288. WeakReference<Component> deletionChecker (this);
  289. activeSubMenu.reset();
  290. currentChild = nullptr;
  291. if (item != nullptr
  292. && item->commandManager != nullptr
  293. && item->itemID != 0)
  294. {
  295. *managerOfChosenCommand = item->commandManager;
  296. }
  297. auto resultID = options.hasWatchedComponentBeenDeleted() ? 0 : getResultItemID (item);
  298. exitModalState (resultID);
  299. if (makeInvisible && deletionChecker != nullptr)
  300. setVisible (false);
  301. if (resultID != 0
  302. && item != nullptr
  303. && item->action != nullptr)
  304. MessageManager::callAsync (item->action);
  305. }
  306. }
  307. static int getResultItemID (const PopupMenu::Item* item)
  308. {
  309. if (item == nullptr)
  310. return 0;
  311. if (auto* cc = item->customCallback.get())
  312. if (! cc->menuItemTriggered())
  313. return 0;
  314. return item->itemID;
  315. }
  316. void dismissMenu (const PopupMenu::Item* item)
  317. {
  318. if (parent != nullptr)
  319. {
  320. parent->dismissMenu (item);
  321. }
  322. else
  323. {
  324. if (item != nullptr)
  325. {
  326. // need a copy of this on the stack as the one passed in will get deleted during this call
  327. auto mi (*item);
  328. hide (&mi, false);
  329. }
  330. else
  331. {
  332. hide (nullptr, false);
  333. }
  334. }
  335. }
  336. float getDesktopScaleFactor() const override { return scaleFactor * Desktop::getInstance().getGlobalScaleFactor(); }
  337. //==============================================================================
  338. bool keyPressed (const KeyPress& key) override
  339. {
  340. if (key.isKeyCode (KeyPress::downKey))
  341. {
  342. selectNextItem (MenuSelectionDirection::forwards);
  343. }
  344. else if (key.isKeyCode (KeyPress::upKey))
  345. {
  346. selectNextItem (MenuSelectionDirection::backwards);
  347. }
  348. else if (key.isKeyCode (KeyPress::leftKey))
  349. {
  350. if (parent != nullptr)
  351. {
  352. Component::SafePointer<MenuWindow> parentWindow (parent);
  353. ItemComponent* currentChildOfParent = parentWindow->currentChild;
  354. hide (nullptr, true);
  355. if (parentWindow != nullptr)
  356. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  357. disableTimerUntilMouseMoves();
  358. }
  359. else if (componentAttachedTo != nullptr)
  360. {
  361. componentAttachedTo->keyPressed (key);
  362. }
  363. }
  364. else if (key.isKeyCode (KeyPress::rightKey))
  365. {
  366. disableTimerUntilMouseMoves();
  367. if (showSubMenuFor (currentChild))
  368. {
  369. if (isSubMenuVisible())
  370. activeSubMenu->selectNextItem (MenuSelectionDirection::current);
  371. }
  372. else if (componentAttachedTo != nullptr)
  373. {
  374. componentAttachedTo->keyPressed (key);
  375. }
  376. }
  377. else if (key.isKeyCode (KeyPress::returnKey) || key.isKeyCode (KeyPress::spaceKey))
  378. {
  379. triggerCurrentlyHighlightedItem();
  380. }
  381. else if (key.isKeyCode (KeyPress::escapeKey))
  382. {
  383. dismissMenu (nullptr);
  384. }
  385. else
  386. {
  387. return false;
  388. }
  389. return true;
  390. }
  391. void inputAttemptWhenModal() override
  392. {
  393. WeakReference<Component> deletionChecker (this);
  394. for (auto* ms : mouseSourceStates)
  395. {
  396. ms->timerCallback();
  397. if (deletionChecker == nullptr)
  398. return;
  399. }
  400. if (! isOverAnyMenu())
  401. {
  402. if (componentAttachedTo != nullptr)
  403. {
  404. // we want to dismiss the menu, but if we do it synchronously, then
  405. // the mouse-click will be allowed to pass through. That's good, except
  406. // when the user clicks on the button that originally popped the menu up,
  407. // as they'll expect the menu to go away, and in fact it'll just
  408. // come back. So only dismiss synchronously if they're not on the original
  409. // comp that we're attached to.
  410. auto mousePos = componentAttachedTo->getMouseXYRelative();
  411. if (componentAttachedTo->reallyContains (mousePos, true))
  412. {
  413. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchronously
  414. return;
  415. }
  416. }
  417. dismissMenu (nullptr);
  418. }
  419. }
  420. void handleCommandMessage (int commandId) override
  421. {
  422. Component::handleCommandMessage (commandId);
  423. if (commandId == PopupMenuSettings::dismissCommandId)
  424. dismissMenu (nullptr);
  425. }
  426. //==============================================================================
  427. void mouseMove (const MouseEvent& e) override { handleMouseEvent (e); }
  428. void mouseDown (const MouseEvent& e) override { handleMouseEvent (e); }
  429. void mouseDrag (const MouseEvent& e) override { handleMouseEvent (e); }
  430. void mouseUp (const MouseEvent& e) override { handleMouseEvent (e); }
  431. void mouseWheelMove (const MouseEvent&, const MouseWheelDetails& wheel) override
  432. {
  433. alterChildYPos (roundToInt (-10.0f * wheel.deltaY * PopupMenuSettings::scrollZone));
  434. }
  435. void handleMouseEvent (const MouseEvent& e)
  436. {
  437. getMouseState (e.source).handleMouseEvent (e);
  438. }
  439. bool windowIsStillValid()
  440. {
  441. if (! isVisible())
  442. return false;
  443. if (componentAttachedTo != options.getTargetComponent())
  444. {
  445. dismissMenu (nullptr);
  446. return false;
  447. }
  448. if (auto* currentlyModalWindow = dynamic_cast<MenuWindow*> (Component::getCurrentlyModalComponent()))
  449. if (! treeContains (currentlyModalWindow))
  450. return false;
  451. return true;
  452. }
  453. static Array<MenuWindow*>& getActiveWindows()
  454. {
  455. static Array<MenuWindow*> activeMenuWindows;
  456. return activeMenuWindows;
  457. }
  458. MouseSourceState& getMouseState (MouseInputSource source)
  459. {
  460. MouseSourceState* mouseState = nullptr;
  461. for (auto* ms : mouseSourceStates)
  462. {
  463. if (ms->source == source) mouseState = ms;
  464. else if (ms->source.getType() != source.getType()) ms->stopTimer();
  465. }
  466. if (mouseState == nullptr)
  467. {
  468. mouseState = new MouseSourceState (*this, source);
  469. mouseSourceStates.add (mouseState);
  470. }
  471. return *mouseState;
  472. }
  473. //==============================================================================
  474. bool isOverAnyMenu() const
  475. {
  476. return parent != nullptr ? parent->isOverAnyMenu()
  477. : isOverChildren();
  478. }
  479. bool isOverChildren() const
  480. {
  481. return isVisible()
  482. && (isAnyMouseOver() || (activeSubMenu != nullptr && activeSubMenu->isOverChildren()));
  483. }
  484. bool isAnyMouseOver() const
  485. {
  486. for (auto* ms : mouseSourceStates)
  487. if (ms->isOver())
  488. return true;
  489. return false;
  490. }
  491. bool treeContains (const MenuWindow* const window) const noexcept
  492. {
  493. auto* mw = this;
  494. while (mw->parent != nullptr)
  495. mw = mw->parent;
  496. while (mw != nullptr)
  497. {
  498. if (mw == window)
  499. return true;
  500. mw = mw->activeSubMenu.get();
  501. }
  502. return false;
  503. }
  504. bool doesAnyJuceCompHaveFocus()
  505. {
  506. bool anyFocused = Process::isForegroundProcess();
  507. if (anyFocused && Component::getCurrentlyFocusedComponent() == nullptr)
  508. {
  509. // because no component at all may have focus, our test here will
  510. // only be triggered when something has focus and then loses it.
  511. anyFocused = ! hasAnyJuceCompHadFocus;
  512. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  513. {
  514. if (ComponentPeer::getPeer (i)->isFocused())
  515. {
  516. anyFocused = true;
  517. hasAnyJuceCompHadFocus = true;
  518. break;
  519. }
  520. }
  521. }
  522. return anyFocused;
  523. }
  524. //==============================================================================
  525. Rectangle<int> getParentArea (Point<int> targetPoint, Component* relativeTo = nullptr)
  526. {
  527. if (relativeTo != nullptr)
  528. targetPoint = relativeTo->localPointToGlobal (targetPoint);
  529. auto parentArea = Desktop::getInstance().getDisplays().getDisplayForPoint (targetPoint * scaleFactor)
  530. #if JUCE_MAC || JUCE_ANDROID
  531. ->userArea;
  532. #else
  533. ->totalArea; // on windows, don't stop the menu overlapping the taskbar
  534. #endif
  535. if (parentComponent == nullptr)
  536. return parentArea;
  537. return parentComponent->getLocalArea (nullptr,
  538. parentComponent->getScreenBounds()
  539. .reduced (getLookAndFeel().getPopupMenuBorderSizeWithOptions (options))
  540. .getIntersection (parentArea));
  541. }
  542. void calculateWindowPos (Rectangle<int> target, const bool alignToRectangle)
  543. {
  544. auto parentArea = getParentArea (target.getCentre()) / scaleFactor;
  545. if (parentComponent != nullptr)
  546. target = parentComponent->getLocalArea (nullptr, target).getIntersection (parentArea);
  547. auto maxMenuHeight = parentArea.getHeight() - 24;
  548. int x, y, widthToUse, heightToUse;
  549. layoutMenuItems (parentArea.getWidth() - 24, maxMenuHeight, widthToUse, heightToUse);
  550. if (alignToRectangle)
  551. {
  552. x = target.getX();
  553. auto spaceUnder = parentArea.getBottom() - target.getBottom();
  554. auto spaceOver = target.getY() - parentArea.getY();
  555. auto bufferHeight = 30;
  556. if (options.getPreferredPopupDirection() == Options::PopupDirection::upwards)
  557. y = (heightToUse < spaceOver - bufferHeight || spaceOver >= spaceUnder) ? target.getY() - heightToUse
  558. : target.getBottom();
  559. else
  560. y = (heightToUse < spaceUnder - bufferHeight || spaceUnder >= spaceOver) ? target.getBottom()
  561. : target.getY() - heightToUse;
  562. }
  563. else
  564. {
  565. bool tendTowardsRight = target.getCentreX() < parentArea.getCentreX();
  566. if (parent != nullptr)
  567. {
  568. if (parent->parent != nullptr)
  569. {
  570. const bool parentGoingRight = (parent->getX() + parent->getWidth() / 2
  571. > parent->parent->getX() + parent->parent->getWidth() / 2);
  572. if (parentGoingRight && target.getRight() + widthToUse < parentArea.getRight() - 4)
  573. tendTowardsRight = true;
  574. else if ((! parentGoingRight) && target.getX() > widthToUse + 4)
  575. tendTowardsRight = false;
  576. }
  577. else if (target.getRight() + widthToUse < parentArea.getRight() - 32)
  578. {
  579. tendTowardsRight = true;
  580. }
  581. }
  582. auto biggestSpace = jmax (parentArea.getRight() - target.getRight(),
  583. target.getX() - parentArea.getX()) - 32;
  584. if (biggestSpace < widthToUse)
  585. {
  586. layoutMenuItems (biggestSpace + target.getWidth() / 3, maxMenuHeight, widthToUse, heightToUse);
  587. if (numColumns > 1)
  588. layoutMenuItems (biggestSpace - 4, maxMenuHeight, widthToUse, heightToUse);
  589. tendTowardsRight = (parentArea.getRight() - target.getRight()) >= (target.getX() - parentArea.getX());
  590. }
  591. x = tendTowardsRight ? jmin (parentArea.getRight() - widthToUse - 4, target.getRight())
  592. : jmax (parentArea.getX() + 4, target.getX() - widthToUse);
  593. if (getLookAndFeel().getPopupMenuBorderSizeWithOptions (options) == 0) // workaround for dismissing the window on mouse up when border size is 0
  594. x += tendTowardsRight ? 1 : -1;
  595. y = target.getCentreY() > parentArea.getCentreY() ? jmax (parentArea.getY(), target.getBottom() - heightToUse)
  596. : target.getY();
  597. }
  598. x = jmax (parentArea.getX() + 1, jmin (parentArea.getRight() - (widthToUse + 6), x));
  599. y = jmax (parentArea.getY() + 1, jmin (parentArea.getBottom() - (heightToUse + 6), y));
  600. windowPos.setBounds (x, y, widthToUse, heightToUse);
  601. // sets this flag if it's big enough to obscure any of its parent menus
  602. hideOnExit = parent != nullptr
  603. && parent->windowPos.intersects (windowPos.expanded (-4, -4));
  604. }
  605. void layoutMenuItems (const int maxMenuW, const int maxMenuH, int& width, int& height)
  606. {
  607. // Ensure we don't try to add an empty column after the final item
  608. if (auto* last = items.getLast())
  609. last->item.shouldBreakAfter = false;
  610. const auto isBreak = [] (const ItemComponent* item) { return item->item.shouldBreakAfter; };
  611. const auto numBreaks = static_cast<int> (std::count_if (items.begin(), items.end(), isBreak));
  612. numColumns = numBreaks + 1;
  613. if (numBreaks == 0)
  614. insertColumnBreaks (maxMenuW, maxMenuH);
  615. workOutManualSize (maxMenuW);
  616. auto actualH = jmin (contentHeight, maxMenuH);
  617. needsToScroll = contentHeight > actualH;
  618. width = updateYPositions();
  619. height = actualH + getLookAndFeel().getPopupMenuBorderSizeWithOptions (options) * 2;
  620. }
  621. void insertColumnBreaks (const int maxMenuW, const int maxMenuH)
  622. {
  623. numColumns = options.getMinimumNumColumns();
  624. contentHeight = 0;
  625. auto maximumNumColumns = options.getMaximumNumColumns() > 0 ? options.getMaximumNumColumns() : 7;
  626. for (;;)
  627. {
  628. auto totalW = workOutBestSize (maxMenuW);
  629. if (totalW > maxMenuW)
  630. {
  631. numColumns = jmax (1, numColumns - 1);
  632. workOutBestSize (maxMenuW); // to update col widths
  633. break;
  634. }
  635. if (totalW > maxMenuW / 2
  636. || contentHeight < maxMenuH
  637. || numColumns >= maximumNumColumns)
  638. break;
  639. ++numColumns;
  640. }
  641. const auto itemsPerColumn = (items.size() + numColumns - 1) / numColumns;
  642. for (auto i = 0;; i += itemsPerColumn)
  643. {
  644. const auto breakIndex = i + itemsPerColumn - 1;
  645. if (breakIndex >= items.size())
  646. break;
  647. items[breakIndex]->item.shouldBreakAfter = true;
  648. }
  649. if (! items.isEmpty())
  650. (*std::prev (items.end()))->item.shouldBreakAfter = false;
  651. }
  652. int correctColumnWidths (const int maxMenuW)
  653. {
  654. auto totalW = std::accumulate (columnWidths.begin(), columnWidths.end(), 0);
  655. const auto minWidth = jmin (maxMenuW, options.getMinimumWidth());
  656. if (totalW < minWidth)
  657. {
  658. totalW = minWidth;
  659. for (auto& column : columnWidths)
  660. column = totalW / numColumns;
  661. }
  662. return totalW;
  663. }
  664. void workOutManualSize (const int maxMenuW)
  665. {
  666. contentHeight = 0;
  667. columnWidths.clear();
  668. for (auto it = items.begin(), end = items.end(); it != end;)
  669. {
  670. const auto isBreak = [] (const ItemComponent* item) { return item->item.shouldBreakAfter; };
  671. const auto nextBreak = std::find_if (it, end, isBreak);
  672. const auto columnEnd = nextBreak == end ? end : std::next (nextBreak);
  673. const auto getMaxWidth = [] (int acc, const ItemComponent* item) { return jmax (acc, item->getWidth()); };
  674. const auto colW = std::accumulate (it, columnEnd, options.getStandardItemHeight(), getMaxWidth);
  675. const auto adjustedColW = jmin (maxMenuW / jmax (1, numColumns - 2),
  676. colW + getLookAndFeel().getPopupMenuBorderSizeWithOptions (options) * 2);
  677. const auto sumHeight = [] (int acc, const ItemComponent* item) { return acc + item->getHeight(); };
  678. const auto colH = std::accumulate (it, columnEnd, 0, sumHeight);
  679. contentHeight = jmax (contentHeight, colH);
  680. columnWidths.add (adjustedColW);
  681. it = columnEnd;
  682. }
  683. correctColumnWidths (maxMenuW);
  684. }
  685. int workOutBestSize (const int maxMenuW)
  686. {
  687. contentHeight = 0;
  688. int childNum = 0;
  689. for (int col = 0; col < numColumns; ++col)
  690. {
  691. int colW = options.getStandardItemHeight(), colH = 0;
  692. auto numChildren = jmin (items.size() - childNum,
  693. (items.size() + numColumns - 1) / numColumns);
  694. for (int i = numChildren; --i >= 0;)
  695. {
  696. colW = jmax (colW, items.getUnchecked (childNum + i)->getWidth());
  697. colH += items.getUnchecked (childNum + i)->getHeight();
  698. }
  699. colW = jmin (maxMenuW / jmax (1, numColumns - 2),
  700. colW + getLookAndFeel().getPopupMenuBorderSizeWithOptions (options) * 2);
  701. columnWidths.set (col, colW);
  702. contentHeight = jmax (contentHeight, colH);
  703. childNum += numChildren;
  704. }
  705. return correctColumnWidths (maxMenuW);
  706. }
  707. void ensureItemIsVisible (const int itemID, int wantedY)
  708. {
  709. jassert (itemID != 0);
  710. for (int i = items.size(); --i >= 0;)
  711. {
  712. if (auto* m = items.getUnchecked (i))
  713. {
  714. if (m->item.itemID == itemID
  715. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  716. {
  717. auto currentY = m->getY();
  718. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  719. {
  720. if (wantedY < 0)
  721. wantedY = jlimit (PopupMenuSettings::scrollZone,
  722. jmax (PopupMenuSettings::scrollZone,
  723. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  724. currentY);
  725. auto parentArea = getParentArea (windowPos.getPosition(), parentComponent) / scaleFactor;
  726. auto deltaY = wantedY - currentY;
  727. windowPos.setSize (jmin (windowPos.getWidth(), parentArea.getWidth()),
  728. jmin (windowPos.getHeight(), parentArea.getHeight()));
  729. auto newY = jlimit (parentArea.getY(),
  730. parentArea.getBottom() - windowPos.getHeight(),
  731. windowPos.getY() + deltaY);
  732. deltaY -= newY - windowPos.getY();
  733. childYOffset -= deltaY;
  734. windowPos.setPosition (windowPos.getX(), newY);
  735. updateYPositions();
  736. }
  737. break;
  738. }
  739. }
  740. }
  741. }
  742. void resizeToBestWindowPos()
  743. {
  744. auto r = windowPos;
  745. if (childYOffset < 0)
  746. {
  747. r = r.withTop (r.getY() - childYOffset);
  748. }
  749. else if (childYOffset > 0)
  750. {
  751. auto spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  752. if (spaceAtBottom > 0)
  753. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  754. }
  755. setBounds (r);
  756. updateYPositions();
  757. }
  758. void alterChildYPos (int delta)
  759. {
  760. if (canScroll())
  761. {
  762. childYOffset += delta;
  763. childYOffset = [&]
  764. {
  765. if (delta < 0)
  766. return jmax (childYOffset, 0);
  767. if (delta > 0)
  768. {
  769. const auto limit = contentHeight
  770. - windowPos.getHeight()
  771. + getLookAndFeel().getPopupMenuBorderSizeWithOptions (options);
  772. return jmin (childYOffset, limit);
  773. }
  774. return childYOffset;
  775. }();
  776. updateYPositions();
  777. }
  778. else
  779. {
  780. childYOffset = 0;
  781. }
  782. resizeToBestWindowPos();
  783. repaint();
  784. }
  785. int updateYPositions()
  786. {
  787. const auto separatorWidth = getLookAndFeel().getPopupMenuColumnSeparatorWidthWithOptions (options);
  788. const auto initialY = getLookAndFeel().getPopupMenuBorderSizeWithOptions (options)
  789. - (childYOffset + (getY() - windowPos.getY()));
  790. auto col = 0;
  791. auto x = 0;
  792. auto y = initialY;
  793. for (const auto& item : items)
  794. {
  795. jassert (col < columnWidths.size());
  796. const auto columnWidth = columnWidths[col];
  797. item->setBounds (x, y, columnWidth, item->getHeight());
  798. y += item->getHeight();
  799. if (item->item.shouldBreakAfter)
  800. {
  801. col += 1;
  802. x += columnWidth + separatorWidth;
  803. y = initialY;
  804. }
  805. }
  806. return std::accumulate (columnWidths.begin(), columnWidths.end(), 0)
  807. + (separatorWidth * (columnWidths.size() - 1));
  808. }
  809. void setCurrentlyHighlightedChild (ItemComponent* child)
  810. {
  811. if (currentChild != nullptr)
  812. currentChild->setHighlighted (false);
  813. currentChild = child;
  814. if (currentChild != nullptr)
  815. {
  816. currentChild->setHighlighted (true);
  817. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  818. }
  819. }
  820. bool isSubMenuVisible() const noexcept { return activeSubMenu != nullptr && activeSubMenu->isVisible(); }
  821. bool showSubMenuFor (ItemComponent* childComp)
  822. {
  823. activeSubMenu.reset();
  824. if (childComp != nullptr
  825. && hasActiveSubMenu (childComp->item))
  826. {
  827. activeSubMenu.reset (new HelperClasses::MenuWindow (*(childComp->item.subMenu), this,
  828. options.withTargetScreenArea (childComp->getScreenBounds())
  829. .withMinimumWidth (0)
  830. .withTargetComponent (nullptr)
  831. .withParentComponent (parentComponent),
  832. false, dismissOnMouseUp, managerOfChosenCommand, scaleFactor));
  833. activeSubMenu->setVisible (true); // (must be called before enterModalState on Windows to avoid DropShadower confusion)
  834. activeSubMenu->enterModalState (false);
  835. activeSubMenu->toFront (false);
  836. return true;
  837. }
  838. return false;
  839. }
  840. void triggerCurrentlyHighlightedItem()
  841. {
  842. if (currentChild != nullptr
  843. && canBeTriggered (currentChild->item)
  844. && (currentChild->item.customComponent == nullptr
  845. || currentChild->item.customComponent->isTriggeredAutomatically()))
  846. {
  847. dismissMenu (&currentChild->item);
  848. }
  849. }
  850. enum class MenuSelectionDirection
  851. {
  852. forwards,
  853. backwards,
  854. current
  855. };
  856. void selectNextItem (MenuSelectionDirection direction)
  857. {
  858. disableTimerUntilMouseMoves();
  859. auto start = [&]
  860. {
  861. auto index = items.indexOf (currentChild);
  862. if (index >= 0)
  863. return index;
  864. return direction == MenuSelectionDirection::backwards ? items.size() - 1
  865. : 0;
  866. }();
  867. auto preIncrement = (direction != MenuSelectionDirection::current && currentChild != nullptr);
  868. for (int i = items.size(); --i >= 0;)
  869. {
  870. if (preIncrement)
  871. start += (direction == MenuSelectionDirection::backwards ? -1 : 1);
  872. if (auto* mic = items.getUnchecked ((start + items.size()) % items.size()))
  873. {
  874. if (canBeTriggered (mic->item) || hasActiveSubMenu (mic->item))
  875. {
  876. setCurrentlyHighlightedChild (mic);
  877. return;
  878. }
  879. }
  880. if (! preIncrement)
  881. preIncrement = true;
  882. }
  883. }
  884. void disableTimerUntilMouseMoves()
  885. {
  886. disableMouseMoves = true;
  887. if (parent != nullptr)
  888. parent->disableTimerUntilMouseMoves();
  889. }
  890. bool canScroll() const noexcept { return childYOffset != 0 || needsToScroll; }
  891. bool isTopScrollZoneActive() const noexcept { return canScroll() && childYOffset > 0; }
  892. bool isBottomScrollZoneActive() const noexcept { return canScroll() && childYOffset < contentHeight - windowPos.getHeight(); }
  893. //==============================================================================
  894. MenuWindow* parent;
  895. const Options options;
  896. OwnedArray<ItemComponent> items;
  897. ApplicationCommandManager** managerOfChosenCommand;
  898. WeakReference<Component> componentAttachedTo;
  899. Component* parentComponent = nullptr;
  900. Rectangle<int> windowPos;
  901. bool hasBeenOver = false, needsToScroll = false;
  902. bool dismissOnMouseUp, hideOnExit = false, disableMouseMoves = false, hasAnyJuceCompHadFocus = false;
  903. int numColumns = 0, contentHeight = 0, childYOffset = 0;
  904. Component::SafePointer<ItemComponent> currentChild;
  905. std::unique_ptr<MenuWindow> activeSubMenu;
  906. Array<int> columnWidths;
  907. uint32 windowCreationTime, lastFocusedTime, timeEnteredCurrentChildComp;
  908. OwnedArray<MouseSourceState> mouseSourceStates;
  909. float scaleFactor;
  910. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuWindow)
  911. };
  912. //==============================================================================
  913. class MouseSourceState : public Timer
  914. {
  915. public:
  916. MouseSourceState (MenuWindow& w, MouseInputSource s)
  917. : window (w), source (s), lastScrollTime (Time::getMillisecondCounter())
  918. {
  919. startTimerHz (20);
  920. }
  921. void handleMouseEvent (const MouseEvent& e)
  922. {
  923. if (! window.windowIsStillValid())
  924. return;
  925. startTimerHz (20);
  926. handleMousePosition (e.getScreenPosition());
  927. }
  928. void timerCallback() override
  929. {
  930. #if JUCE_WINDOWS
  931. // touch and pen devices on Windows send an offscreen mouse move after mouse up events
  932. // but we don't want to forward these on as they will dismiss the menu
  933. if ((source.isTouch() || source.isPen()) && ! isValidMousePosition())
  934. return;
  935. #endif
  936. if (window.windowIsStillValid())
  937. handleMousePosition (source.getScreenPosition().roundToInt());
  938. }
  939. bool isOver() const
  940. {
  941. return window.reallyContains (window.getLocalPoint (nullptr, source.getScreenPosition()).roundToInt(), true);
  942. }
  943. MenuWindow& window;
  944. MouseInputSource source;
  945. private:
  946. Point<int> lastMousePos;
  947. double scrollAcceleration = 0;
  948. uint32 lastScrollTime, lastMouseMoveTime = 0;
  949. bool isDown = false;
  950. void handleMousePosition (Point<int> globalMousePos)
  951. {
  952. auto localMousePos = window.getLocalPoint (nullptr, globalMousePos);
  953. auto timeNow = Time::getMillisecondCounter();
  954. if (timeNow > window.timeEnteredCurrentChildComp + 100
  955. && window.reallyContains (localMousePos, true)
  956. && window.currentChild != nullptr
  957. && ! (window.disableMouseMoves || window.isSubMenuVisible()))
  958. {
  959. window.showSubMenuFor (window.currentChild);
  960. }
  961. highlightItemUnderMouse (globalMousePos, localMousePos, timeNow);
  962. const bool overScrollArea = scrollIfNecessary (localMousePos, timeNow);
  963. const bool isOverAny = window.isOverAnyMenu();
  964. if (window.hideOnExit && window.hasBeenOver && ! isOverAny)
  965. window.hide (nullptr, true);
  966. else
  967. checkButtonState (localMousePos, timeNow, isDown, overScrollArea, isOverAny);
  968. }
  969. void checkButtonState (Point<int> localMousePos, const uint32 timeNow,
  970. const bool wasDown, const bool overScrollArea, const bool isOverAny)
  971. {
  972. isDown = window.hasBeenOver
  973. && (ModifierKeys::currentModifiers.isAnyMouseButtonDown()
  974. || ComponentPeer::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  975. if (! window.doesAnyJuceCompHaveFocus())
  976. {
  977. if (timeNow > window.lastFocusedTime + 10)
  978. {
  979. PopupMenuSettings::menuWasHiddenBecauseOfAppChange = true;
  980. window.dismissMenu (nullptr);
  981. // Note: This object may have been deleted by the previous call.
  982. }
  983. }
  984. else if (wasDown && timeNow > window.windowCreationTime + 250
  985. && ! (isDown || overScrollArea))
  986. {
  987. if (window.reallyContains (localMousePos, true))
  988. window.triggerCurrentlyHighlightedItem();
  989. else if ((window.hasBeenOver || ! window.dismissOnMouseUp) && ! isOverAny)
  990. window.dismissMenu (nullptr);
  991. // Note: This object may have been deleted by the previous call.
  992. }
  993. else
  994. {
  995. window.lastFocusedTime = timeNow;
  996. }
  997. }
  998. void highlightItemUnderMouse (Point<int> globalMousePos, Point<int> localMousePos, const uint32 timeNow)
  999. {
  1000. if (globalMousePos != lastMousePos || timeNow > lastMouseMoveTime + 350)
  1001. {
  1002. const bool isMouseOver = window.reallyContains (localMousePos, true);
  1003. if (isMouseOver)
  1004. window.hasBeenOver = true;
  1005. if (lastMousePos.getDistanceFrom (globalMousePos) > 2)
  1006. {
  1007. lastMouseMoveTime = timeNow;
  1008. if (window.disableMouseMoves && isMouseOver)
  1009. window.disableMouseMoves = false;
  1010. }
  1011. if (window.disableMouseMoves || (window.activeSubMenu != nullptr && window.activeSubMenu->isOverChildren()))
  1012. return;
  1013. const bool isMovingTowardsMenu = isMouseOver && globalMousePos != lastMousePos
  1014. && isMovingTowardsSubmenu (globalMousePos);
  1015. lastMousePos = globalMousePos;
  1016. if (! isMovingTowardsMenu)
  1017. {
  1018. auto* c = window.getComponentAt (localMousePos);
  1019. if (c == &window)
  1020. c = nullptr;
  1021. auto* itemUnderMouse = dynamic_cast<ItemComponent*> (c);
  1022. if (itemUnderMouse == nullptr && c != nullptr)
  1023. itemUnderMouse = c->findParentComponentOfClass<ItemComponent>();
  1024. if (itemUnderMouse != window.currentChild
  1025. && (isMouseOver || (window.activeSubMenu == nullptr) || ! window.activeSubMenu->isVisible()))
  1026. {
  1027. if (isMouseOver && (c != nullptr) && (window.activeSubMenu != nullptr))
  1028. window.activeSubMenu->hide (nullptr, true);
  1029. if (! isMouseOver)
  1030. itemUnderMouse = nullptr;
  1031. window.setCurrentlyHighlightedChild (itemUnderMouse);
  1032. }
  1033. }
  1034. }
  1035. }
  1036. bool isMovingTowardsSubmenu (Point<int> newGlobalPos) const
  1037. {
  1038. if (window.activeSubMenu == nullptr)
  1039. return false;
  1040. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  1041. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  1042. // extends from the last mouse pos to the submenu's rectangle..
  1043. auto itemScreenBounds = window.activeSubMenu->getScreenBounds();
  1044. auto subX = (float) itemScreenBounds.getX();
  1045. auto oldGlobalPos = lastMousePos;
  1046. if (itemScreenBounds.getX() > window.getX())
  1047. {
  1048. oldGlobalPos -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  1049. }
  1050. else
  1051. {
  1052. oldGlobalPos += Point<int> (2, 0);
  1053. subX += (float) itemScreenBounds.getWidth();
  1054. }
  1055. Path areaTowardsSubMenu;
  1056. areaTowardsSubMenu.addTriangle ((float) oldGlobalPos.x, (float) oldGlobalPos.y,
  1057. subX, (float) itemScreenBounds.getY(),
  1058. subX, (float) itemScreenBounds.getBottom());
  1059. return areaTowardsSubMenu.contains (newGlobalPos.toFloat());
  1060. }
  1061. bool scrollIfNecessary (Point<int> localMousePos, const uint32 timeNow)
  1062. {
  1063. if (window.canScroll()
  1064. && isPositiveAndBelow (localMousePos.x, window.getWidth())
  1065. && (isPositiveAndBelow (localMousePos.y, window.getHeight()) || source.isDragging()))
  1066. {
  1067. if (window.isTopScrollZoneActive() && localMousePos.y < PopupMenuSettings::scrollZone)
  1068. return scroll (timeNow, -1);
  1069. if (window.isBottomScrollZoneActive() && localMousePos.y > window.getHeight() - PopupMenuSettings::scrollZone)
  1070. return scroll (timeNow, 1);
  1071. }
  1072. scrollAcceleration = 1.0;
  1073. return false;
  1074. }
  1075. bool scroll (const uint32 timeNow, const int direction)
  1076. {
  1077. if (timeNow > lastScrollTime + 20)
  1078. {
  1079. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  1080. int amount = 0;
  1081. for (int i = 0; i < window.items.size() && amount == 0; ++i)
  1082. amount = ((int) scrollAcceleration) * window.items.getUnchecked (i)->getHeight();
  1083. window.alterChildYPos (amount * direction);
  1084. lastScrollTime = timeNow;
  1085. }
  1086. return true;
  1087. }
  1088. #if JUCE_WINDOWS
  1089. bool isValidMousePosition()
  1090. {
  1091. auto screenPos = source.getScreenPosition();
  1092. auto localPos = (window.activeSubMenu == nullptr) ? window.getLocalPoint (nullptr, screenPos)
  1093. : window.activeSubMenu->getLocalPoint (nullptr, screenPos);
  1094. if (localPos.x < 0 && localPos.y < 0)
  1095. return false;
  1096. return true;
  1097. }
  1098. #endif
  1099. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MouseSourceState)
  1100. };
  1101. //==============================================================================
  1102. struct NormalComponentWrapper : public PopupMenu::CustomComponent
  1103. {
  1104. NormalComponentWrapper (Component& comp, int w, int h, bool triggerMenuItemAutomaticallyWhenClicked)
  1105. : PopupMenu::CustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  1106. width (w), height (h)
  1107. {
  1108. addAndMakeVisible (comp);
  1109. }
  1110. void getIdealSize (int& idealWidth, int& idealHeight) override
  1111. {
  1112. idealWidth = width;
  1113. idealHeight = height;
  1114. }
  1115. void resized() override
  1116. {
  1117. if (auto* child = getChildComponent (0))
  1118. child->setBounds (getLocalBounds());
  1119. }
  1120. const int width, height;
  1121. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NormalComponentWrapper)
  1122. };
  1123. };
  1124. //==============================================================================
  1125. PopupMenu::PopupMenu (const PopupMenu& other)
  1126. : items (other.items),
  1127. lookAndFeel (other.lookAndFeel)
  1128. {
  1129. }
  1130. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  1131. {
  1132. if (this != &other)
  1133. {
  1134. items = other.items;
  1135. lookAndFeel = other.lookAndFeel;
  1136. }
  1137. return *this;
  1138. }
  1139. PopupMenu::PopupMenu (PopupMenu&& other) noexcept
  1140. : items (std::move (other.items)),
  1141. lookAndFeel (std::move (other.lookAndFeel))
  1142. {
  1143. }
  1144. PopupMenu& PopupMenu::operator= (PopupMenu&& other) noexcept
  1145. {
  1146. items = std::move (other.items);
  1147. lookAndFeel = other.lookAndFeel;
  1148. return *this;
  1149. }
  1150. PopupMenu::~PopupMenu() = default;
  1151. void PopupMenu::clear()
  1152. {
  1153. items.clear();
  1154. }
  1155. //==============================================================================
  1156. PopupMenu::Item::Item() = default;
  1157. PopupMenu::Item::Item (String t) : text (std::move (t)), itemID (-1) {}
  1158. PopupMenu::Item::Item (Item&&) = default;
  1159. PopupMenu::Item& PopupMenu::Item::operator= (Item&&) = default;
  1160. PopupMenu::Item::Item (const Item& other)
  1161. : text (other.text),
  1162. itemID (other.itemID),
  1163. action (other.action),
  1164. subMenu (createCopyIfNotNull (other.subMenu.get())),
  1165. image (other.image != nullptr ? other.image->createCopy() : nullptr),
  1166. customComponent (other.customComponent),
  1167. customCallback (other.customCallback),
  1168. commandManager (other.commandManager),
  1169. shortcutKeyDescription (other.shortcutKeyDescription),
  1170. colour (other.colour),
  1171. isEnabled (other.isEnabled),
  1172. isTicked (other.isTicked),
  1173. isSeparator (other.isSeparator),
  1174. isSectionHeader (other.isSectionHeader),
  1175. shouldBreakAfter (other.shouldBreakAfter)
  1176. {}
  1177. PopupMenu::Item& PopupMenu::Item::operator= (const Item& other)
  1178. {
  1179. text = other.text;
  1180. itemID = other.itemID;
  1181. action = other.action;
  1182. subMenu.reset (createCopyIfNotNull (other.subMenu.get()));
  1183. image = other.image != nullptr ? other.image->createCopy() : std::unique_ptr<Drawable>();
  1184. customComponent = other.customComponent;
  1185. customCallback = other.customCallback;
  1186. commandManager = other.commandManager;
  1187. shortcutKeyDescription = other.shortcutKeyDescription;
  1188. colour = other.colour;
  1189. isEnabled = other.isEnabled;
  1190. isTicked = other.isTicked;
  1191. isSeparator = other.isSeparator;
  1192. isSectionHeader = other.isSectionHeader;
  1193. shouldBreakAfter = other.shouldBreakAfter;
  1194. return *this;
  1195. }
  1196. PopupMenu::Item& PopupMenu::Item::setTicked (bool shouldBeTicked) & noexcept
  1197. {
  1198. isTicked = shouldBeTicked;
  1199. return *this;
  1200. }
  1201. PopupMenu::Item& PopupMenu::Item::setEnabled (bool shouldBeEnabled) & noexcept
  1202. {
  1203. isEnabled = shouldBeEnabled;
  1204. return *this;
  1205. }
  1206. PopupMenu::Item& PopupMenu::Item::setAction (std::function<void()> newAction) & noexcept
  1207. {
  1208. action = std::move (newAction);
  1209. return *this;
  1210. }
  1211. PopupMenu::Item& PopupMenu::Item::setID (int newID) & noexcept
  1212. {
  1213. itemID = newID;
  1214. return *this;
  1215. }
  1216. PopupMenu::Item& PopupMenu::Item::setColour (Colour newColour) & noexcept
  1217. {
  1218. colour = newColour;
  1219. return *this;
  1220. }
  1221. PopupMenu::Item& PopupMenu::Item::setCustomComponent (ReferenceCountedObjectPtr<CustomComponent> comp) & noexcept
  1222. {
  1223. customComponent = comp;
  1224. return *this;
  1225. }
  1226. PopupMenu::Item& PopupMenu::Item::setImage (std::unique_ptr<Drawable> newImage) & noexcept
  1227. {
  1228. image = std::move (newImage);
  1229. return *this;
  1230. }
  1231. PopupMenu::Item&& PopupMenu::Item::setTicked (bool shouldBeTicked) && noexcept
  1232. {
  1233. isTicked = shouldBeTicked;
  1234. return std::move (*this);
  1235. }
  1236. PopupMenu::Item&& PopupMenu::Item::setEnabled (bool shouldBeEnabled) && noexcept
  1237. {
  1238. isEnabled = shouldBeEnabled;
  1239. return std::move (*this);
  1240. }
  1241. PopupMenu::Item&& PopupMenu::Item::setAction (std::function<void()> newAction) && noexcept
  1242. {
  1243. action = std::move (newAction);
  1244. return std::move (*this);
  1245. }
  1246. PopupMenu::Item&& PopupMenu::Item::setID (int newID) && noexcept
  1247. {
  1248. itemID = newID;
  1249. return std::move (*this);
  1250. }
  1251. PopupMenu::Item&& PopupMenu::Item::setColour (Colour newColour) && noexcept
  1252. {
  1253. colour = newColour;
  1254. return std::move (*this);
  1255. }
  1256. PopupMenu::Item&& PopupMenu::Item::setCustomComponent (ReferenceCountedObjectPtr<CustomComponent> comp) && noexcept
  1257. {
  1258. customComponent = comp;
  1259. return std::move (*this);
  1260. }
  1261. PopupMenu::Item&& PopupMenu::Item::setImage (std::unique_ptr<Drawable> newImage) && noexcept
  1262. {
  1263. image = std::move (newImage);
  1264. return std::move (*this);
  1265. }
  1266. void PopupMenu::addItem (Item newItem)
  1267. {
  1268. // An ID of 0 is used as a return value to indicate that the user
  1269. // didn't pick anything, so you shouldn't use it as the ID for an item..
  1270. jassert (newItem.itemID != 0
  1271. || newItem.isSeparator || newItem.isSectionHeader
  1272. || newItem.subMenu != nullptr);
  1273. items.add (std::move (newItem));
  1274. }
  1275. void PopupMenu::addItem (String itemText, std::function<void()> action)
  1276. {
  1277. addItem (std::move (itemText), true, false, std::move (action));
  1278. }
  1279. void PopupMenu::addItem (String itemText, bool isActive, bool isTicked, std::function<void()> action)
  1280. {
  1281. Item i (std::move (itemText));
  1282. i.action = std::move (action);
  1283. i.isEnabled = isActive;
  1284. i.isTicked = isTicked;
  1285. addItem (std::move (i));
  1286. }
  1287. void PopupMenu::addItem (int itemResultID, String itemText, bool isActive, bool isTicked)
  1288. {
  1289. Item i (std::move (itemText));
  1290. i.itemID = itemResultID;
  1291. i.isEnabled = isActive;
  1292. i.isTicked = isTicked;
  1293. addItem (std::move (i));
  1294. }
  1295. static std::unique_ptr<Drawable> createDrawableFromImage (const Image& im)
  1296. {
  1297. if (im.isValid())
  1298. {
  1299. auto d = new DrawableImage();
  1300. d->setImage (im);
  1301. return std::unique_ptr<Drawable> (d);
  1302. }
  1303. return {};
  1304. }
  1305. void PopupMenu::addItem (int itemResultID, String itemText, bool isActive, bool isTicked, const Image& iconToUse)
  1306. {
  1307. addItem (itemResultID, std::move (itemText), isActive, isTicked, createDrawableFromImage (iconToUse));
  1308. }
  1309. void PopupMenu::addItem (int itemResultID, String itemText, bool isActive,
  1310. bool isTicked, std::unique_ptr<Drawable> iconToUse)
  1311. {
  1312. Item i (std::move (itemText));
  1313. i.itemID = itemResultID;
  1314. i.isEnabled = isActive;
  1315. i.isTicked = isTicked;
  1316. i.image = std::move (iconToUse);
  1317. addItem (std::move (i));
  1318. }
  1319. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  1320. const CommandID commandID,
  1321. String displayName,
  1322. std::unique_ptr<Drawable> iconToUse)
  1323. {
  1324. jassert (commandManager != nullptr && commandID != 0);
  1325. if (auto* registeredInfo = commandManager->getCommandForID (commandID))
  1326. {
  1327. ApplicationCommandInfo info (*registeredInfo);
  1328. auto* target = commandManager->getTargetForCommand (commandID, info);
  1329. Item i;
  1330. i.text = displayName.isNotEmpty() ? std::move (displayName) : info.shortName;
  1331. i.itemID = (int) commandID;
  1332. i.commandManager = commandManager;
  1333. i.isEnabled = target != nullptr && (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  1334. i.isTicked = (info.flags & ApplicationCommandInfo::isTicked) != 0;
  1335. i.image = std::move (iconToUse);
  1336. addItem (std::move (i));
  1337. }
  1338. }
  1339. void PopupMenu::addColouredItem (int itemResultID, String itemText, Colour itemTextColour,
  1340. bool isActive, bool isTicked, std::unique_ptr<Drawable> iconToUse)
  1341. {
  1342. Item i (std::move (itemText));
  1343. i.itemID = itemResultID;
  1344. i.colour = itemTextColour;
  1345. i.isEnabled = isActive;
  1346. i.isTicked = isTicked;
  1347. i.image = std::move (iconToUse);
  1348. addItem (std::move (i));
  1349. }
  1350. void PopupMenu::addColouredItem (int itemResultID, String itemText, Colour itemTextColour,
  1351. bool isActive, bool isTicked, const Image& iconToUse)
  1352. {
  1353. Item i (std::move (itemText));
  1354. i.itemID = itemResultID;
  1355. i.colour = itemTextColour;
  1356. i.isEnabled = isActive;
  1357. i.isTicked = isTicked;
  1358. i.image = createDrawableFromImage (iconToUse);
  1359. addItem (std::move (i));
  1360. }
  1361. void PopupMenu::addCustomItem (int itemResultID,
  1362. std::unique_ptr<CustomComponent> cc,
  1363. std::unique_ptr<const PopupMenu> subMenu)
  1364. {
  1365. Item i;
  1366. i.itemID = itemResultID;
  1367. i.customComponent = cc.release();
  1368. i.subMenu.reset (createCopyIfNotNull (subMenu.get()));
  1369. addItem (std::move (i));
  1370. }
  1371. void PopupMenu::addCustomItem (int itemResultID,
  1372. Component& customComponent,
  1373. int idealWidth, int idealHeight,
  1374. bool triggerMenuItemAutomaticallyWhenClicked,
  1375. std::unique_ptr<const PopupMenu> subMenu)
  1376. {
  1377. auto comp = std::make_unique<HelperClasses::NormalComponentWrapper> (customComponent, idealWidth, idealHeight,
  1378. triggerMenuItemAutomaticallyWhenClicked);
  1379. addCustomItem (itemResultID, std::move (comp), std::move (subMenu));
  1380. }
  1381. void PopupMenu::addSubMenu (String subMenuName, PopupMenu subMenu, bool isActive)
  1382. {
  1383. addSubMenu (std::move (subMenuName), std::move (subMenu), isActive, nullptr, false, 0);
  1384. }
  1385. void PopupMenu::addSubMenu (String subMenuName, PopupMenu subMenu, bool isActive,
  1386. const Image& iconToUse, bool isTicked, int itemResultID)
  1387. {
  1388. addSubMenu (std::move (subMenuName), std::move (subMenu), isActive,
  1389. createDrawableFromImage (iconToUse), isTicked, itemResultID);
  1390. }
  1391. void PopupMenu::addSubMenu (String subMenuName, PopupMenu subMenu, bool isActive,
  1392. std::unique_ptr<Drawable> iconToUse, bool isTicked, int itemResultID)
  1393. {
  1394. Item i (std::move (subMenuName));
  1395. i.itemID = itemResultID;
  1396. i.isEnabled = isActive && (itemResultID != 0 || subMenu.getNumItems() > 0);
  1397. i.subMenu.reset (new PopupMenu (std::move (subMenu)));
  1398. i.isTicked = isTicked;
  1399. i.image = std::move (iconToUse);
  1400. addItem (std::move (i));
  1401. }
  1402. void PopupMenu::addSeparator()
  1403. {
  1404. if (items.size() > 0 && ! items.getLast().isSeparator)
  1405. {
  1406. Item i;
  1407. i.isSeparator = true;
  1408. addItem (std::move (i));
  1409. }
  1410. }
  1411. void PopupMenu::addSectionHeader (String title)
  1412. {
  1413. Item i (std::move (title));
  1414. i.itemID = 0;
  1415. i.isSectionHeader = true;
  1416. addItem (std::move (i));
  1417. }
  1418. void PopupMenu::addColumnBreak()
  1419. {
  1420. if (! items.isEmpty())
  1421. std::prev (items.end())->shouldBreakAfter = true;
  1422. }
  1423. //==============================================================================
  1424. PopupMenu::Options::Options()
  1425. {
  1426. targetArea.setPosition (Desktop::getMousePosition());
  1427. }
  1428. PopupMenu::Options PopupMenu::Options::withTargetComponent (Component* comp) const
  1429. {
  1430. Options o (*this);
  1431. o.targetComponent = comp;
  1432. if (comp != nullptr)
  1433. o.targetArea = comp->getScreenBounds();
  1434. return o;
  1435. }
  1436. PopupMenu::Options PopupMenu::Options::withTargetComponent (Component& comp) const
  1437. {
  1438. return withTargetComponent (&comp);
  1439. }
  1440. PopupMenu::Options PopupMenu::Options::withTargetScreenArea (Rectangle<int> area) const
  1441. {
  1442. Options o (*this);
  1443. o.targetArea = area;
  1444. return o;
  1445. }
  1446. PopupMenu::Options PopupMenu::Options::withDeletionCheck (Component& comp) const
  1447. {
  1448. Options o (*this);
  1449. o.componentToWatchForDeletion = &comp;
  1450. o.isWatchingForDeletion = true;
  1451. return o;
  1452. }
  1453. PopupMenu::Options PopupMenu::Options::withMinimumWidth (int w) const
  1454. {
  1455. Options o (*this);
  1456. o.minWidth = w;
  1457. return o;
  1458. }
  1459. PopupMenu::Options PopupMenu::Options::withMinimumNumColumns (int cols) const
  1460. {
  1461. Options o (*this);
  1462. o.minColumns = cols;
  1463. return o;
  1464. }
  1465. PopupMenu::Options PopupMenu::Options::withMaximumNumColumns (int cols) const
  1466. {
  1467. Options o (*this);
  1468. o.maxColumns = cols;
  1469. return o;
  1470. }
  1471. PopupMenu::Options PopupMenu::Options::withStandardItemHeight (int height) const
  1472. {
  1473. Options o (*this);
  1474. o.standardHeight = height;
  1475. return o;
  1476. }
  1477. PopupMenu::Options PopupMenu::Options::withItemThatMustBeVisible (int idOfItemToBeVisible) const
  1478. {
  1479. Options o (*this);
  1480. o.visibleItemID = idOfItemToBeVisible;
  1481. return o;
  1482. }
  1483. PopupMenu::Options PopupMenu::Options::withParentComponent (Component* parent) const
  1484. {
  1485. Options o (*this);
  1486. o.parentComponent = parent;
  1487. return o;
  1488. }
  1489. PopupMenu::Options PopupMenu::Options::withPreferredPopupDirection (PopupDirection direction) const
  1490. {
  1491. Options o (*this);
  1492. o.preferredPopupDirection = direction;
  1493. return o;
  1494. }
  1495. Component* PopupMenu::createWindow (const Options& options,
  1496. ApplicationCommandManager** managerOfChosenCommand) const
  1497. {
  1498. return items.isEmpty() ? nullptr
  1499. : new HelperClasses::MenuWindow (*this, nullptr, options,
  1500. ! options.getTargetScreenArea().isEmpty(),
  1501. ModifierKeys::currentModifiers.isAnyMouseButtonDown(),
  1502. managerOfChosenCommand);
  1503. }
  1504. //==============================================================================
  1505. // This invokes any command manager commands and deletes the menu window when it is dismissed
  1506. struct PopupMenuCompletionCallback : public ModalComponentManager::Callback
  1507. {
  1508. PopupMenuCompletionCallback()
  1509. : prevFocused (Component::getCurrentlyFocusedComponent()),
  1510. prevTopLevel (prevFocused != nullptr ? prevFocused->getTopLevelComponent() : nullptr)
  1511. {
  1512. PopupMenuSettings::menuWasHiddenBecauseOfAppChange = false;
  1513. }
  1514. void modalStateFinished (int result) override
  1515. {
  1516. if (managerOfChosenCommand != nullptr && result != 0)
  1517. {
  1518. ApplicationCommandTarget::InvocationInfo info (result);
  1519. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  1520. managerOfChosenCommand->invoke (info, true);
  1521. }
  1522. // (this would be the place to fade out the component, if that's what's required)
  1523. component.reset();
  1524. if (! PopupMenuSettings::menuWasHiddenBecauseOfAppChange)
  1525. {
  1526. if (prevTopLevel != nullptr)
  1527. prevTopLevel->toFront (true);
  1528. if (prevFocused != nullptr && prevFocused->isShowing())
  1529. prevFocused->grabKeyboardFocus();
  1530. }
  1531. }
  1532. ApplicationCommandManager* managerOfChosenCommand = nullptr;
  1533. std::unique_ptr<Component> component;
  1534. WeakReference<Component> prevFocused, prevTopLevel;
  1535. JUCE_DECLARE_NON_COPYABLE (PopupMenuCompletionCallback)
  1536. };
  1537. int PopupMenu::showWithOptionalCallback (const Options& options,
  1538. ModalComponentManager::Callback* userCallback,
  1539. bool canBeModal)
  1540. {
  1541. std::unique_ptr<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  1542. std::unique_ptr<PopupMenuCompletionCallback> callback (new PopupMenuCompletionCallback());
  1543. if (auto* window = createWindow (options, &(callback->managerOfChosenCommand)))
  1544. {
  1545. callback->component.reset (window);
  1546. window->setVisible (true); // (must be called before enterModalState on Windows to avoid DropShadower confusion)
  1547. window->enterModalState (false, userCallbackDeleter.release());
  1548. ModalComponentManager::getInstance()->attachCallback (window, callback.release());
  1549. window->toFront (false); // need to do this after making it modal, or it could
  1550. // be stuck behind other comps that are already modal..
  1551. #if JUCE_MODAL_LOOPS_PERMITTED
  1552. if (userCallback == nullptr && canBeModal)
  1553. return window->runModalLoop();
  1554. #else
  1555. ignoreUnused (canBeModal);
  1556. jassert (! (userCallback == nullptr && canBeModal));
  1557. #endif
  1558. }
  1559. return 0;
  1560. }
  1561. //==============================================================================
  1562. #if JUCE_MODAL_LOOPS_PERMITTED
  1563. int PopupMenu::showMenu (const Options& options)
  1564. {
  1565. return showWithOptionalCallback (options, nullptr, true);
  1566. }
  1567. #endif
  1568. void PopupMenu::showMenuAsync (const Options& options)
  1569. {
  1570. showWithOptionalCallback (options, nullptr, false);
  1571. }
  1572. void PopupMenu::showMenuAsync (const Options& options, ModalComponentManager::Callback* userCallback)
  1573. {
  1574. #if ! JUCE_MODAL_LOOPS_PERMITTED
  1575. jassert (userCallback != nullptr);
  1576. #endif
  1577. showWithOptionalCallback (options, userCallback, false);
  1578. }
  1579. void PopupMenu::showMenuAsync (const Options& options, std::function<void (int)> userCallback)
  1580. {
  1581. showWithOptionalCallback (options, ModalCallbackFunction::create (userCallback), false);
  1582. }
  1583. //==============================================================================
  1584. #if JUCE_MODAL_LOOPS_PERMITTED
  1585. int PopupMenu::show (int itemIDThatMustBeVisible, int minimumWidth,
  1586. int maximumNumColumns, int standardItemHeight,
  1587. ModalComponentManager::Callback* callback)
  1588. {
  1589. return showWithOptionalCallback (Options().withItemThatMustBeVisible (itemIDThatMustBeVisible)
  1590. .withMinimumWidth (minimumWidth)
  1591. .withMaximumNumColumns (maximumNumColumns)
  1592. .withStandardItemHeight (standardItemHeight),
  1593. callback, true);
  1594. }
  1595. int PopupMenu::showAt (Rectangle<int> screenAreaToAttachTo,
  1596. int itemIDThatMustBeVisible, int minimumWidth,
  1597. int maximumNumColumns, int standardItemHeight,
  1598. ModalComponentManager::Callback* callback)
  1599. {
  1600. return showWithOptionalCallback (Options().withTargetScreenArea (screenAreaToAttachTo)
  1601. .withItemThatMustBeVisible (itemIDThatMustBeVisible)
  1602. .withMinimumWidth (minimumWidth)
  1603. .withMaximumNumColumns (maximumNumColumns)
  1604. .withStandardItemHeight (standardItemHeight),
  1605. callback, true);
  1606. }
  1607. int PopupMenu::showAt (Component* componentToAttachTo,
  1608. int itemIDThatMustBeVisible, int minimumWidth,
  1609. int maximumNumColumns, int standardItemHeight,
  1610. ModalComponentManager::Callback* callback)
  1611. {
  1612. auto options = Options().withItemThatMustBeVisible (itemIDThatMustBeVisible)
  1613. .withMinimumWidth (minimumWidth)
  1614. .withMaximumNumColumns (maximumNumColumns)
  1615. .withStandardItemHeight (standardItemHeight);
  1616. if (componentToAttachTo != nullptr)
  1617. options = options.withTargetComponent (componentToAttachTo);
  1618. return showWithOptionalCallback (options, callback, true);
  1619. }
  1620. #endif
  1621. bool JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  1622. {
  1623. auto& windows = HelperClasses::MenuWindow::getActiveWindows();
  1624. auto numWindows = windows.size();
  1625. for (int i = numWindows; --i >= 0;)
  1626. {
  1627. if (auto* pmw = windows[i])
  1628. {
  1629. pmw->setLookAndFeel (nullptr);
  1630. pmw->dismissMenu (nullptr);
  1631. }
  1632. }
  1633. return numWindows > 0;
  1634. }
  1635. //==============================================================================
  1636. int PopupMenu::getNumItems() const noexcept
  1637. {
  1638. int num = 0;
  1639. for (auto& mi : items)
  1640. if (! mi.isSeparator)
  1641. ++num;
  1642. return num;
  1643. }
  1644. bool PopupMenu::containsCommandItem (const int commandID) const
  1645. {
  1646. for (auto& mi : items)
  1647. if ((mi.itemID == commandID && mi.commandManager != nullptr)
  1648. || (mi.subMenu != nullptr && mi.subMenu->containsCommandItem (commandID)))
  1649. return true;
  1650. return false;
  1651. }
  1652. bool PopupMenu::containsAnyActiveItems() const noexcept
  1653. {
  1654. for (auto& mi : items)
  1655. {
  1656. if (mi.subMenu != nullptr)
  1657. {
  1658. if (mi.subMenu->containsAnyActiveItems())
  1659. return true;
  1660. }
  1661. else if (mi.isEnabled)
  1662. {
  1663. return true;
  1664. }
  1665. }
  1666. return false;
  1667. }
  1668. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  1669. {
  1670. lookAndFeel = newLookAndFeel;
  1671. }
  1672. void PopupMenu::setItem (CustomComponent& c, const Item* itemToUse)
  1673. {
  1674. c.item = itemToUse;
  1675. c.repaint();
  1676. }
  1677. //==============================================================================
  1678. PopupMenu::CustomComponent::CustomComponent (bool autoTrigger)
  1679. : triggeredAutomatically (autoTrigger)
  1680. {
  1681. }
  1682. PopupMenu::CustomComponent::~CustomComponent()
  1683. {
  1684. }
  1685. void PopupMenu::CustomComponent::setHighlighted (bool shouldBeHighlighted)
  1686. {
  1687. isHighlighted = shouldBeHighlighted;
  1688. repaint();
  1689. }
  1690. void PopupMenu::CustomComponent::triggerMenuItem()
  1691. {
  1692. if (auto* mic = findParentComponentOfClass<HelperClasses::ItemComponent>())
  1693. {
  1694. if (auto* pmw = mic->findParentComponentOfClass<HelperClasses::MenuWindow>())
  1695. {
  1696. pmw->dismissMenu (&mic->item);
  1697. }
  1698. else
  1699. {
  1700. // something must have gone wrong with the component hierarchy if this happens..
  1701. jassertfalse;
  1702. }
  1703. }
  1704. else
  1705. {
  1706. // why isn't this component inside a menu? Not much point triggering the item if
  1707. // there's no menu.
  1708. jassertfalse;
  1709. }
  1710. }
  1711. //==============================================================================
  1712. PopupMenu::CustomCallback::CustomCallback() {}
  1713. PopupMenu::CustomCallback::~CustomCallback() {}
  1714. //==============================================================================
  1715. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& m, bool recurse) : searchRecursively (recurse)
  1716. {
  1717. index.add (0);
  1718. menus.add (&m);
  1719. }
  1720. PopupMenu::MenuItemIterator::~MenuItemIterator() = default;
  1721. bool PopupMenu::MenuItemIterator::next()
  1722. {
  1723. if (index.size() == 0 || menus.getLast()->items.size() == 0)
  1724. return false;
  1725. currentItem = const_cast<PopupMenu::Item*> (&(menus.getLast()->items.getReference (index.getLast())));
  1726. if (searchRecursively && currentItem->subMenu != nullptr)
  1727. {
  1728. index.add (0);
  1729. menus.add (currentItem->subMenu.get());
  1730. }
  1731. else
  1732. {
  1733. index.setUnchecked (index.size() - 1, index.getLast() + 1);
  1734. }
  1735. while (index.size() > 0 && index.getLast() >= (int) menus.getLast()->items.size())
  1736. {
  1737. index.removeLast();
  1738. menus.removeLast();
  1739. if (index.size() > 0)
  1740. index.setUnchecked (index.size() - 1, index.getLast() + 1);
  1741. }
  1742. return true;
  1743. }
  1744. PopupMenu::Item& PopupMenu::MenuItemIterator::getItem() const
  1745. {
  1746. jassert (currentItem != nullptr);
  1747. return *(currentItem);
  1748. }
  1749. void PopupMenu::LookAndFeelMethods::drawPopupMenuBackground (Graphics&, int, int) {}
  1750. void PopupMenu::LookAndFeelMethods::drawPopupMenuItem (Graphics&, const Rectangle<int>&,
  1751. bool, bool, bool,
  1752. bool, bool,
  1753. const String&,
  1754. const String&,
  1755. const Drawable*,
  1756. const Colour*) {}
  1757. void PopupMenu::LookAndFeelMethods::drawPopupMenuSectionHeader (Graphics&, const Rectangle<int>&,
  1758. const String&) {}
  1759. void PopupMenu::LookAndFeelMethods::drawPopupMenuUpDownArrow (Graphics&, int, int, bool) {}
  1760. void PopupMenu::LookAndFeelMethods::getIdealPopupMenuItemSize (const String&, bool, int, int&, int&) {}
  1761. int PopupMenu::LookAndFeelMethods::getPopupMenuBorderSize() { return 0; }
  1762. } // namespace juce