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.

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