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.

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