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.

2290 lines
79KB

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