juce_Button.h 20 KB

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