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.

523 lines
21KB

  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. namespace juce
  20. {
  21. //==============================================================================
  22. /**
  23. A base class for buttons.
  24. This contains all the logic for button behaviours such as enabling/disabling,
  25. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  26. and radio groups, etc.
  27. @see TextButton, DrawableButton, ToggleButton
  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. virtual ~Button();
  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 botton'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() {}
  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. /** 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. // This method's parameters have changed - see the new version.
  276. JUCE_DEPRECATED (void setToggleState (bool, bool));
  277. //==============================================================================
  278. /** This abstract base class is implemented by LookAndFeel classes to provide
  279. button-drawing functionality.
  280. */
  281. struct JUCE_API LookAndFeelMethods
  282. {
  283. virtual ~LookAndFeelMethods() {}
  284. virtual void drawButtonBackground (Graphics&, Button&, const Colour& backgroundColour,
  285. bool isMouseOverButton, bool isButtonDown) = 0;
  286. virtual Font getTextButtonFont (TextButton&, int buttonHeight) = 0;
  287. virtual int getTextButtonWidthToFitText (TextButton&, int buttonHeight) = 0;
  288. /** Draws the text for a TextButton. */
  289. virtual void drawButtonText (Graphics&, TextButton&, bool isMouseOverButton, bool isButtonDown) = 0;
  290. /** Draws the contents of a standard ToggleButton. */
  291. virtual void drawToggleButton (Graphics&, ToggleButton&, bool isMouseOverButton, bool isButtonDown) = 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, bool isMouseOverButton, bool isButtonDown) = 0;
  295. virtual void drawDrawableButton (Graphics&, DrawableButton&, bool isMouseOverButton, bool isButtonDown) = 0;
  296. private:
  297. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  298. // These method have been deprecated: see their replacements above.
  299. virtual int getTextButtonFont (TextButton&) { return 0; }
  300. virtual int changeTextButtonWidthToFitText (TextButton&, int) { return 0; }
  301. #endif
  302. };
  303. protected:
  304. //==============================================================================
  305. /** This method is called when the button has been clicked.
  306. Subclasses can override this to perform whatever they actions they need
  307. to do.
  308. Alternatively, a Button::Listener can be added to the button, and these listeners
  309. will be called when the click occurs.
  310. @see triggerClick
  311. */
  312. virtual void clicked();
  313. /** This method is called when the button has been clicked.
  314. By default it just calls clicked(), but you might want to override it to handle
  315. things like clicking when a modifier key is pressed, etc.
  316. @see ModifierKeys
  317. */
  318. virtual void clicked (const ModifierKeys& modifiers);
  319. /** Subclasses should override this to actually paint the button's contents.
  320. It's better to use this than the paint method, because it gives you information
  321. about the over/down state of the button.
  322. @param g the graphics context to use
  323. @param isMouseOverButton true if the button is either in the 'over' or
  324. 'down' state
  325. @param isButtonDown true if the button should be drawn in the 'down' position
  326. */
  327. virtual void paintButton (Graphics& g,
  328. bool isMouseOverButton,
  329. bool isButtonDown) = 0;
  330. /** Called when the button's up/down/over state changes.
  331. Subclasses can override this if they need to do something special when the button
  332. goes up or down.
  333. @see isDown, isOver
  334. */
  335. virtual void buttonStateChanged();
  336. //==============================================================================
  337. /** @internal */
  338. virtual void internalClickCallback (const ModifierKeys&);
  339. /** @internal */
  340. void handleCommandMessage (int commandId) override;
  341. /** @internal */
  342. void mouseEnter (const MouseEvent&) override;
  343. /** @internal */
  344. void mouseExit (const MouseEvent&) override;
  345. /** @internal */
  346. void mouseDown (const MouseEvent&) override;
  347. /** @internal */
  348. void mouseDrag (const MouseEvent&) override;
  349. /** @internal */
  350. void mouseUp (const MouseEvent&) override;
  351. /** @internal */
  352. bool keyPressed (const KeyPress&) override;
  353. /** @internal */
  354. using Component::keyStateChanged;
  355. /** @internal */
  356. void paint (Graphics&) override;
  357. /** @internal */
  358. void parentHierarchyChanged() override;
  359. /** @internal */
  360. void visibilityChanged() override;
  361. /** @internal */
  362. void focusGained (FocusChangeType) override;
  363. /** @internal */
  364. void focusLost (FocusChangeType) override;
  365. /** @internal */
  366. void enablementChanged() override;
  367. private:
  368. //==============================================================================
  369. Array<KeyPress> shortcuts;
  370. WeakReference<Component> keySource;
  371. String text;
  372. ListenerList<Listener> buttonListeners;
  373. class CallbackHelper;
  374. friend class CallbackHelper;
  375. friend struct ContainerDeletePolicy<CallbackHelper>;
  376. ScopedPointer<CallbackHelper> callbackHelper;
  377. uint32 buttonPressTime, lastRepeatTime;
  378. ApplicationCommandManager* commandManagerToUse;
  379. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  380. int radioGroupId, connectedEdgeFlags;
  381. CommandID commandID;
  382. ButtonState buttonState, lastStatePainted;
  383. Value isOn;
  384. bool lastToggleState;
  385. bool clickTogglesState;
  386. bool needsToRelease;
  387. bool needsRepainting;
  388. bool isKeyDown;
  389. bool triggerOnMouseDown;
  390. bool generateTooltip;
  391. void repeatTimerCallback();
  392. bool keyStateChangedCallback();
  393. void applicationCommandListChangeCallback();
  394. void updateAutomaticTooltip (const ApplicationCommandInfo&);
  395. ButtonState updateState();
  396. ButtonState updateState (bool isOver, bool isDown);
  397. bool isShortcutPressed() const;
  398. void turnOffOtherButtonsInGroup (NotificationType);
  399. void flashButtonState();
  400. void sendClickMessage (const ModifierKeys&);
  401. void sendStateMessage();
  402. bool isMouseOrTouchOver (const MouseEvent& e);
  403. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Button)
  404. };
  405. #ifndef DOXYGEN
  406. /** This typedef is just for compatibility with old code and VC6 - newer code should use Button::Listener instead. */
  407. typedef Button::Listener ButtonListener;
  408. #endif
  409. } // namespace juce