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.

2393 lines
83KB

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