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.

1047 lines
47KB

  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. //==============================================================================
  21. /** Creates and displays a popup-menu.
  22. To show a popup-menu, you create one of these, add some items to it, then
  23. call its show() method, which returns the id of the item the user selects.
  24. E.g. @code
  25. void MyWidget::mouseDown (const MouseEvent& e)
  26. {
  27. PopupMenu m;
  28. m.addItem (1, "item 1");
  29. m.addItem (2, "item 2");
  30. m.showMenuAsync (PopupMenu::Options(),
  31. [] (int result)
  32. {
  33. if (result == 0)
  34. {
  35. // user dismissed the menu without picking anything
  36. }
  37. else if (result == 1)
  38. {
  39. // user picked item 1
  40. }
  41. else if (result == 2)
  42. {
  43. // user picked item 2
  44. }
  45. });
  46. }
  47. @endcode
  48. Submenus are easy too: @code
  49. void MyWidget::mouseDown (const MouseEvent& e)
  50. {
  51. PopupMenu subMenu;
  52. subMenu.addItem (1, "item 1");
  53. subMenu.addItem (2, "item 2");
  54. PopupMenu mainMenu;
  55. mainMenu.addItem (3, "item 3");
  56. mainMenu.addSubMenu ("other choices", subMenu);
  57. m.showMenuAsync (...);
  58. }
  59. @endcode
  60. @tags{GUI}
  61. */
  62. class JUCE_API PopupMenu
  63. {
  64. public:
  65. //==============================================================================
  66. /** Creates an empty popup menu. */
  67. PopupMenu() = default;
  68. /** Creates a copy of another menu. */
  69. PopupMenu (const PopupMenu&);
  70. /** Destructor. */
  71. ~PopupMenu();
  72. /** Copies this menu from another one. */
  73. PopupMenu& operator= (const PopupMenu&);
  74. /** Move constructor */
  75. PopupMenu (PopupMenu&&) noexcept;
  76. /** Move assignment operator */
  77. PopupMenu& operator= (PopupMenu&&) noexcept;
  78. //==============================================================================
  79. class CustomComponent;
  80. class CustomCallback;
  81. //==============================================================================
  82. /** Resets the menu, removing all its items. */
  83. void clear();
  84. /** Describes a popup menu item. */
  85. struct JUCE_API Item
  86. {
  87. /** Creates a null item.
  88. You'll need to set some fields after creating an Item before you
  89. can add it to a PopupMenu
  90. */
  91. Item();
  92. /** Creates an item with the given text.
  93. This constructor also initialises the itemID to -1, which makes it suitable for
  94. creating lambda-based item actions.
  95. */
  96. Item (String text);
  97. Item (const Item&);
  98. Item& operator= (const Item&);
  99. Item (Item&&);
  100. Item& operator= (Item&&);
  101. /** The menu item's name. */
  102. String text;
  103. /** The menu item's ID.
  104. This must not be 0 if you want the item to be triggerable, but if you're attaching
  105. an action callback to the item, you can set the itemID to -1 to indicate that it
  106. isn't actively needed.
  107. */
  108. int itemID = 0;
  109. /** An optional function which should be invoked when this menu item is triggered. */
  110. std::function<void()> action;
  111. /** A sub-menu, or nullptr if there isn't one. */
  112. std::unique_ptr<PopupMenu> subMenu;
  113. /** A drawable to use as an icon, or nullptr if there isn't one. */
  114. std::unique_ptr<Drawable> image;
  115. /** A custom component for the item to display, or nullptr if there isn't one. */
  116. ReferenceCountedObjectPtr<CustomComponent> customComponent;
  117. /** A custom callback for the item to use, or nullptr if there isn't one. */
  118. ReferenceCountedObjectPtr<CustomCallback> customCallback;
  119. /** A command manager to use to automatically invoke the command, or nullptr if none is specified. */
  120. ApplicationCommandManager* commandManager = nullptr;
  121. /** An optional string describing the shortcut key for this item.
  122. This is only used for displaying at the right-hand edge of a menu item - the
  123. menu won't attempt to actually catch or process the key. If you supply a
  124. commandManager parameter then the menu will attempt to fill-in this field
  125. automatically.
  126. */
  127. String shortcutKeyDescription;
  128. /** A colour to use to draw the menu text.
  129. By default this is transparent black, which means that the LookAndFeel should choose the colour.
  130. */
  131. Colour colour;
  132. /** True if this menu item is enabled. */
  133. bool isEnabled = true;
  134. /** True if this menu item should have a tick mark next to it. */
  135. bool isTicked = false;
  136. /** True if this menu item is a separator line. */
  137. bool isSeparator = false;
  138. /** True if this menu item is a section header. */
  139. bool isSectionHeader = false;
  140. /** True if this is the final item in the current column. */
  141. bool shouldBreakAfter = false;
  142. /** Sets the isTicked flag (and returns a reference to this item to allow chaining). */
  143. Item& setTicked (bool shouldBeTicked = true) & noexcept;
  144. /** Sets the isEnabled flag (and returns a reference to this item to allow chaining). */
  145. Item& setEnabled (bool shouldBeEnabled) & noexcept;
  146. /** Sets the action property (and returns a reference to this item to allow chaining). */
  147. Item& setAction (std::function<void()> action) & noexcept;
  148. /** Sets the itemID property (and returns a reference to this item to allow chaining). */
  149. Item& setID (int newID) & noexcept;
  150. /** Sets the colour property (and returns a reference to this item to allow chaining). */
  151. Item& setColour (Colour) & noexcept;
  152. /** Sets the customComponent property (and returns a reference to this item to allow chaining). */
  153. Item& setCustomComponent (ReferenceCountedObjectPtr<CustomComponent> customComponent) & noexcept;
  154. /** Sets the image property (and returns a reference to this item to allow chaining). */
  155. Item& setImage (std::unique_ptr<Drawable>) & noexcept;
  156. /** Sets the isTicked flag (and returns a reference to this item to allow chaining). */
  157. Item&& setTicked (bool shouldBeTicked = true) && noexcept;
  158. /** Sets the isEnabled flag (and returns a reference to this item to allow chaining). */
  159. Item&& setEnabled (bool shouldBeEnabled) && noexcept;
  160. /** Sets the action property (and returns a reference to this item to allow chaining). */
  161. Item&& setAction (std::function<void()> action) && noexcept;
  162. /** Sets the itemID property (and returns a reference to this item to allow chaining). */
  163. Item&& setID (int newID) && noexcept;
  164. /** Sets the colour property (and returns a reference to this item to allow chaining). */
  165. Item&& setColour (Colour) && noexcept;
  166. /** Sets the customComponent property (and returns a reference to this item to allow chaining). */
  167. Item&& setCustomComponent (ReferenceCountedObjectPtr<CustomComponent> customComponent) && noexcept;
  168. /** Sets the image property (and returns a reference to this item to allow chaining). */
  169. Item&& setImage (std::unique_ptr<Drawable>) && noexcept;
  170. };
  171. /** Adds an item to the menu.
  172. You can call this method for full control over the item that is added, or use the other
  173. addItem helper methods if you want to pass arguments rather than creating an Item object.
  174. */
  175. void addItem (Item newItem);
  176. /** Adds an item to the menu with an action callback. */
  177. void addItem (String itemText,
  178. std::function<void()> action);
  179. /** Adds an item to the menu with an action callback. */
  180. void addItem (String itemText,
  181. bool isEnabled,
  182. bool isTicked,
  183. std::function<void()> action);
  184. /** Appends a new text item for this menu to show.
  185. @param itemResultID the number that will be returned from the show() method
  186. if the user picks this item. The value should never be
  187. zero, because that's used to indicate that the user didn't
  188. select anything.
  189. @param itemText the text to show.
  190. @param isEnabled if false, the item will be shown 'greyed-out' and can't be picked
  191. @param isTicked if true, the item will be shown with a tick next to it
  192. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  193. */
  194. void addItem (int itemResultID,
  195. String itemText,
  196. bool isEnabled = true,
  197. bool isTicked = false);
  198. /** Appends a new item with an icon.
  199. @param itemResultID the number that will be returned from the show() method
  200. if the user picks this item. The value should never be
  201. zero, because that's used to indicate that the user didn't
  202. select anything.
  203. @param itemText the text to show.
  204. @param isEnabled if false, the item will be shown 'greyed-out' and can't be picked
  205. @param isTicked if true, the item will be shown with a tick next to it
  206. @param iconToUse if this is a valid image, it will be displayed to the left of the item.
  207. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  208. */
  209. void addItem (int itemResultID,
  210. String itemText,
  211. bool isEnabled,
  212. bool isTicked,
  213. const Image& iconToUse);
  214. /** Appends a new item with an icon.
  215. @param itemResultID the number that will be returned from the show() method
  216. if the user picks this item. The value should never be
  217. zero, because that's used to indicate that the user didn't
  218. select anything.
  219. @param itemText the text to show.
  220. @param isEnabled if false, the item will be shown 'greyed-out' and can't be picked
  221. @param isTicked if true, the item will be shown with a tick next to it
  222. @param iconToUse a Drawable object to use as the icon to the left of the item.
  223. The menu will take ownership of this drawable object and will
  224. delete it later when no longer needed
  225. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  226. */
  227. void addItem (int itemResultID,
  228. String itemText,
  229. bool isEnabled,
  230. bool isTicked,
  231. std::unique_ptr<Drawable> iconToUse);
  232. /** Adds an item that represents one of the commands in a command manager object.
  233. @param commandManager the manager to use to trigger the command and get information
  234. about it
  235. @param commandID the ID of the command
  236. @param displayName if this is non-empty, then this string will be used instead of
  237. the command's registered name
  238. @param iconToUse an optional Drawable object to use as the icon to the left of the item.
  239. The menu will take ownership of this drawable object and will
  240. delete it later when no longer needed
  241. */
  242. void addCommandItem (ApplicationCommandManager* commandManager,
  243. CommandID commandID,
  244. String displayName = {},
  245. std::unique_ptr<Drawable> iconToUse = {});
  246. /** Appends a text item with a special colour.
  247. This is the same as addItem(), but specifies a colour to use for the
  248. text, which will override the default colours that are used by the
  249. current look-and-feel. See addItem() for a description of the parameters.
  250. */
  251. void addColouredItem (int itemResultID,
  252. String itemText,
  253. Colour itemTextColour,
  254. bool isEnabled = true,
  255. bool isTicked = false,
  256. const Image& iconToUse = {});
  257. /** Appends a text item with a special colour.
  258. This is the same as addItem(), but specifies a colour to use for the
  259. text, which will override the default colours that are used by the
  260. current look-and-feel. See addItem() for a description of the parameters.
  261. */
  262. void addColouredItem (int itemResultID,
  263. String itemText,
  264. Colour itemTextColour,
  265. bool isEnabled,
  266. bool isTicked,
  267. std::unique_ptr<Drawable> iconToUse);
  268. /** Appends a custom menu item.
  269. This will add a user-defined component to use as a menu item.
  270. Note that native macOS menus do not support custom components.
  271. itemTitle will be used as the fallback text for this item, and will
  272. be exposed to screen reader clients.
  273. @see CustomComponent
  274. */
  275. void addCustomItem (int itemResultID,
  276. std::unique_ptr<CustomComponent> customComponent,
  277. std::unique_ptr<const PopupMenu> optionalSubMenu = nullptr,
  278. const String& itemTitle = {});
  279. /** Appends a custom menu item that can't be used to trigger a result.
  280. This will add a user-defined component to use as a menu item.
  281. The caller must ensure that the passed-in component stays alive
  282. until after the menu has been hidden.
  283. If triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  284. detection of a mouse-click on your component, and use that to trigger the
  285. menu ID specified in itemResultID. If this is false, the menu item can't
  286. be triggered, so itemResultID is not used.
  287. itemTitle will be used as the fallback text for this item, and will
  288. be exposed to screen reader clients.
  289. Note that native macOS menus do not support custom components.
  290. */
  291. void addCustomItem (int itemResultID,
  292. Component& customComponent,
  293. int idealWidth,
  294. int idealHeight,
  295. bool triggerMenuItemAutomaticallyWhenClicked,
  296. std::unique_ptr<const PopupMenu> optionalSubMenu = nullptr,
  297. const String& itemTitle = {});
  298. /** Appends a sub-menu.
  299. If the menu that's passed in is empty, it will appear as an inactive item.
  300. If the itemResultID argument is non-zero, then the sub-menu item itself can be
  301. clicked to trigger it as a command.
  302. */
  303. void addSubMenu (String subMenuName,
  304. PopupMenu subMenu,
  305. bool isEnabled = true);
  306. /** Appends a sub-menu with an icon.
  307. If the menu that's passed in is empty, it will appear as an inactive item.
  308. If the itemResultID argument is non-zero, then the sub-menu item itself can be
  309. clicked to trigger it as a command.
  310. */
  311. void addSubMenu (String subMenuName,
  312. PopupMenu subMenu,
  313. bool isEnabled,
  314. const Image& iconToUse,
  315. bool isTicked = false,
  316. int itemResultID = 0);
  317. /** Appends a sub-menu with an icon.
  318. If the menu that's passed in is empty, it will appear as an inactive item.
  319. If the itemResultID argument is non-zero, then the sub-menu item itself can be
  320. clicked to trigger it as a command.
  321. The iconToUse parameter is a Drawable object to use as the icon to the left of
  322. the item. The menu will take ownership of this drawable object and will delete it
  323. later when no longer needed
  324. */
  325. void addSubMenu (String subMenuName,
  326. PopupMenu subMenu,
  327. bool isEnabled,
  328. std::unique_ptr<Drawable> iconToUse,
  329. bool isTicked = false,
  330. int itemResultID = 0);
  331. /** Appends a separator to the menu, to help break it up into sections.
  332. The menu class is smart enough not to display separators at the top or bottom
  333. of the menu, and it will replace multiple adjacent separators with a single
  334. one, so your code can be quite free and easy about adding these, and it'll
  335. always look ok.
  336. */
  337. void addSeparator();
  338. /** Adds a non-clickable text item to the menu.
  339. This is a bold-font items which can be used as a header to separate the items
  340. into named groups.
  341. */
  342. void addSectionHeader (String title);
  343. /** Adds a column break to the menu, to help break it up into sections.
  344. Subsequent items will be placed in a new column, rather than being appended
  345. to the current column.
  346. If a menu contains explicit column breaks, the menu will never add additional
  347. breaks.
  348. */
  349. void addColumnBreak();
  350. /** Returns the number of items that the menu currently contains.
  351. (This doesn't count separators).
  352. */
  353. int getNumItems() const noexcept;
  354. /** Returns true if the menu contains a command item that triggers the given command. */
  355. bool containsCommandItem (int commandID) const;
  356. /** Returns true if the menu contains any items that can be used. */
  357. bool containsAnyActiveItems() const noexcept;
  358. //==============================================================================
  359. /** Class used to create a set of options to pass to the show() method.
  360. You can chain together a series of calls to this class's methods to create
  361. a set of whatever options you want to specify.
  362. E.g. @code
  363. PopupMenu menu;
  364. ...
  365. menu.showMenu (PopupMenu::Options().withMinimumWidth (100)
  366. .withMaximumNumColumns (3)
  367. .withTargetComponent (myComp));
  368. @endcode
  369. */
  370. class JUCE_API Options
  371. {
  372. public:
  373. /** By default, the target screen area will be the current mouse position. */
  374. Options();
  375. Options (const Options&) = default;
  376. Options& operator= (const Options&) = default;
  377. enum class PopupDirection
  378. {
  379. upwards,
  380. downwards
  381. };
  382. //==============================================================================
  383. /** Sets the target component to use when displaying the menu.
  384. This is normally the button or other control that triggered the menu.
  385. The target component is primarily used to control the scale of the menu, so
  386. it's important to supply a target component if you'll be using your program
  387. on hi-DPI displays.
  388. This function will also set the target screen area, so that the menu displays
  389. next to the target component. If you need to display the menu at a specific
  390. location, you should call withTargetScreenArea() after withTargetComponent.
  391. @see withTargetComponent, withTargetScreenArea
  392. */
  393. JUCE_NODISCARD Options withTargetComponent (Component* targetComponent) const;
  394. JUCE_NODISCARD Options withTargetComponent (Component& targetComponent) const;
  395. /** Sets the region of the screen next to which the menu should be displayed.
  396. To display the menu next to the mouse cursor use withMousePosition(),
  397. which is equivalent to passing the following to this function:
  398. @code
  399. Rectangle<int>{}.withPosition (Desktop::getMousePosition())
  400. @endcode
  401. withTargetComponent() will also set the target screen area. If you need
  402. a target component and a target screen area, make sure to call
  403. withTargetScreenArea() after withTargetComponent().
  404. @see withMousePosition
  405. */
  406. JUCE_NODISCARD Options withTargetScreenArea (Rectangle<int> targetArea) const;
  407. /** Sets the target screen area to match the current mouse position.
  408. Make sure to call this after withTargetComponent().
  409. @see withTargetScreenArea
  410. */
  411. JUCE_NODISCARD Options withMousePosition() const;
  412. /** If the passed component has been deleted when the popup menu exits,
  413. the selected item's action will not be called.
  414. This is useful for avoiding dangling references inside the action
  415. callback, in the case that the callback needs to access a component that
  416. may be deleted.
  417. */
  418. JUCE_NODISCARD Options withDeletionCheck (Component& componentToWatchForDeletion) const;
  419. /** Sets the minimum width of the popup window. */
  420. JUCE_NODISCARD Options withMinimumWidth (int minWidth) const;
  421. /** Sets the minimum number of columns in the popup window. */
  422. JUCE_NODISCARD Options withMinimumNumColumns (int minNumColumns) const;
  423. /** Sets the maximum number of columns in the popup window. */
  424. JUCE_NODISCARD Options withMaximumNumColumns (int maxNumColumns) const;
  425. /** Sets the default height of each item in the popup menu. */
  426. JUCE_NODISCARD Options withStandardItemHeight (int standardHeight) const;
  427. /** Sets an item which must be visible when the menu is initially drawn.
  428. This is useful to ensure that a particular item is shown when the menu
  429. contains too many items to display on a single screen.
  430. */
  431. JUCE_NODISCARD Options withItemThatMustBeVisible (int idOfItemToBeVisible) const;
  432. /** Sets a component that the popup menu will be drawn into.
  433. Some plugin formats, such as AUv3, dislike it when the plugin editor
  434. spawns additional windows. Some AUv3 hosts display pink backgrounds
  435. underneath transparent popup windows, which is confusing and can appear
  436. as though the plugin is malfunctioning. Setting a parent component will
  437. avoid this unwanted behaviour, but with the downside that the menu size
  438. will be constrained by the size of the parent component.
  439. */
  440. JUCE_NODISCARD Options withParentComponent (Component* parentComponent) const;
  441. /** Sets the direction of the popup menu relative to the target screen area. */
  442. JUCE_NODISCARD Options withPreferredPopupDirection (PopupDirection direction) const;
  443. /** Sets an item to select in the menu.
  444. This is useful for controls such as combo boxes, where opening the combo box
  445. with the keyboard should ideally highlight the currently-selected item, allowing
  446. the next/previous item to be selected by pressing up/down on the keyboard, rather
  447. than needing to move the highlighted row down from the top of the menu each time
  448. it is opened.
  449. */
  450. JUCE_NODISCARD Options withInitiallySelectedItem (int idOfItemToBeSelected) const;
  451. //==============================================================================
  452. /** Gets the parent component. This may be nullptr if the Component has been deleted.
  453. @see withParentComponent
  454. */
  455. Component* getParentComponent() const noexcept { return parentComponent; }
  456. /** Gets the target component. This may be nullptr if the Component has been deleted.
  457. @see withTargetComponent
  458. */
  459. Component* getTargetComponent() const noexcept { return targetComponent; }
  460. /** Returns true if the menu was watching a component, and that component has been deleted, and false otherwise.
  461. @see withDeletionCheck
  462. */
  463. bool hasWatchedComponentBeenDeleted() const noexcept { return isWatchingForDeletion && componentToWatchForDeletion == nullptr; }
  464. /** Gets the target screen area.
  465. @see withTargetScreenArea
  466. */
  467. Rectangle<int> getTargetScreenArea() const noexcept { return targetArea; }
  468. /** Gets the minimum width.
  469. @see withMinimumWidth
  470. */
  471. int getMinimumWidth() const noexcept { return minWidth; }
  472. /** Gets the maximum number of columns.
  473. @see withMaximumNumColumns
  474. */
  475. int getMaximumNumColumns() const noexcept { return maxColumns; }
  476. /** Gets the minimum number of columns.
  477. @see withMinimumNumColumns
  478. */
  479. int getMinimumNumColumns() const noexcept { return minColumns; }
  480. /** Gets the default height of items in the menu.
  481. @see withStandardItemHeight
  482. */
  483. int getStandardItemHeight() const noexcept { return standardHeight; }
  484. /** Gets the ID of the item that must be visible when the menu is initially shown.
  485. @see withItemThatMustBeVisible
  486. */
  487. int getItemThatMustBeVisible() const noexcept { return visibleItemID; }
  488. /** Gets the preferred popup menu direction.
  489. @see withPreferredPopupDirection
  490. */
  491. PopupDirection getPreferredPopupDirection() const noexcept { return preferredPopupDirection; }
  492. /** Gets the ID of the item that must be selected when the menu is initially shown.
  493. @see withItemThatMustBeVisible
  494. */
  495. int getInitiallySelectedItemId() const noexcept { return initiallySelectedItemId; }
  496. private:
  497. //==============================================================================
  498. Rectangle<int> targetArea;
  499. WeakReference<Component> targetComponent, parentComponent, componentToWatchForDeletion;
  500. int visibleItemID = 0, minWidth = 0, minColumns = 1, maxColumns = 0, standardHeight = 0, initiallySelectedItemId = 0;
  501. bool isWatchingForDeletion = false;
  502. PopupDirection preferredPopupDirection = PopupDirection::downwards;
  503. };
  504. //==============================================================================
  505. #if JUCE_MODAL_LOOPS_PERMITTED
  506. /** Displays the menu and waits for the user to pick something.
  507. This will display the menu modally, and return the ID of the item that the
  508. user picks. If they click somewhere off the menu to get rid of it without
  509. choosing anything, this will return 0.
  510. The current location of the mouse will be used as the position to show the
  511. menu - to explicitly set the menu's position, use showAt() instead. Depending
  512. on where this point is on the screen, the menu will appear above, below or
  513. to the side of the point.
  514. @param itemIDThatMustBeVisible if you set this to the ID of one of the menu items,
  515. then when the menu first appears, it will make sure
  516. that this item is visible. So if the menu has too many
  517. items to fit on the screen, it will be scrolled to a
  518. position where this item is visible.
  519. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  520. than this if some items are too long to fit.
  521. @param maximumNumColumns if there are too many items to fit on-screen in a single
  522. vertical column, the menu may be laid out as a series of
  523. columns - this is the maximum number allowed. To use the
  524. default value for this (probably about 7), you can pass
  525. in zero.
  526. @param standardItemHeight if this is non-zero, it will be used as the standard
  527. height for menu items (apart from custom items)
  528. @param callback if this is not a nullptr, the menu will be launched
  529. asynchronously, returning immediately, and the callback
  530. will receive a call when the menu is either dismissed or
  531. has an item selected. This object will be owned and
  532. deleted by the system, so make sure that it works safely
  533. and that any pointers that it uses are safely within scope.
  534. @see showAt
  535. */
  536. int show (int itemIDThatMustBeVisible = 0,
  537. int minimumWidth = 0,
  538. int maximumNumColumns = 0,
  539. int standardItemHeight = 0,
  540. ModalComponentManager::Callback* callback = nullptr);
  541. /** Displays the menu at a specific location.
  542. This is the same as show(), but uses a specific location (in global screen
  543. coordinates) rather than the current mouse position.
  544. The screenAreaToAttachTo parameter indicates a screen area to which the menu
  545. will be adjacent. Depending on where this is, the menu will decide which edge to
  546. attach itself to, in order to fit itself fully on-screen. If you just want to
  547. trigger a menu at a specific point, you can pass in a rectangle of size (0, 0)
  548. with the position that you want.
  549. @see show()
  550. */
  551. int showAt (Rectangle<int> screenAreaToAttachTo,
  552. int itemIDThatMustBeVisible = 0,
  553. int minimumWidth = 0,
  554. int maximumNumColumns = 0,
  555. int standardItemHeight = 0,
  556. ModalComponentManager::Callback* callback = nullptr);
  557. /** Displays the menu as if it's attached to a component such as a button.
  558. This is similar to showAt(), but will position it next to the given component, e.g.
  559. so that the menu's edge is aligned with that of the component. This is intended for
  560. things like buttons that trigger a pop-up menu.
  561. */
  562. int showAt (Component* componentToAttachTo,
  563. int itemIDThatMustBeVisible = 0,
  564. int minimumWidth = 0,
  565. int maximumNumColumns = 0,
  566. int standardItemHeight = 0,
  567. ModalComponentManager::Callback* callback = nullptr);
  568. /** Displays and runs the menu modally, with a set of options.
  569. */
  570. int showMenu (const Options& options);
  571. #endif
  572. /** Runs the menu asynchronously. */
  573. void showMenuAsync (const Options& options);
  574. /** Runs the menu asynchronously, with a user-provided callback that will receive the result. */
  575. void showMenuAsync (const Options& options,
  576. ModalComponentManager::Callback* callback);
  577. /** Runs the menu asynchronously, with a user-provided callback that will receive the result. */
  578. void showMenuAsync (const Options& options,
  579. std::function<void (int)> callback);
  580. //==============================================================================
  581. /** Closes any menus that are currently open.
  582. This might be useful if you have a situation where your window is being closed
  583. by some means other than a user action, and you'd like to make sure that menus
  584. aren't left hanging around.
  585. */
  586. static bool JUCE_CALLTYPE dismissAllActiveMenus();
  587. //==============================================================================
  588. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  589. This can be called before show() if you need a customised menu. Be careful
  590. not to delete the LookAndFeel object before the menu has been deleted.
  591. */
  592. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  593. //==============================================================================
  594. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  595. These constants can be used either via the LookAndFeel::setColour()
  596. method for the look and feel that is set for this menu with setLookAndFeel()
  597. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  598. */
  599. enum ColourIds
  600. {
  601. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  602. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  603. colour is specified when the item is added). */
  604. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  605. addSectionHeader() method). */
  606. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  607. highlighted menu item. */
  608. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  609. highlighted item. */
  610. };
  611. //==============================================================================
  612. /**
  613. Allows you to iterate through the items in a pop-up menu, and examine
  614. their properties.
  615. To use this, just create one and repeatedly call its next() method. When this
  616. returns true, all the member variables of the iterator are filled-out with
  617. information describing the menu item. When it returns false, the end of the
  618. list has been reached.
  619. */
  620. class JUCE_API MenuItemIterator
  621. {
  622. public:
  623. //==============================================================================
  624. /** Creates an iterator that will scan through the items in the specified
  625. menu.
  626. Be careful not to add any items to a menu while it is being iterated,
  627. or things could get out of step.
  628. @param menu the menu that needs to be scanned
  629. @param searchRecursively if true, all submenus will be recursed into to
  630. do an exhaustive search
  631. */
  632. MenuItemIterator (const PopupMenu& menu, bool searchRecursively = false);
  633. /** Destructor. */
  634. ~MenuItemIterator();
  635. /** Returns true if there is another item, and sets up all this object's
  636. member variables to reflect that item's properties.
  637. */
  638. bool next();
  639. /** Returns a reference to the description of the current item.
  640. It is only valid to call this after next() has returned true!
  641. */
  642. Item& getItem() const;
  643. private:
  644. //==============================================================================
  645. bool searchRecursively;
  646. Array<int> index;
  647. Array<const PopupMenu*> menus;
  648. PopupMenu::Item* currentItem = nullptr;
  649. MenuItemIterator& operator= (const MenuItemIterator&);
  650. JUCE_LEAK_DETECTOR (MenuItemIterator)
  651. };
  652. //==============================================================================
  653. /** A user-defined component that can be used as an item in a popup menu.
  654. @see PopupMenu::addCustomItem
  655. */
  656. class JUCE_API CustomComponent : public Component,
  657. public SingleThreadedReferenceCountedObject
  658. {
  659. public:
  660. /** Creates a custom item that is triggered automatically. */
  661. CustomComponent();
  662. /** Creates a custom item.
  663. If isTriggeredAutomatically is true, then the menu will automatically detect
  664. a mouse-click on this component and use that to invoke the menu item. If it's
  665. false, then it's up to your class to manually trigger the item when it wants to.
  666. If isTriggeredAutomatically is true, then an accessibility handler 'wrapper'
  667. will be created for the item that allows pressing, focusing, and toggling.
  668. If isTriggeredAutomatically is false, and the item has no submenu, then
  669. no accessibility wrapper will be created and your component must be
  670. independently accessible.
  671. */
  672. explicit CustomComponent (bool isTriggeredAutomatically);
  673. /** Returns a rectangle with the size that this component would like to have.
  674. Note that the size which this method returns isn't necessarily the one that
  675. the menu will give it, as the items will be stretched to have a uniform width.
  676. */
  677. virtual void getIdealSize (int& idealWidth, int& idealHeight) = 0;
  678. /** Dismisses the menu, indicating that this item has been chosen.
  679. This will cause the menu to exit from its modal state, returning
  680. this item's id as the result.
  681. */
  682. void triggerMenuItem();
  683. /** Returns true if this item should be highlighted because the mouse is over it.
  684. You can call this method in your paint() method to find out whether
  685. to draw a highlight.
  686. */
  687. bool isItemHighlighted() const noexcept { return isHighlighted; }
  688. /** Returns a pointer to the Item that holds this custom component, if this
  689. component is currently held by an Item.
  690. You can query the Item for information that you might want to use
  691. in your paint() method, such as the item's enabled and ticked states.
  692. */
  693. const PopupMenu::Item* getItem() const noexcept { return item; }
  694. /** @internal */
  695. bool isTriggeredAutomatically() const noexcept { return triggeredAutomatically; }
  696. /** @internal */
  697. void setHighlighted (bool shouldBeHighlighted);
  698. private:
  699. //==============================================================================
  700. bool isHighlighted = false, triggeredAutomatically;
  701. const PopupMenu::Item* item = nullptr;
  702. friend PopupMenu;
  703. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponent)
  704. };
  705. //==============================================================================
  706. /** A user-defined callback that can be used for specific items in a popup menu.
  707. @see PopupMenu::Item::customCallback
  708. */
  709. class JUCE_API CustomCallback : public SingleThreadedReferenceCountedObject
  710. {
  711. public:
  712. CustomCallback();
  713. ~CustomCallback() override;
  714. /** Callback to indicate this item has been triggered.
  715. @returns true if the itemID should be sent to the exitModalState method, or
  716. false if it should send 0, indicating no further action should be taken
  717. */
  718. virtual bool menuItemTriggered() = 0;
  719. private:
  720. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomCallback)
  721. };
  722. //==============================================================================
  723. /** This abstract base class is implemented by LookAndFeel classes to provide
  724. menu drawing functionality.
  725. */
  726. struct JUCE_API LookAndFeelMethods
  727. {
  728. virtual ~LookAndFeelMethods() = default;
  729. /** Fills the background of a popup menu component. */
  730. virtual void drawPopupMenuBackground (Graphics&, int width, int height);
  731. /** Fills the background of a popup menu component. */
  732. virtual void drawPopupMenuBackgroundWithOptions (Graphics&,
  733. int width,
  734. int height,
  735. const Options&) = 0;
  736. /** Draws one of the items in a popup menu. */
  737. virtual void drawPopupMenuItem (Graphics&, const Rectangle<int>& area,
  738. bool isSeparator, bool isActive, bool isHighlighted,
  739. bool isTicked, bool hasSubMenu,
  740. const String& text,
  741. const String& shortcutKeyText,
  742. const Drawable* icon,
  743. const Colour* textColour);
  744. /** Draws one of the items in a popup menu. */
  745. virtual void drawPopupMenuItemWithOptions (Graphics&, const Rectangle<int>& area,
  746. bool isHighlighted,
  747. const Item& item,
  748. const Options&) = 0;
  749. virtual void drawPopupMenuSectionHeader (Graphics&, const Rectangle<int>&,
  750. const String&);
  751. virtual void drawPopupMenuSectionHeaderWithOptions (Graphics&, const Rectangle<int>& area,
  752. const String& sectionName,
  753. const Options&) = 0;
  754. /** Returns the size and style of font to use in popup menus. */
  755. virtual Font getPopupMenuFont() = 0;
  756. virtual void drawPopupMenuUpDownArrow (Graphics&,
  757. int width, int height,
  758. bool isScrollUpArrow);
  759. virtual void drawPopupMenuUpDownArrowWithOptions (Graphics&,
  760. int width, int height,
  761. bool isScrollUpArrow,
  762. const Options&) = 0;
  763. /** Finds the best size for an item in a popup menu. */
  764. virtual void getIdealPopupMenuItemSize (const String& text,
  765. bool isSeparator,
  766. int standardMenuItemHeight,
  767. int& idealWidth,
  768. int& idealHeight);
  769. /** Finds the best size for an item in a popup menu. */
  770. virtual void getIdealPopupMenuItemSizeWithOptions (const String& text,
  771. bool isSeparator,
  772. int standardMenuItemHeight,
  773. int& idealWidth,
  774. int& idealHeight,
  775. const Options&) = 0;
  776. virtual int getMenuWindowFlags() = 0;
  777. virtual void drawMenuBarBackground (Graphics&, int width, int height,
  778. bool isMouseOverBar,
  779. MenuBarComponent&) = 0;
  780. virtual int getDefaultMenuBarHeight() = 0;
  781. virtual int getMenuBarItemWidth (MenuBarComponent&, int itemIndex, const String& itemText) = 0;
  782. virtual Font getMenuBarFont (MenuBarComponent&, int itemIndex, const String& itemText) = 0;
  783. virtual void drawMenuBarItem (Graphics&, int width, int height,
  784. int itemIndex,
  785. const String& itemText,
  786. bool isMouseOverItem,
  787. bool isMenuOpen,
  788. bool isMouseOverBar,
  789. MenuBarComponent&) = 0;
  790. virtual Component* getParentComponentForMenuOptions (const Options& options) = 0;
  791. virtual void preparePopupMenuWindow (Component& newWindow) = 0;
  792. /** Return true if you want your popup menus to scale with the target component's AffineTransform
  793. or scale factor
  794. */
  795. virtual bool shouldPopupMenuScaleWithTargetComponent (const Options& options) = 0;
  796. virtual int getPopupMenuBorderSize();
  797. virtual int getPopupMenuBorderSizeWithOptions (const Options&) = 0;
  798. /** Implement this to draw some custom decoration between the columns of the popup menu.
  799. `getPopupMenuColumnSeparatorWidthWithOptions` must return a positive value in order
  800. to display the separator.
  801. */
  802. virtual void drawPopupMenuColumnSeparatorWithOptions (Graphics& g,
  803. const Rectangle<int>& bounds,
  804. const Options&) = 0;
  805. /** Return the amount of space that should be left between popup menu columns. */
  806. virtual int getPopupMenuColumnSeparatorWidthWithOptions (const Options&) = 0;
  807. };
  808. //==============================================================================
  809. #ifndef DOXYGEN
  810. [[deprecated ("Use the new method.")]]
  811. int drawPopupMenuItem (Graphics&, int, int, bool, bool, bool, bool, bool, const String&, const String&, Image*, const Colour*) { return 0; }
  812. #endif
  813. private:
  814. //==============================================================================
  815. JUCE_PUBLIC_IN_DLL_BUILD (struct HelperClasses)
  816. class Window;
  817. friend struct HelperClasses;
  818. friend class MenuBarComponent;
  819. Array<Item> items;
  820. WeakReference<LookAndFeel> lookAndFeel;
  821. Component* createWindow (const Options&, ApplicationCommandManager**) const;
  822. int showWithOptionalCallback (const Options&, ModalComponentManager::Callback*, bool);
  823. static void setItem (CustomComponent&, const Item*);
  824. JUCE_LEAK_DETECTOR (PopupMenu)
  825. };
  826. } // namespace juce