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.

1752 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. updateShortcutKeyDescription();
  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. item.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. private:
  117. // NB: we use a copy of the one from the item info in case we're using our own section comp
  118. ReferenceCountedObjectPtr<CustomComponent> customComp;
  119. bool isHighlighted;
  120. void updateShortcutKeyDescription()
  121. {
  122. if (item.commandManager != nullptr && item.itemID != 0)
  123. {
  124. String shortcutKey;
  125. const Array<KeyPress> keyPresses (item.commandManager->getKeyMappings()
  126. ->getKeyPressesAssignedToCommand (item.itemID));
  127. for (int i = 0; i < keyPresses.size(); ++i)
  128. {
  129. const String key (keyPresses.getReference(i).getTextDescriptionWithIcons());
  130. if (shortcutKey.isNotEmpty())
  131. shortcutKey << ", ";
  132. if (key.length() == 1 && key[0] < 128)
  133. shortcutKey << "shortcut: '" << key << '\'';
  134. else
  135. shortcutKey << key;
  136. }
  137. item.shortcutKeyDescription = shortcutKey.trim();
  138. }
  139. }
  140. String getTextForMeasurement() const
  141. {
  142. return item.shortcutKeyDescription.isNotEmpty() ? item.text + " " + item.shortcutKeyDescription
  143. : item.text;
  144. }
  145. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent)
  146. };
  147. //==============================================================================
  148. class MenuWindow : public Component
  149. {
  150. public:
  151. MenuWindow (const PopupMenu& menu, MenuWindow* const parentWindow,
  152. const Options& opts,
  153. const bool alignToRectangle,
  154. const bool shouldDismissOnMouseUp,
  155. ApplicationCommandManager** const manager)
  156. : Component ("menu"),
  157. parent (parentWindow),
  158. options (opts),
  159. managerOfChosenCommand (manager),
  160. componentAttachedTo (options.targetComponent),
  161. hasBeenOver (false),
  162. needsToScroll (false),
  163. dismissOnMouseUp (shouldDismissOnMouseUp),
  164. hideOnExit (false),
  165. disableMouseMoves (false),
  166. hasAnyJuceCompHadFocus (false),
  167. numColumns (0),
  168. contentHeight (0),
  169. childYOffset (0),
  170. windowCreationTime (Time::getMillisecondCounter()),
  171. lastFocusedTime (windowCreationTime),
  172. timeEnteredCurrentChildComp (windowCreationTime)
  173. {
  174. setWantsKeyboardFocus (false);
  175. setMouseClickGrabsKeyboardFocus (false);
  176. setAlwaysOnTop (true);
  177. setLookAndFeel (parent != nullptr ? &(parent->getLookAndFeel())
  178. : menu.lookAndFeel.get());
  179. setOpaque (getLookAndFeel().findColour (PopupMenu::backgroundColourId).isOpaque()
  180. || ! Desktop::canUseSemiTransparentWindows());
  181. for (int i = 0; i < menu.items.size(); ++i)
  182. {
  183. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  184. if (i < menu.items.size() - 1 || ! item->isSeparator)
  185. items.add (new ItemComponent (*item, options.standardHeight, *this));
  186. }
  187. calculateWindowPos (options.targetArea, alignToRectangle);
  188. setTopLeftPosition (windowPos.getPosition());
  189. updateYPositions();
  190. if (options.visibleItemID != 0)
  191. {
  192. const int y = options.targetArea.getY() - windowPos.getY();
  193. ensureItemIsVisible (options.visibleItemID,
  194. isPositiveAndBelow (y, windowPos.getHeight()) ? y : -1);
  195. }
  196. resizeToBestWindowPos();
  197. addToDesktop (ComponentPeer::windowIsTemporary
  198. | ComponentPeer::windowIgnoresKeyPresses
  199. | getLookAndFeel().getMenuWindowFlags());
  200. getActiveWindows().add (this);
  201. Desktop::getInstance().addGlobalMouseListener (this);
  202. }
  203. ~MenuWindow()
  204. {
  205. getActiveWindows().removeFirstMatchingValue (this);
  206. Desktop::getInstance().removeGlobalMouseListener (this);
  207. activeSubMenu = nullptr;
  208. items.clear();
  209. }
  210. //==============================================================================
  211. void paint (Graphics& g) override
  212. {
  213. if (isOpaque())
  214. g.fillAll (Colours::white);
  215. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  216. }
  217. void paintOverChildren (Graphics& g) override
  218. {
  219. if (canScroll())
  220. {
  221. LookAndFeel& lf = getLookAndFeel();
  222. if (isTopScrollZoneActive())
  223. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  224. if (isBottomScrollZoneActive())
  225. {
  226. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  227. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  228. }
  229. }
  230. }
  231. //==============================================================================
  232. // hide this and all sub-comps
  233. void hide (const PopupMenu::Item* const item, const bool makeInvisible)
  234. {
  235. if (isVisible())
  236. {
  237. WeakReference<Component> deletionChecker (this);
  238. activeSubMenu = nullptr;
  239. currentChild = nullptr;
  240. if (item != nullptr
  241. && item->commandManager != nullptr
  242. && item->itemID != 0)
  243. {
  244. *managerOfChosenCommand = item->commandManager;
  245. }
  246. exitModalState (item != nullptr ? item->itemID : 0);
  247. if (makeInvisible && (deletionChecker != nullptr))
  248. setVisible (false);
  249. }
  250. }
  251. void dismissMenu (const PopupMenu::Item* const item)
  252. {
  253. if (parent != nullptr)
  254. {
  255. parent->dismissMenu (item);
  256. }
  257. else
  258. {
  259. if (item != nullptr)
  260. {
  261. // need a copy of this on the stack as the one passed in will get deleted during this call
  262. const PopupMenu::Item mi (*item);
  263. hide (&mi, false);
  264. }
  265. else
  266. {
  267. hide (nullptr, false);
  268. }
  269. }
  270. }
  271. //==============================================================================
  272. bool keyPressed (const KeyPress& key) override
  273. {
  274. if (key.isKeyCode (KeyPress::downKey))
  275. {
  276. selectNextItem (1);
  277. }
  278. else if (key.isKeyCode (KeyPress::upKey))
  279. {
  280. selectNextItem (-1);
  281. }
  282. else if (key.isKeyCode (KeyPress::leftKey))
  283. {
  284. if (parent != nullptr)
  285. {
  286. Component::SafePointer<MenuWindow> parentWindow (parent);
  287. ItemComponent* currentChildOfParent = parentWindow->currentChild;
  288. hide (nullptr, true);
  289. if (parentWindow != nullptr)
  290. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  291. disableTimerUntilMouseMoves();
  292. }
  293. else if (componentAttachedTo != nullptr)
  294. {
  295. componentAttachedTo->keyPressed (key);
  296. }
  297. }
  298. else if (key.isKeyCode (KeyPress::rightKey))
  299. {
  300. disableTimerUntilMouseMoves();
  301. if (showSubMenuFor (currentChild))
  302. {
  303. if (isSubMenuVisible())
  304. activeSubMenu->selectNextItem (1);
  305. }
  306. else if (componentAttachedTo != nullptr)
  307. {
  308. componentAttachedTo->keyPressed (key);
  309. }
  310. }
  311. else if (key.isKeyCode (KeyPress::returnKey))
  312. {
  313. triggerCurrentlyHighlightedItem();
  314. }
  315. else if (key.isKeyCode (KeyPress::escapeKey))
  316. {
  317. dismissMenu (nullptr);
  318. }
  319. else
  320. {
  321. return false;
  322. }
  323. return true;
  324. }
  325. void inputAttemptWhenModal() override
  326. {
  327. WeakReference<Component> deletionChecker (this);
  328. for (int i = mouseSourceStates.size(); --i >= 0;)
  329. {
  330. mouseSourceStates.getUnchecked(i)->timerCallback();
  331. if (deletionChecker == nullptr)
  332. return;
  333. }
  334. if (! isOverAnyMenu())
  335. {
  336. if (componentAttachedTo != nullptr)
  337. {
  338. // we want to dismiss the menu, but if we do it synchronously, then
  339. // the mouse-click will be allowed to pass through. That's good, except
  340. // when the user clicks on the button that originally popped the menu up,
  341. // as they'll expect the menu to go away, and in fact it'll just
  342. // come back. So only dismiss synchronously if they're not on the original
  343. // comp that we're attached to.
  344. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  345. if (componentAttachedTo->reallyContains (mousePos, true))
  346. {
  347. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  348. return;
  349. }
  350. }
  351. dismissMenu (nullptr);
  352. }
  353. }
  354. void handleCommandMessage (int commandId) override
  355. {
  356. Component::handleCommandMessage (commandId);
  357. if (commandId == PopupMenuSettings::dismissCommandId)
  358. dismissMenu (nullptr);
  359. }
  360. //==============================================================================
  361. void mouseMove (const MouseEvent& e) override { handleMouseEvent (e); }
  362. void mouseDown (const MouseEvent& e) override { handleMouseEvent (e); }
  363. void mouseDrag (const MouseEvent& e) override { handleMouseEvent (e); }
  364. void mouseUp (const MouseEvent& e) override { handleMouseEvent (e); }
  365. void mouseWheelMove (const MouseEvent&, const MouseWheelDetails& wheel) override
  366. {
  367. alterChildYPos (roundToInt (-10.0f * wheel.deltaY * PopupMenuSettings::scrollZone));
  368. }
  369. void handleMouseEvent (const MouseEvent& e)
  370. {
  371. getMouseState (e.source).handleMouseEvent (e);
  372. }
  373. bool windowIsStillValid()
  374. {
  375. if (! isVisible())
  376. return false;
  377. if (componentAttachedTo != options.targetComponent)
  378. {
  379. dismissMenu (nullptr);
  380. return false;
  381. }
  382. if (MenuWindow* currentlyModalWindow = dynamic_cast<MenuWindow*> (Component::getCurrentlyModalComponent()))
  383. if (! treeContains (currentlyModalWindow))
  384. return false;
  385. return true;
  386. }
  387. static Array<MenuWindow*>& getActiveWindows()
  388. {
  389. static Array<MenuWindow*> activeMenuWindows;
  390. return activeMenuWindows;
  391. }
  392. MouseSourceState& getMouseState (MouseInputSource source)
  393. {
  394. for (int i = mouseSourceStates.size(); --i >= 0;)
  395. {
  396. MouseSourceState& ms = *mouseSourceStates.getUnchecked(i);
  397. if (ms.source == source)
  398. return ms;
  399. }
  400. MouseSourceState* ms = new MouseSourceState (*this, source);
  401. mouseSourceStates.add (ms);
  402. return *ms;
  403. }
  404. //==============================================================================
  405. bool isOverAnyMenu() const
  406. {
  407. return parent != nullptr ? parent->isOverAnyMenu()
  408. : isOverChildren();
  409. }
  410. bool isOverChildren() const
  411. {
  412. return isVisible()
  413. && (isAnyMouseOver() || (activeSubMenu != nullptr && activeSubMenu->isOverChildren()));
  414. }
  415. bool isAnyMouseOver() const
  416. {
  417. for (int i = 0; i < mouseSourceStates.size(); ++i)
  418. if (mouseSourceStates.getUnchecked(i)->isOver())
  419. return true;
  420. return false;
  421. }
  422. bool treeContains (const MenuWindow* const window) const noexcept
  423. {
  424. const MenuWindow* mw = this;
  425. while (mw->parent != nullptr)
  426. mw = mw->parent;
  427. while (mw != nullptr)
  428. {
  429. if (mw == window)
  430. return true;
  431. mw = mw->activeSubMenu;
  432. }
  433. return false;
  434. }
  435. bool doesAnyJuceCompHaveFocus()
  436. {
  437. bool anyFocused = Process::isForegroundProcess();
  438. if (anyFocused && Component::getCurrentlyFocusedComponent() == nullptr)
  439. {
  440. // because no component at all may have focus, our test here will
  441. // only be triggered when something has focus and then loses it.
  442. anyFocused = ! hasAnyJuceCompHadFocus;
  443. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  444. {
  445. if (ComponentPeer::getPeer (i)->isFocused())
  446. {
  447. anyFocused = true;
  448. hasAnyJuceCompHadFocus = true;
  449. break;
  450. }
  451. }
  452. }
  453. return anyFocused;
  454. }
  455. //==============================================================================
  456. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  457. {
  458. const Rectangle<int> mon (Desktop::getInstance().getDisplays()
  459. .getDisplayContaining (target.getCentre())
  460. #if JUCE_MAC
  461. .userArea);
  462. #else
  463. .totalArea); // on windows, don't stop the menu overlapping the taskbar
  464. #endif
  465. const int maxMenuHeight = mon.getHeight() - 24;
  466. int x, y, widthToUse, heightToUse;
  467. layoutMenuItems (mon.getWidth() - 24, maxMenuHeight, widthToUse, heightToUse);
  468. if (alignToRectangle)
  469. {
  470. x = target.getX();
  471. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  472. const int spaceOver = target.getY() - mon.getY();
  473. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  474. y = target.getBottom();
  475. else
  476. y = target.getY() - heightToUse;
  477. }
  478. else
  479. {
  480. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  481. if (parent != nullptr)
  482. {
  483. if (parent->parent != nullptr)
  484. {
  485. const bool parentGoingRight = (parent->getX() + parent->getWidth() / 2
  486. > parent->parent->getX() + parent->parent->getWidth() / 2);
  487. if (parentGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  488. tendTowardsRight = true;
  489. else if ((! parentGoingRight) && target.getX() > widthToUse + 4)
  490. tendTowardsRight = false;
  491. }
  492. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  493. {
  494. tendTowardsRight = true;
  495. }
  496. }
  497. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  498. target.getX() - mon.getX()) - 32;
  499. if (biggestSpace < widthToUse)
  500. {
  501. layoutMenuItems (biggestSpace + target.getWidth() / 3, maxMenuHeight, widthToUse, heightToUse);
  502. if (numColumns > 1)
  503. layoutMenuItems (biggestSpace - 4, maxMenuHeight, widthToUse, heightToUse);
  504. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  505. }
  506. if (tendTowardsRight)
  507. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  508. else
  509. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  510. y = target.getY();
  511. if (target.getCentreY() > mon.getCentreY())
  512. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  513. }
  514. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  515. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  516. windowPos.setBounds (x, y, widthToUse, heightToUse);
  517. // sets this flag if it's big enough to obscure any of its parent menus
  518. hideOnExit = parent != nullptr
  519. && parent->windowPos.intersects (windowPos.expanded (-4, -4));
  520. }
  521. void layoutMenuItems (const int maxMenuW, const int maxMenuH, int& width, int& height)
  522. {
  523. numColumns = 0;
  524. contentHeight = 0;
  525. int totalW;
  526. const int maximumNumColumns = options.maxColumns > 0 ? options.maxColumns : 7;
  527. do
  528. {
  529. ++numColumns;
  530. totalW = workOutBestSize (maxMenuW);
  531. if (totalW > maxMenuW)
  532. {
  533. numColumns = jmax (1, numColumns - 1);
  534. workOutBestSize (maxMenuW); // to update col widths
  535. break;
  536. }
  537. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  538. {
  539. break;
  540. }
  541. } while (numColumns < maximumNumColumns);
  542. const int actualH = jmin (contentHeight, maxMenuH);
  543. needsToScroll = contentHeight > actualH;
  544. width = updateYPositions();
  545. height = actualH + PopupMenuSettings::borderSize * 2;
  546. }
  547. int workOutBestSize (const int maxMenuW)
  548. {
  549. int totalW = 0;
  550. contentHeight = 0;
  551. int childNum = 0;
  552. for (int col = 0; col < numColumns; ++col)
  553. {
  554. int colW = options.standardHeight, colH = 0;
  555. const int numChildren = jmin (items.size() - childNum,
  556. (items.size() + numColumns - 1) / numColumns);
  557. for (int i = numChildren; --i >= 0;)
  558. {
  559. colW = jmax (colW, items.getUnchecked (childNum + i)->getWidth());
  560. colH += items.getUnchecked (childNum + i)->getHeight();
  561. }
  562. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  563. columnWidths.set (col, colW);
  564. totalW += colW;
  565. contentHeight = jmax (contentHeight, colH);
  566. childNum += numChildren;
  567. }
  568. if (totalW < options.minWidth)
  569. {
  570. totalW = options.minWidth;
  571. for (int col = 0; col < numColumns; ++col)
  572. columnWidths.set (0, totalW / numColumns);
  573. }
  574. return totalW;
  575. }
  576. void ensureItemIsVisible (const int itemID, int wantedY)
  577. {
  578. jassert (itemID != 0);
  579. for (int i = items.size(); --i >= 0;)
  580. {
  581. if (ItemComponent* const m = items.getUnchecked(i))
  582. {
  583. if (m->item.itemID == itemID
  584. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  585. {
  586. const int currentY = m->getY();
  587. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  588. {
  589. if (wantedY < 0)
  590. wantedY = jlimit (PopupMenuSettings::scrollZone,
  591. jmax (PopupMenuSettings::scrollZone,
  592. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  593. currentY);
  594. const Rectangle<int> mon (Desktop::getInstance().getDisplays()
  595. .getDisplayContaining (windowPos.getPosition()).userArea);
  596. int deltaY = wantedY - currentY;
  597. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  598. jmin (windowPos.getHeight(), mon.getHeight()));
  599. const int newY = jlimit (mon.getY(),
  600. mon.getBottom() - windowPos.getHeight(),
  601. windowPos.getY() + deltaY);
  602. deltaY -= newY - windowPos.getY();
  603. childYOffset -= deltaY;
  604. windowPos.setPosition (windowPos.getX(), newY);
  605. updateYPositions();
  606. }
  607. break;
  608. }
  609. }
  610. }
  611. }
  612. void resizeToBestWindowPos()
  613. {
  614. Rectangle<int> r (windowPos);
  615. if (childYOffset < 0)
  616. {
  617. r = r.withTop (r.getY() - childYOffset);
  618. }
  619. else if (childYOffset > 0)
  620. {
  621. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  622. if (spaceAtBottom > 0)
  623. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  624. }
  625. setBounds (r);
  626. updateYPositions();
  627. }
  628. void alterChildYPos (const int delta)
  629. {
  630. if (canScroll())
  631. {
  632. childYOffset += delta;
  633. if (delta < 0)
  634. childYOffset = jmax (childYOffset, 0);
  635. else if (delta > 0)
  636. childYOffset = jmin (childYOffset,
  637. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  638. updateYPositions();
  639. }
  640. else
  641. {
  642. childYOffset = 0;
  643. }
  644. resizeToBestWindowPos();
  645. repaint();
  646. }
  647. int updateYPositions()
  648. {
  649. int x = 0;
  650. int childNum = 0;
  651. for (int col = 0; col < numColumns; ++col)
  652. {
  653. const int numChildren = jmin (items.size() - childNum,
  654. (items.size() + numColumns - 1) / numColumns);
  655. const int colW = columnWidths [col];
  656. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  657. for (int i = 0; i < numChildren; ++i)
  658. {
  659. Component* const c = items.getUnchecked (childNum + i);
  660. c->setBounds (x, y, colW, c->getHeight());
  661. y += c->getHeight();
  662. }
  663. x += colW;
  664. childNum += numChildren;
  665. }
  666. return x;
  667. }
  668. void setCurrentlyHighlightedChild (ItemComponent* const child)
  669. {
  670. if (currentChild != nullptr)
  671. currentChild->setHighlighted (false);
  672. currentChild = child;
  673. if (currentChild != nullptr)
  674. {
  675. currentChild->setHighlighted (true);
  676. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  677. }
  678. }
  679. bool isSubMenuVisible() const noexcept { return activeSubMenu != nullptr && activeSubMenu->isVisible(); }
  680. bool showSubMenuFor (ItemComponent* const childComp)
  681. {
  682. activeSubMenu = nullptr;
  683. if (childComp != nullptr
  684. && hasActiveSubMenu (childComp->item))
  685. {
  686. activeSubMenu = new HelperClasses::MenuWindow (*(childComp->item.subMenu), this,
  687. options.withTargetScreenArea (childComp->getScreenBounds())
  688. .withMinimumWidth (0)
  689. .withTargetComponent (nullptr),
  690. false, dismissOnMouseUp, managerOfChosenCommand);
  691. activeSubMenu->setVisible (true); // (must be called before enterModalState on Windows to avoid DropShadower confusion)
  692. activeSubMenu->enterModalState (false);
  693. activeSubMenu->toFront (false);
  694. return true;
  695. }
  696. return false;
  697. }
  698. void triggerCurrentlyHighlightedItem()
  699. {
  700. if (currentChild != nullptr
  701. && canBeTriggered (currentChild->item)
  702. && (currentChild->item.customComponent == nullptr
  703. || currentChild->item.customComponent->isTriggeredAutomatically()))
  704. {
  705. dismissMenu (&currentChild->item);
  706. }
  707. }
  708. void selectNextItem (const int delta)
  709. {
  710. disableTimerUntilMouseMoves();
  711. int start = jmax (0, items.indexOf (currentChild));
  712. for (int i = items.size(); --i >= 0;)
  713. {
  714. start += delta;
  715. if (ItemComponent* mic = items.getUnchecked ((start + items.size()) % items.size()))
  716. {
  717. if (canBeTriggered (mic->item) || hasActiveSubMenu (mic->item))
  718. {
  719. setCurrentlyHighlightedChild (mic);
  720. break;
  721. }
  722. }
  723. }
  724. }
  725. void disableTimerUntilMouseMoves()
  726. {
  727. disableMouseMoves = true;
  728. if (parent != nullptr)
  729. parent->disableTimerUntilMouseMoves();
  730. }
  731. bool canScroll() const noexcept { return childYOffset != 0 || needsToScroll; }
  732. bool isTopScrollZoneActive() const noexcept { return canScroll() && childYOffset > 0; }
  733. bool isBottomScrollZoneActive() const noexcept { return canScroll() && childYOffset < contentHeight - windowPos.getHeight(); }
  734. //==============================================================================
  735. MenuWindow* parent;
  736. const Options options;
  737. OwnedArray<ItemComponent> items;
  738. ApplicationCommandManager** managerOfChosenCommand;
  739. WeakReference<Component> componentAttachedTo;
  740. Rectangle<int> windowPos;
  741. bool hasBeenOver, needsToScroll;
  742. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  743. int numColumns, contentHeight, childYOffset;
  744. Component::SafePointer<ItemComponent> currentChild;
  745. ScopedPointer<MenuWindow> activeSubMenu;
  746. Array<int> columnWidths;
  747. uint32 windowCreationTime, lastFocusedTime, timeEnteredCurrentChildComp;
  748. OwnedArray<MouseSourceState> mouseSourceStates;
  749. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuWindow)
  750. };
  751. //==============================================================================
  752. class MouseSourceState : private Timer
  753. {
  754. public:
  755. MouseSourceState (MenuWindow& w, MouseInputSource s)
  756. : window (w), source (s), scrollAcceleration (1.0),
  757. lastScrollTime (Time::getMillisecondCounter()),
  758. lastMouseMoveTime (0), isDown (false)
  759. {
  760. }
  761. void handleMouseEvent (const MouseEvent& e)
  762. {
  763. if (! window.windowIsStillValid())
  764. return;
  765. startTimerHz (20);
  766. handleMousePosition (e.getScreenPosition());
  767. }
  768. void timerCallback() override
  769. {
  770. if (window.windowIsStillValid())
  771. handleMousePosition (source.getScreenPosition().roundToInt());
  772. }
  773. bool isOver() const
  774. {
  775. return window.reallyContains (window.getLocalPoint (nullptr, source.getScreenPosition()).roundToInt(), true);
  776. }
  777. MenuWindow& window;
  778. MouseInputSource source;
  779. private:
  780. Point<int> lastMousePos;
  781. double scrollAcceleration;
  782. uint32 lastScrollTime, lastMouseMoveTime;
  783. bool isDown;
  784. void handleMousePosition (Point<int> globalMousePos)
  785. {
  786. const Point<int> localMousePos (window.getLocalPoint (nullptr, globalMousePos));
  787. const uint32 timeNow = Time::getMillisecondCounter();
  788. if (timeNow > window.timeEnteredCurrentChildComp + 100
  789. && window.reallyContains (localMousePos, true)
  790. && window.currentChild != nullptr
  791. && ! (window.disableMouseMoves || window.isSubMenuVisible()))
  792. {
  793. window.showSubMenuFor (window.currentChild);
  794. }
  795. highlightItemUnderMouse (globalMousePos, localMousePos, timeNow);
  796. const bool overScrollArea = scrollIfNecessary (localMousePos, timeNow);
  797. const bool isOverAny = window.isOverAnyMenu();
  798. if (window.hideOnExit && window.hasBeenOver && ! isOverAny)
  799. window.hide (nullptr, true);
  800. else
  801. checkButtonState (localMousePos, timeNow, isDown, overScrollArea, isOverAny);
  802. }
  803. void checkButtonState (Point<int> localMousePos, const uint32 timeNow,
  804. const bool wasDown, const bool overScrollArea, const bool isOverAny)
  805. {
  806. isDown = window.hasBeenOver
  807. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  808. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  809. if (! window.doesAnyJuceCompHaveFocus())
  810. {
  811. if (timeNow > window.lastFocusedTime + 10)
  812. {
  813. PopupMenuSettings::menuWasHiddenBecauseOfAppChange = true;
  814. window.dismissMenu (nullptr);
  815. // Note: this object may have been deleted by the previous call..
  816. }
  817. }
  818. else if (wasDown && timeNow > window.windowCreationTime + 250
  819. && ! (isDown || overScrollArea))
  820. {
  821. if (window.reallyContains (localMousePos, true))
  822. window.triggerCurrentlyHighlightedItem();
  823. else if ((window.hasBeenOver || ! window.dismissOnMouseUp) && ! isOverAny)
  824. window.dismissMenu (nullptr);
  825. // Note: this object may have been deleted by the previous call..
  826. }
  827. else
  828. {
  829. window.lastFocusedTime = timeNow;
  830. }
  831. }
  832. void highlightItemUnderMouse (Point<int> globalMousePos, Point<int> localMousePos, const uint32 timeNow)
  833. {
  834. if (globalMousePos != lastMousePos || timeNow > lastMouseMoveTime + 350)
  835. {
  836. const bool isMouseOver = window.reallyContains (localMousePos, true);
  837. if (isMouseOver)
  838. window.hasBeenOver = true;
  839. if (lastMousePos.getDistanceFrom (globalMousePos) > 2)
  840. {
  841. lastMouseMoveTime = timeNow;
  842. if (window.disableMouseMoves && isMouseOver)
  843. window.disableMouseMoves = false;
  844. }
  845. if (window.disableMouseMoves || (window.activeSubMenu != nullptr && window.activeSubMenu->isOverChildren()))
  846. return;
  847. const bool isMovingTowardsMenu = isMouseOver && globalMousePos != lastMousePos
  848. && isMovingTowardsSubmenu (globalMousePos);
  849. lastMousePos = globalMousePos;
  850. if (! isMovingTowardsMenu)
  851. {
  852. Component* c = window.getComponentAt (localMousePos);
  853. if (c == &window)
  854. c = nullptr;
  855. ItemComponent* itemUnderMouse = dynamic_cast<ItemComponent*> (c);
  856. if (itemUnderMouse == nullptr && c != nullptr)
  857. itemUnderMouse = c->findParentComponentOfClass<ItemComponent>();
  858. if (itemUnderMouse != window.currentChild
  859. && (isMouseOver || (window.activeSubMenu == nullptr) || ! window.activeSubMenu->isVisible()))
  860. {
  861. if (isMouseOver && (c != nullptr) && (window.activeSubMenu != nullptr))
  862. window.activeSubMenu->hide (nullptr, true);
  863. if (! isMouseOver)
  864. itemUnderMouse = nullptr;
  865. window.setCurrentlyHighlightedChild (itemUnderMouse);
  866. }
  867. }
  868. }
  869. }
  870. bool isMovingTowardsSubmenu (Point<int> newGlobalPos) const
  871. {
  872. if (window.activeSubMenu == nullptr)
  873. return false;
  874. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  875. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  876. // extends from the last mouse pos to the submenu's rectangle..
  877. const Rectangle<int> itemScreenBounds (window.activeSubMenu->getScreenBounds());
  878. float subX = (float) itemScreenBounds.getX();
  879. Point<int> oldGlobalPos (lastMousePos);
  880. if (itemScreenBounds.getX() > window.getX())
  881. {
  882. oldGlobalPos -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  883. }
  884. else
  885. {
  886. oldGlobalPos += Point<int> (2, 0);
  887. subX += itemScreenBounds.getWidth();
  888. }
  889. Path areaTowardsSubMenu;
  890. areaTowardsSubMenu.addTriangle ((float) oldGlobalPos.x, (float) oldGlobalPos.y,
  891. subX, (float) itemScreenBounds.getY(),
  892. subX, (float) itemScreenBounds.getBottom());
  893. return areaTowardsSubMenu.contains (newGlobalPos.toFloat());
  894. }
  895. bool scrollIfNecessary (Point<int> localMousePos, const uint32 timeNow)
  896. {
  897. if (window.canScroll()
  898. && isPositiveAndBelow (localMousePos.x, window.getWidth())
  899. && (isPositiveAndBelow (localMousePos.y, window.getHeight()) || source.isDragging()))
  900. {
  901. if (window.isTopScrollZoneActive() && localMousePos.y < PopupMenuSettings::scrollZone)
  902. return scroll (timeNow, -1);
  903. if (window.isBottomScrollZoneActive() && localMousePos.y > window.getHeight() - PopupMenuSettings::scrollZone)
  904. return scroll (timeNow, 1);
  905. }
  906. scrollAcceleration = 1.0;
  907. return false;
  908. }
  909. bool scroll (const uint32 timeNow, const int direction)
  910. {
  911. if (timeNow > lastScrollTime + 20)
  912. {
  913. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  914. int amount = 0;
  915. for (int i = 0; i < window.items.size() && amount == 0; ++i)
  916. amount = ((int) scrollAcceleration) * window.items.getUnchecked(i)->getHeight();
  917. window.alterChildYPos (amount * direction);
  918. lastScrollTime = timeNow;
  919. }
  920. return true;
  921. }
  922. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MouseSourceState)
  923. };
  924. //==============================================================================
  925. struct NormalComponentWrapper : public PopupMenu::CustomComponent
  926. {
  927. NormalComponentWrapper (Component* const comp, const int w, const int h,
  928. const bool triggerMenuItemAutomaticallyWhenClicked)
  929. : PopupMenu::CustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  930. width (w), height (h)
  931. {
  932. addAndMakeVisible (comp);
  933. }
  934. void getIdealSize (int& idealWidth, int& idealHeight) override
  935. {
  936. idealWidth = width;
  937. idealHeight = height;
  938. }
  939. void resized() override
  940. {
  941. if (Component* const child = getChildComponent(0))
  942. child->setBounds (getLocalBounds());
  943. }
  944. const int width, height;
  945. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NormalComponentWrapper)
  946. };
  947. };
  948. //==============================================================================
  949. PopupMenu::PopupMenu()
  950. {
  951. }
  952. PopupMenu::PopupMenu (const PopupMenu& other)
  953. : lookAndFeel (other.lookAndFeel)
  954. {
  955. items.addCopiesOf (other.items);
  956. }
  957. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  958. {
  959. if (this != &other)
  960. {
  961. lookAndFeel = other.lookAndFeel;
  962. clear();
  963. items.addCopiesOf (other.items);
  964. }
  965. return *this;
  966. }
  967. #if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
  968. PopupMenu::PopupMenu (PopupMenu&& other) noexcept
  969. : lookAndFeel (other.lookAndFeel)
  970. {
  971. items.swapWith (other.items);
  972. }
  973. PopupMenu& PopupMenu::operator= (PopupMenu&& other) noexcept
  974. {
  975. jassert (this != &other); // hopefully the compiler should make this situation impossible!
  976. items.swapWith (other.items);
  977. lookAndFeel = other.lookAndFeel;
  978. return *this;
  979. }
  980. #endif
  981. PopupMenu::~PopupMenu()
  982. {
  983. }
  984. void PopupMenu::clear()
  985. {
  986. items.clear();
  987. }
  988. //==============================================================================
  989. PopupMenu::Item::Item() noexcept
  990. : itemID (0),
  991. commandManager (nullptr),
  992. colour (0x00000000),
  993. isEnabled (true),
  994. isTicked (false),
  995. isSeparator (false),
  996. isSectionHeader (false)
  997. {
  998. }
  999. PopupMenu::Item::Item (const Item& other)
  1000. : text (other.text),
  1001. itemID (other.itemID),
  1002. subMenu (createCopyIfNotNull (other.subMenu.get())),
  1003. image (other.image != nullptr ? other.image->createCopy() : nullptr),
  1004. customComponent (other.customComponent),
  1005. commandManager (other.commandManager),
  1006. shortcutKeyDescription (other.shortcutKeyDescription),
  1007. colour (other.colour),
  1008. isEnabled (other.isEnabled),
  1009. isTicked (other.isTicked),
  1010. isSeparator (other.isSeparator),
  1011. isSectionHeader (other.isSectionHeader)
  1012. {
  1013. }
  1014. PopupMenu::Item& PopupMenu::Item::operator= (const Item& other)
  1015. {
  1016. text = other.text;
  1017. itemID = other.itemID;
  1018. subMenu = createCopyIfNotNull (other.subMenu.get());
  1019. image = (other.image != nullptr ? other.image->createCopy() : nullptr);
  1020. customComponent = other.customComponent;
  1021. commandManager = other.commandManager;
  1022. shortcutKeyDescription = other.shortcutKeyDescription;
  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. }