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.

1818 lines
60KB

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