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.

2319 lines
80KB

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