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.

1873 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. struct 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() override
  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. struct MenuWindow : public Component
  152. {
  153. MenuWindow (const PopupMenu& menu, MenuWindow* parentWindow,
  154. const Options& opts, bool alignToRectangle, bool shouldDismissOnMouseUp,
  155. ApplicationCommandManager** manager, float parentScaleFactor = 1.0f)
  156. : Component ("menu"),
  157. parent (parentWindow),
  158. options (opts),
  159. managerOfChosenCommand (manager),
  160. componentAttachedTo (options.getTargetComponent()),
  161. dismissOnMouseUp (shouldDismissOnMouseUp),
  162. windowCreationTime (Time::getMillisecondCounter()),
  163. lastFocusedTime (windowCreationTime),
  164. timeEnteredCurrentChildComp (windowCreationTime),
  165. scaleFactor (parentWindow != nullptr ? parentScaleFactor : 1.0f)
  166. {
  167. setWantsKeyboardFocus (false);
  168. setMouseClickGrabsKeyboardFocus (false);
  169. setAlwaysOnTop (true);
  170. setLookAndFeel (parent != nullptr ? &(parent->getLookAndFeel())
  171. : menu.lookAndFeel.get());
  172. auto& lf = getLookAndFeel();
  173. parentComponent = lf.getParentComponentForMenuOptions (options);
  174. const_cast<Options&>(options) = options.withParentComponent (parentComponent);
  175. if (parentComponent == nullptr && parentWindow == nullptr && lf.shouldPopupMenuScaleWithTargetComponent (options))
  176. if (auto* targetComponent = options.getTargetComponent())
  177. scaleFactor = Component::getApproximateScaleFactorForComponent (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. Desktop::getInstance().addGlobalMouseListener (this);
  208. }
  209. getActiveWindows().add (this);
  210. lf.preparePopupMenuWindow (*this);
  211. getMouseState (Desktop::getInstance().getMainMouseSource()); // forces creation of a mouse source watcher for the main mouse
  212. }
  213. ~MenuWindow() override
  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, Component* relativeTo = nullptr)
  483. {
  484. if (relativeTo != nullptr)
  485. targetPoint = relativeTo->localPointToGlobal (targetPoint);
  486. auto parentArea = Desktop::getInstance().getDisplays().findDisplayForPoint (targetPoint)
  487. #if JUCE_MAC || JUCE_ANDROID
  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()) / scaleFactor;
  502. if (parentComponent != nullptr)
  503. target = parentComponent->getLocalArea (nullptr, target).getIntersection (parentArea);
  504. auto 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. auto spaceUnder = parentArea.getBottom() - target.getBottom();
  511. auto spaceOver = target.getY() - parentArea.getY();
  512. auto bufferHeight = 30;
  513. if (options.getPreferredPopupDirection() == Options::PopupDirection::upwards)
  514. y = (heightToUse < spaceOver - bufferHeight || spaceOver >= spaceUnder) ? target.getY() - heightToUse
  515. : target.getBottom();
  516. else
  517. y = (heightToUse < spaceUnder - bufferHeight || spaceUnder >= spaceOver) ? target.getBottom()
  518. : target.getY() - heightToUse;
  519. }
  520. else
  521. {
  522. bool tendTowardsRight = target.getCentreX() < parentArea.getCentreX();
  523. if (parent != nullptr)
  524. {
  525. if (parent->parent != nullptr)
  526. {
  527. const bool parentGoingRight = (parent->getX() + parent->getWidth() / 2
  528. > parent->parent->getX() + parent->parent->getWidth() / 2);
  529. if (parentGoingRight && target.getRight() + widthToUse < parentArea.getRight() - 4)
  530. tendTowardsRight = true;
  531. else if ((! parentGoingRight) && target.getX() > widthToUse + 4)
  532. tendTowardsRight = false;
  533. }
  534. else if (target.getRight() + widthToUse < parentArea.getRight() - 32)
  535. {
  536. tendTowardsRight = true;
  537. }
  538. }
  539. auto biggestSpace = jmax (parentArea.getRight() - target.getRight(),
  540. target.getX() - parentArea.getX()) - 32;
  541. if (biggestSpace < widthToUse)
  542. {
  543. layoutMenuItems (biggestSpace + target.getWidth() / 3, maxMenuHeight, widthToUse, heightToUse);
  544. if (numColumns > 1)
  545. layoutMenuItems (biggestSpace - 4, maxMenuHeight, widthToUse, heightToUse);
  546. tendTowardsRight = (parentArea.getRight() - target.getRight()) >= (target.getX() - parentArea.getX());
  547. }
  548. x = tendTowardsRight ? jmin (parentArea.getRight() - widthToUse - 4, target.getRight())
  549. : jmax (parentArea.getX() + 4, target.getX() - widthToUse);
  550. if (getLookAndFeel().getPopupMenuBorderSize() == 0) // workaround for dismissing the window on mouse up when border size is 0
  551. x += tendTowardsRight ? 1 : -1;
  552. y = target.getCentreY() > parentArea.getCentreY() ? jmax (parentArea.getY(), target.getBottom() - heightToUse)
  553. : target.getY();
  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 = options.getMinimumNumColumns();
  565. contentHeight = 0;
  566. auto maximumNumColumns = options.getMaximumNumColumns() > 0 ? options.getMaximumNumColumns() : 7;
  567. for (;;)
  568. {
  569. auto totalW = workOutBestSize (maxMenuW);
  570. if (totalW > maxMenuW)
  571. {
  572. numColumns = jmax (1, numColumns - 1);
  573. workOutBestSize (maxMenuW); // to update col widths
  574. break;
  575. }
  576. if (totalW > maxMenuW / 2
  577. || contentHeight < maxMenuH
  578. || numColumns >= maximumNumColumns)
  579. break;
  580. ++numColumns;
  581. }
  582. auto actualH = jmin (contentHeight, maxMenuH);
  583. needsToScroll = contentHeight > actualH;
  584. width = updateYPositions();
  585. height = actualH + getLookAndFeel().getPopupMenuBorderSize() * 2;
  586. }
  587. int workOutBestSize (const int maxMenuW)
  588. {
  589. int totalW = 0;
  590. contentHeight = 0;
  591. int childNum = 0;
  592. for (int col = 0; col < numColumns; ++col)
  593. {
  594. int colW = options.getStandardItemHeight(), colH = 0;
  595. auto numChildren = jmin (items.size() - childNum,
  596. (items.size() + numColumns - 1) / numColumns);
  597. for (int i = numChildren; --i >= 0;)
  598. {
  599. colW = jmax (colW, items.getUnchecked (childNum + i)->getWidth());
  600. colH += items.getUnchecked (childNum + i)->getHeight();
  601. }
  602. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + getLookAndFeel().getPopupMenuBorderSize() * 2);
  603. columnWidths.set (col, colW);
  604. totalW += colW;
  605. contentHeight = jmax (contentHeight, colH);
  606. childNum += numChildren;
  607. }
  608. // width must never be larger than the screen
  609. auto minWidth = jmin (maxMenuW, options.getMinimumWidth());
  610. if (totalW < minWidth)
  611. {
  612. totalW = minWidth;
  613. for (int col = 0; col < numColumns; ++col)
  614. columnWidths.set (0, totalW / numColumns);
  615. }
  616. return totalW;
  617. }
  618. void ensureItemIsVisible (const int itemID, int wantedY)
  619. {
  620. jassert (itemID != 0);
  621. for (int i = items.size(); --i >= 0;)
  622. {
  623. if (auto* m = items.getUnchecked (i))
  624. {
  625. if (m->item.itemID == itemID
  626. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  627. {
  628. auto currentY = m->getY();
  629. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  630. {
  631. if (wantedY < 0)
  632. wantedY = jlimit (PopupMenuSettings::scrollZone,
  633. jmax (PopupMenuSettings::scrollZone,
  634. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  635. currentY);
  636. auto parentArea = getParentArea (windowPos.getPosition(), parentComponent) / scaleFactor;
  637. auto deltaY = wantedY - currentY;
  638. windowPos.setSize (jmin (windowPos.getWidth(), parentArea.getWidth()),
  639. jmin (windowPos.getHeight(), parentArea.getHeight()));
  640. auto newY = jlimit (parentArea.getY(),
  641. parentArea.getBottom() - windowPos.getHeight(),
  642. windowPos.getY() + deltaY);
  643. deltaY -= newY - windowPos.getY();
  644. childYOffset -= deltaY;
  645. windowPos.setPosition (windowPos.getX(), newY);
  646. updateYPositions();
  647. }
  648. break;
  649. }
  650. }
  651. }
  652. }
  653. void resizeToBestWindowPos()
  654. {
  655. auto r = windowPos;
  656. if (childYOffset < 0)
  657. {
  658. r = r.withTop (r.getY() - childYOffset);
  659. }
  660. else if (childYOffset > 0)
  661. {
  662. auto spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  663. if (spaceAtBottom > 0)
  664. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  665. }
  666. setBounds (r);
  667. updateYPositions();
  668. }
  669. void alterChildYPos (int delta)
  670. {
  671. if (canScroll())
  672. {
  673. childYOffset += delta;
  674. if (delta < 0)
  675. childYOffset = jmax (childYOffset, 0);
  676. else if (delta > 0)
  677. childYOffset = jmin (childYOffset,
  678. contentHeight - windowPos.getHeight() + getLookAndFeel().getPopupMenuBorderSize());
  679. updateYPositions();
  680. }
  681. else
  682. {
  683. childYOffset = 0;
  684. }
  685. resizeToBestWindowPos();
  686. repaint();
  687. }
  688. int updateYPositions()
  689. {
  690. int x = 0;
  691. int childNum = 0;
  692. for (int col = 0; col < numColumns; ++col)
  693. {
  694. auto numChildren = jmin (items.size() - childNum,
  695. (items.size() + numColumns - 1) / numColumns);
  696. auto colW = columnWidths[col];
  697. auto y = getLookAndFeel().getPopupMenuBorderSize() - (childYOffset + (getY() - windowPos.getY()));
  698. for (int i = 0; i < numChildren; ++i)
  699. {
  700. auto* c = items.getUnchecked (childNum + i);
  701. c->setBounds (x, y, colW, c->getHeight());
  702. y += c->getHeight();
  703. }
  704. x += colW;
  705. childNum += numChildren;
  706. }
  707. return x;
  708. }
  709. void setCurrentlyHighlightedChild (ItemComponent* child)
  710. {
  711. if (currentChild != nullptr)
  712. currentChild->setHighlighted (false);
  713. currentChild = child;
  714. if (currentChild != nullptr)
  715. {
  716. currentChild->setHighlighted (true);
  717. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  718. }
  719. }
  720. bool isSubMenuVisible() const noexcept { return activeSubMenu != nullptr && activeSubMenu->isVisible(); }
  721. bool showSubMenuFor (ItemComponent* childComp)
  722. {
  723. activeSubMenu.reset();
  724. if (childComp != nullptr
  725. && hasActiveSubMenu (childComp->item))
  726. {
  727. activeSubMenu.reset (new HelperClasses::MenuWindow (*(childComp->item.subMenu), this,
  728. options.withTargetScreenArea (childComp->getScreenBounds())
  729. .withMinimumWidth (0)
  730. .withTargetComponent (nullptr)
  731. .withParentComponent (parentComponent),
  732. false, dismissOnMouseUp, managerOfChosenCommand, scaleFactor));
  733. activeSubMenu->setVisible (true); // (must be called before enterModalState on Windows to avoid DropShadower confusion)
  734. activeSubMenu->enterModalState (false);
  735. activeSubMenu->toFront (false);
  736. return true;
  737. }
  738. return false;
  739. }
  740. void triggerCurrentlyHighlightedItem()
  741. {
  742. if (currentChild != nullptr
  743. && canBeTriggered (currentChild->item)
  744. && (currentChild->item.customComponent == nullptr
  745. || currentChild->item.customComponent->isTriggeredAutomatically()))
  746. {
  747. dismissMenu (&currentChild->item);
  748. }
  749. }
  750. void selectNextItem (int delta)
  751. {
  752. disableTimerUntilMouseMoves();
  753. auto start = jmax (0, items.indexOf (currentChild));
  754. for (int i = items.size(); --i >= 0;)
  755. {
  756. start += delta;
  757. if (auto* mic = items.getUnchecked ((start + items.size()) % items.size()))
  758. {
  759. if (canBeTriggered (mic->item) || hasActiveSubMenu (mic->item))
  760. {
  761. setCurrentlyHighlightedChild (mic);
  762. break;
  763. }
  764. }
  765. }
  766. }
  767. void disableTimerUntilMouseMoves()
  768. {
  769. disableMouseMoves = true;
  770. if (parent != nullptr)
  771. parent->disableTimerUntilMouseMoves();
  772. }
  773. bool canScroll() const noexcept { return childYOffset != 0 || needsToScroll; }
  774. bool isTopScrollZoneActive() const noexcept { return canScroll() && childYOffset > 0; }
  775. bool isBottomScrollZoneActive() const noexcept { return canScroll() && childYOffset < contentHeight - windowPos.getHeight(); }
  776. //==============================================================================
  777. MenuWindow* parent;
  778. const Options options;
  779. OwnedArray<ItemComponent> items;
  780. ApplicationCommandManager** managerOfChosenCommand;
  781. WeakReference<Component> componentAttachedTo;
  782. Component* parentComponent = nullptr;
  783. Rectangle<int> windowPos;
  784. bool hasBeenOver = false, needsToScroll = false;
  785. bool dismissOnMouseUp, hideOnExit = false, disableMouseMoves = false, hasAnyJuceCompHadFocus = false;
  786. int numColumns = 0, contentHeight = 0, childYOffset = 0;
  787. Component::SafePointer<ItemComponent> currentChild;
  788. std::unique_ptr<MenuWindow> activeSubMenu;
  789. Array<int> columnWidths;
  790. uint32 windowCreationTime, lastFocusedTime, timeEnteredCurrentChildComp;
  791. OwnedArray<MouseSourceState> mouseSourceStates;
  792. float scaleFactor;
  793. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuWindow)
  794. };
  795. //==============================================================================
  796. class MouseSourceState : public Timer
  797. {
  798. public:
  799. MouseSourceState (MenuWindow& w, MouseInputSource s)
  800. : window (w), source (s), lastScrollTime (Time::getMillisecondCounter())
  801. {
  802. startTimerHz (20);
  803. }
  804. void handleMouseEvent (const MouseEvent& e)
  805. {
  806. if (! window.windowIsStillValid())
  807. return;
  808. startTimerHz (20);
  809. handleMousePosition (e.getScreenPosition());
  810. }
  811. void timerCallback() override
  812. {
  813. #if JUCE_WINDOWS
  814. // touch and pen devices on Windows send an offscreen mouse move after mouse up events
  815. // but we don't want to forward these on as they will dismiss the menu
  816. if ((source.isTouch() || source.isPen()) && ! isValidMousePosition())
  817. return;
  818. #endif
  819. if (window.windowIsStillValid())
  820. handleMousePosition (source.getScreenPosition().roundToInt());
  821. }
  822. bool isOver() const
  823. {
  824. return window.reallyContains (window.getLocalPoint (nullptr, source.getScreenPosition()).roundToInt(), true);
  825. }
  826. MenuWindow& window;
  827. MouseInputSource source;
  828. private:
  829. Point<int> lastMousePos;
  830. double scrollAcceleration = 0;
  831. uint32 lastScrollTime, lastMouseMoveTime = 0;
  832. bool isDown = false;
  833. void handleMousePosition (Point<int> globalMousePos)
  834. {
  835. auto localMousePos = window.getLocalPoint (nullptr, globalMousePos);
  836. auto timeNow = Time::getMillisecondCounter();
  837. if (timeNow > window.timeEnteredCurrentChildComp + 100
  838. && window.reallyContains (localMousePos, true)
  839. && window.currentChild != nullptr
  840. && ! (window.disableMouseMoves || window.isSubMenuVisible()))
  841. {
  842. window.showSubMenuFor (window.currentChild);
  843. }
  844. highlightItemUnderMouse (globalMousePos, localMousePos, timeNow);
  845. const bool overScrollArea = scrollIfNecessary (localMousePos, timeNow);
  846. const bool isOverAny = window.isOverAnyMenu();
  847. if (window.hideOnExit && window.hasBeenOver && ! isOverAny)
  848. window.hide (nullptr, true);
  849. else
  850. checkButtonState (localMousePos, timeNow, isDown, overScrollArea, isOverAny);
  851. }
  852. void checkButtonState (Point<int> localMousePos, const uint32 timeNow,
  853. const bool wasDown, const bool overScrollArea, const bool isOverAny)
  854. {
  855. isDown = window.hasBeenOver
  856. && (ModifierKeys::currentModifiers.isAnyMouseButtonDown()
  857. || ComponentPeer::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  858. if (! window.doesAnyJuceCompHaveFocus())
  859. {
  860. if (timeNow > window.lastFocusedTime + 10)
  861. {
  862. PopupMenuSettings::menuWasHiddenBecauseOfAppChange = true;
  863. window.dismissMenu (nullptr);
  864. // Note: This object may have been deleted by the previous call.
  865. }
  866. }
  867. else if (wasDown && timeNow > window.windowCreationTime + 250
  868. && ! (isDown || overScrollArea))
  869. {
  870. if (window.reallyContains (localMousePos, true))
  871. window.triggerCurrentlyHighlightedItem();
  872. else if ((window.hasBeenOver || ! window.dismissOnMouseUp) && ! isOverAny)
  873. window.dismissMenu (nullptr);
  874. // Note: This object may have been deleted by the previous call.
  875. }
  876. else
  877. {
  878. window.lastFocusedTime = timeNow;
  879. }
  880. }
  881. void highlightItemUnderMouse (Point<int> globalMousePos, Point<int> localMousePos, const uint32 timeNow)
  882. {
  883. if (globalMousePos != lastMousePos || timeNow > lastMouseMoveTime + 350)
  884. {
  885. const bool isMouseOver = window.reallyContains (localMousePos, true);
  886. if (isMouseOver)
  887. window.hasBeenOver = true;
  888. if (lastMousePos.getDistanceFrom (globalMousePos) > 2)
  889. {
  890. lastMouseMoveTime = timeNow;
  891. if (window.disableMouseMoves && isMouseOver)
  892. window.disableMouseMoves = false;
  893. }
  894. if (window.disableMouseMoves || (window.activeSubMenu != nullptr && window.activeSubMenu->isOverChildren()))
  895. return;
  896. const bool isMovingTowardsMenu = isMouseOver && globalMousePos != lastMousePos
  897. && isMovingTowardsSubmenu (globalMousePos);
  898. lastMousePos = globalMousePos;
  899. if (! isMovingTowardsMenu)
  900. {
  901. auto* c = window.getComponentAt (localMousePos);
  902. if (c == &window)
  903. c = nullptr;
  904. auto* itemUnderMouse = dynamic_cast<ItemComponent*> (c);
  905. if (itemUnderMouse == nullptr && c != nullptr)
  906. itemUnderMouse = c->findParentComponentOfClass<ItemComponent>();
  907. if (itemUnderMouse != window.currentChild
  908. && (isMouseOver || (window.activeSubMenu == nullptr) || ! window.activeSubMenu->isVisible()))
  909. {
  910. if (isMouseOver && (c != nullptr) && (window.activeSubMenu != nullptr))
  911. window.activeSubMenu->hide (nullptr, true);
  912. if (! isMouseOver)
  913. itemUnderMouse = nullptr;
  914. window.setCurrentlyHighlightedChild (itemUnderMouse);
  915. }
  916. }
  917. }
  918. }
  919. bool isMovingTowardsSubmenu (Point<int> newGlobalPos) const
  920. {
  921. if (window.activeSubMenu == nullptr)
  922. return false;
  923. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  924. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  925. // extends from the last mouse pos to the submenu's rectangle..
  926. auto itemScreenBounds = window.activeSubMenu->getScreenBounds();
  927. auto subX = (float) itemScreenBounds.getX();
  928. auto oldGlobalPos = lastMousePos;
  929. if (itemScreenBounds.getX() > window.getX())
  930. {
  931. oldGlobalPos -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  932. }
  933. else
  934. {
  935. oldGlobalPos += Point<int> (2, 0);
  936. subX += itemScreenBounds.getWidth();
  937. }
  938. Path areaTowardsSubMenu;
  939. areaTowardsSubMenu.addTriangle ((float) oldGlobalPos.x, (float) oldGlobalPos.y,
  940. subX, (float) itemScreenBounds.getY(),
  941. subX, (float) itemScreenBounds.getBottom());
  942. return areaTowardsSubMenu.contains (newGlobalPos.toFloat());
  943. }
  944. bool scrollIfNecessary (Point<int> localMousePos, const uint32 timeNow)
  945. {
  946. if (window.canScroll()
  947. && isPositiveAndBelow (localMousePos.x, window.getWidth())
  948. && (isPositiveAndBelow (localMousePos.y, window.getHeight()) || source.isDragging()))
  949. {
  950. if (window.isTopScrollZoneActive() && localMousePos.y < PopupMenuSettings::scrollZone)
  951. return scroll (timeNow, -1);
  952. if (window.isBottomScrollZoneActive() && localMousePos.y > window.getHeight() - PopupMenuSettings::scrollZone)
  953. return scroll (timeNow, 1);
  954. }
  955. scrollAcceleration = 1.0;
  956. return false;
  957. }
  958. bool scroll (const uint32 timeNow, const int direction)
  959. {
  960. if (timeNow > lastScrollTime + 20)
  961. {
  962. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  963. int amount = 0;
  964. for (int i = 0; i < window.items.size() && amount == 0; ++i)
  965. amount = ((int) scrollAcceleration) * window.items.getUnchecked (i)->getHeight();
  966. window.alterChildYPos (amount * direction);
  967. lastScrollTime = timeNow;
  968. }
  969. return true;
  970. }
  971. #if JUCE_WINDOWS
  972. bool isValidMousePosition()
  973. {
  974. auto screenPos = source.getScreenPosition();
  975. auto localPos = (window.activeSubMenu == nullptr) ? window.getLocalPoint (nullptr, screenPos)
  976. : window.activeSubMenu->getLocalPoint (nullptr, screenPos);
  977. if (localPos.x < 0 && localPos.y < 0)
  978. return false;
  979. return true;
  980. }
  981. #endif
  982. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MouseSourceState)
  983. };
  984. //==============================================================================
  985. struct NormalComponentWrapper : public PopupMenu::CustomComponent
  986. {
  987. NormalComponentWrapper (Component* comp, int w, int h, bool triggerMenuItemAutomaticallyWhenClicked)
  988. : PopupMenu::CustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  989. width (w), height (h)
  990. {
  991. addAndMakeVisible (comp);
  992. }
  993. void getIdealSize (int& idealWidth, int& idealHeight) override
  994. {
  995. idealWidth = width;
  996. idealHeight = height;
  997. }
  998. void resized() override
  999. {
  1000. if (auto* child = getChildComponent (0))
  1001. child->setBounds (getLocalBounds());
  1002. }
  1003. const int width, height;
  1004. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NormalComponentWrapper)
  1005. };
  1006. };
  1007. //==============================================================================
  1008. PopupMenu::PopupMenu()
  1009. {
  1010. }
  1011. PopupMenu::PopupMenu (const PopupMenu& other)
  1012. : lookAndFeel (other.lookAndFeel)
  1013. {
  1014. items.addCopiesOf (other.items);
  1015. }
  1016. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  1017. {
  1018. if (this != &other)
  1019. {
  1020. lookAndFeel = other.lookAndFeel;
  1021. clear();
  1022. items.addCopiesOf (other.items);
  1023. }
  1024. return *this;
  1025. }
  1026. PopupMenu::PopupMenu (PopupMenu&& other) noexcept
  1027. : lookAndFeel (other.lookAndFeel)
  1028. {
  1029. items.swapWith (other.items);
  1030. }
  1031. PopupMenu& PopupMenu::operator= (PopupMenu&& other) noexcept
  1032. {
  1033. jassert (this != &other); // hopefully the compiler should make this situation impossible!
  1034. items.swapWith (other.items);
  1035. lookAndFeel = other.lookAndFeel;
  1036. return *this;
  1037. }
  1038. PopupMenu::~PopupMenu()
  1039. {
  1040. }
  1041. void PopupMenu::clear()
  1042. {
  1043. items.clear();
  1044. }
  1045. //==============================================================================
  1046. PopupMenu::Item::Item() noexcept
  1047. {
  1048. }
  1049. PopupMenu::Item::Item (const Item& other)
  1050. : text (other.text),
  1051. itemID (other.itemID),
  1052. subMenu (createCopyIfNotNull (other.subMenu.get())),
  1053. image (other.image != nullptr ? other.image->createCopy() : nullptr),
  1054. customComponent (other.customComponent),
  1055. customCallback (other.customCallback),
  1056. commandManager (other.commandManager),
  1057. shortcutKeyDescription (other.shortcutKeyDescription),
  1058. colour (other.colour),
  1059. isEnabled (other.isEnabled),
  1060. isTicked (other.isTicked),
  1061. isSeparator (other.isSeparator),
  1062. isSectionHeader (other.isSectionHeader)
  1063. {
  1064. }
  1065. PopupMenu::Item& PopupMenu::Item::operator= (const Item& other)
  1066. {
  1067. text = other.text;
  1068. itemID = other.itemID;
  1069. subMenu.reset (createCopyIfNotNull (other.subMenu.get()));
  1070. image = other.image != nullptr ? other.image->createCopy() : std::unique_ptr<Drawable>();
  1071. customComponent = other.customComponent;
  1072. customCallback = other.customCallback;
  1073. commandManager = other.commandManager;
  1074. shortcutKeyDescription = other.shortcutKeyDescription;
  1075. colour = other.colour;
  1076. isEnabled = other.isEnabled;
  1077. isTicked = other.isTicked;
  1078. isSeparator = other.isSeparator;
  1079. isSectionHeader = other.isSectionHeader;
  1080. return *this;
  1081. }
  1082. void PopupMenu::addItem (const Item& newItem)
  1083. {
  1084. // An ID of 0 is used as a return value to indicate that the user
  1085. // didn't pick anything, so you shouldn't use it as the ID for an item..
  1086. jassert (newItem.itemID != 0
  1087. || newItem.isSeparator || newItem.isSectionHeader
  1088. || newItem.subMenu != nullptr);
  1089. items.add (new Item (newItem));
  1090. }
  1091. void PopupMenu::addItem (int itemResultID, const String& itemText, bool isActive, bool isTicked)
  1092. {
  1093. Item i;
  1094. i.text = itemText;
  1095. i.itemID = itemResultID;
  1096. i.isEnabled = isActive;
  1097. i.isTicked = isTicked;
  1098. addItem (i);
  1099. }
  1100. static std::unique_ptr<Drawable> createDrawableFromImage (const Image& im)
  1101. {
  1102. if (im.isValid())
  1103. {
  1104. auto d = new DrawableImage();
  1105. d->setImage (im);
  1106. return std::unique_ptr<Drawable> (d);
  1107. }
  1108. return {};
  1109. }
  1110. void PopupMenu::addItem (int itemResultID, const String& itemText, bool isActive, bool isTicked, const Image& iconToUse)
  1111. {
  1112. addItem (itemResultID, itemText, isActive, isTicked, createDrawableFromImage (iconToUse));
  1113. }
  1114. void PopupMenu::addItem (int itemResultID, const String& itemText, bool isActive,
  1115. bool isTicked, std::unique_ptr<Drawable> iconToUse)
  1116. {
  1117. Item i;
  1118. i.text = itemText;
  1119. i.itemID = itemResultID;
  1120. i.isEnabled = isActive;
  1121. i.isTicked = isTicked;
  1122. i.image = std::move (iconToUse);
  1123. addItem (i);
  1124. }
  1125. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  1126. const CommandID commandID,
  1127. const String& displayName,
  1128. std::unique_ptr<Drawable> iconToUse)
  1129. {
  1130. jassert (commandManager != nullptr && commandID != 0);
  1131. if (auto* registeredInfo = commandManager->getCommandForID (commandID))
  1132. {
  1133. ApplicationCommandInfo info (*registeredInfo);
  1134. auto* target = commandManager->getTargetForCommand (commandID, info);
  1135. Item i;
  1136. i.text = displayName.isNotEmpty() ? displayName : info.shortName;
  1137. i.itemID = (int) commandID;
  1138. i.commandManager = commandManager;
  1139. i.isEnabled = target != nullptr && (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  1140. i.isTicked = (info.flags & ApplicationCommandInfo::isTicked) != 0;
  1141. i.image = std::move (iconToUse);
  1142. addItem (i);
  1143. }
  1144. }
  1145. void PopupMenu::addColouredItem (int itemResultID, const String& itemText, Colour itemTextColour,
  1146. bool isActive, bool isTicked, std::unique_ptr<Drawable> iconToUse)
  1147. {
  1148. Item i;
  1149. i.text = itemText;
  1150. i.itemID = itemResultID;
  1151. i.colour = itemTextColour;
  1152. i.isEnabled = isActive;
  1153. i.isTicked = isTicked;
  1154. i.image = std::move (iconToUse);
  1155. addItem (i);
  1156. }
  1157. void PopupMenu::addColouredItem (int itemResultID, const String& itemText, Colour itemTextColour,
  1158. bool isActive, bool isTicked, const Image& iconToUse)
  1159. {
  1160. Item i;
  1161. i.text = itemText;
  1162. i.itemID = itemResultID;
  1163. i.colour = itemTextColour;
  1164. i.isEnabled = isActive;
  1165. i.isTicked = isTicked;
  1166. i.image = createDrawableFromImage (iconToUse);
  1167. addItem (i);
  1168. }
  1169. void PopupMenu::addCustomItem (int itemResultID, CustomComponent* cc, const PopupMenu* subMenu)
  1170. {
  1171. Item i;
  1172. i.itemID = itemResultID;
  1173. i.customComponent = cc;
  1174. i.subMenu.reset (createCopyIfNotNull (subMenu));
  1175. addItem (i);
  1176. }
  1177. void PopupMenu::addCustomItem (int itemResultID, Component* customComponent, int idealWidth, int idealHeight,
  1178. bool triggerMenuItemAutomaticallyWhenClicked, const PopupMenu* subMenu)
  1179. {
  1180. addCustomItem (itemResultID,
  1181. new HelperClasses::NormalComponentWrapper (customComponent, idealWidth, idealHeight,
  1182. triggerMenuItemAutomaticallyWhenClicked),
  1183. subMenu);
  1184. }
  1185. void PopupMenu::addSubMenu (const String& subMenuName, const PopupMenu& subMenu, bool isActive)
  1186. {
  1187. addSubMenu (subMenuName, subMenu, isActive, nullptr, false, 0);
  1188. }
  1189. void PopupMenu::addSubMenu (const String& subMenuName, const PopupMenu& subMenu, bool isActive,
  1190. const Image& iconToUse, bool isTicked, int itemResultID)
  1191. {
  1192. addSubMenu (subMenuName, subMenu, isActive, createDrawableFromImage (iconToUse), isTicked, itemResultID);
  1193. }
  1194. void PopupMenu::addSubMenu (const String& subMenuName, const PopupMenu& subMenu, bool isActive,
  1195. std::unique_ptr<Drawable> iconToUse, bool isTicked, int itemResultID)
  1196. {
  1197. Item i;
  1198. i.text = subMenuName;
  1199. i.itemID = itemResultID;
  1200. i.subMenu.reset (new PopupMenu (subMenu));
  1201. i.isEnabled = isActive && (itemResultID != 0 || subMenu.getNumItems() > 0);
  1202. i.isTicked = isTicked;
  1203. i.image = std::move (iconToUse);
  1204. addItem (i);
  1205. }
  1206. void PopupMenu::addSeparator()
  1207. {
  1208. if (items.size() > 0 && ! items.getLast()->isSeparator)
  1209. {
  1210. Item i;
  1211. i.isSeparator = true;
  1212. addItem (i);
  1213. }
  1214. }
  1215. void PopupMenu::addSectionHeader (const String& title)
  1216. {
  1217. Item i;
  1218. i.text = title;
  1219. i.isSectionHeader = true;
  1220. addItem (i);
  1221. }
  1222. //==============================================================================
  1223. PopupMenu::Options::Options()
  1224. {
  1225. targetArea.setPosition (Desktop::getMousePosition());
  1226. }
  1227. PopupMenu::Options PopupMenu::Options::withTargetComponent (Component* comp) const noexcept
  1228. {
  1229. Options o (*this);
  1230. o.targetComponent = comp;
  1231. if (comp != nullptr)
  1232. o.targetArea = comp->getScreenBounds();
  1233. return o;
  1234. }
  1235. PopupMenu::Options PopupMenu::Options::withTargetScreenArea (Rectangle<int> area) const noexcept
  1236. {
  1237. Options o (*this);
  1238. o.targetArea = area;
  1239. return o;
  1240. }
  1241. PopupMenu::Options PopupMenu::Options::withMinimumWidth (int w) const noexcept
  1242. {
  1243. Options o (*this);
  1244. o.minWidth = w;
  1245. return o;
  1246. }
  1247. PopupMenu::Options PopupMenu::Options::withMinimumNumColumns (int cols) const noexcept
  1248. {
  1249. Options o (*this);
  1250. o.minColumns = cols;
  1251. return o;
  1252. }
  1253. PopupMenu::Options PopupMenu::Options::withMaximumNumColumns (int cols) const noexcept
  1254. {
  1255. Options o (*this);
  1256. o.maxColumns = cols;
  1257. return o;
  1258. }
  1259. PopupMenu::Options PopupMenu::Options::withStandardItemHeight (int height) const noexcept
  1260. {
  1261. Options o (*this);
  1262. o.standardHeight = height;
  1263. return o;
  1264. }
  1265. PopupMenu::Options PopupMenu::Options::withItemThatMustBeVisible (int idOfItemToBeVisible) const noexcept
  1266. {
  1267. Options o (*this);
  1268. o.visibleItemID = idOfItemToBeVisible;
  1269. return o;
  1270. }
  1271. PopupMenu::Options PopupMenu::Options::withParentComponent (Component* parent) const noexcept
  1272. {
  1273. Options o (*this);
  1274. o.parentComponent = parent;
  1275. return o;
  1276. }
  1277. PopupMenu::Options PopupMenu::Options::withPreferredPopupDirection (PopupDirection direction) const noexcept
  1278. {
  1279. Options o (*this);
  1280. o.preferredPopupDirection = direction;
  1281. return o;
  1282. }
  1283. Component* PopupMenu::createWindow (const Options& options,
  1284. ApplicationCommandManager** managerOfChosenCommand) const
  1285. {
  1286. return items.isEmpty() ? nullptr
  1287. : new HelperClasses::MenuWindow (*this, nullptr, options,
  1288. ! options.getTargetScreenArea().isEmpty(),
  1289. ModifierKeys::currentModifiers.isAnyMouseButtonDown(),
  1290. managerOfChosenCommand);
  1291. }
  1292. //==============================================================================
  1293. // This invokes any command manager commands and deletes the menu window when it is dismissed
  1294. struct PopupMenuCompletionCallback : public ModalComponentManager::Callback
  1295. {
  1296. PopupMenuCompletionCallback()
  1297. : prevFocused (Component::getCurrentlyFocusedComponent()),
  1298. prevTopLevel (prevFocused != nullptr ? prevFocused->getTopLevelComponent() : nullptr)
  1299. {
  1300. PopupMenuSettings::menuWasHiddenBecauseOfAppChange = false;
  1301. }
  1302. void modalStateFinished (int result) override
  1303. {
  1304. if (managerOfChosenCommand != nullptr && result != 0)
  1305. {
  1306. ApplicationCommandTarget::InvocationInfo info (result);
  1307. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  1308. managerOfChosenCommand->invoke (info, true);
  1309. }
  1310. // (this would be the place to fade out the component, if that's what's required)
  1311. component.reset();
  1312. if (! PopupMenuSettings::menuWasHiddenBecauseOfAppChange)
  1313. {
  1314. if (prevTopLevel != nullptr)
  1315. prevTopLevel->toFront (true);
  1316. if (prevFocused != nullptr && prevFocused->isShowing())
  1317. prevFocused->grabKeyboardFocus();
  1318. }
  1319. }
  1320. ApplicationCommandManager* managerOfChosenCommand = nullptr;
  1321. std::unique_ptr<Component> component;
  1322. WeakReference<Component> prevFocused, prevTopLevel;
  1323. JUCE_DECLARE_NON_COPYABLE (PopupMenuCompletionCallback)
  1324. };
  1325. int PopupMenu::showWithOptionalCallback (const Options& options, ModalComponentManager::Callback* const userCallback,
  1326. const bool canBeModal)
  1327. {
  1328. std::unique_ptr<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  1329. std::unique_ptr<PopupMenuCompletionCallback> callback (new PopupMenuCompletionCallback());
  1330. if (auto* window = createWindow (options, &(callback->managerOfChosenCommand)))
  1331. {
  1332. callback->component.reset (window);
  1333. window->setVisible (true); // (must be called before enterModalState on Windows to avoid DropShadower confusion)
  1334. window->enterModalState (false, userCallbackDeleter.release());
  1335. ModalComponentManager::getInstance()->attachCallback (window, callback.release());
  1336. window->toFront (false); // need to do this after making it modal, or it could
  1337. // be stuck behind other comps that are already modal..
  1338. #if JUCE_MODAL_LOOPS_PERMITTED
  1339. if (userCallback == nullptr && canBeModal)
  1340. return window->runModalLoop();
  1341. #else
  1342. ignoreUnused (canBeModal);
  1343. jassert (! (userCallback == nullptr && canBeModal));
  1344. #endif
  1345. }
  1346. return 0;
  1347. }
  1348. //==============================================================================
  1349. #if JUCE_MODAL_LOOPS_PERMITTED
  1350. int PopupMenu::showMenu (const Options& options)
  1351. {
  1352. return showWithOptionalCallback (options, nullptr, true);
  1353. }
  1354. #endif
  1355. void PopupMenu::showMenuAsync (const Options& options, ModalComponentManager::Callback* userCallback)
  1356. {
  1357. #if ! JUCE_MODAL_LOOPS_PERMITTED
  1358. jassert (userCallback != nullptr);
  1359. #endif
  1360. showWithOptionalCallback (options, userCallback, false);
  1361. }
  1362. void PopupMenu::showMenuAsync (const Options& options, std::function<void(int)> userCallback)
  1363. {
  1364. showWithOptionalCallback (options, ModalCallbackFunction::create (userCallback), false);
  1365. }
  1366. //==============================================================================
  1367. #if JUCE_MODAL_LOOPS_PERMITTED
  1368. int PopupMenu::show (int itemIDThatMustBeVisible, int minimumWidth,
  1369. int maximumNumColumns, int standardItemHeight,
  1370. ModalComponentManager::Callback* callback)
  1371. {
  1372. return showWithOptionalCallback (Options().withItemThatMustBeVisible (itemIDThatMustBeVisible)
  1373. .withMinimumWidth (minimumWidth)
  1374. .withMaximumNumColumns (maximumNumColumns)
  1375. .withStandardItemHeight (standardItemHeight),
  1376. callback, true);
  1377. }
  1378. int PopupMenu::showAt (Rectangle<int> screenAreaToAttachTo,
  1379. int itemIDThatMustBeVisible, int minimumWidth,
  1380. int maximumNumColumns, int standardItemHeight,
  1381. ModalComponentManager::Callback* callback)
  1382. {
  1383. return showWithOptionalCallback (Options().withTargetScreenArea (screenAreaToAttachTo)
  1384. .withItemThatMustBeVisible (itemIDThatMustBeVisible)
  1385. .withMinimumWidth (minimumWidth)
  1386. .withMaximumNumColumns (maximumNumColumns)
  1387. .withStandardItemHeight (standardItemHeight),
  1388. callback, true);
  1389. }
  1390. int PopupMenu::showAt (Component* componentToAttachTo,
  1391. int itemIDThatMustBeVisible, int minimumWidth,
  1392. int maximumNumColumns, int standardItemHeight,
  1393. ModalComponentManager::Callback* callback)
  1394. {
  1395. auto options = Options().withItemThatMustBeVisible (itemIDThatMustBeVisible)
  1396. .withMinimumWidth (minimumWidth)
  1397. .withMaximumNumColumns (maximumNumColumns)
  1398. .withStandardItemHeight (standardItemHeight);
  1399. if (componentToAttachTo != nullptr)
  1400. options = options.withTargetComponent (componentToAttachTo);
  1401. return showWithOptionalCallback (options, callback, true);
  1402. }
  1403. #endif
  1404. bool JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  1405. {
  1406. auto& windows = HelperClasses::MenuWindow::getActiveWindows();
  1407. auto numWindows = windows.size();
  1408. for (int i = numWindows; --i >= 0;)
  1409. {
  1410. if (auto* pmw = windows[i])
  1411. {
  1412. pmw->setLookAndFeel (nullptr);
  1413. pmw->dismissMenu (nullptr);
  1414. }
  1415. }
  1416. return numWindows > 0;
  1417. }
  1418. //==============================================================================
  1419. int PopupMenu::getNumItems() const noexcept
  1420. {
  1421. int num = 0;
  1422. for (auto* mi : items)
  1423. if (! mi->isSeparator)
  1424. ++num;
  1425. return num;
  1426. }
  1427. bool PopupMenu::containsCommandItem (const int commandID) const
  1428. {
  1429. for (auto* mi : items)
  1430. if ((mi->itemID == commandID && mi->commandManager != nullptr)
  1431. || (mi->subMenu != nullptr && mi->subMenu->containsCommandItem (commandID)))
  1432. return true;
  1433. return false;
  1434. }
  1435. bool PopupMenu::containsAnyActiveItems() const noexcept
  1436. {
  1437. for (auto* mi : items)
  1438. {
  1439. if (mi->subMenu != nullptr)
  1440. {
  1441. if (mi->subMenu->containsAnyActiveItems())
  1442. return true;
  1443. }
  1444. else if (mi->isEnabled)
  1445. {
  1446. return true;
  1447. }
  1448. }
  1449. return false;
  1450. }
  1451. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  1452. {
  1453. lookAndFeel = newLookAndFeel;
  1454. }
  1455. //==============================================================================
  1456. PopupMenu::CustomComponent::CustomComponent (bool autoTrigger)
  1457. : triggeredAutomatically (autoTrigger)
  1458. {
  1459. }
  1460. PopupMenu::CustomComponent::~CustomComponent()
  1461. {
  1462. }
  1463. void PopupMenu::CustomComponent::setHighlighted (bool shouldBeHighlighted)
  1464. {
  1465. isHighlighted = shouldBeHighlighted;
  1466. repaint();
  1467. }
  1468. void PopupMenu::CustomComponent::triggerMenuItem()
  1469. {
  1470. if (auto* mic = findParentComponentOfClass<HelperClasses::ItemComponent>())
  1471. {
  1472. if (auto* pmw = mic->findParentComponentOfClass<HelperClasses::MenuWindow>())
  1473. {
  1474. pmw->dismissMenu (&mic->item);
  1475. }
  1476. else
  1477. {
  1478. // something must have gone wrong with the component hierarchy if this happens..
  1479. jassertfalse;
  1480. }
  1481. }
  1482. else
  1483. {
  1484. // why isn't this component inside a menu? Not much point triggering the item if
  1485. // there's no menu.
  1486. jassertfalse;
  1487. }
  1488. }
  1489. //==============================================================================
  1490. PopupMenu::CustomCallback::CustomCallback() {}
  1491. PopupMenu::CustomCallback::~CustomCallback() {}
  1492. //==============================================================================
  1493. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& m, bool recurse) : searchRecursively (recurse)
  1494. {
  1495. index.add (0);
  1496. menus.add (&m);
  1497. }
  1498. PopupMenu::MenuItemIterator::~MenuItemIterator() {}
  1499. bool PopupMenu::MenuItemIterator::next()
  1500. {
  1501. if (index.size() == 0 || menus.getLast()->items.size() == 0)
  1502. return false;
  1503. currentItem = menus.getLast()->items.getUnchecked (index.getLast());
  1504. if (searchRecursively && currentItem->subMenu != nullptr)
  1505. {
  1506. index.add (0);
  1507. menus.add (currentItem->subMenu.get());
  1508. }
  1509. else
  1510. {
  1511. index.setUnchecked (index.size() - 1, index.getLast() + 1);
  1512. }
  1513. while (index.size() > 0 && index.getLast() >= menus.getLast()->items.size())
  1514. {
  1515. index.removeLast();
  1516. menus.removeLast();
  1517. if (index.size() > 0)
  1518. index.setUnchecked (index.size() - 1, index.getLast() + 1);
  1519. }
  1520. return true;
  1521. }
  1522. PopupMenu::Item& PopupMenu::MenuItemIterator::getItem() const noexcept
  1523. {
  1524. jassert (currentItem != nullptr);
  1525. return *(currentItem);
  1526. }
  1527. } // namespace juce