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.

1884 lines
63KB

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