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.

1888 lines
64KB

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