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 68KB

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