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.

2322 lines
81KB

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