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.

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