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.

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