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.

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