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.

1860 lines
62KB

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