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.

2382 lines
83KB

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