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.

2315 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. const auto border = getLookAndFeel().getPopupMenuBorderSizeWithOptions (options);
  694. y = target.getCentreY() > parentArea.getCentreY() ? jmax (parentArea.getY(), target.getBottom() - heightToUse) + border
  695. : target.getY() - border;
  696. }
  697. x = jmax (parentArea.getX() + 1, jmin (parentArea.getRight() - (widthToUse + 6), x));
  698. y = jmax (parentArea.getY() + 1, jmin (parentArea.getBottom() - (heightToUse + 6), y));
  699. windowPos.setBounds (x, y, widthToUse, heightToUse);
  700. // sets this flag if it's big enough to obscure any of its parent menus
  701. hideOnExit = parent != nullptr
  702. && parent->windowPos.intersects (windowPos.expanded (-4, -4));
  703. }
  704. void layoutMenuItems (const int maxMenuW, const int maxMenuH, int& width, int& height)
  705. {
  706. // Ensure we don't try to add an empty column after the final item
  707. if (auto* last = items.getLast())
  708. last->item.shouldBreakAfter = false;
  709. const auto isBreak = [] (const ItemComponent* item) { return item->item.shouldBreakAfter; };
  710. const auto numBreaks = static_cast<int> (std::count_if (items.begin(), items.end(), isBreak));
  711. numColumns = numBreaks + 1;
  712. if (numBreaks == 0)
  713. insertColumnBreaks (maxMenuW, maxMenuH);
  714. workOutManualSize (maxMenuW);
  715. height = jmin (contentHeight, maxMenuH);
  716. needsToScroll = contentHeight > height;
  717. width = updateYPositions();
  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. contentHeight += getLookAndFeel().getPopupMenuBorderSizeWithOptions (options) * 2;
  782. correctColumnWidths (maxMenuW);
  783. }
  784. int workOutBestSize (const int maxMenuW)
  785. {
  786. contentHeight = 0;
  787. int childNum = 0;
  788. for (int col = 0; col < numColumns; ++col)
  789. {
  790. int colW = options.getStandardItemHeight(), colH = 0;
  791. auto numChildren = jmin (items.size() - childNum,
  792. (items.size() + numColumns - 1) / numColumns);
  793. for (int i = numChildren; --i >= 0;)
  794. {
  795. colW = jmax (colW, items.getUnchecked (childNum + i)->getWidth());
  796. colH += items.getUnchecked (childNum + i)->getHeight();
  797. }
  798. colW = jmin (maxMenuW / jmax (1, numColumns - 2),
  799. colW + getLookAndFeel().getPopupMenuBorderSizeWithOptions (options) * 2);
  800. columnWidths.set (col, colW);
  801. contentHeight = jmax (contentHeight, colH);
  802. childNum += numChildren;
  803. }
  804. return correctColumnWidths (maxMenuW);
  805. }
  806. void ensureItemComponentIsVisible (const ItemComponent& itemComp, int wantedY)
  807. {
  808. if (windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  809. {
  810. auto currentY = itemComp.getY();
  811. if (wantedY > 0 || currentY < 0 || itemComp.getBottom() > windowPos.getHeight())
  812. {
  813. if (wantedY < 0)
  814. wantedY = jlimit (PopupMenuSettings::scrollZone,
  815. jmax (PopupMenuSettings::scrollZone,
  816. windowPos.getHeight() - (PopupMenuSettings::scrollZone + itemComp.getHeight())),
  817. currentY);
  818. auto parentArea = getParentArea (windowPos.getPosition(), parentComponent) / scaleFactor;
  819. auto deltaY = wantedY - currentY;
  820. windowPos.setSize (jmin (windowPos.getWidth(), parentArea.getWidth()),
  821. jmin (windowPos.getHeight(), parentArea.getHeight()));
  822. auto newY = jlimit (parentArea.getY(),
  823. parentArea.getBottom() - windowPos.getHeight(),
  824. windowPos.getY() + deltaY);
  825. deltaY -= newY - windowPos.getY();
  826. childYOffset -= deltaY;
  827. windowPos.setPosition (windowPos.getX(), newY);
  828. updateYPositions();
  829. }
  830. }
  831. }
  832. void resizeToBestWindowPos()
  833. {
  834. auto r = windowPos;
  835. if (childYOffset < 0)
  836. {
  837. r = r.withTop (r.getY() - childYOffset);
  838. }
  839. else if (childYOffset > 0)
  840. {
  841. auto spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  842. if (spaceAtBottom > 0)
  843. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  844. }
  845. setBounds (r);
  846. updateYPositions();
  847. }
  848. void alterChildYPos (int delta)
  849. {
  850. if (canScroll())
  851. {
  852. childYOffset += delta;
  853. childYOffset = [&]
  854. {
  855. if (delta < 0)
  856. return jmax (childYOffset, 0);
  857. if (delta > 0)
  858. {
  859. const auto limit = contentHeight
  860. - windowPos.getHeight()
  861. + getLookAndFeel().getPopupMenuBorderSizeWithOptions (options);
  862. return jmin (childYOffset, limit);
  863. }
  864. return childYOffset;
  865. }();
  866. updateYPositions();
  867. }
  868. else
  869. {
  870. childYOffset = 0;
  871. }
  872. resizeToBestWindowPos();
  873. repaint();
  874. }
  875. int updateYPositions()
  876. {
  877. const auto separatorWidth = getLookAndFeel().getPopupMenuColumnSeparatorWidthWithOptions (options);
  878. const auto initialY = getLookAndFeel().getPopupMenuBorderSizeWithOptions (options)
  879. - (childYOffset + (getY() - windowPos.getY()));
  880. auto col = 0;
  881. auto x = 0;
  882. auto y = initialY;
  883. for (const auto& item : items)
  884. {
  885. jassert (col < columnWidths.size());
  886. const auto columnWidth = columnWidths[col];
  887. item->setBounds (x, y, columnWidth, item->getHeight());
  888. y += item->getHeight();
  889. if (item->item.shouldBreakAfter)
  890. {
  891. col += 1;
  892. x += columnWidth + separatorWidth;
  893. y = initialY;
  894. }
  895. }
  896. return std::accumulate (columnWidths.begin(), columnWidths.end(), 0)
  897. + (separatorWidth * (columnWidths.size() - 1));
  898. }
  899. void setCurrentlyHighlightedChild (ItemComponent* child)
  900. {
  901. if (currentChild != nullptr)
  902. currentChild->setHighlighted (false);
  903. currentChild = child;
  904. if (currentChild != nullptr)
  905. {
  906. currentChild->setHighlighted (true);
  907. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  908. }
  909. if (auto* handler = getAccessibilityHandler())
  910. handler->notifyAccessibilityEvent (AccessibilityEvent::rowSelectionChanged);
  911. }
  912. bool isSubMenuVisible() const noexcept { return activeSubMenu != nullptr && activeSubMenu->isVisible(); }
  913. bool showSubMenuFor (ItemComponent* childComp)
  914. {
  915. activeSubMenu.reset();
  916. if (childComp != nullptr
  917. && hasActiveSubMenu (childComp->item))
  918. {
  919. activeSubMenu.reset (new HelperClasses::MenuWindow (*(childComp->item.subMenu), this,
  920. options.withTargetScreenArea (childComp->getScreenBounds())
  921. .withMinimumWidth (0)
  922. .withTargetComponent (nullptr)
  923. .withParentComponent (parentComponent),
  924. false, dismissOnMouseUp, managerOfChosenCommand, scaleFactor));
  925. activeSubMenu->setVisible (true); // (must be called before enterModalState on Windows to avoid DropShadower confusion)
  926. activeSubMenu->enterModalState (false);
  927. activeSubMenu->toFront (false);
  928. return true;
  929. }
  930. return false;
  931. }
  932. void triggerCurrentlyHighlightedItem()
  933. {
  934. if (currentChild != nullptr
  935. && canBeTriggered (currentChild->item)
  936. && (currentChild->item.customComponent == nullptr
  937. || currentChild->item.customComponent->isTriggeredAutomatically()))
  938. {
  939. dismissMenu (&currentChild->item);
  940. }
  941. }
  942. enum class MenuSelectionDirection
  943. {
  944. forwards,
  945. backwards,
  946. current
  947. };
  948. void selectNextItem (MenuSelectionDirection direction)
  949. {
  950. disableTimerUntilMouseMoves();
  951. auto start = [&]
  952. {
  953. auto index = items.indexOf (currentChild);
  954. if (index >= 0)
  955. return index;
  956. return direction == MenuSelectionDirection::backwards ? items.size() - 1
  957. : 0;
  958. }();
  959. auto preIncrement = (direction != MenuSelectionDirection::current && currentChild != nullptr);
  960. for (int i = items.size(); --i >= 0;)
  961. {
  962. if (preIncrement)
  963. start += (direction == MenuSelectionDirection::backwards ? -1 : 1);
  964. if (auto* mic = items.getUnchecked ((start + items.size()) % items.size()))
  965. {
  966. if (canBeTriggered (mic->item) || hasActiveSubMenu (mic->item))
  967. {
  968. setCurrentlyHighlightedChild (mic);
  969. return;
  970. }
  971. }
  972. if (! preIncrement)
  973. preIncrement = true;
  974. }
  975. }
  976. void disableTimerUntilMouseMoves()
  977. {
  978. disableMouseMoves = true;
  979. if (parent != nullptr)
  980. parent->disableTimerUntilMouseMoves();
  981. }
  982. bool canScroll() const noexcept { return childYOffset != 0 || needsToScroll; }
  983. bool isTopScrollZoneActive() const noexcept { return canScroll() && childYOffset > 0; }
  984. bool isBottomScrollZoneActive() const noexcept { return canScroll() && childYOffset < contentHeight - windowPos.getHeight(); }
  985. //==============================================================================
  986. std::unique_ptr<AccessibilityHandler> createAccessibilityHandler() override
  987. {
  988. return std::make_unique<AccessibilityHandler> (*this,
  989. AccessibilityRole::popupMenu,
  990. AccessibilityActions().addAction (AccessibilityActionType::focus, [this]
  991. {
  992. if (currentChild != nullptr)
  993. {
  994. if (auto* handler = currentChild->getAccessibilityHandler())
  995. handler->grabFocus();
  996. }
  997. else
  998. {
  999. selectNextItem (MenuSelectionDirection::forwards);
  1000. }
  1001. }));
  1002. }
  1003. //==============================================================================
  1004. MenuWindow* parent;
  1005. const Options options;
  1006. OwnedArray<ItemComponent> items;
  1007. ApplicationCommandManager** managerOfChosenCommand;
  1008. WeakReference<Component> componentAttachedTo;
  1009. Component* parentComponent = nullptr;
  1010. Rectangle<int> windowPos;
  1011. bool hasBeenOver = false, needsToScroll = false;
  1012. bool dismissOnMouseUp, hideOnExit = false, disableMouseMoves = false, hasAnyJuceCompHadFocus = false;
  1013. int numColumns = 0, contentHeight = 0, childYOffset = 0;
  1014. Component::SafePointer<ItemComponent> currentChild;
  1015. std::unique_ptr<MenuWindow> activeSubMenu;
  1016. Array<int> columnWidths;
  1017. uint32 windowCreationTime, lastFocusedTime, timeEnteredCurrentChildComp;
  1018. OwnedArray<MouseSourceState> mouseSourceStates;
  1019. float scaleFactor;
  1020. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuWindow)
  1021. };
  1022. //==============================================================================
  1023. class MouseSourceState : public Timer
  1024. {
  1025. public:
  1026. MouseSourceState (MenuWindow& w, MouseInputSource s)
  1027. : window (w), source (s), lastScrollTime (Time::getMillisecondCounter())
  1028. {
  1029. startTimerHz (20);
  1030. }
  1031. void handleMouseEvent (const MouseEvent& e)
  1032. {
  1033. if (! window.windowIsStillValid())
  1034. return;
  1035. startTimerHz (20);
  1036. handleMousePosition (e.getScreenPosition());
  1037. }
  1038. void timerCallback() override
  1039. {
  1040. #if JUCE_WINDOWS
  1041. // touch and pen devices on Windows send an offscreen mouse move after mouse up events
  1042. // but we don't want to forward these on as they will dismiss the menu
  1043. if ((source.isTouch() || source.isPen()) && ! isValidMousePosition())
  1044. return;
  1045. #endif
  1046. if (window.windowIsStillValid())
  1047. handleMousePosition (source.getScreenPosition().roundToInt());
  1048. }
  1049. bool isOver() const
  1050. {
  1051. return window.reallyContains (window.getLocalPoint (nullptr, source.getScreenPosition()).roundToInt(), true);
  1052. }
  1053. MenuWindow& window;
  1054. MouseInputSource source;
  1055. private:
  1056. Point<int> lastMousePos;
  1057. double scrollAcceleration = 0;
  1058. uint32 lastScrollTime, lastMouseMoveTime = 0;
  1059. bool isDown = false;
  1060. void handleMousePosition (Point<int> globalMousePos)
  1061. {
  1062. auto localMousePos = window.getLocalPoint (nullptr, globalMousePos);
  1063. auto timeNow = Time::getMillisecondCounter();
  1064. if (timeNow > window.timeEnteredCurrentChildComp + 100
  1065. && window.reallyContains (localMousePos, true)
  1066. && window.currentChild != nullptr
  1067. && ! (window.disableMouseMoves || window.isSubMenuVisible()))
  1068. {
  1069. window.showSubMenuFor (window.currentChild);
  1070. }
  1071. highlightItemUnderMouse (globalMousePos, localMousePos, timeNow);
  1072. const bool overScrollArea = scrollIfNecessary (localMousePos, timeNow);
  1073. const bool isOverAny = window.isOverAnyMenu();
  1074. if (window.hideOnExit && window.hasBeenOver && ! isOverAny)
  1075. window.hide (nullptr, true);
  1076. else
  1077. checkButtonState (localMousePos, timeNow, isDown, overScrollArea, isOverAny);
  1078. }
  1079. void checkButtonState (Point<int> localMousePos, const uint32 timeNow,
  1080. const bool wasDown, const bool overScrollArea, const bool isOverAny)
  1081. {
  1082. isDown = window.hasBeenOver
  1083. && (ModifierKeys::currentModifiers.isAnyMouseButtonDown()
  1084. || ComponentPeer::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  1085. if (! window.doesAnyJuceCompHaveFocus())
  1086. {
  1087. if (timeNow > window.lastFocusedTime + 10)
  1088. {
  1089. PopupMenuSettings::menuWasHiddenBecauseOfAppChange = true;
  1090. window.dismissMenu (nullptr);
  1091. // Note: This object may have been deleted by the previous call.
  1092. }
  1093. }
  1094. else if (wasDown && timeNow > window.windowCreationTime + 250
  1095. && ! (isDown || overScrollArea))
  1096. {
  1097. if (window.reallyContains (localMousePos, true))
  1098. window.triggerCurrentlyHighlightedItem();
  1099. else if ((window.hasBeenOver || ! window.dismissOnMouseUp) && ! isOverAny)
  1100. window.dismissMenu (nullptr);
  1101. // Note: This object may have been deleted by the previous call.
  1102. }
  1103. else
  1104. {
  1105. window.lastFocusedTime = timeNow;
  1106. }
  1107. }
  1108. void highlightItemUnderMouse (Point<int> globalMousePos, Point<int> localMousePos, const uint32 timeNow)
  1109. {
  1110. if (globalMousePos != lastMousePos || timeNow > lastMouseMoveTime + 350)
  1111. {
  1112. const auto isMouseOver = window.reallyContains (localMousePos, true);
  1113. if (isMouseOver)
  1114. window.hasBeenOver = true;
  1115. if (lastMousePos.getDistanceFrom (globalMousePos) > 2)
  1116. {
  1117. lastMouseMoveTime = timeNow;
  1118. if (window.disableMouseMoves && isMouseOver)
  1119. window.disableMouseMoves = false;
  1120. }
  1121. if (window.disableMouseMoves || (window.activeSubMenu != nullptr && window.activeSubMenu->isOverChildren()))
  1122. return;
  1123. const bool isMovingTowardsMenu = isMouseOver && globalMousePos != lastMousePos
  1124. && isMovingTowardsSubmenu (globalMousePos);
  1125. lastMousePos = globalMousePos;
  1126. if (! isMovingTowardsMenu)
  1127. {
  1128. auto* c = window.getComponentAt (localMousePos);
  1129. if (c == &window)
  1130. c = nullptr;
  1131. auto* itemUnderMouse = dynamic_cast<ItemComponent*> (c);
  1132. if (itemUnderMouse == nullptr && c != nullptr)
  1133. itemUnderMouse = c->findParentComponentOfClass<ItemComponent>();
  1134. if (itemUnderMouse != window.currentChild
  1135. && (isMouseOver || (window.activeSubMenu == nullptr) || ! window.activeSubMenu->isVisible()))
  1136. {
  1137. if (isMouseOver && (c != nullptr) && (window.activeSubMenu != nullptr))
  1138. window.activeSubMenu->hide (nullptr, true);
  1139. if (! isMouseOver)
  1140. {
  1141. if (! window.hasBeenOver)
  1142. return;
  1143. itemUnderMouse = nullptr;
  1144. }
  1145. window.setCurrentlyHighlightedChild (itemUnderMouse);
  1146. }
  1147. }
  1148. }
  1149. }
  1150. bool isMovingTowardsSubmenu (Point<int> newGlobalPos) const
  1151. {
  1152. if (window.activeSubMenu == nullptr)
  1153. return false;
  1154. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  1155. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  1156. // extends from the last mouse pos to the submenu's rectangle..
  1157. auto itemScreenBounds = window.activeSubMenu->getScreenBounds();
  1158. auto subX = (float) itemScreenBounds.getX();
  1159. auto oldGlobalPos = lastMousePos;
  1160. if (itemScreenBounds.getX() > window.getX())
  1161. {
  1162. oldGlobalPos -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  1163. }
  1164. else
  1165. {
  1166. oldGlobalPos += Point<int> (2, 0);
  1167. subX += (float) itemScreenBounds.getWidth();
  1168. }
  1169. Path areaTowardsSubMenu;
  1170. areaTowardsSubMenu.addTriangle ((float) oldGlobalPos.x, (float) oldGlobalPos.y,
  1171. subX, (float) itemScreenBounds.getY(),
  1172. subX, (float) itemScreenBounds.getBottom());
  1173. return areaTowardsSubMenu.contains (newGlobalPos.toFloat());
  1174. }
  1175. bool scrollIfNecessary (Point<int> localMousePos, const uint32 timeNow)
  1176. {
  1177. if (window.canScroll()
  1178. && isPositiveAndBelow (localMousePos.x, window.getWidth())
  1179. && (isPositiveAndBelow (localMousePos.y, window.getHeight()) || source.isDragging()))
  1180. {
  1181. if (window.isTopScrollZoneActive() && localMousePos.y < PopupMenuSettings::scrollZone)
  1182. return scroll (timeNow, -1);
  1183. if (window.isBottomScrollZoneActive() && localMousePos.y > window.getHeight() - PopupMenuSettings::scrollZone)
  1184. return scroll (timeNow, 1);
  1185. }
  1186. scrollAcceleration = 1.0;
  1187. return false;
  1188. }
  1189. bool scroll (const uint32 timeNow, const int direction)
  1190. {
  1191. if (timeNow > lastScrollTime + 20)
  1192. {
  1193. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  1194. int amount = 0;
  1195. for (int i = 0; i < window.items.size() && amount == 0; ++i)
  1196. amount = ((int) scrollAcceleration) * window.items.getUnchecked (i)->getHeight();
  1197. window.alterChildYPos (amount * direction);
  1198. lastScrollTime = timeNow;
  1199. }
  1200. return true;
  1201. }
  1202. #if JUCE_WINDOWS
  1203. bool isValidMousePosition()
  1204. {
  1205. auto screenPos = source.getScreenPosition();
  1206. auto localPos = (window.activeSubMenu == nullptr) ? window.getLocalPoint (nullptr, screenPos)
  1207. : window.activeSubMenu->getLocalPoint (nullptr, screenPos);
  1208. if (localPos.x < 0 && localPos.y < 0)
  1209. return false;
  1210. return true;
  1211. }
  1212. #endif
  1213. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MouseSourceState)
  1214. };
  1215. //==============================================================================
  1216. struct NormalComponentWrapper : public PopupMenu::CustomComponent
  1217. {
  1218. NormalComponentWrapper (Component& comp, int w, int h, bool triggerMenuItemAutomaticallyWhenClicked)
  1219. : PopupMenu::CustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  1220. width (w), height (h)
  1221. {
  1222. addAndMakeVisible (comp);
  1223. }
  1224. void getIdealSize (int& idealWidth, int& idealHeight) override
  1225. {
  1226. idealWidth = width;
  1227. idealHeight = height;
  1228. }
  1229. void resized() override
  1230. {
  1231. if (auto* child = getChildComponent (0))
  1232. child->setBounds (getLocalBounds());
  1233. }
  1234. const int width, height;
  1235. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NormalComponentWrapper)
  1236. };
  1237. };
  1238. //==============================================================================
  1239. PopupMenu::PopupMenu (const PopupMenu& other)
  1240. : items (other.items),
  1241. lookAndFeel (other.lookAndFeel)
  1242. {
  1243. }
  1244. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  1245. {
  1246. if (this != &other)
  1247. {
  1248. items = other.items;
  1249. lookAndFeel = other.lookAndFeel;
  1250. }
  1251. return *this;
  1252. }
  1253. PopupMenu::PopupMenu (PopupMenu&& other) noexcept
  1254. : items (std::move (other.items)),
  1255. lookAndFeel (std::move (other.lookAndFeel))
  1256. {
  1257. }
  1258. PopupMenu& PopupMenu::operator= (PopupMenu&& other) noexcept
  1259. {
  1260. items = std::move (other.items);
  1261. lookAndFeel = other.lookAndFeel;
  1262. return *this;
  1263. }
  1264. PopupMenu::~PopupMenu() = default;
  1265. void PopupMenu::clear()
  1266. {
  1267. items.clear();
  1268. }
  1269. //==============================================================================
  1270. PopupMenu::Item::Item() = default;
  1271. PopupMenu::Item::Item (String t) : text (std::move (t)), itemID (-1) {}
  1272. PopupMenu::Item::Item (Item&&) = default;
  1273. PopupMenu::Item& PopupMenu::Item::operator= (Item&&) = default;
  1274. PopupMenu::Item::Item (const Item& other)
  1275. : text (other.text),
  1276. itemID (other.itemID),
  1277. action (other.action),
  1278. subMenu (createCopyIfNotNull (other.subMenu.get())),
  1279. image (other.image != nullptr ? other.image->createCopy() : nullptr),
  1280. customComponent (other.customComponent),
  1281. customCallback (other.customCallback),
  1282. commandManager (other.commandManager),
  1283. shortcutKeyDescription (other.shortcutKeyDescription),
  1284. colour (other.colour),
  1285. isEnabled (other.isEnabled),
  1286. isTicked (other.isTicked),
  1287. isSeparator (other.isSeparator),
  1288. isSectionHeader (other.isSectionHeader),
  1289. shouldBreakAfter (other.shouldBreakAfter)
  1290. {}
  1291. PopupMenu::Item& PopupMenu::Item::operator= (const Item& other)
  1292. {
  1293. text = other.text;
  1294. itemID = other.itemID;
  1295. action = other.action;
  1296. subMenu.reset (createCopyIfNotNull (other.subMenu.get()));
  1297. image = other.image != nullptr ? other.image->createCopy() : std::unique_ptr<Drawable>();
  1298. customComponent = other.customComponent;
  1299. customCallback = other.customCallback;
  1300. commandManager = other.commandManager;
  1301. shortcutKeyDescription = other.shortcutKeyDescription;
  1302. colour = other.colour;
  1303. isEnabled = other.isEnabled;
  1304. isTicked = other.isTicked;
  1305. isSeparator = other.isSeparator;
  1306. isSectionHeader = other.isSectionHeader;
  1307. shouldBreakAfter = other.shouldBreakAfter;
  1308. return *this;
  1309. }
  1310. PopupMenu::Item& PopupMenu::Item::setTicked (bool shouldBeTicked) & noexcept
  1311. {
  1312. isTicked = shouldBeTicked;
  1313. return *this;
  1314. }
  1315. PopupMenu::Item& PopupMenu::Item::setEnabled (bool shouldBeEnabled) & noexcept
  1316. {
  1317. isEnabled = shouldBeEnabled;
  1318. return *this;
  1319. }
  1320. PopupMenu::Item& PopupMenu::Item::setAction (std::function<void()> newAction) & noexcept
  1321. {
  1322. action = std::move (newAction);
  1323. return *this;
  1324. }
  1325. PopupMenu::Item& PopupMenu::Item::setID (int newID) & noexcept
  1326. {
  1327. itemID = newID;
  1328. return *this;
  1329. }
  1330. PopupMenu::Item& PopupMenu::Item::setColour (Colour newColour) & noexcept
  1331. {
  1332. colour = newColour;
  1333. return *this;
  1334. }
  1335. PopupMenu::Item& PopupMenu::Item::setCustomComponent (ReferenceCountedObjectPtr<CustomComponent> comp) & noexcept
  1336. {
  1337. customComponent = comp;
  1338. return *this;
  1339. }
  1340. PopupMenu::Item& PopupMenu::Item::setImage (std::unique_ptr<Drawable> newImage) & noexcept
  1341. {
  1342. image = std::move (newImage);
  1343. return *this;
  1344. }
  1345. PopupMenu::Item&& PopupMenu::Item::setTicked (bool shouldBeTicked) && noexcept
  1346. {
  1347. isTicked = shouldBeTicked;
  1348. return std::move (*this);
  1349. }
  1350. PopupMenu::Item&& PopupMenu::Item::setEnabled (bool shouldBeEnabled) && noexcept
  1351. {
  1352. isEnabled = shouldBeEnabled;
  1353. return std::move (*this);
  1354. }
  1355. PopupMenu::Item&& PopupMenu::Item::setAction (std::function<void()> newAction) && noexcept
  1356. {
  1357. action = std::move (newAction);
  1358. return std::move (*this);
  1359. }
  1360. PopupMenu::Item&& PopupMenu::Item::setID (int newID) && noexcept
  1361. {
  1362. itemID = newID;
  1363. return std::move (*this);
  1364. }
  1365. PopupMenu::Item&& PopupMenu::Item::setColour (Colour newColour) && noexcept
  1366. {
  1367. colour = newColour;
  1368. return std::move (*this);
  1369. }
  1370. PopupMenu::Item&& PopupMenu::Item::setCustomComponent (ReferenceCountedObjectPtr<CustomComponent> comp) && noexcept
  1371. {
  1372. customComponent = comp;
  1373. return std::move (*this);
  1374. }
  1375. PopupMenu::Item&& PopupMenu::Item::setImage (std::unique_ptr<Drawable> newImage) && noexcept
  1376. {
  1377. image = std::move (newImage);
  1378. return std::move (*this);
  1379. }
  1380. void PopupMenu::addItem (Item newItem)
  1381. {
  1382. // An ID of 0 is used as a return value to indicate that the user
  1383. // didn't pick anything, so you shouldn't use it as the ID for an item..
  1384. jassert (newItem.itemID != 0
  1385. || newItem.isSeparator || newItem.isSectionHeader
  1386. || newItem.subMenu != nullptr);
  1387. items.add (std::move (newItem));
  1388. }
  1389. void PopupMenu::addItem (String itemText, std::function<void()> action)
  1390. {
  1391. addItem (std::move (itemText), true, false, std::move (action));
  1392. }
  1393. void PopupMenu::addItem (String itemText, bool isActive, bool isTicked, std::function<void()> action)
  1394. {
  1395. Item i (std::move (itemText));
  1396. i.action = std::move (action);
  1397. i.isEnabled = isActive;
  1398. i.isTicked = isTicked;
  1399. addItem (std::move (i));
  1400. }
  1401. void PopupMenu::addItem (int itemResultID, String itemText, bool isActive, bool isTicked)
  1402. {
  1403. Item i (std::move (itemText));
  1404. i.itemID = itemResultID;
  1405. i.isEnabled = isActive;
  1406. i.isTicked = isTicked;
  1407. addItem (std::move (i));
  1408. }
  1409. static std::unique_ptr<Drawable> createDrawableFromImage (const Image& im)
  1410. {
  1411. if (im.isValid())
  1412. {
  1413. auto d = new DrawableImage();
  1414. d->setImage (im);
  1415. return std::unique_ptr<Drawable> (d);
  1416. }
  1417. return {};
  1418. }
  1419. void PopupMenu::addItem (int itemResultID, String itemText, bool isActive, bool isTicked, const Image& iconToUse)
  1420. {
  1421. addItem (itemResultID, std::move (itemText), isActive, isTicked, createDrawableFromImage (iconToUse));
  1422. }
  1423. void PopupMenu::addItem (int itemResultID, String itemText, bool isActive,
  1424. bool isTicked, std::unique_ptr<Drawable> iconToUse)
  1425. {
  1426. Item i (std::move (itemText));
  1427. i.itemID = itemResultID;
  1428. i.isEnabled = isActive;
  1429. i.isTicked = isTicked;
  1430. i.image = std::move (iconToUse);
  1431. addItem (std::move (i));
  1432. }
  1433. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  1434. const CommandID commandID,
  1435. String displayName,
  1436. std::unique_ptr<Drawable> iconToUse)
  1437. {
  1438. jassert (commandManager != nullptr && commandID != 0);
  1439. if (auto* registeredInfo = commandManager->getCommandForID (commandID))
  1440. {
  1441. ApplicationCommandInfo info (*registeredInfo);
  1442. auto* target = commandManager->getTargetForCommand (commandID, info);
  1443. Item i;
  1444. i.text = displayName.isNotEmpty() ? std::move (displayName) : info.shortName;
  1445. i.itemID = (int) commandID;
  1446. i.commandManager = commandManager;
  1447. i.isEnabled = target != nullptr && (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  1448. i.isTicked = (info.flags & ApplicationCommandInfo::isTicked) != 0;
  1449. i.image = std::move (iconToUse);
  1450. addItem (std::move (i));
  1451. }
  1452. }
  1453. void PopupMenu::addColouredItem (int itemResultID, String itemText, Colour itemTextColour,
  1454. bool isActive, bool isTicked, std::unique_ptr<Drawable> iconToUse)
  1455. {
  1456. Item i (std::move (itemText));
  1457. i.itemID = itemResultID;
  1458. i.colour = itemTextColour;
  1459. i.isEnabled = isActive;
  1460. i.isTicked = isTicked;
  1461. i.image = std::move (iconToUse);
  1462. addItem (std::move (i));
  1463. }
  1464. void PopupMenu::addColouredItem (int itemResultID, String itemText, Colour itemTextColour,
  1465. bool isActive, bool isTicked, const Image& iconToUse)
  1466. {
  1467. Item i (std::move (itemText));
  1468. i.itemID = itemResultID;
  1469. i.colour = itemTextColour;
  1470. i.isEnabled = isActive;
  1471. i.isTicked = isTicked;
  1472. i.image = createDrawableFromImage (iconToUse);
  1473. addItem (std::move (i));
  1474. }
  1475. void PopupMenu::addCustomItem (int itemResultID,
  1476. std::unique_ptr<CustomComponent> cc,
  1477. std::unique_ptr<const PopupMenu> subMenu)
  1478. {
  1479. Item i;
  1480. i.itemID = itemResultID;
  1481. i.customComponent = cc.release();
  1482. i.subMenu.reset (createCopyIfNotNull (subMenu.get()));
  1483. addItem (std::move (i));
  1484. }
  1485. void PopupMenu::addCustomItem (int itemResultID,
  1486. Component& customComponent,
  1487. int idealWidth, int idealHeight,
  1488. bool triggerMenuItemAutomaticallyWhenClicked,
  1489. std::unique_ptr<const PopupMenu> subMenu)
  1490. {
  1491. auto comp = std::make_unique<HelperClasses::NormalComponentWrapper> (customComponent, idealWidth, idealHeight,
  1492. triggerMenuItemAutomaticallyWhenClicked);
  1493. addCustomItem (itemResultID, std::move (comp), std::move (subMenu));
  1494. }
  1495. void PopupMenu::addSubMenu (String subMenuName, PopupMenu subMenu, bool isActive)
  1496. {
  1497. addSubMenu (std::move (subMenuName), std::move (subMenu), isActive, nullptr, false, 0);
  1498. }
  1499. void PopupMenu::addSubMenu (String subMenuName, PopupMenu subMenu, bool isActive,
  1500. const Image& iconToUse, bool isTicked, int itemResultID)
  1501. {
  1502. addSubMenu (std::move (subMenuName), std::move (subMenu), isActive,
  1503. createDrawableFromImage (iconToUse), isTicked, itemResultID);
  1504. }
  1505. void PopupMenu::addSubMenu (String subMenuName, PopupMenu subMenu, bool isActive,
  1506. std::unique_ptr<Drawable> iconToUse, bool isTicked, int itemResultID)
  1507. {
  1508. Item i (std::move (subMenuName));
  1509. i.itemID = itemResultID;
  1510. i.isEnabled = isActive && (itemResultID != 0 || subMenu.getNumItems() > 0);
  1511. i.subMenu.reset (new PopupMenu (std::move (subMenu)));
  1512. i.isTicked = isTicked;
  1513. i.image = std::move (iconToUse);
  1514. addItem (std::move (i));
  1515. }
  1516. void PopupMenu::addSeparator()
  1517. {
  1518. if (items.size() > 0 && ! items.getLast().isSeparator)
  1519. {
  1520. Item i;
  1521. i.isSeparator = true;
  1522. addItem (std::move (i));
  1523. }
  1524. }
  1525. void PopupMenu::addSectionHeader (String title)
  1526. {
  1527. Item i (std::move (title));
  1528. i.itemID = 0;
  1529. i.isSectionHeader = true;
  1530. addItem (std::move (i));
  1531. }
  1532. void PopupMenu::addColumnBreak()
  1533. {
  1534. if (! items.isEmpty())
  1535. std::prev (items.end())->shouldBreakAfter = true;
  1536. }
  1537. //==============================================================================
  1538. PopupMenu::Options::Options()
  1539. {
  1540. targetArea.setPosition (Desktop::getMousePosition());
  1541. }
  1542. template <typename Member, typename Item>
  1543. static PopupMenu::Options with (PopupMenu::Options options, Member&& member, Item&& item)
  1544. {
  1545. options.*member = std::forward<Item> (item);
  1546. return options;
  1547. }
  1548. PopupMenu::Options PopupMenu::Options::withTargetComponent (Component* comp) const
  1549. {
  1550. auto o = with (*this, &Options::targetComponent, comp);
  1551. if (comp != nullptr)
  1552. o.targetArea = comp->getScreenBounds();
  1553. return o;
  1554. }
  1555. PopupMenu::Options PopupMenu::Options::withTargetComponent (Component& comp) const
  1556. {
  1557. return withTargetComponent (&comp);
  1558. }
  1559. PopupMenu::Options PopupMenu::Options::withTargetScreenArea (Rectangle<int> area) const
  1560. {
  1561. return with (*this, &Options::targetArea, area);
  1562. }
  1563. PopupMenu::Options PopupMenu::Options::withDeletionCheck (Component& comp) const
  1564. {
  1565. return with (with (*this, &Options::isWatchingForDeletion, true),
  1566. &Options::componentToWatchForDeletion,
  1567. &comp);
  1568. }
  1569. PopupMenu::Options PopupMenu::Options::withMinimumWidth (int w) const
  1570. {
  1571. return with (*this, &Options::minWidth, w);
  1572. }
  1573. PopupMenu::Options PopupMenu::Options::withMinimumNumColumns (int cols) const
  1574. {
  1575. return with (*this, &Options::minColumns, cols);
  1576. }
  1577. PopupMenu::Options PopupMenu::Options::withMaximumNumColumns (int cols) const
  1578. {
  1579. return with (*this, &Options::maxColumns, cols);
  1580. }
  1581. PopupMenu::Options PopupMenu::Options::withStandardItemHeight (int height) const
  1582. {
  1583. return with (*this, &Options::standardHeight, height);
  1584. }
  1585. PopupMenu::Options PopupMenu::Options::withItemThatMustBeVisible (int idOfItemToBeVisible) const
  1586. {
  1587. return with (*this, &Options::visibleItemID, idOfItemToBeVisible);
  1588. }
  1589. PopupMenu::Options PopupMenu::Options::withParentComponent (Component* parent) const
  1590. {
  1591. return with (*this, &Options::parentComponent, parent);
  1592. }
  1593. PopupMenu::Options PopupMenu::Options::withPreferredPopupDirection (PopupDirection direction) const
  1594. {
  1595. return with (*this, &Options::preferredPopupDirection, direction);
  1596. }
  1597. PopupMenu::Options PopupMenu::Options::withInitiallySelectedItem (int idOfItemToBeSelected) const
  1598. {
  1599. return with (*this, &Options::initiallySelectedItemId, idOfItemToBeSelected);
  1600. }
  1601. Component* PopupMenu::createWindow (const Options& options,
  1602. ApplicationCommandManager** managerOfChosenCommand) const
  1603. {
  1604. return items.isEmpty() ? nullptr
  1605. : new HelperClasses::MenuWindow (*this, nullptr, options,
  1606. ! options.getTargetScreenArea().isEmpty(),
  1607. ModifierKeys::currentModifiers.isAnyMouseButtonDown(),
  1608. managerOfChosenCommand);
  1609. }
  1610. //==============================================================================
  1611. // This invokes any command manager commands and deletes the menu window when it is dismissed
  1612. struct PopupMenuCompletionCallback : public ModalComponentManager::Callback
  1613. {
  1614. PopupMenuCompletionCallback() = default;
  1615. void modalStateFinished (int result) override
  1616. {
  1617. if (managerOfChosenCommand != nullptr && result != 0)
  1618. {
  1619. ApplicationCommandTarget::InvocationInfo info (result);
  1620. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  1621. managerOfChosenCommand->invoke (info, true);
  1622. }
  1623. // (this would be the place to fade out the component, if that's what's required)
  1624. component.reset();
  1625. if (PopupMenuSettings::menuWasHiddenBecauseOfAppChange)
  1626. return;
  1627. auto* focusComponent = getComponentToPassFocusTo();
  1628. const auto focusedIsNotMinimised = [focusComponent]
  1629. {
  1630. if (focusComponent != nullptr)
  1631. if (auto* peer = focusComponent->getPeer())
  1632. return ! peer->isMinimised();
  1633. return false;
  1634. }();
  1635. if (focusedIsNotMinimised)
  1636. {
  1637. if (auto* topLevel = focusComponent->getTopLevelComponent())
  1638. topLevel->toFront (true);
  1639. if (focusComponent->isShowing() && ! focusComponent->hasKeyboardFocus (true))
  1640. focusComponent->grabKeyboardFocus();
  1641. }
  1642. }
  1643. Component* getComponentToPassFocusTo() const
  1644. {
  1645. if (auto* current = Component::getCurrentlyFocusedComponent())
  1646. return current;
  1647. return prevFocused.get();
  1648. }
  1649. ApplicationCommandManager* managerOfChosenCommand = nullptr;
  1650. std::unique_ptr<Component> component;
  1651. WeakReference<Component> prevFocused { Component::getCurrentlyFocusedComponent() };
  1652. JUCE_DECLARE_NON_COPYABLE (PopupMenuCompletionCallback)
  1653. };
  1654. int PopupMenu::showWithOptionalCallback (const Options& options,
  1655. ModalComponentManager::Callback* userCallback,
  1656. bool canBeModal)
  1657. {
  1658. std::unique_ptr<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  1659. std::unique_ptr<PopupMenuCompletionCallback> callback (new PopupMenuCompletionCallback());
  1660. if (auto* window = createWindow (options, &(callback->managerOfChosenCommand)))
  1661. {
  1662. callback->component.reset (window);
  1663. PopupMenuSettings::menuWasHiddenBecauseOfAppChange = false;
  1664. window->setVisible (true); // (must be called before enterModalState on Windows to avoid DropShadower confusion)
  1665. window->enterModalState (false, userCallbackDeleter.release());
  1666. ModalComponentManager::getInstance()->attachCallback (window, callback.release());
  1667. window->toFront (false); // need to do this after making it modal, or it could
  1668. // be stuck behind other comps that are already modal..
  1669. #if JUCE_MODAL_LOOPS_PERMITTED
  1670. if (userCallback == nullptr && canBeModal)
  1671. return window->runModalLoop();
  1672. #else
  1673. ignoreUnused (canBeModal);
  1674. jassert (! (userCallback == nullptr && canBeModal));
  1675. #endif
  1676. }
  1677. return 0;
  1678. }
  1679. //==============================================================================
  1680. #if JUCE_MODAL_LOOPS_PERMITTED
  1681. int PopupMenu::showMenu (const Options& options)
  1682. {
  1683. return showWithOptionalCallback (options, nullptr, true);
  1684. }
  1685. #endif
  1686. void PopupMenu::showMenuAsync (const Options& options)
  1687. {
  1688. showWithOptionalCallback (options, nullptr, false);
  1689. }
  1690. void PopupMenu::showMenuAsync (const Options& options, ModalComponentManager::Callback* userCallback)
  1691. {
  1692. #if ! JUCE_MODAL_LOOPS_PERMITTED
  1693. jassert (userCallback != nullptr);
  1694. #endif
  1695. showWithOptionalCallback (options, userCallback, false);
  1696. }
  1697. void PopupMenu::showMenuAsync (const Options& options, std::function<void (int)> userCallback)
  1698. {
  1699. showWithOptionalCallback (options, ModalCallbackFunction::create (userCallback), false);
  1700. }
  1701. //==============================================================================
  1702. #if JUCE_MODAL_LOOPS_PERMITTED
  1703. int PopupMenu::show (int itemIDThatMustBeVisible, int minimumWidth,
  1704. int maximumNumColumns, int standardItemHeight,
  1705. ModalComponentManager::Callback* callback)
  1706. {
  1707. return showWithOptionalCallback (Options().withItemThatMustBeVisible (itemIDThatMustBeVisible)
  1708. .withMinimumWidth (minimumWidth)
  1709. .withMaximumNumColumns (maximumNumColumns)
  1710. .withStandardItemHeight (standardItemHeight),
  1711. callback, true);
  1712. }
  1713. int PopupMenu::showAt (Rectangle<int> screenAreaToAttachTo,
  1714. int itemIDThatMustBeVisible, int minimumWidth,
  1715. int maximumNumColumns, int standardItemHeight,
  1716. ModalComponentManager::Callback* callback)
  1717. {
  1718. return showWithOptionalCallback (Options().withTargetScreenArea (screenAreaToAttachTo)
  1719. .withItemThatMustBeVisible (itemIDThatMustBeVisible)
  1720. .withMinimumWidth (minimumWidth)
  1721. .withMaximumNumColumns (maximumNumColumns)
  1722. .withStandardItemHeight (standardItemHeight),
  1723. callback, true);
  1724. }
  1725. int PopupMenu::showAt (Component* componentToAttachTo,
  1726. int itemIDThatMustBeVisible, int minimumWidth,
  1727. int maximumNumColumns, int standardItemHeight,
  1728. ModalComponentManager::Callback* callback)
  1729. {
  1730. auto options = Options().withItemThatMustBeVisible (itemIDThatMustBeVisible)
  1731. .withMinimumWidth (minimumWidth)
  1732. .withMaximumNumColumns (maximumNumColumns)
  1733. .withStandardItemHeight (standardItemHeight);
  1734. if (componentToAttachTo != nullptr)
  1735. options = options.withTargetComponent (componentToAttachTo);
  1736. return showWithOptionalCallback (options, callback, true);
  1737. }
  1738. #endif
  1739. bool JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  1740. {
  1741. auto& windows = HelperClasses::MenuWindow::getActiveWindows();
  1742. auto numWindows = windows.size();
  1743. for (int i = numWindows; --i >= 0;)
  1744. {
  1745. if (auto* pmw = windows[i])
  1746. {
  1747. pmw->setLookAndFeel (nullptr);
  1748. pmw->dismissMenu (nullptr);
  1749. }
  1750. }
  1751. return numWindows > 0;
  1752. }
  1753. //==============================================================================
  1754. int PopupMenu::getNumItems() const noexcept
  1755. {
  1756. int num = 0;
  1757. for (auto& mi : items)
  1758. if (! mi.isSeparator)
  1759. ++num;
  1760. return num;
  1761. }
  1762. bool PopupMenu::containsCommandItem (const int commandID) const
  1763. {
  1764. for (auto& mi : items)
  1765. if ((mi.itemID == commandID && mi.commandManager != nullptr)
  1766. || (mi.subMenu != nullptr && mi.subMenu->containsCommandItem (commandID)))
  1767. return true;
  1768. return false;
  1769. }
  1770. bool PopupMenu::containsAnyActiveItems() const noexcept
  1771. {
  1772. for (auto& mi : items)
  1773. {
  1774. if (mi.subMenu != nullptr)
  1775. {
  1776. if (mi.subMenu->containsAnyActiveItems())
  1777. return true;
  1778. }
  1779. else if (mi.isEnabled)
  1780. {
  1781. return true;
  1782. }
  1783. }
  1784. return false;
  1785. }
  1786. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  1787. {
  1788. lookAndFeel = newLookAndFeel;
  1789. }
  1790. void PopupMenu::setItem (CustomComponent& c, const Item* itemToUse)
  1791. {
  1792. c.item = itemToUse;
  1793. c.repaint();
  1794. }
  1795. //==============================================================================
  1796. PopupMenu::CustomComponent::CustomComponent (bool autoTrigger)
  1797. : triggeredAutomatically (autoTrigger)
  1798. {
  1799. }
  1800. PopupMenu::CustomComponent::~CustomComponent()
  1801. {
  1802. }
  1803. void PopupMenu::CustomComponent::setHighlighted (bool shouldBeHighlighted)
  1804. {
  1805. isHighlighted = shouldBeHighlighted;
  1806. repaint();
  1807. }
  1808. void PopupMenu::CustomComponent::triggerMenuItem()
  1809. {
  1810. if (auto* mic = findParentComponentOfClass<HelperClasses::ItemComponent>())
  1811. {
  1812. if (auto* pmw = mic->findParentComponentOfClass<HelperClasses::MenuWindow>())
  1813. {
  1814. pmw->dismissMenu (&mic->item);
  1815. }
  1816. else
  1817. {
  1818. // something must have gone wrong with the component hierarchy if this happens..
  1819. jassertfalse;
  1820. }
  1821. }
  1822. else
  1823. {
  1824. // why isn't this component inside a menu? Not much point triggering the item if
  1825. // there's no menu.
  1826. jassertfalse;
  1827. }
  1828. }
  1829. //==============================================================================
  1830. PopupMenu::CustomCallback::CustomCallback() {}
  1831. PopupMenu::CustomCallback::~CustomCallback() {}
  1832. //==============================================================================
  1833. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& m, bool recurse) : searchRecursively (recurse)
  1834. {
  1835. index.add (0);
  1836. menus.add (&m);
  1837. }
  1838. PopupMenu::MenuItemIterator::~MenuItemIterator() = default;
  1839. bool PopupMenu::MenuItemIterator::next()
  1840. {
  1841. if (index.size() == 0 || menus.getLast()->items.size() == 0)
  1842. return false;
  1843. currentItem = const_cast<PopupMenu::Item*> (&(menus.getLast()->items.getReference (index.getLast())));
  1844. if (searchRecursively && currentItem->subMenu != nullptr)
  1845. {
  1846. index.add (0);
  1847. menus.add (currentItem->subMenu.get());
  1848. }
  1849. else
  1850. {
  1851. index.setUnchecked (index.size() - 1, index.getLast() + 1);
  1852. }
  1853. while (index.size() > 0 && index.getLast() >= (int) menus.getLast()->items.size())
  1854. {
  1855. index.removeLast();
  1856. menus.removeLast();
  1857. if (index.size() > 0)
  1858. index.setUnchecked (index.size() - 1, index.getLast() + 1);
  1859. }
  1860. return true;
  1861. }
  1862. PopupMenu::Item& PopupMenu::MenuItemIterator::getItem() const
  1863. {
  1864. jassert (currentItem != nullptr);
  1865. return *(currentItem);
  1866. }
  1867. void PopupMenu::LookAndFeelMethods::drawPopupMenuBackground (Graphics&, int, int) {}
  1868. void PopupMenu::LookAndFeelMethods::drawPopupMenuItem (Graphics&, const Rectangle<int>&,
  1869. bool, bool, bool,
  1870. bool, bool,
  1871. const String&,
  1872. const String&,
  1873. const Drawable*,
  1874. const Colour*) {}
  1875. void PopupMenu::LookAndFeelMethods::drawPopupMenuSectionHeader (Graphics&, const Rectangle<int>&,
  1876. const String&) {}
  1877. void PopupMenu::LookAndFeelMethods::drawPopupMenuUpDownArrow (Graphics&, int, int, bool) {}
  1878. void PopupMenu::LookAndFeelMethods::getIdealPopupMenuItemSize (const String&, bool, int, int&, int&) {}
  1879. int PopupMenu::LookAndFeelMethods::getPopupMenuBorderSize() { return 0; }
  1880. } // namespace juce