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.

2357 lines
82KB

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