Audio plugin host https://kx.studio/carla
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.

juce_PopupMenu.cpp 62KB

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