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.

2178 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, true);
  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. if (! Process::isForegroundProcess())
  507. return false;
  508. if (Component::getCurrentlyFocusedComponent() != nullptr)
  509. return true;
  510. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  511. {
  512. if (ComponentPeer::getPeer (i)->isFocused())
  513. {
  514. hasAnyJuceCompHadFocus = true;
  515. return true;
  516. }
  517. }
  518. return ! hasAnyJuceCompHadFocus;
  519. }
  520. //==============================================================================
  521. Rectangle<int> getParentArea (Point<int> targetPoint, Component* relativeTo = nullptr)
  522. {
  523. if (relativeTo != nullptr)
  524. targetPoint = relativeTo->localPointToGlobal (targetPoint);
  525. auto parentArea = Desktop::getInstance().getDisplays().getDisplayForPoint (targetPoint * scaleFactor)
  526. #if JUCE_MAC || JUCE_ANDROID
  527. ->userArea;
  528. #else
  529. ->totalArea; // on windows, don't stop the menu overlapping the taskbar
  530. #endif
  531. if (parentComponent == nullptr)
  532. return parentArea;
  533. return parentComponent->getLocalArea (nullptr,
  534. parentComponent->getScreenBounds()
  535. .reduced (getLookAndFeel().getPopupMenuBorderSizeWithOptions (options))
  536. .getIntersection (parentArea));
  537. }
  538. void calculateWindowPos (Rectangle<int> target, const bool alignToRectangle)
  539. {
  540. auto parentArea = getParentArea (target.getCentre()) / scaleFactor;
  541. if (parentComponent != nullptr)
  542. target = parentComponent->getLocalArea (nullptr, target).getIntersection (parentArea);
  543. auto maxMenuHeight = parentArea.getHeight() - 24;
  544. int x, y, widthToUse, heightToUse;
  545. layoutMenuItems (parentArea.getWidth() - 24, maxMenuHeight, widthToUse, heightToUse);
  546. if (alignToRectangle)
  547. {
  548. x = target.getX();
  549. auto spaceUnder = parentArea.getBottom() - target.getBottom();
  550. auto spaceOver = target.getY() - parentArea.getY();
  551. auto bufferHeight = 30;
  552. if (options.getPreferredPopupDirection() == Options::PopupDirection::upwards)
  553. y = (heightToUse < spaceOver - bufferHeight || spaceOver >= spaceUnder) ? target.getY() - heightToUse
  554. : target.getBottom();
  555. else
  556. y = (heightToUse < spaceUnder - bufferHeight || spaceUnder >= spaceOver) ? target.getBottom()
  557. : target.getY() - heightToUse;
  558. }
  559. else
  560. {
  561. bool tendTowardsRight = target.getCentreX() < parentArea.getCentreX();
  562. if (parent != nullptr)
  563. {
  564. if (parent->parent != nullptr)
  565. {
  566. const bool parentGoingRight = (parent->getX() + parent->getWidth() / 2
  567. > parent->parent->getX() + parent->parent->getWidth() / 2);
  568. if (parentGoingRight && target.getRight() + widthToUse < parentArea.getRight() - 4)
  569. tendTowardsRight = true;
  570. else if ((! parentGoingRight) && target.getX() > widthToUse + 4)
  571. tendTowardsRight = false;
  572. }
  573. else if (target.getRight() + widthToUse < parentArea.getRight() - 32)
  574. {
  575. tendTowardsRight = true;
  576. }
  577. }
  578. auto biggestSpace = jmax (parentArea.getRight() - target.getRight(),
  579. target.getX() - parentArea.getX()) - 32;
  580. if (biggestSpace < widthToUse)
  581. {
  582. layoutMenuItems (biggestSpace + target.getWidth() / 3, maxMenuHeight, widthToUse, heightToUse);
  583. if (numColumns > 1)
  584. layoutMenuItems (biggestSpace - 4, maxMenuHeight, widthToUse, heightToUse);
  585. tendTowardsRight = (parentArea.getRight() - target.getRight()) >= (target.getX() - parentArea.getX());
  586. }
  587. x = tendTowardsRight ? jmin (parentArea.getRight() - widthToUse - 4, target.getRight())
  588. : jmax (parentArea.getX() + 4, target.getX() - widthToUse);
  589. if (getLookAndFeel().getPopupMenuBorderSizeWithOptions (options) == 0) // workaround for dismissing the window on mouse up when border size is 0
  590. x += tendTowardsRight ? 1 : -1;
  591. y = target.getCentreY() > parentArea.getCentreY() ? jmax (parentArea.getY(), target.getBottom() - heightToUse)
  592. : target.getY();
  593. }
  594. x = jmax (parentArea.getX() + 1, jmin (parentArea.getRight() - (widthToUse + 6), x));
  595. y = jmax (parentArea.getY() + 1, jmin (parentArea.getBottom() - (heightToUse + 6), y));
  596. windowPos.setBounds (x, y, widthToUse, heightToUse);
  597. // sets this flag if it's big enough to obscure any of its parent menus
  598. hideOnExit = parent != nullptr
  599. && parent->windowPos.intersects (windowPos.expanded (-4, -4));
  600. }
  601. void layoutMenuItems (const int maxMenuW, const int maxMenuH, int& width, int& height)
  602. {
  603. // Ensure we don't try to add an empty column after the final item
  604. if (auto* last = items.getLast())
  605. last->item.shouldBreakAfter = false;
  606. const auto isBreak = [] (const ItemComponent* item) { return item->item.shouldBreakAfter; };
  607. const auto numBreaks = static_cast<int> (std::count_if (items.begin(), items.end(), isBreak));
  608. numColumns = numBreaks + 1;
  609. if (numBreaks == 0)
  610. insertColumnBreaks (maxMenuW, maxMenuH);
  611. workOutManualSize (maxMenuW);
  612. auto actualH = jmin (contentHeight, maxMenuH);
  613. needsToScroll = contentHeight > actualH;
  614. width = updateYPositions();
  615. height = actualH + getLookAndFeel().getPopupMenuBorderSizeWithOptions (options) * 2;
  616. }
  617. void insertColumnBreaks (const int maxMenuW, const int maxMenuH)
  618. {
  619. numColumns = options.getMinimumNumColumns();
  620. contentHeight = 0;
  621. auto maximumNumColumns = options.getMaximumNumColumns() > 0 ? options.getMaximumNumColumns() : 7;
  622. for (;;)
  623. {
  624. auto totalW = workOutBestSize (maxMenuW);
  625. if (totalW > maxMenuW)
  626. {
  627. numColumns = jmax (1, numColumns - 1);
  628. workOutBestSize (maxMenuW); // to update col widths
  629. break;
  630. }
  631. if (totalW > maxMenuW / 2
  632. || contentHeight < maxMenuH
  633. || numColumns >= maximumNumColumns)
  634. break;
  635. ++numColumns;
  636. }
  637. const auto itemsPerColumn = (items.size() + numColumns - 1) / numColumns;
  638. for (auto i = 0;; i += itemsPerColumn)
  639. {
  640. const auto breakIndex = i + itemsPerColumn - 1;
  641. if (breakIndex >= items.size())
  642. break;
  643. items[breakIndex]->item.shouldBreakAfter = true;
  644. }
  645. if (! items.isEmpty())
  646. (*std::prev (items.end()))->item.shouldBreakAfter = false;
  647. }
  648. int correctColumnWidths (const int maxMenuW)
  649. {
  650. auto totalW = std::accumulate (columnWidths.begin(), columnWidths.end(), 0);
  651. const auto minWidth = jmin (maxMenuW, options.getMinimumWidth());
  652. if (totalW < minWidth)
  653. {
  654. totalW = minWidth;
  655. for (auto& column : columnWidths)
  656. column = totalW / numColumns;
  657. }
  658. return totalW;
  659. }
  660. void workOutManualSize (const int maxMenuW)
  661. {
  662. contentHeight = 0;
  663. columnWidths.clear();
  664. for (auto it = items.begin(), end = items.end(); it != end;)
  665. {
  666. const auto isBreak = [] (const ItemComponent* item) { return item->item.shouldBreakAfter; };
  667. const auto nextBreak = std::find_if (it, end, isBreak);
  668. const auto columnEnd = nextBreak == end ? end : std::next (nextBreak);
  669. const auto getMaxWidth = [] (int acc, const ItemComponent* item) { return jmax (acc, item->getWidth()); };
  670. const auto colW = std::accumulate (it, columnEnd, options.getStandardItemHeight(), getMaxWidth);
  671. const auto adjustedColW = jmin (maxMenuW / jmax (1, numColumns - 2),
  672. colW + getLookAndFeel().getPopupMenuBorderSizeWithOptions (options) * 2);
  673. const auto sumHeight = [] (int acc, const ItemComponent* item) { return acc + item->getHeight(); };
  674. const auto colH = std::accumulate (it, columnEnd, 0, sumHeight);
  675. contentHeight = jmax (contentHeight, colH);
  676. columnWidths.add (adjustedColW);
  677. it = columnEnd;
  678. }
  679. correctColumnWidths (maxMenuW);
  680. }
  681. int workOutBestSize (const int maxMenuW)
  682. {
  683. contentHeight = 0;
  684. int childNum = 0;
  685. for (int col = 0; col < numColumns; ++col)
  686. {
  687. int colW = options.getStandardItemHeight(), colH = 0;
  688. auto numChildren = jmin (items.size() - childNum,
  689. (items.size() + numColumns - 1) / numColumns);
  690. for (int i = numChildren; --i >= 0;)
  691. {
  692. colW = jmax (colW, items.getUnchecked (childNum + i)->getWidth());
  693. colH += items.getUnchecked (childNum + i)->getHeight();
  694. }
  695. colW = jmin (maxMenuW / jmax (1, numColumns - 2),
  696. colW + getLookAndFeel().getPopupMenuBorderSizeWithOptions (options) * 2);
  697. columnWidths.set (col, colW);
  698. contentHeight = jmax (contentHeight, colH);
  699. childNum += numChildren;
  700. }
  701. return correctColumnWidths (maxMenuW);
  702. }
  703. void ensureItemIsVisible (const int itemID, int wantedY)
  704. {
  705. jassert (itemID != 0);
  706. for (int i = items.size(); --i >= 0;)
  707. {
  708. if (auto* m = items.getUnchecked (i))
  709. {
  710. if (m->item.itemID == itemID
  711. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  712. {
  713. auto currentY = m->getY();
  714. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  715. {
  716. if (wantedY < 0)
  717. wantedY = jlimit (PopupMenuSettings::scrollZone,
  718. jmax (PopupMenuSettings::scrollZone,
  719. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  720. currentY);
  721. auto parentArea = getParentArea (windowPos.getPosition(), parentComponent) / scaleFactor;
  722. auto deltaY = wantedY - currentY;
  723. windowPos.setSize (jmin (windowPos.getWidth(), parentArea.getWidth()),
  724. jmin (windowPos.getHeight(), parentArea.getHeight()));
  725. auto newY = jlimit (parentArea.getY(),
  726. parentArea.getBottom() - windowPos.getHeight(),
  727. windowPos.getY() + deltaY);
  728. deltaY -= newY - windowPos.getY();
  729. childYOffset -= deltaY;
  730. windowPos.setPosition (windowPos.getX(), newY);
  731. updateYPositions();
  732. }
  733. break;
  734. }
  735. }
  736. }
  737. }
  738. void resizeToBestWindowPos()
  739. {
  740. auto r = windowPos;
  741. if (childYOffset < 0)
  742. {
  743. r = r.withTop (r.getY() - childYOffset);
  744. }
  745. else if (childYOffset > 0)
  746. {
  747. auto spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  748. if (spaceAtBottom > 0)
  749. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  750. }
  751. setBounds (r);
  752. updateYPositions();
  753. }
  754. void alterChildYPos (int delta)
  755. {
  756. if (canScroll())
  757. {
  758. childYOffset += delta;
  759. childYOffset = [&]
  760. {
  761. if (delta < 0)
  762. return jmax (childYOffset, 0);
  763. if (delta > 0)
  764. {
  765. const auto limit = contentHeight
  766. - windowPos.getHeight()
  767. + getLookAndFeel().getPopupMenuBorderSizeWithOptions (options);
  768. return jmin (childYOffset, limit);
  769. }
  770. return childYOffset;
  771. }();
  772. updateYPositions();
  773. }
  774. else
  775. {
  776. childYOffset = 0;
  777. }
  778. resizeToBestWindowPos();
  779. repaint();
  780. }
  781. int updateYPositions()
  782. {
  783. const auto separatorWidth = getLookAndFeel().getPopupMenuColumnSeparatorWidthWithOptions (options);
  784. const auto initialY = getLookAndFeel().getPopupMenuBorderSizeWithOptions (options)
  785. - (childYOffset + (getY() - windowPos.getY()));
  786. auto col = 0;
  787. auto x = 0;
  788. auto y = initialY;
  789. for (const auto& item : items)
  790. {
  791. jassert (col < columnWidths.size());
  792. const auto columnWidth = columnWidths[col];
  793. item->setBounds (x, y, columnWidth, item->getHeight());
  794. y += item->getHeight();
  795. if (item->item.shouldBreakAfter)
  796. {
  797. col += 1;
  798. x += columnWidth + separatorWidth;
  799. y = initialY;
  800. }
  801. }
  802. return std::accumulate (columnWidths.begin(), columnWidths.end(), 0)
  803. + (separatorWidth * (columnWidths.size() - 1));
  804. }
  805. void setCurrentlyHighlightedChild (ItemComponent* child)
  806. {
  807. if (currentChild != nullptr)
  808. currentChild->setHighlighted (false);
  809. currentChild = child;
  810. if (currentChild != nullptr)
  811. {
  812. currentChild->setHighlighted (true);
  813. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  814. }
  815. }
  816. bool isSubMenuVisible() const noexcept { return activeSubMenu != nullptr && activeSubMenu->isVisible(); }
  817. bool showSubMenuFor (ItemComponent* childComp)
  818. {
  819. activeSubMenu.reset();
  820. if (childComp != nullptr
  821. && hasActiveSubMenu (childComp->item))
  822. {
  823. activeSubMenu.reset (new HelperClasses::MenuWindow (*(childComp->item.subMenu), this,
  824. options.withTargetScreenArea (childComp->getScreenBounds())
  825. .withMinimumWidth (0)
  826. .withTargetComponent (nullptr)
  827. .withParentComponent (parentComponent),
  828. false, dismissOnMouseUp, managerOfChosenCommand, scaleFactor));
  829. activeSubMenu->setVisible (true); // (must be called before enterModalState on Windows to avoid DropShadower confusion)
  830. activeSubMenu->enterModalState (false);
  831. activeSubMenu->toFront (false);
  832. return true;
  833. }
  834. return false;
  835. }
  836. void triggerCurrentlyHighlightedItem()
  837. {
  838. if (currentChild != nullptr
  839. && canBeTriggered (currentChild->item)
  840. && (currentChild->item.customComponent == nullptr
  841. || currentChild->item.customComponent->isTriggeredAutomatically()))
  842. {
  843. dismissMenu (&currentChild->item);
  844. }
  845. }
  846. enum class MenuSelectionDirection
  847. {
  848. forwards,
  849. backwards,
  850. current
  851. };
  852. void selectNextItem (MenuSelectionDirection direction)
  853. {
  854. disableTimerUntilMouseMoves();
  855. auto start = [&]
  856. {
  857. auto index = items.indexOf (currentChild);
  858. if (index >= 0)
  859. return index;
  860. return direction == MenuSelectionDirection::backwards ? items.size() - 1
  861. : 0;
  862. }();
  863. auto preIncrement = (direction != MenuSelectionDirection::current && currentChild != nullptr);
  864. for (int i = items.size(); --i >= 0;)
  865. {
  866. if (preIncrement)
  867. start += (direction == MenuSelectionDirection::backwards ? -1 : 1);
  868. if (auto* mic = items.getUnchecked ((start + items.size()) % items.size()))
  869. {
  870. if (canBeTriggered (mic->item) || hasActiveSubMenu (mic->item))
  871. {
  872. setCurrentlyHighlightedChild (mic);
  873. return;
  874. }
  875. }
  876. if (! preIncrement)
  877. preIncrement = true;
  878. }
  879. }
  880. void disableTimerUntilMouseMoves()
  881. {
  882. disableMouseMoves = true;
  883. if (parent != nullptr)
  884. parent->disableTimerUntilMouseMoves();
  885. }
  886. bool canScroll() const noexcept { return childYOffset != 0 || needsToScroll; }
  887. bool isTopScrollZoneActive() const noexcept { return canScroll() && childYOffset > 0; }
  888. bool isBottomScrollZoneActive() const noexcept { return canScroll() && childYOffset < contentHeight - windowPos.getHeight(); }
  889. //==============================================================================
  890. MenuWindow* parent;
  891. const Options options;
  892. OwnedArray<ItemComponent> items;
  893. ApplicationCommandManager** managerOfChosenCommand;
  894. WeakReference<Component> componentAttachedTo;
  895. Component* parentComponent = nullptr;
  896. Rectangle<int> windowPos;
  897. bool hasBeenOver = false, needsToScroll = false;
  898. bool dismissOnMouseUp, hideOnExit = false, disableMouseMoves = false, hasAnyJuceCompHadFocus = false;
  899. int numColumns = 0, contentHeight = 0, childYOffset = 0;
  900. Component::SafePointer<ItemComponent> currentChild;
  901. std::unique_ptr<MenuWindow> activeSubMenu;
  902. Array<int> columnWidths;
  903. uint32 windowCreationTime, lastFocusedTime, timeEnteredCurrentChildComp;
  904. OwnedArray<MouseSourceState> mouseSourceStates;
  905. float scaleFactor;
  906. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuWindow)
  907. };
  908. //==============================================================================
  909. class MouseSourceState : public Timer
  910. {
  911. public:
  912. MouseSourceState (MenuWindow& w, MouseInputSource s)
  913. : window (w), source (s), lastScrollTime (Time::getMillisecondCounter())
  914. {
  915. startTimerHz (20);
  916. }
  917. void handleMouseEvent (const MouseEvent& e)
  918. {
  919. if (! window.windowIsStillValid())
  920. return;
  921. startTimerHz (20);
  922. handleMousePosition (e.getScreenPosition());
  923. }
  924. void timerCallback() override
  925. {
  926. #if JUCE_WINDOWS
  927. // touch and pen devices on Windows send an offscreen mouse move after mouse up events
  928. // but we don't want to forward these on as they will dismiss the menu
  929. if ((source.isTouch() || source.isPen()) && ! isValidMousePosition())
  930. return;
  931. #endif
  932. if (window.windowIsStillValid())
  933. handleMousePosition (source.getScreenPosition().roundToInt());
  934. }
  935. bool isOver() const
  936. {
  937. return window.reallyContains (window.getLocalPoint (nullptr, source.getScreenPosition()).roundToInt(), true);
  938. }
  939. MenuWindow& window;
  940. MouseInputSource source;
  941. private:
  942. Point<int> lastMousePos;
  943. double scrollAcceleration = 0;
  944. uint32 lastScrollTime, lastMouseMoveTime = 0;
  945. bool isDown = false;
  946. void handleMousePosition (Point<int> globalMousePos)
  947. {
  948. auto localMousePos = window.getLocalPoint (nullptr, globalMousePos);
  949. auto timeNow = Time::getMillisecondCounter();
  950. if (timeNow > window.timeEnteredCurrentChildComp + 100
  951. && window.reallyContains (localMousePos, true)
  952. && window.currentChild != nullptr
  953. && ! (window.disableMouseMoves || window.isSubMenuVisible()))
  954. {
  955. window.showSubMenuFor (window.currentChild);
  956. }
  957. highlightItemUnderMouse (globalMousePos, localMousePos, timeNow);
  958. const bool overScrollArea = scrollIfNecessary (localMousePos, timeNow);
  959. const bool isOverAny = window.isOverAnyMenu();
  960. if (window.hideOnExit && window.hasBeenOver && ! isOverAny)
  961. window.hide (nullptr, true);
  962. else
  963. checkButtonState (localMousePos, timeNow, isDown, overScrollArea, isOverAny);
  964. }
  965. void checkButtonState (Point<int> localMousePos, const uint32 timeNow,
  966. const bool wasDown, const bool overScrollArea, const bool isOverAny)
  967. {
  968. isDown = window.hasBeenOver
  969. && (ModifierKeys::currentModifiers.isAnyMouseButtonDown()
  970. || ComponentPeer::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  971. if (! window.doesAnyJuceCompHaveFocus())
  972. {
  973. if (timeNow > window.lastFocusedTime + 10)
  974. {
  975. PopupMenuSettings::menuWasHiddenBecauseOfAppChange = true;
  976. window.dismissMenu (nullptr);
  977. // Note: This object may have been deleted by the previous call.
  978. }
  979. }
  980. else if (wasDown && timeNow > window.windowCreationTime + 250
  981. && ! (isDown || overScrollArea))
  982. {
  983. if (window.reallyContains (localMousePos, true))
  984. window.triggerCurrentlyHighlightedItem();
  985. else if ((window.hasBeenOver || ! window.dismissOnMouseUp) && ! isOverAny)
  986. window.dismissMenu (nullptr);
  987. // Note: This object may have been deleted by the previous call.
  988. }
  989. else
  990. {
  991. window.lastFocusedTime = timeNow;
  992. }
  993. }
  994. void highlightItemUnderMouse (Point<int> globalMousePos, Point<int> localMousePos, const uint32 timeNow)
  995. {
  996. if (globalMousePos != lastMousePos || timeNow > lastMouseMoveTime + 350)
  997. {
  998. const bool isMouseOver = window.reallyContains (localMousePos, true);
  999. if (isMouseOver)
  1000. window.hasBeenOver = true;
  1001. if (lastMousePos.getDistanceFrom (globalMousePos) > 2)
  1002. {
  1003. lastMouseMoveTime = timeNow;
  1004. if (window.disableMouseMoves && isMouseOver)
  1005. window.disableMouseMoves = false;
  1006. }
  1007. if (window.disableMouseMoves || (window.activeSubMenu != nullptr && window.activeSubMenu->isOverChildren()))
  1008. return;
  1009. const bool isMovingTowardsMenu = isMouseOver && globalMousePos != lastMousePos
  1010. && isMovingTowardsSubmenu (globalMousePos);
  1011. lastMousePos = globalMousePos;
  1012. if (! isMovingTowardsMenu)
  1013. {
  1014. auto* c = window.getComponentAt (localMousePos);
  1015. if (c == &window)
  1016. c = nullptr;
  1017. auto* itemUnderMouse = dynamic_cast<ItemComponent*> (c);
  1018. if (itemUnderMouse == nullptr && c != nullptr)
  1019. itemUnderMouse = c->findParentComponentOfClass<ItemComponent>();
  1020. if (itemUnderMouse != window.currentChild
  1021. && (isMouseOver || (window.activeSubMenu == nullptr) || ! window.activeSubMenu->isVisible()))
  1022. {
  1023. if (isMouseOver && (c != nullptr) && (window.activeSubMenu != nullptr))
  1024. window.activeSubMenu->hide (nullptr, true);
  1025. if (! isMouseOver)
  1026. itemUnderMouse = nullptr;
  1027. window.setCurrentlyHighlightedChild (itemUnderMouse);
  1028. }
  1029. }
  1030. }
  1031. }
  1032. bool isMovingTowardsSubmenu (Point<int> newGlobalPos) const
  1033. {
  1034. if (window.activeSubMenu == nullptr)
  1035. return false;
  1036. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  1037. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  1038. // extends from the last mouse pos to the submenu's rectangle..
  1039. auto itemScreenBounds = window.activeSubMenu->getScreenBounds();
  1040. auto subX = (float) itemScreenBounds.getX();
  1041. auto oldGlobalPos = lastMousePos;
  1042. if (itemScreenBounds.getX() > window.getX())
  1043. {
  1044. oldGlobalPos -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  1045. }
  1046. else
  1047. {
  1048. oldGlobalPos += Point<int> (2, 0);
  1049. subX += (float) itemScreenBounds.getWidth();
  1050. }
  1051. Path areaTowardsSubMenu;
  1052. areaTowardsSubMenu.addTriangle ((float) oldGlobalPos.x, (float) oldGlobalPos.y,
  1053. subX, (float) itemScreenBounds.getY(),
  1054. subX, (float) itemScreenBounds.getBottom());
  1055. return areaTowardsSubMenu.contains (newGlobalPos.toFloat());
  1056. }
  1057. bool scrollIfNecessary (Point<int> localMousePos, const uint32 timeNow)
  1058. {
  1059. if (window.canScroll()
  1060. && isPositiveAndBelow (localMousePos.x, window.getWidth())
  1061. && (isPositiveAndBelow (localMousePos.y, window.getHeight()) || source.isDragging()))
  1062. {
  1063. if (window.isTopScrollZoneActive() && localMousePos.y < PopupMenuSettings::scrollZone)
  1064. return scroll (timeNow, -1);
  1065. if (window.isBottomScrollZoneActive() && localMousePos.y > window.getHeight() - PopupMenuSettings::scrollZone)
  1066. return scroll (timeNow, 1);
  1067. }
  1068. scrollAcceleration = 1.0;
  1069. return false;
  1070. }
  1071. bool scroll (const uint32 timeNow, const int direction)
  1072. {
  1073. if (timeNow > lastScrollTime + 20)
  1074. {
  1075. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  1076. int amount = 0;
  1077. for (int i = 0; i < window.items.size() && amount == 0; ++i)
  1078. amount = ((int) scrollAcceleration) * window.items.getUnchecked (i)->getHeight();
  1079. window.alterChildYPos (amount * direction);
  1080. lastScrollTime = timeNow;
  1081. }
  1082. return true;
  1083. }
  1084. #if JUCE_WINDOWS
  1085. bool isValidMousePosition()
  1086. {
  1087. auto screenPos = source.getScreenPosition();
  1088. auto localPos = (window.activeSubMenu == nullptr) ? window.getLocalPoint (nullptr, screenPos)
  1089. : window.activeSubMenu->getLocalPoint (nullptr, screenPos);
  1090. if (localPos.x < 0 && localPos.y < 0)
  1091. return false;
  1092. return true;
  1093. }
  1094. #endif
  1095. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MouseSourceState)
  1096. };
  1097. //==============================================================================
  1098. struct NormalComponentWrapper : public PopupMenu::CustomComponent
  1099. {
  1100. NormalComponentWrapper (Component& comp, int w, int h, bool triggerMenuItemAutomaticallyWhenClicked)
  1101. : PopupMenu::CustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  1102. width (w), height (h)
  1103. {
  1104. addAndMakeVisible (comp);
  1105. }
  1106. void getIdealSize (int& idealWidth, int& idealHeight) override
  1107. {
  1108. idealWidth = width;
  1109. idealHeight = height;
  1110. }
  1111. void resized() override
  1112. {
  1113. if (auto* child = getChildComponent (0))
  1114. child->setBounds (getLocalBounds());
  1115. }
  1116. const int width, height;
  1117. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NormalComponentWrapper)
  1118. };
  1119. };
  1120. //==============================================================================
  1121. PopupMenu::PopupMenu (const PopupMenu& other)
  1122. : items (other.items),
  1123. lookAndFeel (other.lookAndFeel)
  1124. {
  1125. }
  1126. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  1127. {
  1128. if (this != &other)
  1129. {
  1130. items = other.items;
  1131. lookAndFeel = other.lookAndFeel;
  1132. }
  1133. return *this;
  1134. }
  1135. PopupMenu::PopupMenu (PopupMenu&& other) noexcept
  1136. : items (std::move (other.items)),
  1137. lookAndFeel (std::move (other.lookAndFeel))
  1138. {
  1139. }
  1140. PopupMenu& PopupMenu::operator= (PopupMenu&& other) noexcept
  1141. {
  1142. items = std::move (other.items);
  1143. lookAndFeel = other.lookAndFeel;
  1144. return *this;
  1145. }
  1146. PopupMenu::~PopupMenu() = default;
  1147. void PopupMenu::clear()
  1148. {
  1149. items.clear();
  1150. }
  1151. //==============================================================================
  1152. PopupMenu::Item::Item() = default;
  1153. PopupMenu::Item::Item (String t) : text (std::move (t)), itemID (-1) {}
  1154. PopupMenu::Item::Item (Item&&) = default;
  1155. PopupMenu::Item& PopupMenu::Item::operator= (Item&&) = default;
  1156. PopupMenu::Item::Item (const Item& other)
  1157. : text (other.text),
  1158. itemID (other.itemID),
  1159. action (other.action),
  1160. subMenu (createCopyIfNotNull (other.subMenu.get())),
  1161. image (other.image != nullptr ? other.image->createCopy() : nullptr),
  1162. customComponent (other.customComponent),
  1163. customCallback (other.customCallback),
  1164. commandManager (other.commandManager),
  1165. shortcutKeyDescription (other.shortcutKeyDescription),
  1166. colour (other.colour),
  1167. isEnabled (other.isEnabled),
  1168. isTicked (other.isTicked),
  1169. isSeparator (other.isSeparator),
  1170. isSectionHeader (other.isSectionHeader),
  1171. shouldBreakAfter (other.shouldBreakAfter)
  1172. {}
  1173. PopupMenu::Item& PopupMenu::Item::operator= (const Item& other)
  1174. {
  1175. text = other.text;
  1176. itemID = other.itemID;
  1177. action = other.action;
  1178. subMenu.reset (createCopyIfNotNull (other.subMenu.get()));
  1179. image = other.image != nullptr ? other.image->createCopy() : std::unique_ptr<Drawable>();
  1180. customComponent = other.customComponent;
  1181. customCallback = other.customCallback;
  1182. commandManager = other.commandManager;
  1183. shortcutKeyDescription = other.shortcutKeyDescription;
  1184. colour = other.colour;
  1185. isEnabled = other.isEnabled;
  1186. isTicked = other.isTicked;
  1187. isSeparator = other.isSeparator;
  1188. isSectionHeader = other.isSectionHeader;
  1189. shouldBreakAfter = other.shouldBreakAfter;
  1190. return *this;
  1191. }
  1192. PopupMenu::Item& PopupMenu::Item::setTicked (bool shouldBeTicked) & noexcept
  1193. {
  1194. isTicked = shouldBeTicked;
  1195. return *this;
  1196. }
  1197. PopupMenu::Item& PopupMenu::Item::setEnabled (bool shouldBeEnabled) & noexcept
  1198. {
  1199. isEnabled = shouldBeEnabled;
  1200. return *this;
  1201. }
  1202. PopupMenu::Item& PopupMenu::Item::setAction (std::function<void()> newAction) & noexcept
  1203. {
  1204. action = std::move (newAction);
  1205. return *this;
  1206. }
  1207. PopupMenu::Item& PopupMenu::Item::setID (int newID) & noexcept
  1208. {
  1209. itemID = newID;
  1210. return *this;
  1211. }
  1212. PopupMenu::Item& PopupMenu::Item::setColour (Colour newColour) & noexcept
  1213. {
  1214. colour = newColour;
  1215. return *this;
  1216. }
  1217. PopupMenu::Item& PopupMenu::Item::setCustomComponent (ReferenceCountedObjectPtr<CustomComponent> comp) & noexcept
  1218. {
  1219. customComponent = comp;
  1220. return *this;
  1221. }
  1222. PopupMenu::Item& PopupMenu::Item::setImage (std::unique_ptr<Drawable> newImage) & noexcept
  1223. {
  1224. image = std::move (newImage);
  1225. return *this;
  1226. }
  1227. PopupMenu::Item&& PopupMenu::Item::setTicked (bool shouldBeTicked) && noexcept
  1228. {
  1229. isTicked = shouldBeTicked;
  1230. return std::move (*this);
  1231. }
  1232. PopupMenu::Item&& PopupMenu::Item::setEnabled (bool shouldBeEnabled) && noexcept
  1233. {
  1234. isEnabled = shouldBeEnabled;
  1235. return std::move (*this);
  1236. }
  1237. PopupMenu::Item&& PopupMenu::Item::setAction (std::function<void()> newAction) && noexcept
  1238. {
  1239. action = std::move (newAction);
  1240. return std::move (*this);
  1241. }
  1242. PopupMenu::Item&& PopupMenu::Item::setID (int newID) && noexcept
  1243. {
  1244. itemID = newID;
  1245. return std::move (*this);
  1246. }
  1247. PopupMenu::Item&& PopupMenu::Item::setColour (Colour newColour) && noexcept
  1248. {
  1249. colour = newColour;
  1250. return std::move (*this);
  1251. }
  1252. PopupMenu::Item&& PopupMenu::Item::setCustomComponent (ReferenceCountedObjectPtr<CustomComponent> comp) && noexcept
  1253. {
  1254. customComponent = comp;
  1255. return std::move (*this);
  1256. }
  1257. PopupMenu::Item&& PopupMenu::Item::setImage (std::unique_ptr<Drawable> newImage) && noexcept
  1258. {
  1259. image = std::move (newImage);
  1260. return std::move (*this);
  1261. }
  1262. void PopupMenu::addItem (Item newItem)
  1263. {
  1264. // An ID of 0 is used as a return value to indicate that the user
  1265. // didn't pick anything, so you shouldn't use it as the ID for an item..
  1266. jassert (newItem.itemID != 0
  1267. || newItem.isSeparator || newItem.isSectionHeader
  1268. || newItem.subMenu != nullptr);
  1269. items.add (std::move (newItem));
  1270. }
  1271. void PopupMenu::addItem (String itemText, std::function<void()> action)
  1272. {
  1273. addItem (std::move (itemText), true, false, std::move (action));
  1274. }
  1275. void PopupMenu::addItem (String itemText, bool isActive, bool isTicked, std::function<void()> action)
  1276. {
  1277. Item i (std::move (itemText));
  1278. i.action = std::move (action);
  1279. i.isEnabled = isActive;
  1280. i.isTicked = isTicked;
  1281. addItem (std::move (i));
  1282. }
  1283. void PopupMenu::addItem (int itemResultID, String itemText, bool isActive, bool isTicked)
  1284. {
  1285. Item i (std::move (itemText));
  1286. i.itemID = itemResultID;
  1287. i.isEnabled = isActive;
  1288. i.isTicked = isTicked;
  1289. addItem (std::move (i));
  1290. }
  1291. static std::unique_ptr<Drawable> createDrawableFromImage (const Image& im)
  1292. {
  1293. if (im.isValid())
  1294. {
  1295. auto d = new DrawableImage();
  1296. d->setImage (im);
  1297. return std::unique_ptr<Drawable> (d);
  1298. }
  1299. return {};
  1300. }
  1301. void PopupMenu::addItem (int itemResultID, String itemText, bool isActive, bool isTicked, const Image& iconToUse)
  1302. {
  1303. addItem (itemResultID, std::move (itemText), isActive, isTicked, createDrawableFromImage (iconToUse));
  1304. }
  1305. void PopupMenu::addItem (int itemResultID, String itemText, bool isActive,
  1306. bool isTicked, std::unique_ptr<Drawable> iconToUse)
  1307. {
  1308. Item i (std::move (itemText));
  1309. i.itemID = itemResultID;
  1310. i.isEnabled = isActive;
  1311. i.isTicked = isTicked;
  1312. i.image = std::move (iconToUse);
  1313. addItem (std::move (i));
  1314. }
  1315. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  1316. const CommandID commandID,
  1317. String displayName,
  1318. std::unique_ptr<Drawable> iconToUse)
  1319. {
  1320. jassert (commandManager != nullptr && commandID != 0);
  1321. if (auto* registeredInfo = commandManager->getCommandForID (commandID))
  1322. {
  1323. ApplicationCommandInfo info (*registeredInfo);
  1324. auto* target = commandManager->getTargetForCommand (commandID, info);
  1325. Item i;
  1326. i.text = displayName.isNotEmpty() ? std::move (displayName) : info.shortName;
  1327. i.itemID = (int) commandID;
  1328. i.commandManager = commandManager;
  1329. i.isEnabled = target != nullptr && (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  1330. i.isTicked = (info.flags & ApplicationCommandInfo::isTicked) != 0;
  1331. i.image = std::move (iconToUse);
  1332. addItem (std::move (i));
  1333. }
  1334. }
  1335. void PopupMenu::addColouredItem (int itemResultID, String itemText, Colour itemTextColour,
  1336. bool isActive, bool isTicked, std::unique_ptr<Drawable> iconToUse)
  1337. {
  1338. Item i (std::move (itemText));
  1339. i.itemID = itemResultID;
  1340. i.colour = itemTextColour;
  1341. i.isEnabled = isActive;
  1342. i.isTicked = isTicked;
  1343. i.image = std::move (iconToUse);
  1344. addItem (std::move (i));
  1345. }
  1346. void PopupMenu::addColouredItem (int itemResultID, String itemText, Colour itemTextColour,
  1347. bool isActive, bool isTicked, const Image& iconToUse)
  1348. {
  1349. Item i (std::move (itemText));
  1350. i.itemID = itemResultID;
  1351. i.colour = itemTextColour;
  1352. i.isEnabled = isActive;
  1353. i.isTicked = isTicked;
  1354. i.image = createDrawableFromImage (iconToUse);
  1355. addItem (std::move (i));
  1356. }
  1357. void PopupMenu::addCustomItem (int itemResultID,
  1358. std::unique_ptr<CustomComponent> cc,
  1359. std::unique_ptr<const PopupMenu> subMenu)
  1360. {
  1361. Item i;
  1362. i.itemID = itemResultID;
  1363. i.customComponent = cc.release();
  1364. i.subMenu.reset (createCopyIfNotNull (subMenu.get()));
  1365. addItem (std::move (i));
  1366. }
  1367. void PopupMenu::addCustomItem (int itemResultID,
  1368. Component& customComponent,
  1369. int idealWidth, int idealHeight,
  1370. bool triggerMenuItemAutomaticallyWhenClicked,
  1371. std::unique_ptr<const PopupMenu> subMenu)
  1372. {
  1373. auto comp = std::make_unique<HelperClasses::NormalComponentWrapper> (customComponent, idealWidth, idealHeight,
  1374. triggerMenuItemAutomaticallyWhenClicked);
  1375. addCustomItem (itemResultID, std::move (comp), std::move (subMenu));
  1376. }
  1377. void PopupMenu::addSubMenu (String subMenuName, PopupMenu subMenu, bool isActive)
  1378. {
  1379. addSubMenu (std::move (subMenuName), std::move (subMenu), isActive, nullptr, false, 0);
  1380. }
  1381. void PopupMenu::addSubMenu (String subMenuName, PopupMenu subMenu, bool isActive,
  1382. const Image& iconToUse, bool isTicked, int itemResultID)
  1383. {
  1384. addSubMenu (std::move (subMenuName), std::move (subMenu), isActive,
  1385. createDrawableFromImage (iconToUse), isTicked, itemResultID);
  1386. }
  1387. void PopupMenu::addSubMenu (String subMenuName, PopupMenu subMenu, bool isActive,
  1388. std::unique_ptr<Drawable> iconToUse, bool isTicked, int itemResultID)
  1389. {
  1390. Item i (std::move (subMenuName));
  1391. i.itemID = itemResultID;
  1392. i.isEnabled = isActive && (itemResultID != 0 || subMenu.getNumItems() > 0);
  1393. i.subMenu.reset (new PopupMenu (std::move (subMenu)));
  1394. i.isTicked = isTicked;
  1395. i.image = std::move (iconToUse);
  1396. addItem (std::move (i));
  1397. }
  1398. void PopupMenu::addSeparator()
  1399. {
  1400. if (items.size() > 0 && ! items.getLast().isSeparator)
  1401. {
  1402. Item i;
  1403. i.isSeparator = true;
  1404. addItem (std::move (i));
  1405. }
  1406. }
  1407. void PopupMenu::addSectionHeader (String title)
  1408. {
  1409. Item i (std::move (title));
  1410. i.itemID = 0;
  1411. i.isSectionHeader = true;
  1412. addItem (std::move (i));
  1413. }
  1414. void PopupMenu::addColumnBreak()
  1415. {
  1416. if (! items.isEmpty())
  1417. std::prev (items.end())->shouldBreakAfter = true;
  1418. }
  1419. //==============================================================================
  1420. PopupMenu::Options::Options()
  1421. {
  1422. targetArea.setPosition (Desktop::getMousePosition());
  1423. }
  1424. PopupMenu::Options PopupMenu::Options::withTargetComponent (Component* comp) const
  1425. {
  1426. Options o (*this);
  1427. o.targetComponent = comp;
  1428. if (comp != nullptr)
  1429. o.targetArea = comp->getScreenBounds();
  1430. return o;
  1431. }
  1432. PopupMenu::Options PopupMenu::Options::withTargetComponent (Component& comp) const
  1433. {
  1434. return withTargetComponent (&comp);
  1435. }
  1436. PopupMenu::Options PopupMenu::Options::withTargetScreenArea (Rectangle<int> area) const
  1437. {
  1438. Options o (*this);
  1439. o.targetArea = area;
  1440. return o;
  1441. }
  1442. PopupMenu::Options PopupMenu::Options::withDeletionCheck (Component& comp) const
  1443. {
  1444. Options o (*this);
  1445. o.componentToWatchForDeletion = &comp;
  1446. o.isWatchingForDeletion = true;
  1447. return o;
  1448. }
  1449. PopupMenu::Options PopupMenu::Options::withMinimumWidth (int w) const
  1450. {
  1451. Options o (*this);
  1452. o.minWidth = w;
  1453. return o;
  1454. }
  1455. PopupMenu::Options PopupMenu::Options::withMinimumNumColumns (int cols) const
  1456. {
  1457. Options o (*this);
  1458. o.minColumns = cols;
  1459. return o;
  1460. }
  1461. PopupMenu::Options PopupMenu::Options::withMaximumNumColumns (int cols) const
  1462. {
  1463. Options o (*this);
  1464. o.maxColumns = cols;
  1465. return o;
  1466. }
  1467. PopupMenu::Options PopupMenu::Options::withStandardItemHeight (int height) const
  1468. {
  1469. Options o (*this);
  1470. o.standardHeight = height;
  1471. return o;
  1472. }
  1473. PopupMenu::Options PopupMenu::Options::withItemThatMustBeVisible (int idOfItemToBeVisible) const
  1474. {
  1475. Options o (*this);
  1476. o.visibleItemID = idOfItemToBeVisible;
  1477. return o;
  1478. }
  1479. PopupMenu::Options PopupMenu::Options::withParentComponent (Component* parent) const
  1480. {
  1481. Options o (*this);
  1482. o.parentComponent = parent;
  1483. return o;
  1484. }
  1485. PopupMenu::Options PopupMenu::Options::withPreferredPopupDirection (PopupDirection direction) const
  1486. {
  1487. Options o (*this);
  1488. o.preferredPopupDirection = direction;
  1489. return o;
  1490. }
  1491. Component* PopupMenu::createWindow (const Options& options,
  1492. ApplicationCommandManager** managerOfChosenCommand) const
  1493. {
  1494. return items.isEmpty() ? nullptr
  1495. : new HelperClasses::MenuWindow (*this, nullptr, options,
  1496. ! options.getTargetScreenArea().isEmpty(),
  1497. ModifierKeys::currentModifiers.isAnyMouseButtonDown(),
  1498. managerOfChosenCommand);
  1499. }
  1500. //==============================================================================
  1501. // This invokes any command manager commands and deletes the menu window when it is dismissed
  1502. struct PopupMenuCompletionCallback : public ModalComponentManager::Callback
  1503. {
  1504. PopupMenuCompletionCallback() = default;
  1505. void modalStateFinished (int result) override
  1506. {
  1507. if (managerOfChosenCommand != nullptr && result != 0)
  1508. {
  1509. ApplicationCommandTarget::InvocationInfo info (result);
  1510. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  1511. managerOfChosenCommand->invoke (info, true);
  1512. }
  1513. // (this would be the place to fade out the component, if that's what's required)
  1514. component.reset();
  1515. if (PopupMenuSettings::menuWasHiddenBecauseOfAppChange)
  1516. return;
  1517. auto* focusComponent = getComponentToPassFocusTo();
  1518. const auto focusedIsNotMinimised = [focusComponent]
  1519. {
  1520. if (focusComponent != nullptr)
  1521. if (auto* peer = focusComponent->getPeer())
  1522. return ! peer->isMinimised();
  1523. return false;
  1524. }();
  1525. if (focusedIsNotMinimised)
  1526. {
  1527. if (auto* topLevel = focusComponent->getTopLevelComponent())
  1528. topLevel->toFront (true);
  1529. if (focusComponent->isShowing() && ! focusComponent->hasKeyboardFocus (true))
  1530. focusComponent->grabKeyboardFocus();
  1531. }
  1532. }
  1533. Component* getComponentToPassFocusTo() const
  1534. {
  1535. if (auto* current = Component::getCurrentlyFocusedComponent())
  1536. return current;
  1537. return prevFocused.get();
  1538. }
  1539. ApplicationCommandManager* managerOfChosenCommand = nullptr;
  1540. std::unique_ptr<Component> component;
  1541. WeakReference<Component> prevFocused { Component::getCurrentlyFocusedComponent() };
  1542. JUCE_DECLARE_NON_COPYABLE (PopupMenuCompletionCallback)
  1543. };
  1544. int PopupMenu::showWithOptionalCallback (const Options& options,
  1545. ModalComponentManager::Callback* userCallback,
  1546. bool canBeModal)
  1547. {
  1548. std::unique_ptr<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  1549. std::unique_ptr<PopupMenuCompletionCallback> callback (new PopupMenuCompletionCallback());
  1550. if (auto* window = createWindow (options, &(callback->managerOfChosenCommand)))
  1551. {
  1552. callback->component.reset (window);
  1553. PopupMenuSettings::menuWasHiddenBecauseOfAppChange = false;
  1554. window->setVisible (true); // (must be called before enterModalState on Windows to avoid DropShadower confusion)
  1555. window->enterModalState (false, userCallbackDeleter.release());
  1556. ModalComponentManager::getInstance()->attachCallback (window, callback.release());
  1557. window->toFront (false); // need to do this after making it modal, or it could
  1558. // be stuck behind other comps that are already modal..
  1559. #if JUCE_MODAL_LOOPS_PERMITTED
  1560. if (userCallback == nullptr && canBeModal)
  1561. return window->runModalLoop();
  1562. #else
  1563. ignoreUnused (canBeModal);
  1564. jassert (! (userCallback == nullptr && canBeModal));
  1565. #endif
  1566. }
  1567. return 0;
  1568. }
  1569. //==============================================================================
  1570. #if JUCE_MODAL_LOOPS_PERMITTED
  1571. int PopupMenu::showMenu (const Options& options)
  1572. {
  1573. return showWithOptionalCallback (options, nullptr, true);
  1574. }
  1575. #endif
  1576. void PopupMenu::showMenuAsync (const Options& options)
  1577. {
  1578. showWithOptionalCallback (options, nullptr, false);
  1579. }
  1580. void PopupMenu::showMenuAsync (const Options& options, ModalComponentManager::Callback* userCallback)
  1581. {
  1582. #if ! JUCE_MODAL_LOOPS_PERMITTED
  1583. jassert (userCallback != nullptr);
  1584. #endif
  1585. showWithOptionalCallback (options, userCallback, false);
  1586. }
  1587. void PopupMenu::showMenuAsync (const Options& options, std::function<void (int)> userCallback)
  1588. {
  1589. showWithOptionalCallback (options, ModalCallbackFunction::create (userCallback), false);
  1590. }
  1591. //==============================================================================
  1592. #if JUCE_MODAL_LOOPS_PERMITTED
  1593. int PopupMenu::show (int itemIDThatMustBeVisible, int minimumWidth,
  1594. int maximumNumColumns, int standardItemHeight,
  1595. ModalComponentManager::Callback* callback)
  1596. {
  1597. return showWithOptionalCallback (Options().withItemThatMustBeVisible (itemIDThatMustBeVisible)
  1598. .withMinimumWidth (minimumWidth)
  1599. .withMaximumNumColumns (maximumNumColumns)
  1600. .withStandardItemHeight (standardItemHeight),
  1601. callback, true);
  1602. }
  1603. int PopupMenu::showAt (Rectangle<int> screenAreaToAttachTo,
  1604. int itemIDThatMustBeVisible, int minimumWidth,
  1605. int maximumNumColumns, int standardItemHeight,
  1606. ModalComponentManager::Callback* callback)
  1607. {
  1608. return showWithOptionalCallback (Options().withTargetScreenArea (screenAreaToAttachTo)
  1609. .withItemThatMustBeVisible (itemIDThatMustBeVisible)
  1610. .withMinimumWidth (minimumWidth)
  1611. .withMaximumNumColumns (maximumNumColumns)
  1612. .withStandardItemHeight (standardItemHeight),
  1613. callback, true);
  1614. }
  1615. int PopupMenu::showAt (Component* componentToAttachTo,
  1616. int itemIDThatMustBeVisible, int minimumWidth,
  1617. int maximumNumColumns, int standardItemHeight,
  1618. ModalComponentManager::Callback* callback)
  1619. {
  1620. auto options = Options().withItemThatMustBeVisible (itemIDThatMustBeVisible)
  1621. .withMinimumWidth (minimumWidth)
  1622. .withMaximumNumColumns (maximumNumColumns)
  1623. .withStandardItemHeight (standardItemHeight);
  1624. if (componentToAttachTo != nullptr)
  1625. options = options.withTargetComponent (componentToAttachTo);
  1626. return showWithOptionalCallback (options, callback, true);
  1627. }
  1628. #endif
  1629. bool JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  1630. {
  1631. auto& windows = HelperClasses::MenuWindow::getActiveWindows();
  1632. auto numWindows = windows.size();
  1633. for (int i = numWindows; --i >= 0;)
  1634. {
  1635. if (auto* pmw = windows[i])
  1636. {
  1637. pmw->setLookAndFeel (nullptr);
  1638. pmw->dismissMenu (nullptr);
  1639. }
  1640. }
  1641. return numWindows > 0;
  1642. }
  1643. //==============================================================================
  1644. int PopupMenu::getNumItems() const noexcept
  1645. {
  1646. int num = 0;
  1647. for (auto& mi : items)
  1648. if (! mi.isSeparator)
  1649. ++num;
  1650. return num;
  1651. }
  1652. bool PopupMenu::containsCommandItem (const int commandID) const
  1653. {
  1654. for (auto& mi : items)
  1655. if ((mi.itemID == commandID && mi.commandManager != nullptr)
  1656. || (mi.subMenu != nullptr && mi.subMenu->containsCommandItem (commandID)))
  1657. return true;
  1658. return false;
  1659. }
  1660. bool PopupMenu::containsAnyActiveItems() const noexcept
  1661. {
  1662. for (auto& mi : items)
  1663. {
  1664. if (mi.subMenu != nullptr)
  1665. {
  1666. if (mi.subMenu->containsAnyActiveItems())
  1667. return true;
  1668. }
  1669. else if (mi.isEnabled)
  1670. {
  1671. return true;
  1672. }
  1673. }
  1674. return false;
  1675. }
  1676. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  1677. {
  1678. lookAndFeel = newLookAndFeel;
  1679. }
  1680. void PopupMenu::setItem (CustomComponent& c, const Item* itemToUse)
  1681. {
  1682. c.item = itemToUse;
  1683. c.repaint();
  1684. }
  1685. //==============================================================================
  1686. PopupMenu::CustomComponent::CustomComponent (bool autoTrigger)
  1687. : triggeredAutomatically (autoTrigger)
  1688. {
  1689. }
  1690. PopupMenu::CustomComponent::~CustomComponent()
  1691. {
  1692. }
  1693. void PopupMenu::CustomComponent::setHighlighted (bool shouldBeHighlighted)
  1694. {
  1695. isHighlighted = shouldBeHighlighted;
  1696. repaint();
  1697. }
  1698. void PopupMenu::CustomComponent::triggerMenuItem()
  1699. {
  1700. if (auto* mic = findParentComponentOfClass<HelperClasses::ItemComponent>())
  1701. {
  1702. if (auto* pmw = mic->findParentComponentOfClass<HelperClasses::MenuWindow>())
  1703. {
  1704. pmw->dismissMenu (&mic->item);
  1705. }
  1706. else
  1707. {
  1708. // something must have gone wrong with the component hierarchy if this happens..
  1709. jassertfalse;
  1710. }
  1711. }
  1712. else
  1713. {
  1714. // why isn't this component inside a menu? Not much point triggering the item if
  1715. // there's no menu.
  1716. jassertfalse;
  1717. }
  1718. }
  1719. //==============================================================================
  1720. PopupMenu::CustomCallback::CustomCallback() {}
  1721. PopupMenu::CustomCallback::~CustomCallback() {}
  1722. //==============================================================================
  1723. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& m, bool recurse) : searchRecursively (recurse)
  1724. {
  1725. index.add (0);
  1726. menus.add (&m);
  1727. }
  1728. PopupMenu::MenuItemIterator::~MenuItemIterator() = default;
  1729. bool PopupMenu::MenuItemIterator::next()
  1730. {
  1731. if (index.size() == 0 || menus.getLast()->items.size() == 0)
  1732. return false;
  1733. currentItem = const_cast<PopupMenu::Item*> (&(menus.getLast()->items.getReference (index.getLast())));
  1734. if (searchRecursively && currentItem->subMenu != nullptr)
  1735. {
  1736. index.add (0);
  1737. menus.add (currentItem->subMenu.get());
  1738. }
  1739. else
  1740. {
  1741. index.setUnchecked (index.size() - 1, index.getLast() + 1);
  1742. }
  1743. while (index.size() > 0 && index.getLast() >= (int) menus.getLast()->items.size())
  1744. {
  1745. index.removeLast();
  1746. menus.removeLast();
  1747. if (index.size() > 0)
  1748. index.setUnchecked (index.size() - 1, index.getLast() + 1);
  1749. }
  1750. return true;
  1751. }
  1752. PopupMenu::Item& PopupMenu::MenuItemIterator::getItem() const
  1753. {
  1754. jassert (currentItem != nullptr);
  1755. return *(currentItem);
  1756. }
  1757. void PopupMenu::LookAndFeelMethods::drawPopupMenuBackground (Graphics&, int, int) {}
  1758. void PopupMenu::LookAndFeelMethods::drawPopupMenuItem (Graphics&, const Rectangle<int>&,
  1759. bool, bool, bool,
  1760. bool, bool,
  1761. const String&,
  1762. const String&,
  1763. const Drawable*,
  1764. const Colour*) {}
  1765. void PopupMenu::LookAndFeelMethods::drawPopupMenuSectionHeader (Graphics&, const Rectangle<int>&,
  1766. const String&) {}
  1767. void PopupMenu::LookAndFeelMethods::drawPopupMenuUpDownArrow (Graphics&, int, int, bool) {}
  1768. void PopupMenu::LookAndFeelMethods::getIdealPopupMenuItemSize (const String&, bool, int, int&, int&) {}
  1769. int PopupMenu::LookAndFeelMethods::getPopupMenuBorderSize() { return 0; }
  1770. } // namespace juce