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.

697 lines
19KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI 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. class Button::CallbackHelper : public Timer,
  18. public ApplicationCommandManagerListener,
  19. public ValueListener,
  20. public KeyListener
  21. {
  22. public:
  23. CallbackHelper (Button& b) : button (b) {}
  24. void timerCallback() override
  25. {
  26. button.repeatTimerCallback();
  27. }
  28. bool keyStateChanged (bool, Component*) override
  29. {
  30. return button.keyStateChangedCallback();
  31. }
  32. void valueChanged (Value& value) override
  33. {
  34. if (value.refersToSameSourceAs (button.isOn))
  35. button.setToggleState (button.isOn.getValue(), sendNotification);
  36. }
  37. bool keyPressed (const KeyPress&, Component*) override
  38. {
  39. // returning true will avoid forwarding events for keys that we're using as shortcuts
  40. return button.isShortcutPressed();
  41. }
  42. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) override
  43. {
  44. if (info.commandID == button.commandID
  45. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  46. button.flashButtonState();
  47. }
  48. void applicationCommandListChanged() override
  49. {
  50. button.applicationCommandListChangeCallback();
  51. }
  52. private:
  53. Button& button;
  54. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CallbackHelper)
  55. };
  56. //==============================================================================
  57. Button::Button (const String& name)
  58. : Component (name),
  59. text (name),
  60. buttonPressTime (0),
  61. lastRepeatTime (0),
  62. commandManagerToUse (nullptr),
  63. autoRepeatDelay (-1),
  64. autoRepeatSpeed (0),
  65. autoRepeatMinimumDelay (-1),
  66. radioGroupId (0),
  67. connectedEdgeFlags (0),
  68. commandID(),
  69. buttonState (buttonNormal),
  70. lastStatePainted (buttonNormal),
  71. lastToggleState (false),
  72. clickTogglesState (false),
  73. needsToRelease (false),
  74. needsRepainting (false),
  75. isKeyDown (false),
  76. triggerOnMouseDown (false),
  77. generateTooltip (false)
  78. {
  79. callbackHelper = new CallbackHelper (*this);
  80. setWantsKeyboardFocus (true);
  81. isOn.addListener (callbackHelper);
  82. }
  83. Button::~Button()
  84. {
  85. clearShortcuts();
  86. if (commandManagerToUse != nullptr)
  87. commandManagerToUse->removeListener (callbackHelper);
  88. isOn.removeListener (callbackHelper);
  89. callbackHelper = nullptr;
  90. }
  91. //==============================================================================
  92. void Button::setButtonText (const String& newText)
  93. {
  94. if (text != newText)
  95. {
  96. text = newText;
  97. repaint();
  98. }
  99. }
  100. void Button::setTooltip (const String& newTooltip)
  101. {
  102. SettableTooltipClient::setTooltip (newTooltip);
  103. generateTooltip = false;
  104. }
  105. void Button::updateAutomaticTooltip (const ApplicationCommandInfo& info)
  106. {
  107. if (generateTooltip && commandManagerToUse != nullptr)
  108. {
  109. String tt (info.description.isNotEmpty() ? info.description
  110. : info.shortName);
  111. Array<KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  112. for (int i = 0; i < keyPresses.size(); ++i)
  113. {
  114. const String key (keyPresses.getReference(i).getTextDescription());
  115. tt << " [";
  116. if (key.length() == 1)
  117. tt << TRANS("shortcut") << ": '" << key << "']";
  118. else
  119. tt << key << ']';
  120. }
  121. SettableTooltipClient::setTooltip (tt);
  122. }
  123. }
  124. void Button::setConnectedEdges (const int newFlags)
  125. {
  126. if (connectedEdgeFlags != newFlags)
  127. {
  128. connectedEdgeFlags = newFlags;
  129. repaint();
  130. }
  131. }
  132. //==============================================================================
  133. void Button::setToggleState (const bool shouldBeOn, const NotificationType notification)
  134. {
  135. if (shouldBeOn != lastToggleState)
  136. {
  137. WeakReference<Component> deletionWatcher (this);
  138. if (shouldBeOn)
  139. {
  140. turnOffOtherButtonsInGroup (notification);
  141. if (deletionWatcher == nullptr)
  142. return;
  143. }
  144. // This test is done so that if the value is void rather than explicitly set to
  145. // false, the value won't be changed unless the required value is true.
  146. if (getToggleState() != shouldBeOn)
  147. {
  148. isOn = shouldBeOn;
  149. if (deletionWatcher == nullptr)
  150. return;
  151. }
  152. lastToggleState = shouldBeOn;
  153. repaint();
  154. if (notification != dontSendNotification)
  155. {
  156. // async callbacks aren't possible here
  157. jassert (notification != sendNotificationAsync);
  158. sendClickMessage (ModifierKeys::getCurrentModifiers());
  159. if (deletionWatcher == nullptr)
  160. return;
  161. }
  162. if (notification != dontSendNotification)
  163. sendStateMessage();
  164. else
  165. buttonStateChanged();
  166. }
  167. }
  168. void Button::setToggleState (const bool shouldBeOn, bool sendChange)
  169. {
  170. setToggleState (shouldBeOn, sendChange ? sendNotification : dontSendNotification);
  171. }
  172. void Button::setClickingTogglesState (const bool shouldToggle) noexcept
  173. {
  174. clickTogglesState = shouldToggle;
  175. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  176. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  177. // it is that this button represents, and the button will update its state to reflect this
  178. // in the applicationCommandListChanged() method.
  179. jassert (commandManagerToUse == nullptr || ! clickTogglesState);
  180. }
  181. bool Button::getClickingTogglesState() const noexcept
  182. {
  183. return clickTogglesState;
  184. }
  185. void Button::setRadioGroupId (const int newGroupId, NotificationType notification)
  186. {
  187. if (radioGroupId != newGroupId)
  188. {
  189. radioGroupId = newGroupId;
  190. if (lastToggleState)
  191. turnOffOtherButtonsInGroup (notification);
  192. }
  193. }
  194. void Button::turnOffOtherButtonsInGroup (const NotificationType notification)
  195. {
  196. if (Component* const p = getParentComponent())
  197. {
  198. if (radioGroupId != 0)
  199. {
  200. WeakReference<Component> deletionWatcher (this);
  201. for (int i = p->getNumChildComponents(); --i >= 0;)
  202. {
  203. Component* const c = p->getChildComponent (i);
  204. if (c != this)
  205. {
  206. if (Button* const b = dynamic_cast<Button*> (c))
  207. {
  208. if (b->getRadioGroupId() == radioGroupId)
  209. {
  210. b->setToggleState (false, notification);
  211. if (deletionWatcher == nullptr)
  212. return;
  213. }
  214. }
  215. }
  216. }
  217. }
  218. }
  219. }
  220. //==============================================================================
  221. void Button::enablementChanged()
  222. {
  223. updateState();
  224. repaint();
  225. }
  226. Button::ButtonState Button::updateState()
  227. {
  228. return updateState (isMouseOver (true), isMouseButtonDown());
  229. }
  230. Button::ButtonState Button::updateState (const bool over, const bool down)
  231. {
  232. ButtonState newState = buttonNormal;
  233. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  234. {
  235. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  236. newState = buttonDown;
  237. else if (over)
  238. newState = buttonOver;
  239. }
  240. setState (newState);
  241. return newState;
  242. }
  243. void Button::setState (const ButtonState newState)
  244. {
  245. if (buttonState != newState)
  246. {
  247. buttonState = newState;
  248. repaint();
  249. if (buttonState == buttonDown)
  250. {
  251. buttonPressTime = Time::getApproximateMillisecondCounter();
  252. lastRepeatTime = 0;
  253. }
  254. sendStateMessage();
  255. }
  256. }
  257. bool Button::isDown() const noexcept { return buttonState == buttonDown; }
  258. bool Button::isOver() const noexcept { return buttonState != buttonNormal; }
  259. void Button::buttonStateChanged() {}
  260. uint32 Button::getMillisecondsSinceButtonDown() const noexcept
  261. {
  262. const uint32 now = Time::getApproximateMillisecondCounter();
  263. return now > buttonPressTime ? now - buttonPressTime : 0;
  264. }
  265. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) noexcept
  266. {
  267. triggerOnMouseDown = isTriggeredOnMouseDown;
  268. }
  269. //==============================================================================
  270. void Button::clicked()
  271. {
  272. }
  273. void Button::clicked (const ModifierKeys&)
  274. {
  275. clicked();
  276. }
  277. enum { clickMessageId = 0x2f3f4f99 };
  278. void Button::triggerClick()
  279. {
  280. postCommandMessage (clickMessageId);
  281. }
  282. void Button::internalClickCallback (const ModifierKeys& modifiers)
  283. {
  284. if (clickTogglesState)
  285. {
  286. const bool shouldBeOn = (radioGroupId != 0 || ! lastToggleState);
  287. if (shouldBeOn != getToggleState())
  288. {
  289. setToggleState (shouldBeOn, sendNotification);
  290. return;
  291. }
  292. }
  293. sendClickMessage (modifiers);
  294. }
  295. void Button::flashButtonState()
  296. {
  297. if (isEnabled())
  298. {
  299. needsToRelease = true;
  300. setState (buttonDown);
  301. callbackHelper->startTimer (100);
  302. }
  303. }
  304. void Button::handleCommandMessage (int commandId)
  305. {
  306. if (commandId == clickMessageId)
  307. {
  308. if (isEnabled())
  309. {
  310. flashButtonState();
  311. internalClickCallback (ModifierKeys::getCurrentModifiers());
  312. }
  313. }
  314. else
  315. {
  316. Component::handleCommandMessage (commandId);
  317. }
  318. }
  319. //==============================================================================
  320. void Button::addListener (ButtonListener* const newListener)
  321. {
  322. buttonListeners.add (newListener);
  323. }
  324. void Button::removeListener (ButtonListener* const listener)
  325. {
  326. buttonListeners.remove (listener);
  327. }
  328. void Button::sendClickMessage (const ModifierKeys& modifiers)
  329. {
  330. Component::BailOutChecker checker (this);
  331. if (commandManagerToUse != nullptr && commandID != 0)
  332. {
  333. ApplicationCommandTarget::InvocationInfo info (commandID);
  334. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  335. info.originatingComponent = this;
  336. commandManagerToUse->invoke (info, true);
  337. }
  338. clicked (modifiers);
  339. if (! checker.shouldBailOut())
  340. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  341. }
  342. void Button::sendStateMessage()
  343. {
  344. Component::BailOutChecker checker (this);
  345. buttonStateChanged();
  346. if (! checker.shouldBailOut())
  347. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  348. }
  349. //==============================================================================
  350. void Button::paint (Graphics& g)
  351. {
  352. if (needsToRelease && isEnabled())
  353. {
  354. needsToRelease = false;
  355. needsRepainting = true;
  356. }
  357. paintButton (g, isOver(), isDown());
  358. lastStatePainted = buttonState;
  359. }
  360. //==============================================================================
  361. void Button::mouseEnter (const MouseEvent&) { updateState (true, false); }
  362. void Button::mouseExit (const MouseEvent&) { updateState (false, false); }
  363. void Button::mouseDown (const MouseEvent& e)
  364. {
  365. updateState (true, true);
  366. if (isDown())
  367. {
  368. if (autoRepeatDelay >= 0)
  369. callbackHelper->startTimer (autoRepeatDelay);
  370. if (triggerOnMouseDown)
  371. internalClickCallback (e.mods);
  372. }
  373. }
  374. void Button::mouseUp (const MouseEvent& e)
  375. {
  376. const bool wasDown = isDown();
  377. const bool wasOver = isOver();
  378. updateState (isMouseOrTouchOver (e), false);
  379. if (wasDown && wasOver && ! triggerOnMouseDown)
  380. {
  381. if (lastStatePainted != buttonDown)
  382. flashButtonState();
  383. internalClickCallback (e.mods);
  384. }
  385. }
  386. void Button::mouseDrag (const MouseEvent& e)
  387. {
  388. const ButtonState oldState = buttonState;
  389. updateState (isMouseOrTouchOver (e), true);
  390. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  391. callbackHelper->startTimer (autoRepeatSpeed);
  392. }
  393. bool Button::isMouseOrTouchOver (const MouseEvent& e)
  394. {
  395. if (e.source.isTouch())
  396. return getLocalBounds().toFloat().contains (e.position);
  397. return isMouseOver();
  398. }
  399. void Button::focusGained (FocusChangeType)
  400. {
  401. updateState();
  402. repaint();
  403. }
  404. void Button::focusLost (FocusChangeType)
  405. {
  406. updateState();
  407. repaint();
  408. }
  409. void Button::visibilityChanged()
  410. {
  411. needsToRelease = false;
  412. updateState();
  413. }
  414. void Button::parentHierarchyChanged()
  415. {
  416. Component* const newKeySource = (shortcuts.size() == 0) ? nullptr : getTopLevelComponent();
  417. if (newKeySource != keySource.get())
  418. {
  419. if (keySource != nullptr)
  420. keySource->removeKeyListener (callbackHelper);
  421. keySource = newKeySource;
  422. if (keySource != nullptr)
  423. keySource->addKeyListener (callbackHelper);
  424. }
  425. }
  426. //==============================================================================
  427. void Button::setCommandToTrigger (ApplicationCommandManager* const newCommandManager,
  428. const CommandID newCommandID, const bool generateTip)
  429. {
  430. commandID = newCommandID;
  431. generateTooltip = generateTip;
  432. if (commandManagerToUse != newCommandManager)
  433. {
  434. if (commandManagerToUse != nullptr)
  435. commandManagerToUse->removeListener (callbackHelper);
  436. commandManagerToUse = newCommandManager;
  437. if (commandManagerToUse != nullptr)
  438. commandManagerToUse->addListener (callbackHelper);
  439. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  440. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  441. // it is that this button represents, and the button will update its state to reflect this
  442. // in the applicationCommandListChanged() method.
  443. jassert (commandManagerToUse == nullptr || ! clickTogglesState);
  444. }
  445. if (commandManagerToUse != nullptr)
  446. applicationCommandListChangeCallback();
  447. else
  448. setEnabled (true);
  449. }
  450. void Button::applicationCommandListChangeCallback()
  451. {
  452. if (commandManagerToUse != nullptr)
  453. {
  454. ApplicationCommandInfo info (0);
  455. if (commandManagerToUse->getTargetForCommand (commandID, info) != nullptr)
  456. {
  457. updateAutomaticTooltip (info);
  458. setEnabled ((info.flags & ApplicationCommandInfo::isDisabled) == 0);
  459. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, dontSendNotification);
  460. }
  461. else
  462. {
  463. setEnabled (false);
  464. }
  465. }
  466. }
  467. //==============================================================================
  468. void Button::addShortcut (const KeyPress& key)
  469. {
  470. if (key.isValid())
  471. {
  472. jassert (! isRegisteredForShortcut (key)); // already registered!
  473. shortcuts.add (key);
  474. parentHierarchyChanged();
  475. }
  476. }
  477. void Button::clearShortcuts()
  478. {
  479. shortcuts.clear();
  480. parentHierarchyChanged();
  481. }
  482. bool Button::isShortcutPressed() const
  483. {
  484. if (isShowing() && ! isCurrentlyBlockedByAnotherModalComponent())
  485. for (int i = shortcuts.size(); --i >= 0;)
  486. if (shortcuts.getReference(i).isCurrentlyDown())
  487. return true;
  488. return false;
  489. }
  490. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  491. {
  492. for (int i = shortcuts.size(); --i >= 0;)
  493. if (key == shortcuts.getReference(i))
  494. return true;
  495. return false;
  496. }
  497. bool Button::keyStateChangedCallback()
  498. {
  499. if (! isEnabled())
  500. return false;
  501. const bool wasDown = isKeyDown;
  502. isKeyDown = isShortcutPressed();
  503. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  504. callbackHelper->startTimer (autoRepeatDelay);
  505. updateState();
  506. if (isEnabled() && wasDown && ! isKeyDown)
  507. {
  508. internalClickCallback (ModifierKeys::getCurrentModifiers());
  509. // (return immediately - this button may now have been deleted)
  510. return true;
  511. }
  512. return wasDown || isKeyDown;
  513. }
  514. bool Button::keyPressed (const KeyPress& key)
  515. {
  516. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  517. {
  518. triggerClick();
  519. return true;
  520. }
  521. return false;
  522. }
  523. //==============================================================================
  524. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  525. const int repeatMillisecs,
  526. const int minimumDelayInMillisecs) noexcept
  527. {
  528. autoRepeatDelay = initialDelayMillisecs;
  529. autoRepeatSpeed = repeatMillisecs;
  530. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  531. }
  532. void Button::repeatTimerCallback()
  533. {
  534. if (needsRepainting)
  535. {
  536. callbackHelper->stopTimer();
  537. updateState();
  538. needsRepainting = false;
  539. }
  540. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState() == buttonDown)))
  541. {
  542. int repeatSpeed = autoRepeatSpeed;
  543. if (autoRepeatMinimumDelay >= 0)
  544. {
  545. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  546. timeHeldDown *= timeHeldDown;
  547. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  548. }
  549. repeatSpeed = jmax (1, repeatSpeed);
  550. const uint32 now = Time::getMillisecondCounter();
  551. // if we've been blocked from repeating often enough, speed up the repeat timer to compensate..
  552. if (lastRepeatTime != 0 && (int) (now - lastRepeatTime) > repeatSpeed * 2)
  553. repeatSpeed = jmax (1, repeatSpeed / 2);
  554. lastRepeatTime = now;
  555. callbackHelper->startTimer (repeatSpeed);
  556. internalClickCallback (ModifierKeys::getCurrentModifiers());
  557. }
  558. else if (! needsToRelease)
  559. {
  560. callbackHelper->stopTimer();
  561. }
  562. }