The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1888 lines
64KB

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