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.

2015 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 (int i = 0; i < menu.items.size(); ++i)
  178. {
  179. auto& item = menu.items.getReference (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 (const PopupMenu& other)
  1026. : items (other.items),
  1027. lookAndFeel (other.lookAndFeel)
  1028. {
  1029. }
  1030. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  1031. {
  1032. if (this != &other)
  1033. {
  1034. items = other.items;
  1035. lookAndFeel = other.lookAndFeel;
  1036. }
  1037. return *this;
  1038. }
  1039. PopupMenu::PopupMenu (PopupMenu&& other) noexcept
  1040. : items (std::move (other.items)),
  1041. lookAndFeel (std::move (other.lookAndFeel))
  1042. {
  1043. }
  1044. PopupMenu& PopupMenu::operator= (PopupMenu&& other) noexcept
  1045. {
  1046. items = std::move (other.items);
  1047. lookAndFeel = other.lookAndFeel;
  1048. return *this;
  1049. }
  1050. PopupMenu::~PopupMenu() = default;
  1051. void PopupMenu::clear()
  1052. {
  1053. items.clear();
  1054. }
  1055. //==============================================================================
  1056. PopupMenu::Item::Item() = default;
  1057. PopupMenu::Item::Item (String t) : text (std::move (t)), itemID (-1) {}
  1058. PopupMenu::Item::Item (Item&&) = default;
  1059. PopupMenu::Item& PopupMenu::Item::operator= (Item&&) = default;
  1060. PopupMenu::Item::Item (const Item& other)
  1061. : text (other.text),
  1062. itemID (other.itemID),
  1063. action (other.action),
  1064. subMenu (createCopyIfNotNull (other.subMenu.get())),
  1065. image (other.image != nullptr ? other.image->createCopy() : nullptr),
  1066. customComponent (other.customComponent),
  1067. customCallback (other.customCallback),
  1068. commandManager (other.commandManager),
  1069. shortcutKeyDescription (other.shortcutKeyDescription),
  1070. colour (other.colour),
  1071. isEnabled (other.isEnabled),
  1072. isTicked (other.isTicked),
  1073. isSeparator (other.isSeparator),
  1074. isSectionHeader (other.isSectionHeader)
  1075. {
  1076. }
  1077. PopupMenu::Item& PopupMenu::Item::operator= (const Item& other)
  1078. {
  1079. text = other.text;
  1080. itemID = other.itemID;
  1081. action = other.action;
  1082. subMenu.reset (createCopyIfNotNull (other.subMenu.get()));
  1083. image = other.image != nullptr ? other.image->createCopy() : std::unique_ptr<Drawable>();
  1084. customComponent = other.customComponent;
  1085. customCallback = other.customCallback;
  1086. commandManager = other.commandManager;
  1087. shortcutKeyDescription = other.shortcutKeyDescription;
  1088. colour = other.colour;
  1089. isEnabled = other.isEnabled;
  1090. isTicked = other.isTicked;
  1091. isSeparator = other.isSeparator;
  1092. isSectionHeader = other.isSectionHeader;
  1093. return *this;
  1094. }
  1095. PopupMenu::Item& PopupMenu::Item::setTicked (bool shouldBeTicked) & noexcept
  1096. {
  1097. isTicked = shouldBeTicked;
  1098. return *this;
  1099. }
  1100. PopupMenu::Item& PopupMenu::Item::setEnabled (bool shouldBeEnabled) & noexcept
  1101. {
  1102. isEnabled = shouldBeEnabled;
  1103. return *this;
  1104. }
  1105. PopupMenu::Item& PopupMenu::Item::setAction (std::function<void()> newAction) & noexcept
  1106. {
  1107. action = std::move (newAction);
  1108. return *this;
  1109. }
  1110. PopupMenu::Item& PopupMenu::Item::setID (int newID) & noexcept
  1111. {
  1112. itemID = newID;
  1113. return *this;
  1114. }
  1115. PopupMenu::Item& PopupMenu::Item::setColour (Colour newColour) & noexcept
  1116. {
  1117. colour = newColour;
  1118. return *this;
  1119. }
  1120. PopupMenu::Item& PopupMenu::Item::setCustomComponent (ReferenceCountedObjectPtr<CustomComponent> comp) & noexcept
  1121. {
  1122. customComponent = comp;
  1123. return *this;
  1124. }
  1125. PopupMenu::Item& PopupMenu::Item::setImage (std::unique_ptr<Drawable> newImage) & noexcept
  1126. {
  1127. image = std::move (newImage);
  1128. return *this;
  1129. }
  1130. PopupMenu::Item&& PopupMenu::Item::setTicked (bool shouldBeTicked) && noexcept
  1131. {
  1132. isTicked = shouldBeTicked;
  1133. return std::move (*this);
  1134. }
  1135. PopupMenu::Item&& PopupMenu::Item::setEnabled (bool shouldBeEnabled) && noexcept
  1136. {
  1137. isEnabled = shouldBeEnabled;
  1138. return std::move (*this);
  1139. }
  1140. PopupMenu::Item&& PopupMenu::Item::setAction (std::function<void()> newAction) && noexcept
  1141. {
  1142. action = std::move (newAction);
  1143. return std::move (*this);
  1144. }
  1145. PopupMenu::Item&& PopupMenu::Item::setID (int newID) && noexcept
  1146. {
  1147. itemID = newID;
  1148. return std::move (*this);
  1149. }
  1150. PopupMenu::Item&& PopupMenu::Item::setColour (Colour newColour) && noexcept
  1151. {
  1152. colour = newColour;
  1153. return std::move (*this);
  1154. }
  1155. PopupMenu::Item&& PopupMenu::Item::setCustomComponent (ReferenceCountedObjectPtr<CustomComponent> comp) && noexcept
  1156. {
  1157. customComponent = comp;
  1158. return std::move (*this);
  1159. }
  1160. PopupMenu::Item&& PopupMenu::Item::setImage (std::unique_ptr<Drawable> newImage) && noexcept
  1161. {
  1162. image = std::move (newImage);
  1163. return std::move (*this);
  1164. }
  1165. void PopupMenu::addItem (Item newItem)
  1166. {
  1167. // An ID of 0 is used as a return value to indicate that the user
  1168. // didn't pick anything, so you shouldn't use it as the ID for an item..
  1169. jassert (newItem.itemID != 0
  1170. || newItem.isSeparator || newItem.isSectionHeader
  1171. || newItem.subMenu != nullptr);
  1172. items.add (std::move (newItem));
  1173. }
  1174. void PopupMenu::addItem (String itemText, std::function<void()> action)
  1175. {
  1176. addItem (std::move (itemText), true, false, std::move (action));
  1177. }
  1178. void PopupMenu::addItem (String itemText, bool isActive, bool isTicked, std::function<void()> action)
  1179. {
  1180. Item i (std::move (itemText));
  1181. i.action = std::move (action);
  1182. i.isEnabled = isActive;
  1183. i.isTicked = isTicked;
  1184. addItem (std::move (i));
  1185. }
  1186. void PopupMenu::addItem (int itemResultID, String itemText, bool isActive, bool isTicked)
  1187. {
  1188. Item i (std::move (itemText));
  1189. i.itemID = itemResultID;
  1190. i.isEnabled = isActive;
  1191. i.isTicked = isTicked;
  1192. addItem (std::move (i));
  1193. }
  1194. static std::unique_ptr<Drawable> createDrawableFromImage (const Image& im)
  1195. {
  1196. if (im.isValid())
  1197. {
  1198. auto d = new DrawableImage();
  1199. d->setImage (im);
  1200. return std::unique_ptr<Drawable> (d);
  1201. }
  1202. return {};
  1203. }
  1204. void PopupMenu::addItem (int itemResultID, String itemText, bool isActive, bool isTicked, const Image& iconToUse)
  1205. {
  1206. addItem (itemResultID, std::move (itemText), isActive, isTicked, createDrawableFromImage (iconToUse));
  1207. }
  1208. void PopupMenu::addItem (int itemResultID, String itemText, bool isActive,
  1209. bool isTicked, std::unique_ptr<Drawable> iconToUse)
  1210. {
  1211. Item i (std::move (itemText));
  1212. i.itemID = itemResultID;
  1213. i.isEnabled = isActive;
  1214. i.isTicked = isTicked;
  1215. i.image = std::move (iconToUse);
  1216. addItem (std::move (i));
  1217. }
  1218. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  1219. const CommandID commandID,
  1220. String displayName,
  1221. std::unique_ptr<Drawable> iconToUse)
  1222. {
  1223. jassert (commandManager != nullptr && commandID != 0);
  1224. if (auto* registeredInfo = commandManager->getCommandForID (commandID))
  1225. {
  1226. ApplicationCommandInfo info (*registeredInfo);
  1227. auto* target = commandManager->getTargetForCommand (commandID, info);
  1228. Item i;
  1229. i.text = displayName.isNotEmpty() ? std::move (displayName) : info.shortName;
  1230. i.itemID = (int) commandID;
  1231. i.commandManager = commandManager;
  1232. i.isEnabled = target != nullptr && (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  1233. i.isTicked = (info.flags & ApplicationCommandInfo::isTicked) != 0;
  1234. i.image = std::move (iconToUse);
  1235. addItem (std::move (i));
  1236. }
  1237. }
  1238. void PopupMenu::addColouredItem (int itemResultID, String itemText, Colour itemTextColour,
  1239. bool isActive, bool isTicked, std::unique_ptr<Drawable> iconToUse)
  1240. {
  1241. Item i (std::move (itemText));
  1242. i.itemID = itemResultID;
  1243. i.colour = itemTextColour;
  1244. i.isEnabled = isActive;
  1245. i.isTicked = isTicked;
  1246. i.image = std::move (iconToUse);
  1247. addItem (std::move (i));
  1248. }
  1249. void PopupMenu::addColouredItem (int itemResultID, String itemText, Colour itemTextColour,
  1250. bool isActive, bool isTicked, const Image& iconToUse)
  1251. {
  1252. Item i (std::move (itemText));
  1253. i.itemID = itemResultID;
  1254. i.colour = itemTextColour;
  1255. i.isEnabled = isActive;
  1256. i.isTicked = isTicked;
  1257. i.image = createDrawableFromImage (iconToUse);
  1258. addItem (std::move (i));
  1259. }
  1260. void PopupMenu::addCustomItem (int itemResultID,
  1261. std::unique_ptr<CustomComponent> cc,
  1262. std::unique_ptr<const PopupMenu> subMenu)
  1263. {
  1264. Item i;
  1265. i.itemID = itemResultID;
  1266. i.customComponent = cc.release();
  1267. i.subMenu.reset (createCopyIfNotNull (subMenu.get()));
  1268. addItem (std::move (i));
  1269. }
  1270. void PopupMenu::addCustomItem (int itemResultID,
  1271. Component& customComponent,
  1272. int idealWidth, int idealHeight,
  1273. bool triggerMenuItemAutomaticallyWhenClicked,
  1274. std::unique_ptr<const PopupMenu> subMenu)
  1275. {
  1276. auto comp = std::make_unique<HelperClasses::NormalComponentWrapper> (customComponent, idealWidth, idealHeight,
  1277. triggerMenuItemAutomaticallyWhenClicked);
  1278. addCustomItem (itemResultID, std::move (comp), std::move (subMenu));
  1279. }
  1280. void PopupMenu::addSubMenu (String subMenuName, PopupMenu subMenu, bool isActive)
  1281. {
  1282. addSubMenu (std::move (subMenuName), std::move (subMenu), isActive, nullptr, false, 0);
  1283. }
  1284. void PopupMenu::addSubMenu (String subMenuName, PopupMenu subMenu, bool isActive,
  1285. const Image& iconToUse, bool isTicked, int itemResultID)
  1286. {
  1287. addSubMenu (std::move (subMenuName), std::move (subMenu), isActive,
  1288. createDrawableFromImage (iconToUse), isTicked, itemResultID);
  1289. }
  1290. void PopupMenu::addSubMenu (String subMenuName, PopupMenu subMenu, bool isActive,
  1291. std::unique_ptr<Drawable> iconToUse, bool isTicked, int itemResultID)
  1292. {
  1293. Item i (std::move (subMenuName));
  1294. i.itemID = itemResultID;
  1295. i.isEnabled = isActive && (itemResultID != 0 || subMenu.getNumItems() > 0);
  1296. i.subMenu.reset (new PopupMenu (std::move (subMenu)));
  1297. i.isTicked = isTicked;
  1298. i.image = std::move (iconToUse);
  1299. addItem (std::move (i));
  1300. }
  1301. void PopupMenu::addSeparator()
  1302. {
  1303. if (items.size() > 0 && ! items.getLast().isSeparator)
  1304. {
  1305. Item i;
  1306. i.isSeparator = true;
  1307. addItem (std::move (i));
  1308. }
  1309. }
  1310. void PopupMenu::addSectionHeader (String title)
  1311. {
  1312. Item i (std::move (title));
  1313. i.itemID = 0;
  1314. i.isSectionHeader = true;
  1315. addItem (std::move (i));
  1316. }
  1317. //==============================================================================
  1318. PopupMenu::Options::Options()
  1319. {
  1320. targetArea.setPosition (Desktop::getMousePosition());
  1321. }
  1322. PopupMenu::Options PopupMenu::Options::withTargetComponent (Component* comp) const
  1323. {
  1324. Options o (*this);
  1325. o.targetComponent = comp;
  1326. if (comp != nullptr)
  1327. o.targetArea = comp->getScreenBounds();
  1328. return o;
  1329. }
  1330. PopupMenu::Options PopupMenu::Options::withTargetComponent (Component& comp) const
  1331. {
  1332. return withTargetComponent (&comp);
  1333. }
  1334. PopupMenu::Options PopupMenu::Options::withTargetScreenArea (Rectangle<int> area) const
  1335. {
  1336. Options o (*this);
  1337. o.targetArea = area;
  1338. return o;
  1339. }
  1340. PopupMenu::Options PopupMenu::Options::withDeletionCheck (Component& comp) const
  1341. {
  1342. Options o (*this);
  1343. o.componentToWatchForDeletion = &comp;
  1344. o.isWatchingForDeletion = true;
  1345. return o;
  1346. }
  1347. PopupMenu::Options PopupMenu::Options::withMinimumWidth (int w) const
  1348. {
  1349. Options o (*this);
  1350. o.minWidth = w;
  1351. return o;
  1352. }
  1353. PopupMenu::Options PopupMenu::Options::withMinimumNumColumns (int cols) const
  1354. {
  1355. Options o (*this);
  1356. o.minColumns = cols;
  1357. return o;
  1358. }
  1359. PopupMenu::Options PopupMenu::Options::withMaximumNumColumns (int cols) const
  1360. {
  1361. Options o (*this);
  1362. o.maxColumns = cols;
  1363. return o;
  1364. }
  1365. PopupMenu::Options PopupMenu::Options::withStandardItemHeight (int height) const
  1366. {
  1367. Options o (*this);
  1368. o.standardHeight = height;
  1369. return o;
  1370. }
  1371. PopupMenu::Options PopupMenu::Options::withItemThatMustBeVisible (int idOfItemToBeVisible) const
  1372. {
  1373. Options o (*this);
  1374. o.visibleItemID = idOfItemToBeVisible;
  1375. return o;
  1376. }
  1377. PopupMenu::Options PopupMenu::Options::withParentComponent (Component* parent) const
  1378. {
  1379. Options o (*this);
  1380. o.parentComponent = parent;
  1381. return o;
  1382. }
  1383. PopupMenu::Options PopupMenu::Options::withPreferredPopupDirection (PopupDirection direction) const
  1384. {
  1385. Options o (*this);
  1386. o.preferredPopupDirection = direction;
  1387. return o;
  1388. }
  1389. Component* PopupMenu::createWindow (const Options& options,
  1390. ApplicationCommandManager** managerOfChosenCommand) const
  1391. {
  1392. return items.isEmpty() ? nullptr
  1393. : new HelperClasses::MenuWindow (*this, nullptr, options,
  1394. ! options.getTargetScreenArea().isEmpty(),
  1395. ModifierKeys::currentModifiers.isAnyMouseButtonDown(),
  1396. managerOfChosenCommand);
  1397. }
  1398. //==============================================================================
  1399. // This invokes any command manager commands and deletes the menu window when it is dismissed
  1400. struct PopupMenuCompletionCallback : public ModalComponentManager::Callback
  1401. {
  1402. PopupMenuCompletionCallback()
  1403. : prevFocused (Component::getCurrentlyFocusedComponent()),
  1404. prevTopLevel (prevFocused != nullptr ? prevFocused->getTopLevelComponent() : nullptr)
  1405. {
  1406. PopupMenuSettings::menuWasHiddenBecauseOfAppChange = false;
  1407. }
  1408. void modalStateFinished (int result) override
  1409. {
  1410. if (managerOfChosenCommand != nullptr && result != 0)
  1411. {
  1412. ApplicationCommandTarget::InvocationInfo info (result);
  1413. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  1414. managerOfChosenCommand->invoke (info, true);
  1415. }
  1416. // (this would be the place to fade out the component, if that's what's required)
  1417. component.reset();
  1418. if (! PopupMenuSettings::menuWasHiddenBecauseOfAppChange)
  1419. {
  1420. if (prevTopLevel != nullptr)
  1421. prevTopLevel->toFront (true);
  1422. if (prevFocused != nullptr && prevFocused->isShowing())
  1423. prevFocused->grabKeyboardFocus();
  1424. }
  1425. }
  1426. ApplicationCommandManager* managerOfChosenCommand = nullptr;
  1427. std::unique_ptr<Component> component;
  1428. WeakReference<Component> prevFocused, prevTopLevel;
  1429. JUCE_DECLARE_NON_COPYABLE (PopupMenuCompletionCallback)
  1430. };
  1431. int PopupMenu::showWithOptionalCallback (const Options& options,
  1432. ModalComponentManager::Callback* userCallback,
  1433. bool canBeModal)
  1434. {
  1435. std::unique_ptr<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  1436. std::unique_ptr<PopupMenuCompletionCallback> callback (new PopupMenuCompletionCallback());
  1437. if (auto* window = createWindow (options, &(callback->managerOfChosenCommand)))
  1438. {
  1439. callback->component.reset (window);
  1440. window->setVisible (true); // (must be called before enterModalState on Windows to avoid DropShadower confusion)
  1441. window->enterModalState (false, userCallbackDeleter.release());
  1442. ModalComponentManager::getInstance()->attachCallback (window, callback.release());
  1443. window->toFront (false); // need to do this after making it modal, or it could
  1444. // be stuck behind other comps that are already modal..
  1445. #if JUCE_MODAL_LOOPS_PERMITTED
  1446. if (userCallback == nullptr && canBeModal)
  1447. return window->runModalLoop();
  1448. #else
  1449. ignoreUnused (canBeModal);
  1450. jassert (! (userCallback == nullptr && canBeModal));
  1451. #endif
  1452. }
  1453. return 0;
  1454. }
  1455. //==============================================================================
  1456. #if JUCE_MODAL_LOOPS_PERMITTED
  1457. int PopupMenu::showMenu (const Options& options)
  1458. {
  1459. return showWithOptionalCallback (options, nullptr, true);
  1460. }
  1461. #endif
  1462. void PopupMenu::showMenuAsync (const Options& options)
  1463. {
  1464. showWithOptionalCallback (options, nullptr, false);
  1465. }
  1466. void PopupMenu::showMenuAsync (const Options& options, ModalComponentManager::Callback* userCallback)
  1467. {
  1468. #if ! JUCE_MODAL_LOOPS_PERMITTED
  1469. jassert (userCallback != nullptr);
  1470. #endif
  1471. showWithOptionalCallback (options, userCallback, false);
  1472. }
  1473. void PopupMenu::showMenuAsync (const Options& options, std::function<void(int)> userCallback)
  1474. {
  1475. showWithOptionalCallback (options, ModalCallbackFunction::create (userCallback), false);
  1476. }
  1477. //==============================================================================
  1478. #if JUCE_MODAL_LOOPS_PERMITTED
  1479. int PopupMenu::show (int itemIDThatMustBeVisible, int minimumWidth,
  1480. int maximumNumColumns, int standardItemHeight,
  1481. ModalComponentManager::Callback* callback)
  1482. {
  1483. return showWithOptionalCallback (Options().withItemThatMustBeVisible (itemIDThatMustBeVisible)
  1484. .withMinimumWidth (minimumWidth)
  1485. .withMaximumNumColumns (maximumNumColumns)
  1486. .withStandardItemHeight (standardItemHeight),
  1487. callback, true);
  1488. }
  1489. int PopupMenu::showAt (Rectangle<int> screenAreaToAttachTo,
  1490. int itemIDThatMustBeVisible, int minimumWidth,
  1491. int maximumNumColumns, int standardItemHeight,
  1492. ModalComponentManager::Callback* callback)
  1493. {
  1494. return showWithOptionalCallback (Options().withTargetScreenArea (screenAreaToAttachTo)
  1495. .withItemThatMustBeVisible (itemIDThatMustBeVisible)
  1496. .withMinimumWidth (minimumWidth)
  1497. .withMaximumNumColumns (maximumNumColumns)
  1498. .withStandardItemHeight (standardItemHeight),
  1499. callback, true);
  1500. }
  1501. int PopupMenu::showAt (Component* componentToAttachTo,
  1502. int itemIDThatMustBeVisible, int minimumWidth,
  1503. int maximumNumColumns, int standardItemHeight,
  1504. ModalComponentManager::Callback* callback)
  1505. {
  1506. auto options = Options().withItemThatMustBeVisible (itemIDThatMustBeVisible)
  1507. .withMinimumWidth (minimumWidth)
  1508. .withMaximumNumColumns (maximumNumColumns)
  1509. .withStandardItemHeight (standardItemHeight);
  1510. if (componentToAttachTo != nullptr)
  1511. options = options.withTargetComponent (componentToAttachTo);
  1512. return showWithOptionalCallback (options, callback, true);
  1513. }
  1514. #endif
  1515. bool JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  1516. {
  1517. auto& windows = HelperClasses::MenuWindow::getActiveWindows();
  1518. auto numWindows = windows.size();
  1519. for (int i = numWindows; --i >= 0;)
  1520. {
  1521. if (auto* pmw = windows[i])
  1522. {
  1523. pmw->setLookAndFeel (nullptr);
  1524. pmw->dismissMenu (nullptr);
  1525. }
  1526. }
  1527. return numWindows > 0;
  1528. }
  1529. //==============================================================================
  1530. int PopupMenu::getNumItems() const noexcept
  1531. {
  1532. int num = 0;
  1533. for (auto& mi : items)
  1534. if (! mi.isSeparator)
  1535. ++num;
  1536. return num;
  1537. }
  1538. bool PopupMenu::containsCommandItem (const int commandID) const
  1539. {
  1540. for (auto& mi : items)
  1541. if ((mi.itemID == commandID && mi.commandManager != nullptr)
  1542. || (mi.subMenu != nullptr && mi.subMenu->containsCommandItem (commandID)))
  1543. return true;
  1544. return false;
  1545. }
  1546. bool PopupMenu::containsAnyActiveItems() const noexcept
  1547. {
  1548. for (auto& mi : items)
  1549. {
  1550. if (mi.subMenu != nullptr)
  1551. {
  1552. if (mi.subMenu->containsAnyActiveItems())
  1553. return true;
  1554. }
  1555. else if (mi.isEnabled)
  1556. {
  1557. return true;
  1558. }
  1559. }
  1560. return false;
  1561. }
  1562. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  1563. {
  1564. lookAndFeel = newLookAndFeel;
  1565. }
  1566. void PopupMenu::setItem (CustomComponent& c, const Item* itemToUse)
  1567. {
  1568. c.item = itemToUse;
  1569. c.repaint();
  1570. }
  1571. //==============================================================================
  1572. PopupMenu::CustomComponent::CustomComponent (bool autoTrigger)
  1573. : triggeredAutomatically (autoTrigger)
  1574. {
  1575. }
  1576. PopupMenu::CustomComponent::~CustomComponent()
  1577. {
  1578. }
  1579. void PopupMenu::CustomComponent::setHighlighted (bool shouldBeHighlighted)
  1580. {
  1581. isHighlighted = shouldBeHighlighted;
  1582. repaint();
  1583. }
  1584. void PopupMenu::CustomComponent::triggerMenuItem()
  1585. {
  1586. if (auto* mic = findParentComponentOfClass<HelperClasses::ItemComponent>())
  1587. {
  1588. if (auto* pmw = mic->findParentComponentOfClass<HelperClasses::MenuWindow>())
  1589. {
  1590. pmw->dismissMenu (&mic->item);
  1591. }
  1592. else
  1593. {
  1594. // something must have gone wrong with the component hierarchy if this happens..
  1595. jassertfalse;
  1596. }
  1597. }
  1598. else
  1599. {
  1600. // why isn't this component inside a menu? Not much point triggering the item if
  1601. // there's no menu.
  1602. jassertfalse;
  1603. }
  1604. }
  1605. //==============================================================================
  1606. PopupMenu::CustomCallback::CustomCallback() {}
  1607. PopupMenu::CustomCallback::~CustomCallback() {}
  1608. //==============================================================================
  1609. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& m, bool recurse) : searchRecursively (recurse)
  1610. {
  1611. index.add (0);
  1612. menus.add (&m);
  1613. }
  1614. PopupMenu::MenuItemIterator::~MenuItemIterator() = default;
  1615. bool PopupMenu::MenuItemIterator::next()
  1616. {
  1617. if (index.size() == 0 || menus.getLast()->items.size() == 0)
  1618. return false;
  1619. currentItem = const_cast<PopupMenu::Item*> (&(menus.getLast()->items.getReference (index.getLast())));
  1620. if (searchRecursively && currentItem->subMenu != nullptr)
  1621. {
  1622. index.add (0);
  1623. menus.add (currentItem->subMenu.get());
  1624. }
  1625. else
  1626. {
  1627. index.setUnchecked (index.size() - 1, index.getLast() + 1);
  1628. }
  1629. while (index.size() > 0 && index.getLast() >= (int) menus.getLast()->items.size())
  1630. {
  1631. index.removeLast();
  1632. menus.removeLast();
  1633. if (index.size() > 0)
  1634. index.setUnchecked (index.size() - 1, index.getLast() + 1);
  1635. }
  1636. return true;
  1637. }
  1638. PopupMenu::Item& PopupMenu::MenuItemIterator::getItem() const
  1639. {
  1640. jassert (currentItem != nullptr);
  1641. return *(currentItem);
  1642. }
  1643. } // namespace juce