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.

2326 lines
81KB

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