Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1821 lines
61KB

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