Audio plugin host https://kx.studio/carla
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.

2002 lines
67KB

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