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.

1983 lines
67KB

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