Audio plugin host https://kx.studio/carla
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.

2372 lines
82KB

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