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.

2019 lines
68KB

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