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.

521 lines
21KB

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