The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

543 lines
22KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 7 technical preview.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For the technical preview this file cannot be licensed commercially.
  8. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  9. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  10. DISCLAIMED.
  11. ==============================================================================
  12. */
  13. namespace juce
  14. {
  15. //==============================================================================
  16. /**
  17. A base class for buttons.
  18. This contains all the logic for button behaviours such as enabling/disabling,
  19. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  20. and radio groups, etc.
  21. @see TextButton, DrawableButton, ToggleButton
  22. @tags{GUI}
  23. */
  24. class JUCE_API Button : public Component,
  25. public SettableTooltipClient
  26. {
  27. protected:
  28. //==============================================================================
  29. /** Creates a button.
  30. @param buttonName the text to put in the button (the component's name is also
  31. initially set to this string, but these can be changed later
  32. using the setName() and setButtonText() methods)
  33. */
  34. explicit Button (const String& buttonName);
  35. public:
  36. /** Destructor. */
  37. ~Button() override;
  38. //==============================================================================
  39. /** Changes the button's text.
  40. @see getButtonText
  41. */
  42. void setButtonText (const String& newText);
  43. /** Returns the text displayed in the button.
  44. @see setButtonText
  45. */
  46. const String& getButtonText() const { return text; }
  47. //==============================================================================
  48. /** Returns true if the button is currently being held down.
  49. @see isOver
  50. */
  51. bool isDown() const noexcept;
  52. /** Returns true if the mouse is currently over the button.
  53. This will be also be true if the button is being held down.
  54. @see isDown
  55. */
  56. bool isOver() const noexcept;
  57. //==============================================================================
  58. /** Indicates that the button's on/off state is toggleable.
  59. By default this is false, and will only be true for ToggleButtons, buttons that
  60. are a part of a radio button group, and buttons for which
  61. getClickingTogglesState() == true, however you can use this method to manually
  62. indicate that a button is toggleable.
  63. This will present the button as toggleable to accessibility clients and add an
  64. accessible "toggle" action for the button that invokes setToggleState().
  65. @see ToggleButton, isToggleable, setToggleState, setClickingTogglesState, setRadioGroupId
  66. */
  67. void setToggleable (bool shouldBeToggleable);
  68. /** Returns true if the button's on/off state is toggleable.
  69. @see setToggleable, setClickingTogglesState
  70. */
  71. bool isToggleable() const noexcept { return canBeToggled || clickTogglesState; }
  72. /** A button has an on/off state associated with it, and this changes that.
  73. By default buttons are 'off' and for simple buttons that you click to perform
  74. an action you won't change this. Toggle buttons, however will want to
  75. change their state when turned on or off.
  76. @param shouldBeOn whether to set the button's toggle state to be on or
  77. off. If it's a member of a button group, this will
  78. always try to turn it on, and to turn off any other
  79. buttons in the group
  80. @param notification determines the behaviour if the value changes - this
  81. can invoke a synchronous call to clicked(), but
  82. sendNotificationAsync is not supported
  83. @see getToggleState, setRadioGroupId
  84. */
  85. void setToggleState (bool shouldBeOn, NotificationType notification);
  86. /** Returns true if the button is 'on'.
  87. By default buttons are 'off' and for simple buttons that you click to perform
  88. an action you won't change this. Toggle buttons, however will want to
  89. change their state when turned on or off.
  90. @see setToggleState
  91. */
  92. bool getToggleState() const noexcept { return isOn.getValue(); }
  93. /** Returns the Value object that represents the button's toggle state.
  94. You can use this Value object to connect the button's state to external values or setters,
  95. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  96. your own Value object.
  97. @see getToggleState, Value
  98. */
  99. Value& getToggleStateValue() noexcept { return isOn; }
  100. /** This tells the button to automatically flip the toggle state when
  101. the button is clicked.
  102. If set to true, then before the clicked() callback occurs, the toggle-state
  103. of the button is flipped. This will also cause isToggleable() to return true.
  104. @see isToggleable
  105. */
  106. void setClickingTogglesState (bool shouldAutoToggleOnClick) noexcept;
  107. /** Returns true if this button is set to be an automatic toggle-button.
  108. This returns the last value that was passed to setClickingTogglesState().
  109. */
  110. bool getClickingTogglesState() const noexcept { return clickTogglesState; }
  111. //==============================================================================
  112. /** Enables the button to act as a member of a mutually-exclusive group
  113. of 'radio buttons'.
  114. If the group ID is set to a non-zero number, then this button will
  115. act as part of a group of buttons with the same ID, only one of
  116. which can be 'on' at the same time. Note that when it's part of
  117. a group, clicking a toggle-button that's 'on' won't turn it off.
  118. To find other buttons with the same ID, this button will search through
  119. its sibling components for ToggleButtons, so all the buttons for a
  120. particular group must be placed inside the same parent component.
  121. Set the group ID back to zero if you want it to act as a normal toggle
  122. button again.
  123. The notification argument lets you specify how other buttons should react
  124. to being turned on or off in response to this call.
  125. @see getRadioGroupId
  126. */
  127. void setRadioGroupId (int newGroupId, NotificationType notification = sendNotification);
  128. /** Returns the ID of the group to which this button belongs.
  129. (See setRadioGroupId() for an explanation of this).
  130. */
  131. int getRadioGroupId() const noexcept { return radioGroupId; }
  132. //==============================================================================
  133. /**
  134. Used to receive callbacks when a button is clicked.
  135. @see Button::addListener, Button::removeListener
  136. */
  137. class JUCE_API Listener
  138. {
  139. public:
  140. /** Destructor. */
  141. virtual ~Listener() = default;
  142. /** Called when the button is clicked. */
  143. virtual void buttonClicked (Button*) = 0;
  144. /** Called when the button's state changes. */
  145. virtual void buttonStateChanged (Button*) {}
  146. };
  147. /** Registers a listener to receive events when this button's state changes.
  148. If the listener is already registered, this will not register it again.
  149. @see removeListener
  150. */
  151. void addListener (Listener* newListener);
  152. /** Removes a previously-registered button listener
  153. @see addListener
  154. */
  155. void removeListener (Listener* listener);
  156. //==============================================================================
  157. /** You can assign a lambda to this callback object to have it called when the button is clicked. */
  158. std::function<void()> onClick;
  159. /** You can assign a lambda to this callback object to have it called when the button's state changes. */
  160. std::function<void()> onStateChange;
  161. //==============================================================================
  162. /** Causes the button to act as if it's been clicked.
  163. This will asynchronously make the button draw itself going down and up, and
  164. will then call back the clicked() method as if mouse was clicked on it.
  165. @see clicked
  166. */
  167. virtual void triggerClick();
  168. //==============================================================================
  169. /** Sets a command ID for this button to automatically invoke when it's clicked.
  170. When the button is pressed, it will use the given manager to trigger the
  171. command ID.
  172. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  173. before this button is. To disable the command triggering, call this method and
  174. pass nullptr as the command manager.
  175. If generateTooltip is true, then the button's tooltip will be automatically
  176. generated based on the name of this command and its current shortcut key.
  177. @see addShortcut, getCommandID
  178. */
  179. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  180. CommandID commandID,
  181. bool generateTooltip);
  182. /** Returns the command ID that was set by setCommandToTrigger(). */
  183. CommandID getCommandID() const noexcept { return commandID; }
  184. //==============================================================================
  185. /** Assigns a shortcut key to trigger the button.
  186. The button registers itself with its top-level parent component for keypresses.
  187. Note that a different way of linking buttons to keypresses is by using the
  188. setCommandToTrigger() method to invoke a command.
  189. @see clearShortcuts
  190. */
  191. void addShortcut (const KeyPress&);
  192. /** Removes all key shortcuts that had been set for this button.
  193. @see addShortcut
  194. */
  195. void clearShortcuts();
  196. /** Returns true if the given keypress is a shortcut for this button.
  197. @see addShortcut
  198. */
  199. bool isRegisteredForShortcut (const KeyPress&) const;
  200. //==============================================================================
  201. /** Sets an auto-repeat speed for the button when it is held down.
  202. (Auto-repeat is disabled by default).
  203. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  204. triggering the next click. If this is zero, auto-repeat
  205. is disabled
  206. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  207. triggered
  208. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  209. get faster, the longer the button is held down, up to the
  210. minimum interval specified here
  211. */
  212. void setRepeatSpeed (int initialDelayInMillisecs,
  213. int repeatDelayInMillisecs,
  214. int minimumDelayInMillisecs = -1) noexcept;
  215. /** Sets whether the button click should happen when the mouse is pressed or released.
  216. By default the button is only considered to have been clicked when the mouse is
  217. released, but setting this to true will make it call the clicked() method as soon
  218. as the button is pressed.
  219. This is useful if the button is being used to show a pop-up menu, as it allows
  220. the click to be used as a drag onto the menu.
  221. */
  222. void setTriggeredOnMouseDown (bool isTriggeredOnMouseDown) noexcept;
  223. /** Returns whether the button click happens when the mouse is pressed or released.
  224. @see setTriggeredOnMouseDown
  225. */
  226. bool getTriggeredOnMouseDown() const noexcept;
  227. /** Returns the number of milliseconds since the last time the button
  228. went into the 'down' state.
  229. */
  230. uint32 getMillisecondsSinceButtonDown() const noexcept;
  231. //==============================================================================
  232. /** Sets the tooltip for this button.
  233. @see TooltipClient, TooltipWindow
  234. */
  235. void setTooltip (const String& newTooltip) override;
  236. //==============================================================================
  237. /** A combination of these flags are used by setConnectedEdges(). */
  238. enum ConnectedEdgeFlags
  239. {
  240. ConnectedOnLeft = 1,
  241. ConnectedOnRight = 2,
  242. ConnectedOnTop = 4,
  243. ConnectedOnBottom = 8
  244. };
  245. /** Hints about which edges of the button might be connected to adjoining buttons.
  246. The value passed in is a bitwise combination of any of the values in the
  247. ConnectedEdgeFlags enum.
  248. E.g. if you are placing two buttons adjacent to each other, you could use this to
  249. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  250. without rounded corners on the edges that connect. It's only a hint, so the
  251. LookAndFeel can choose to ignore it if it's not relevant for this type of
  252. button.
  253. */
  254. void setConnectedEdges (int connectedEdgeFlags);
  255. /** Returns the set of flags passed into setConnectedEdges(). */
  256. int getConnectedEdgeFlags() const noexcept { return connectedEdgeFlags; }
  257. /** Indicates whether the button adjoins another one on its left edge.
  258. @see setConnectedEdges
  259. */
  260. bool isConnectedOnLeft() const noexcept { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  261. /** Indicates whether the button adjoins another one on its right edge.
  262. @see setConnectedEdges
  263. */
  264. bool isConnectedOnRight() const noexcept { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  265. /** Indicates whether the button adjoins another one on its top edge.
  266. @see setConnectedEdges
  267. */
  268. bool isConnectedOnTop() const noexcept { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  269. /** Indicates whether the button adjoins another one on its bottom edge.
  270. @see setConnectedEdges
  271. */
  272. bool isConnectedOnBottom() const noexcept { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  273. //==============================================================================
  274. /** Used by setState(). */
  275. enum ButtonState
  276. {
  277. buttonNormal,
  278. buttonOver,
  279. buttonDown
  280. };
  281. /** Can be used to force the button into a particular state.
  282. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  283. from happening.
  284. The state that you set here will only last until it is automatically changed when the mouse
  285. enters or exits the button, or the mouse-button is pressed or released.
  286. */
  287. void setState (ButtonState newState);
  288. /** Returns the button's current over/down/up state. */
  289. ButtonState getState() const noexcept { return buttonState; }
  290. //==============================================================================
  291. /** This abstract base class is implemented by LookAndFeel classes to provide
  292. button-drawing functionality.
  293. */
  294. struct JUCE_API LookAndFeelMethods
  295. {
  296. virtual ~LookAndFeelMethods() = default;
  297. virtual void drawButtonBackground (Graphics&, Button&, const Colour& backgroundColour,
  298. bool shouldDrawButtonAsHighlighted, bool shouldDrawButtonAsDown) = 0;
  299. virtual Font getTextButtonFont (TextButton&, int buttonHeight) = 0;
  300. virtual int getTextButtonWidthToFitText (TextButton&, int buttonHeight) = 0;
  301. /** Draws the text for a TextButton. */
  302. virtual void drawButtonText (Graphics&, TextButton&,
  303. bool shouldDrawButtonAsHighlighted, bool shouldDrawButtonAsDown) = 0;
  304. /** Draws the contents of a standard ToggleButton. */
  305. virtual void drawToggleButton (Graphics&, ToggleButton&,
  306. bool shouldDrawButtonAsHighlighted, bool shouldDrawButtonAsDown) = 0;
  307. virtual void changeToggleButtonWidthToFitText (ToggleButton&) = 0;
  308. virtual void drawTickBox (Graphics&, Component&, float x, float y, float w, float h,
  309. bool ticked, bool isEnabled,
  310. bool shouldDrawButtonAsHighlighted, bool shouldDrawButtonAsDown) = 0;
  311. virtual void drawDrawableButton (Graphics&, DrawableButton&,
  312. bool shouldDrawButtonAsHighlighted, bool shouldDrawButtonAsDown) = 0;
  313. };
  314. //==============================================================================
  315. #ifndef DOXYGEN
  316. [[deprecated ("This method's parameters have changed.")]]
  317. void setToggleState (bool, bool);
  318. #endif
  319. protected:
  320. //==============================================================================
  321. /** This method is called when the button has been clicked.
  322. Subclasses can override this to perform whatever actions they need to do.
  323. In general, you wouldn't use this method to receive clicks, but should get your callbacks
  324. by attaching a std::function to the onClick callback, or adding a Button::Listener.
  325. @see triggerClick, onClick
  326. */
  327. virtual void clicked();
  328. /** This method is called when the button has been clicked.
  329. By default it just calls clicked(), but you might want to override it to handle
  330. things like clicking when a modifier key is pressed, etc.
  331. @see ModifierKeys
  332. */
  333. virtual void clicked (const ModifierKeys& modifiers);
  334. /** Subclasses should override this to actually paint the button's contents.
  335. It's better to use this than the paint method, because it gives you information
  336. about the over/down state of the button.
  337. @param g the graphics context to use
  338. @param shouldDrawButtonAsHighlighted true if the button is either in the 'over' or 'down' state
  339. @param shouldDrawButtonAsDown true if the button should be drawn in the 'down' position
  340. */
  341. virtual void paintButton (Graphics& g,
  342. bool shouldDrawButtonAsHighlighted,
  343. bool shouldDrawButtonAsDown) = 0;
  344. /** Called when the button's up/down/over state changes.
  345. Subclasses can override this if they need to do something special when the button
  346. goes up or down.
  347. @see isDown, isOver
  348. */
  349. virtual void buttonStateChanged();
  350. //==============================================================================
  351. /** @internal */
  352. virtual void internalClickCallback (const ModifierKeys&);
  353. /** @internal */
  354. void handleCommandMessage (int commandId) override;
  355. /** @internal */
  356. void mouseEnter (const MouseEvent&) override;
  357. /** @internal */
  358. void mouseExit (const MouseEvent&) override;
  359. /** @internal */
  360. void mouseDown (const MouseEvent&) override;
  361. /** @internal */
  362. void mouseDrag (const MouseEvent&) override;
  363. /** @internal */
  364. void mouseUp (const MouseEvent&) override;
  365. /** @internal */
  366. bool keyPressed (const KeyPress&) override;
  367. /** @internal */
  368. using Component::keyStateChanged;
  369. /** @internal */
  370. void paint (Graphics&) override;
  371. /** @internal */
  372. void parentHierarchyChanged() override;
  373. /** @internal */
  374. void visibilityChanged() override;
  375. /** @internal */
  376. void focusGained (FocusChangeType) override;
  377. /** @internal */
  378. void focusLost (FocusChangeType) override;
  379. /** @internal */
  380. void enablementChanged() override;
  381. private:
  382. //==============================================================================
  383. Array<KeyPress> shortcuts;
  384. WeakReference<Component> keySource;
  385. String text;
  386. ListenerList<Listener> buttonListeners;
  387. struct CallbackHelper;
  388. std::unique_ptr<CallbackHelper> callbackHelper;
  389. uint32 buttonPressTime = 0, lastRepeatTime = 0;
  390. ApplicationCommandManager* commandManagerToUse = nullptr;
  391. int autoRepeatDelay = -1, autoRepeatSpeed = 0, autoRepeatMinimumDelay = -1;
  392. int radioGroupId = 0, connectedEdgeFlags = 0;
  393. CommandID commandID = {};
  394. ButtonState buttonState = buttonNormal, lastStatePainted = buttonNormal;
  395. Value isOn;
  396. bool canBeToggled = false;
  397. bool lastToggleState = false;
  398. bool clickTogglesState = false;
  399. bool needsToRelease = false;
  400. bool needsRepainting = false;
  401. bool isKeyDown = false;
  402. bool triggerOnMouseDown = false;
  403. bool generateTooltip = false;
  404. std::unique_ptr<AccessibilityHandler> createAccessibilityHandler() override;
  405. void checkToggleableState (bool wasToggleable);
  406. void repeatTimerCallback();
  407. bool keyStateChangedCallback();
  408. void applicationCommandListChangeCallback();
  409. void updateAutomaticTooltip (const ApplicationCommandInfo&);
  410. ButtonState updateState();
  411. ButtonState updateState (bool isOver, bool isDown);
  412. bool isShortcutPressed() const;
  413. void turnOffOtherButtonsInGroup (NotificationType click, NotificationType state);
  414. void flashButtonState();
  415. void sendClickMessage (const ModifierKeys&);
  416. void sendStateMessage();
  417. void setToggleState (bool shouldBeOn, NotificationType click, NotificationType state);
  418. bool isMouseSourceOver (const MouseEvent& e);
  419. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Button)
  420. };
  421. } // namespace juce