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.

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