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.

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