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

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