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