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.

514 lines
21KB

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