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.

521 lines
20KB

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