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.

1797 lines
60KB

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