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.

516 lines
20KB

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