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.

1754 lines
59KB

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