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.

1843 lines
61KB

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