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.

1881 lines
63KB

  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 JUCE_WINDOWS
  824. // touch and pen devices on Windows send an offscreen mouse move after mouse up events
  825. // but we don't want to forward these on as they will dismiss the menu
  826. if ((source.isTouch() || source.isPen()) && ! isValidMousePosition())
  827. return;
  828. #endif
  829. if (window.windowIsStillValid())
  830. handleMousePosition (source.getScreenPosition().roundToInt());
  831. }
  832. bool isOver() const
  833. {
  834. return window.reallyContains (window.getLocalPoint (nullptr, source.getScreenPosition()).roundToInt(), true);
  835. }
  836. MenuWindow& window;
  837. MouseInputSource source;
  838. private:
  839. Point<int> lastMousePos;
  840. double scrollAcceleration = 0;
  841. uint32 lastScrollTime, lastMouseMoveTime = 0;
  842. bool isDown = false;
  843. void handleMousePosition (Point<int> globalMousePos)
  844. {
  845. auto localMousePos = window.getLocalPoint (nullptr, globalMousePos);
  846. auto timeNow = Time::getMillisecondCounter();
  847. if (timeNow > window.timeEnteredCurrentChildComp + 100
  848. && window.reallyContains (localMousePos, true)
  849. && window.currentChild != nullptr
  850. && ! (window.disableMouseMoves || window.isSubMenuVisible()))
  851. {
  852. window.showSubMenuFor (window.currentChild);
  853. }
  854. highlightItemUnderMouse (globalMousePos, localMousePos, timeNow);
  855. const bool overScrollArea = scrollIfNecessary (localMousePos, timeNow);
  856. const bool isOverAny = window.isOverAnyMenu();
  857. if (window.hideOnExit && window.hasBeenOver && ! isOverAny)
  858. window.hide (nullptr, true);
  859. else
  860. checkButtonState (localMousePos, timeNow, isDown, overScrollArea, isOverAny);
  861. }
  862. void checkButtonState (Point<int> localMousePos, const uint32 timeNow,
  863. const bool wasDown, const bool overScrollArea, const bool isOverAny)
  864. {
  865. isDown = window.hasBeenOver
  866. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  867. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  868. if (! window.doesAnyJuceCompHaveFocus())
  869. {
  870. if (timeNow > window.lastFocusedTime + 10)
  871. {
  872. PopupMenuSettings::menuWasHiddenBecauseOfAppChange = true;
  873. window.dismissMenu (nullptr);
  874. // Note: this object may have been deleted by the previous call..
  875. }
  876. }
  877. else if (wasDown && timeNow > window.windowCreationTime + 250
  878. && ! (isDown || overScrollArea))
  879. {
  880. if (window.reallyContains (localMousePos, true))
  881. window.triggerCurrentlyHighlightedItem();
  882. else if ((window.hasBeenOver || ! window.dismissOnMouseUp) && ! isOverAny)
  883. window.dismissMenu (nullptr);
  884. // Note: this object may have been deleted by the previous call..
  885. }
  886. else
  887. {
  888. window.lastFocusedTime = timeNow;
  889. }
  890. }
  891. void highlightItemUnderMouse (Point<int> globalMousePos, Point<int> localMousePos, const uint32 timeNow)
  892. {
  893. if (globalMousePos != lastMousePos || timeNow > lastMouseMoveTime + 350)
  894. {
  895. const bool isMouseOver = window.reallyContains (localMousePos, true);
  896. if (isMouseOver)
  897. window.hasBeenOver = true;
  898. if (lastMousePos.getDistanceFrom (globalMousePos) > 2)
  899. {
  900. lastMouseMoveTime = timeNow;
  901. if (window.disableMouseMoves && isMouseOver)
  902. window.disableMouseMoves = false;
  903. }
  904. if (window.disableMouseMoves || (window.activeSubMenu != nullptr && window.activeSubMenu->isOverChildren()))
  905. return;
  906. const bool isMovingTowardsMenu = isMouseOver && globalMousePos != lastMousePos
  907. && isMovingTowardsSubmenu (globalMousePos);
  908. lastMousePos = globalMousePos;
  909. if (! isMovingTowardsMenu)
  910. {
  911. auto* c = window.getComponentAt (localMousePos);
  912. if (c == &window)
  913. c = nullptr;
  914. auto* itemUnderMouse = dynamic_cast<ItemComponent*> (c);
  915. if (itemUnderMouse == nullptr && c != nullptr)
  916. itemUnderMouse = c->findParentComponentOfClass<ItemComponent>();
  917. if (itemUnderMouse != window.currentChild
  918. && (isMouseOver || (window.activeSubMenu == nullptr) || ! window.activeSubMenu->isVisible()))
  919. {
  920. if (isMouseOver && (c != nullptr) && (window.activeSubMenu != nullptr))
  921. window.activeSubMenu->hide (nullptr, true);
  922. if (! isMouseOver)
  923. itemUnderMouse = nullptr;
  924. window.setCurrentlyHighlightedChild (itemUnderMouse);
  925. }
  926. }
  927. }
  928. }
  929. bool isMovingTowardsSubmenu (Point<int> newGlobalPos) const
  930. {
  931. if (window.activeSubMenu == nullptr)
  932. return false;
  933. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  934. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  935. // extends from the last mouse pos to the submenu's rectangle..
  936. auto itemScreenBounds = window.activeSubMenu->getScreenBounds();
  937. auto subX = (float) itemScreenBounds.getX();
  938. auto oldGlobalPos = lastMousePos;
  939. if (itemScreenBounds.getX() > window.getX())
  940. {
  941. oldGlobalPos -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  942. }
  943. else
  944. {
  945. oldGlobalPos += Point<int> (2, 0);
  946. subX += itemScreenBounds.getWidth();
  947. }
  948. Path areaTowardsSubMenu;
  949. areaTowardsSubMenu.addTriangle ((float) oldGlobalPos.x, (float) oldGlobalPos.y,
  950. subX, (float) itemScreenBounds.getY(),
  951. subX, (float) itemScreenBounds.getBottom());
  952. return areaTowardsSubMenu.contains (newGlobalPos.toFloat());
  953. }
  954. bool scrollIfNecessary (Point<int> localMousePos, const uint32 timeNow)
  955. {
  956. if (window.canScroll()
  957. && isPositiveAndBelow (localMousePos.x, window.getWidth())
  958. && (isPositiveAndBelow (localMousePos.y, window.getHeight()) || source.isDragging()))
  959. {
  960. if (window.isTopScrollZoneActive() && localMousePos.y < PopupMenuSettings::scrollZone)
  961. return scroll (timeNow, -1);
  962. if (window.isBottomScrollZoneActive() && localMousePos.y > window.getHeight() - PopupMenuSettings::scrollZone)
  963. return scroll (timeNow, 1);
  964. }
  965. scrollAcceleration = 1.0;
  966. return false;
  967. }
  968. bool scroll (const uint32 timeNow, const int direction)
  969. {
  970. if (timeNow > lastScrollTime + 20)
  971. {
  972. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  973. int amount = 0;
  974. for (int i = 0; i < window.items.size() && amount == 0; ++i)
  975. amount = ((int) scrollAcceleration) * window.items.getUnchecked (i)->getHeight();
  976. window.alterChildYPos (amount * direction);
  977. lastScrollTime = timeNow;
  978. }
  979. return true;
  980. }
  981. #if JUCE_WINDOWS
  982. bool isValidMousePosition()
  983. {
  984. auto screenPos = source.getScreenPosition();
  985. auto localPos = (window.activeSubMenu == nullptr) ? window.getLocalPoint (nullptr, screenPos)
  986. : window.activeSubMenu->getLocalPoint (nullptr, screenPos);
  987. if (localPos.x < 0 && localPos.y < 0)
  988. return false;
  989. return true;
  990. }
  991. #endif
  992. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MouseSourceState)
  993. };
  994. //==============================================================================
  995. struct NormalComponentWrapper : public PopupMenu::CustomComponent
  996. {
  997. NormalComponentWrapper (Component* comp, int w, int h, bool triggerMenuItemAutomaticallyWhenClicked)
  998. : PopupMenu::CustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  999. width (w), height (h)
  1000. {
  1001. addAndMakeVisible (comp);
  1002. }
  1003. void getIdealSize (int& idealWidth, int& idealHeight) override
  1004. {
  1005. idealWidth = width;
  1006. idealHeight = height;
  1007. }
  1008. void resized() override
  1009. {
  1010. if (auto* child = getChildComponent (0))
  1011. child->setBounds (getLocalBounds());
  1012. }
  1013. const int width, height;
  1014. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NormalComponentWrapper)
  1015. };
  1016. };
  1017. //==============================================================================
  1018. PopupMenu::PopupMenu()
  1019. {
  1020. }
  1021. PopupMenu::PopupMenu (const PopupMenu& other)
  1022. : lookAndFeel (other.lookAndFeel)
  1023. {
  1024. items.addCopiesOf (other.items);
  1025. }
  1026. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  1027. {
  1028. if (this != &other)
  1029. {
  1030. lookAndFeel = other.lookAndFeel;
  1031. clear();
  1032. items.addCopiesOf (other.items);
  1033. }
  1034. return *this;
  1035. }
  1036. PopupMenu::PopupMenu (PopupMenu&& other) noexcept
  1037. : lookAndFeel (other.lookAndFeel)
  1038. {
  1039. items.swapWith (other.items);
  1040. }
  1041. PopupMenu& PopupMenu::operator= (PopupMenu&& other) noexcept
  1042. {
  1043. jassert (this != &other); // hopefully the compiler should make this situation impossible!
  1044. items.swapWith (other.items);
  1045. lookAndFeel = other.lookAndFeel;
  1046. return *this;
  1047. }
  1048. PopupMenu::~PopupMenu()
  1049. {
  1050. }
  1051. void PopupMenu::clear()
  1052. {
  1053. items.clear();
  1054. }
  1055. //==============================================================================
  1056. PopupMenu::Item::Item() noexcept
  1057. : itemID (0),
  1058. commandManager (nullptr),
  1059. colour (0x00000000),
  1060. isEnabled (true),
  1061. isTicked (false),
  1062. isSeparator (false),
  1063. isSectionHeader (false)
  1064. {
  1065. }
  1066. PopupMenu::Item::Item (const Item& other)
  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. {
  1081. }
  1082. PopupMenu::Item& PopupMenu::Item::operator= (const Item& other)
  1083. {
  1084. text = other.text;
  1085. itemID = other.itemID;
  1086. subMenu = createCopyIfNotNull (other.subMenu.get());
  1087. image = (other.image != nullptr ? other.image->createCopy() : nullptr);
  1088. customComponent = other.customComponent;
  1089. customCallback = other.customCallback;
  1090. commandManager = other.commandManager;
  1091. shortcutKeyDescription = other.shortcutKeyDescription;
  1092. colour = other.colour;
  1093. isEnabled = other.isEnabled;
  1094. isTicked = other.isTicked;
  1095. isSeparator = other.isSeparator;
  1096. isSectionHeader = other.isSectionHeader;
  1097. return *this;
  1098. }
  1099. void PopupMenu::addItem (const Item& newItem)
  1100. {
  1101. // An ID of 0 is used as a return value to indicate that the user
  1102. // didn't pick anything, so you shouldn't use it as the ID for an item..
  1103. jassert (newItem.itemID != 0
  1104. || newItem.isSeparator || newItem.isSectionHeader
  1105. || newItem.subMenu != nullptr);
  1106. items.add (new Item (newItem));
  1107. }
  1108. void PopupMenu::addItem (int itemResultID, const String& itemText, bool isActive, bool isTicked)
  1109. {
  1110. Item i;
  1111. i.text = itemText;
  1112. i.itemID = itemResultID;
  1113. i.isEnabled = isActive;
  1114. i.isTicked = isTicked;
  1115. addItem (i);
  1116. }
  1117. static Drawable* createDrawableFromImage (const Image& im)
  1118. {
  1119. if (im.isValid())
  1120. {
  1121. auto d = new DrawableImage();
  1122. d->setImage (im);
  1123. return d;
  1124. }
  1125. return nullptr;
  1126. }
  1127. void PopupMenu::addItem (int itemResultID, const String& itemText, bool isActive, bool isTicked, const Image& iconToUse)
  1128. {
  1129. addItem (itemResultID, itemText, isActive, isTicked, createDrawableFromImage (iconToUse));
  1130. }
  1131. void PopupMenu::addItem (int itemResultID, const String& itemText, bool isActive, bool isTicked, Drawable* iconToUse)
  1132. {
  1133. Item i;
  1134. i.text = itemText;
  1135. i.itemID = itemResultID;
  1136. i.isEnabled = isActive;
  1137. i.isTicked = isTicked;
  1138. i.image = iconToUse;
  1139. addItem (i);
  1140. }
  1141. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  1142. const CommandID commandID,
  1143. const String& displayName,
  1144. Drawable* iconToUse)
  1145. {
  1146. jassert (commandManager != nullptr && commandID != 0);
  1147. if (auto* registeredInfo = commandManager->getCommandForID (commandID))
  1148. {
  1149. ApplicationCommandInfo info (*registeredInfo);
  1150. auto* target = commandManager->getTargetForCommand (commandID, info);
  1151. Item i;
  1152. i.text = displayName.isNotEmpty() ? displayName : info.shortName;
  1153. i.itemID = (int) commandID;
  1154. i.commandManager = commandManager;
  1155. i.isEnabled = target != nullptr && (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  1156. i.isTicked = (info.flags & ApplicationCommandInfo::isTicked) != 0;
  1157. i.image = iconToUse;
  1158. addItem (i);
  1159. }
  1160. }
  1161. void PopupMenu::addColouredItem (int itemResultID, const String& itemText, Colour itemTextColour,
  1162. bool isActive, bool isTicked, Drawable* iconToUse)
  1163. {
  1164. Item i;
  1165. i.text = itemText;
  1166. i.itemID = itemResultID;
  1167. i.colour = itemTextColour;
  1168. i.isEnabled = isActive;
  1169. i.isTicked = isTicked;
  1170. i.image = iconToUse;
  1171. addItem (i);
  1172. }
  1173. void PopupMenu::addColouredItem (int itemResultID, const String& itemText, Colour itemTextColour,
  1174. bool isActive, bool isTicked, const Image& iconToUse)
  1175. {
  1176. Item i;
  1177. i.text = itemText;
  1178. i.itemID = itemResultID;
  1179. i.colour = itemTextColour;
  1180. i.isEnabled = isActive;
  1181. i.isTicked = isTicked;
  1182. i.image = createDrawableFromImage (iconToUse);
  1183. addItem (i);
  1184. }
  1185. void PopupMenu::addCustomItem (int itemResultID, CustomComponent* cc, const PopupMenu* subMenu)
  1186. {
  1187. Item i;
  1188. i.itemID = itemResultID;
  1189. i.customComponent = cc;
  1190. i.subMenu = createCopyIfNotNull (subMenu);
  1191. addItem (i);
  1192. }
  1193. void PopupMenu::addCustomItem (int itemResultID, Component* customComponent, int idealWidth, int idealHeight,
  1194. bool triggerMenuItemAutomaticallyWhenClicked, const PopupMenu* subMenu)
  1195. {
  1196. addCustomItem (itemResultID,
  1197. new HelperClasses::NormalComponentWrapper (customComponent, idealWidth, idealHeight,
  1198. triggerMenuItemAutomaticallyWhenClicked),
  1199. subMenu);
  1200. }
  1201. void PopupMenu::addSubMenu (const String& subMenuName, const PopupMenu& subMenu, bool isActive)
  1202. {
  1203. addSubMenu (subMenuName, subMenu, isActive, nullptr, false, 0);
  1204. }
  1205. void PopupMenu::addSubMenu (const String& subMenuName, const PopupMenu& subMenu, bool isActive,
  1206. const Image& iconToUse, bool isTicked, int itemResultID)
  1207. {
  1208. addSubMenu (subMenuName, subMenu, isActive, createDrawableFromImage (iconToUse), isTicked, itemResultID);
  1209. }
  1210. void PopupMenu::addSubMenu (const String& subMenuName, const PopupMenu& subMenu, bool isActive,
  1211. Drawable* iconToUse, bool isTicked, int itemResultID)
  1212. {
  1213. Item i;
  1214. i.text = subMenuName;
  1215. i.itemID = itemResultID;
  1216. i.subMenu = new PopupMenu (subMenu);
  1217. i.isEnabled = isActive && (itemResultID != 0 || subMenu.getNumItems() > 0);
  1218. i.isTicked = isTicked;
  1219. i.image = iconToUse;
  1220. addItem (i);
  1221. }
  1222. void PopupMenu::addSeparator()
  1223. {
  1224. if (items.size() > 0 && ! items.getLast()->isSeparator)
  1225. {
  1226. Item i;
  1227. i.isSeparator = true;
  1228. addItem (i);
  1229. }
  1230. }
  1231. void PopupMenu::addSectionHeader (const String& title)
  1232. {
  1233. Item i;
  1234. i.text = title;
  1235. i.isSectionHeader = true;
  1236. addItem (i);
  1237. }
  1238. //==============================================================================
  1239. PopupMenu::Options::Options()
  1240. : targetComponent (nullptr),
  1241. parentComponent (nullptr),
  1242. visibleItemID (0),
  1243. minWidth (0),
  1244. maxColumns (0),
  1245. standardHeight (0)
  1246. {
  1247. targetArea.setPosition (Desktop::getMousePosition());
  1248. }
  1249. PopupMenu::Options PopupMenu::Options::withTargetComponent (Component* comp) const noexcept
  1250. {
  1251. Options o (*this);
  1252. o.targetComponent = comp;
  1253. if (comp != nullptr)
  1254. o.targetArea = comp->getScreenBounds();
  1255. return o;
  1256. }
  1257. PopupMenu::Options PopupMenu::Options::withTargetScreenArea (const Rectangle<int>& area) const noexcept
  1258. {
  1259. Options o (*this);
  1260. o.targetArea = area;
  1261. return o;
  1262. }
  1263. PopupMenu::Options PopupMenu::Options::withMinimumWidth (int w) const noexcept
  1264. {
  1265. Options o (*this);
  1266. o.minWidth = w;
  1267. return o;
  1268. }
  1269. PopupMenu::Options PopupMenu::Options::withMaximumNumColumns (int cols) const noexcept
  1270. {
  1271. Options o (*this);
  1272. o.maxColumns = cols;
  1273. return o;
  1274. }
  1275. PopupMenu::Options PopupMenu::Options::withStandardItemHeight (int height) const noexcept
  1276. {
  1277. Options o (*this);
  1278. o.standardHeight = height;
  1279. return o;
  1280. }
  1281. PopupMenu::Options PopupMenu::Options::withItemThatMustBeVisible (int idOfItemToBeVisible) const noexcept
  1282. {
  1283. Options o (*this);
  1284. o.visibleItemID = idOfItemToBeVisible;
  1285. return o;
  1286. }
  1287. PopupMenu::Options PopupMenu::Options::withParentComponent (Component* parent) const noexcept
  1288. {
  1289. Options o (*this);
  1290. o.parentComponent = parent;
  1291. return o;
  1292. }
  1293. Component* PopupMenu::createWindow (const Options& options,
  1294. ApplicationCommandManager** managerOfChosenCommand) const
  1295. {
  1296. if (items.size() > 0)
  1297. return new HelperClasses::MenuWindow (*this, nullptr, options,
  1298. ! options.targetArea.isEmpty(),
  1299. ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  1300. managerOfChosenCommand);
  1301. return nullptr;
  1302. }
  1303. //==============================================================================
  1304. // This invokes any command manager commands and deletes the menu window when it is dismissed
  1305. struct PopupMenuCompletionCallback : public ModalComponentManager::Callback
  1306. {
  1307. PopupMenuCompletionCallback()
  1308. : prevFocused (Component::getCurrentlyFocusedComponent()),
  1309. prevTopLevel (prevFocused != nullptr ? prevFocused->getTopLevelComponent() : nullptr)
  1310. {
  1311. PopupMenuSettings::menuWasHiddenBecauseOfAppChange = false;
  1312. }
  1313. void modalStateFinished (int result) override
  1314. {
  1315. if (managerOfChosenCommand != nullptr && result != 0)
  1316. {
  1317. ApplicationCommandTarget::InvocationInfo info (result);
  1318. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  1319. managerOfChosenCommand->invoke (info, true);
  1320. }
  1321. // (this would be the place to fade out the component, if that's what's required)
  1322. component = nullptr;
  1323. if (! PopupMenuSettings::menuWasHiddenBecauseOfAppChange)
  1324. {
  1325. if (prevTopLevel != nullptr)
  1326. prevTopLevel->toFront (true);
  1327. if (prevFocused != nullptr)
  1328. prevFocused->grabKeyboardFocus();
  1329. }
  1330. }
  1331. ApplicationCommandManager* managerOfChosenCommand = nullptr;
  1332. ScopedPointer<Component> component;
  1333. WeakReference<Component> prevFocused, prevTopLevel;
  1334. JUCE_DECLARE_NON_COPYABLE (PopupMenuCompletionCallback)
  1335. };
  1336. int PopupMenu::showWithOptionalCallback (const Options& options, ModalComponentManager::Callback* const userCallback,
  1337. const bool canBeModal)
  1338. {
  1339. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  1340. ScopedPointer<PopupMenuCompletionCallback> callback (new PopupMenuCompletionCallback());
  1341. if (auto* window = createWindow (options, &(callback->managerOfChosenCommand)))
  1342. {
  1343. callback->component = window;
  1344. window->setVisible (true); // (must be called before enterModalState on Windows to avoid DropShadower confusion)
  1345. window->enterModalState (false, userCallbackDeleter.release());
  1346. ModalComponentManager::getInstance()->attachCallback (window, callback.release());
  1347. window->toFront (false); // need to do this after making it modal, or it could
  1348. // be stuck behind other comps that are already modal..
  1349. #if JUCE_MODAL_LOOPS_PERMITTED
  1350. if (userCallback == nullptr && canBeModal)
  1351. return window->runModalLoop();
  1352. #else
  1353. ignoreUnused (canBeModal);
  1354. jassert (! (userCallback == nullptr && canBeModal));
  1355. #endif
  1356. }
  1357. return 0;
  1358. }
  1359. //==============================================================================
  1360. #if JUCE_MODAL_LOOPS_PERMITTED
  1361. int PopupMenu::showMenu (const Options& options)
  1362. {
  1363. return showWithOptionalCallback (options, nullptr, true);
  1364. }
  1365. #endif
  1366. void PopupMenu::showMenuAsync (const Options& options, ModalComponentManager::Callback* userCallback)
  1367. {
  1368. #if ! JUCE_MODAL_LOOPS_PERMITTED
  1369. jassert (userCallback != nullptr);
  1370. #endif
  1371. showWithOptionalCallback (options, userCallback, false);
  1372. }
  1373. //==============================================================================
  1374. #if JUCE_MODAL_LOOPS_PERMITTED
  1375. int PopupMenu::show (const int itemIDThatMustBeVisible,
  1376. const int minimumWidth, const int maximumNumColumns,
  1377. const int standardItemHeight,
  1378. ModalComponentManager::Callback* callback)
  1379. {
  1380. return showWithOptionalCallback (Options().withItemThatMustBeVisible (itemIDThatMustBeVisible)
  1381. .withMinimumWidth (minimumWidth)
  1382. .withMaximumNumColumns (maximumNumColumns)
  1383. .withStandardItemHeight (standardItemHeight),
  1384. callback, true);
  1385. }
  1386. int PopupMenu::showAt (const Rectangle<int>& screenAreaToAttachTo,
  1387. const int itemIDThatMustBeVisible,
  1388. const int minimumWidth, const int maximumNumColumns,
  1389. const int standardItemHeight,
  1390. ModalComponentManager::Callback* callback)
  1391. {
  1392. return showWithOptionalCallback (Options().withTargetScreenArea (screenAreaToAttachTo)
  1393. .withItemThatMustBeVisible (itemIDThatMustBeVisible)
  1394. .withMinimumWidth (minimumWidth)
  1395. .withMaximumNumColumns (maximumNumColumns)
  1396. .withStandardItemHeight (standardItemHeight),
  1397. callback, true);
  1398. }
  1399. int PopupMenu::showAt (Component* componentToAttachTo,
  1400. const int itemIDThatMustBeVisible,
  1401. const int minimumWidth, const int maximumNumColumns,
  1402. const int standardItemHeight,
  1403. ModalComponentManager::Callback* callback)
  1404. {
  1405. Options options (Options().withItemThatMustBeVisible (itemIDThatMustBeVisible)
  1406. .withMinimumWidth (minimumWidth)
  1407. .withMaximumNumColumns (maximumNumColumns)
  1408. .withStandardItemHeight (standardItemHeight));
  1409. if (componentToAttachTo != nullptr)
  1410. options = options.withTargetComponent (componentToAttachTo);
  1411. return showWithOptionalCallback (options, callback, true);
  1412. }
  1413. #endif
  1414. bool JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  1415. {
  1416. auto& windows = HelperClasses::MenuWindow::getActiveWindows();
  1417. auto numWindows = windows.size();
  1418. for (int i = numWindows; --i >= 0;)
  1419. if (auto* pmw = windows[i])
  1420. pmw->dismissMenu (nullptr);
  1421. return numWindows > 0;
  1422. }
  1423. //==============================================================================
  1424. int PopupMenu::getNumItems() const noexcept
  1425. {
  1426. int num = 0;
  1427. for (auto* mi : items)
  1428. if (! mi->isSeparator)
  1429. ++num;
  1430. return num;
  1431. }
  1432. bool PopupMenu::containsCommandItem (const int commandID) const
  1433. {
  1434. for (auto* mi : items)
  1435. if ((mi->itemID == commandID && mi->commandManager != nullptr)
  1436. || (mi->subMenu != nullptr && mi->subMenu->containsCommandItem (commandID)))
  1437. return true;
  1438. return false;
  1439. }
  1440. bool PopupMenu::containsAnyActiveItems() const noexcept
  1441. {
  1442. for (auto* mi : items)
  1443. {
  1444. if (mi->subMenu != nullptr)
  1445. {
  1446. if (mi->subMenu->containsAnyActiveItems())
  1447. return true;
  1448. }
  1449. else if (mi->isEnabled)
  1450. {
  1451. return true;
  1452. }
  1453. }
  1454. return false;
  1455. }
  1456. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  1457. {
  1458. lookAndFeel = newLookAndFeel;
  1459. }
  1460. //==============================================================================
  1461. PopupMenu::CustomComponent::CustomComponent (bool autoTrigger)
  1462. : isHighlighted (false),
  1463. triggeredAutomatically (autoTrigger)
  1464. {
  1465. }
  1466. PopupMenu::CustomComponent::~CustomComponent()
  1467. {
  1468. }
  1469. void PopupMenu::CustomComponent::setHighlighted (bool shouldBeHighlighted)
  1470. {
  1471. isHighlighted = shouldBeHighlighted;
  1472. repaint();
  1473. }
  1474. void PopupMenu::CustomComponent::triggerMenuItem()
  1475. {
  1476. if (auto* mic = findParentComponentOfClass<HelperClasses::ItemComponent>())
  1477. {
  1478. if (auto* pmw = mic->findParentComponentOfClass<HelperClasses::MenuWindow>())
  1479. {
  1480. pmw->dismissMenu (&mic->item);
  1481. }
  1482. else
  1483. {
  1484. // something must have gone wrong with the component hierarchy if this happens..
  1485. jassertfalse;
  1486. }
  1487. }
  1488. else
  1489. {
  1490. // why isn't this component inside a menu? Not much point triggering the item if
  1491. // there's no menu.
  1492. jassertfalse;
  1493. }
  1494. }
  1495. //==============================================================================
  1496. PopupMenu::CustomCallback::CustomCallback() {}
  1497. PopupMenu::CustomCallback::~CustomCallback() {}
  1498. //==============================================================================
  1499. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& m, bool searchR) : searchRecursively (searchR)
  1500. {
  1501. currentItem = nullptr;
  1502. index.add (0);
  1503. menus.add (&m);
  1504. }
  1505. PopupMenu::MenuItemIterator::~MenuItemIterator() {}
  1506. bool PopupMenu::MenuItemIterator::next()
  1507. {
  1508. if (index.size() == 0 || menus.getLast()->items.size() == 0)
  1509. return false;
  1510. currentItem = menus.getLast()->items.getUnchecked (index.getLast());
  1511. if (searchRecursively && currentItem->subMenu != nullptr)
  1512. {
  1513. index.add (0);
  1514. menus.add (currentItem->subMenu);
  1515. }
  1516. else
  1517. index.setUnchecked (index.size() - 1, index.getLast() + 1);
  1518. while (index.size() > 0 && index.getLast() >= menus.getLast()->items.size())
  1519. {
  1520. index.removeLast();
  1521. menus.removeLast();
  1522. if (index.size() > 0)
  1523. index.setUnchecked (index.size() - 1, index.getLast() + 1);
  1524. }
  1525. return true;
  1526. }
  1527. PopupMenu::Item& PopupMenu::MenuItemIterator::getItem() const noexcept
  1528. {
  1529. jassert (currentItem != nullptr);
  1530. return *(currentItem);
  1531. }
  1532. } // namespace juce