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.

2184 lines
75KB

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