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.

682 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. if (getToggleState() != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  145. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  146. lastToggleState = shouldBeOn;
  147. repaint();
  148. if (notification != dontSendNotification)
  149. {
  150. // async callbacks aren't possible here
  151. jassert (notification != sendNotificationAsync);
  152. sendClickMessage (ModifierKeys::getCurrentModifiers());
  153. if (deletionWatcher == nullptr)
  154. return;
  155. }
  156. if (notification != dontSendNotification)
  157. sendStateMessage();
  158. else
  159. buttonStateChanged();
  160. }
  161. }
  162. void Button::setToggleState (const bool shouldBeOn, bool sendChange)
  163. {
  164. setToggleState (shouldBeOn, sendChange ? sendNotification : dontSendNotification);
  165. }
  166. void Button::setClickingTogglesState (const bool shouldToggle) noexcept
  167. {
  168. clickTogglesState = shouldToggle;
  169. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  170. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  171. // it is that this button represents, and the button will update its state to reflect this
  172. // in the applicationCommandListChanged() method.
  173. jassert (commandManagerToUse == nullptr || ! clickTogglesState);
  174. }
  175. bool Button::getClickingTogglesState() const noexcept
  176. {
  177. return clickTogglesState;
  178. }
  179. void Button::setRadioGroupId (const int newGroupId, NotificationType notification)
  180. {
  181. if (radioGroupId != newGroupId)
  182. {
  183. radioGroupId = newGroupId;
  184. if (lastToggleState)
  185. turnOffOtherButtonsInGroup (notification);
  186. }
  187. }
  188. void Button::turnOffOtherButtonsInGroup (const NotificationType notification)
  189. {
  190. if (Component* const p = getParentComponent())
  191. {
  192. if (radioGroupId != 0)
  193. {
  194. WeakReference<Component> deletionWatcher (this);
  195. for (int i = p->getNumChildComponents(); --i >= 0;)
  196. {
  197. Component* const c = p->getChildComponent (i);
  198. if (c != this)
  199. {
  200. if (Button* const b = dynamic_cast<Button*> (c))
  201. {
  202. if (b->getRadioGroupId() == radioGroupId)
  203. {
  204. b->setToggleState (false, notification);
  205. if (deletionWatcher == nullptr)
  206. return;
  207. }
  208. }
  209. }
  210. }
  211. }
  212. }
  213. }
  214. //==============================================================================
  215. void Button::enablementChanged()
  216. {
  217. updateState();
  218. repaint();
  219. }
  220. Button::ButtonState Button::updateState()
  221. {
  222. return updateState (isMouseOver (true), isMouseButtonDown());
  223. }
  224. Button::ButtonState Button::updateState (const bool over, const bool down)
  225. {
  226. ButtonState newState = buttonNormal;
  227. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  228. {
  229. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  230. newState = buttonDown;
  231. else if (over)
  232. newState = buttonOver;
  233. }
  234. setState (newState);
  235. return newState;
  236. }
  237. void Button::setState (const ButtonState newState)
  238. {
  239. if (buttonState != newState)
  240. {
  241. buttonState = newState;
  242. repaint();
  243. if (buttonState == buttonDown)
  244. {
  245. buttonPressTime = Time::getApproximateMillisecondCounter();
  246. lastRepeatTime = 0;
  247. }
  248. sendStateMessage();
  249. }
  250. }
  251. bool Button::isDown() const noexcept { return buttonState == buttonDown; }
  252. bool Button::isOver() const noexcept { return buttonState != buttonNormal; }
  253. void Button::buttonStateChanged() {}
  254. uint32 Button::getMillisecondsSinceButtonDown() const noexcept
  255. {
  256. const uint32 now = Time::getApproximateMillisecondCounter();
  257. return now > buttonPressTime ? now - buttonPressTime : 0;
  258. }
  259. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) noexcept
  260. {
  261. triggerOnMouseDown = isTriggeredOnMouseDown;
  262. }
  263. //==============================================================================
  264. void Button::clicked()
  265. {
  266. }
  267. void Button::clicked (const ModifierKeys&)
  268. {
  269. clicked();
  270. }
  271. enum { clickMessageId = 0x2f3f4f99 };
  272. void Button::triggerClick()
  273. {
  274. postCommandMessage (clickMessageId);
  275. }
  276. void Button::internalClickCallback (const ModifierKeys& modifiers)
  277. {
  278. if (clickTogglesState)
  279. {
  280. const bool shouldBeOn = (radioGroupId != 0 || ! lastToggleState);
  281. if (shouldBeOn != getToggleState())
  282. {
  283. setToggleState (shouldBeOn, sendNotification);
  284. return;
  285. }
  286. }
  287. sendClickMessage (modifiers);
  288. }
  289. void Button::flashButtonState()
  290. {
  291. if (isEnabled())
  292. {
  293. needsToRelease = true;
  294. setState (buttonDown);
  295. callbackHelper->startTimer (100);
  296. }
  297. }
  298. void Button::handleCommandMessage (int commandId)
  299. {
  300. if (commandId == clickMessageId)
  301. {
  302. if (isEnabled())
  303. {
  304. flashButtonState();
  305. internalClickCallback (ModifierKeys::getCurrentModifiers());
  306. }
  307. }
  308. else
  309. {
  310. Component::handleCommandMessage (commandId);
  311. }
  312. }
  313. //==============================================================================
  314. void Button::addListener (ButtonListener* const newListener)
  315. {
  316. buttonListeners.add (newListener);
  317. }
  318. void Button::removeListener (ButtonListener* const listener)
  319. {
  320. buttonListeners.remove (listener);
  321. }
  322. void Button::sendClickMessage (const ModifierKeys& modifiers)
  323. {
  324. Component::BailOutChecker checker (this);
  325. if (commandManagerToUse != nullptr && commandID != 0)
  326. {
  327. ApplicationCommandTarget::InvocationInfo info (commandID);
  328. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  329. info.originatingComponent = this;
  330. commandManagerToUse->invoke (info, true);
  331. }
  332. clicked (modifiers);
  333. if (! checker.shouldBailOut())
  334. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  335. }
  336. void Button::sendStateMessage()
  337. {
  338. Component::BailOutChecker checker (this);
  339. buttonStateChanged();
  340. if (! checker.shouldBailOut())
  341. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  342. }
  343. //==============================================================================
  344. void Button::paint (Graphics& g)
  345. {
  346. if (needsToRelease && isEnabled())
  347. {
  348. needsToRelease = false;
  349. needsRepainting = true;
  350. }
  351. paintButton (g, isOver(), isDown());
  352. lastStatePainted = buttonState;
  353. }
  354. //==============================================================================
  355. void Button::mouseEnter (const MouseEvent&) { updateState (true, false); }
  356. void Button::mouseExit (const MouseEvent&) { updateState (false, false); }
  357. void Button::mouseDown (const MouseEvent& e)
  358. {
  359. updateState (true, true);
  360. if (isDown())
  361. {
  362. if (autoRepeatDelay >= 0)
  363. callbackHelper->startTimer (autoRepeatDelay);
  364. if (triggerOnMouseDown)
  365. internalClickCallback (e.mods);
  366. }
  367. }
  368. void Button::mouseUp (const MouseEvent& e)
  369. {
  370. const bool wasDown = isDown();
  371. const bool wasOver = isOver();
  372. updateState (isMouseOver(), false);
  373. if (wasDown && wasOver && ! triggerOnMouseDown)
  374. {
  375. if (lastStatePainted != buttonDown)
  376. flashButtonState();
  377. internalClickCallback (e.mods);
  378. }
  379. }
  380. void Button::mouseDrag (const MouseEvent&)
  381. {
  382. const ButtonState oldState = buttonState;
  383. updateState (isMouseOver(), true);
  384. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  385. callbackHelper->startTimer (autoRepeatSpeed);
  386. }
  387. void Button::focusGained (FocusChangeType)
  388. {
  389. updateState();
  390. repaint();
  391. }
  392. void Button::focusLost (FocusChangeType)
  393. {
  394. updateState();
  395. repaint();
  396. }
  397. void Button::visibilityChanged()
  398. {
  399. needsToRelease = false;
  400. updateState();
  401. }
  402. void Button::parentHierarchyChanged()
  403. {
  404. Component* const newKeySource = (shortcuts.size() == 0) ? nullptr : getTopLevelComponent();
  405. if (newKeySource != keySource.get())
  406. {
  407. if (keySource != nullptr)
  408. keySource->removeKeyListener (callbackHelper);
  409. keySource = newKeySource;
  410. if (keySource != nullptr)
  411. keySource->addKeyListener (callbackHelper);
  412. }
  413. }
  414. //==============================================================================
  415. void Button::setCommandToTrigger (ApplicationCommandManager* const newCommandManager,
  416. const CommandID newCommandID, const bool generateTip)
  417. {
  418. commandID = newCommandID;
  419. generateTooltip = generateTip;
  420. if (commandManagerToUse != newCommandManager)
  421. {
  422. if (commandManagerToUse != nullptr)
  423. commandManagerToUse->removeListener (callbackHelper);
  424. commandManagerToUse = newCommandManager;
  425. if (commandManagerToUse != nullptr)
  426. commandManagerToUse->addListener (callbackHelper);
  427. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  428. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  429. // it is that this button represents, and the button will update its state to reflect this
  430. // in the applicationCommandListChanged() method.
  431. jassert (commandManagerToUse == nullptr || ! clickTogglesState);
  432. }
  433. if (commandManagerToUse != nullptr)
  434. applicationCommandListChangeCallback();
  435. else
  436. setEnabled (true);
  437. }
  438. void Button::applicationCommandListChangeCallback()
  439. {
  440. if (commandManagerToUse != nullptr)
  441. {
  442. ApplicationCommandInfo info (0);
  443. if (commandManagerToUse->getTargetForCommand (commandID, info) != nullptr)
  444. {
  445. updateAutomaticTooltip (info);
  446. setEnabled ((info.flags & ApplicationCommandInfo::isDisabled) == 0);
  447. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, dontSendNotification);
  448. }
  449. else
  450. {
  451. setEnabled (false);
  452. }
  453. }
  454. }
  455. //==============================================================================
  456. void Button::addShortcut (const KeyPress& key)
  457. {
  458. if (key.isValid())
  459. {
  460. jassert (! isRegisteredForShortcut (key)); // already registered!
  461. shortcuts.add (key);
  462. parentHierarchyChanged();
  463. }
  464. }
  465. void Button::clearShortcuts()
  466. {
  467. shortcuts.clear();
  468. parentHierarchyChanged();
  469. }
  470. bool Button::isShortcutPressed() const
  471. {
  472. if (isShowing() && ! isCurrentlyBlockedByAnotherModalComponent())
  473. for (int i = shortcuts.size(); --i >= 0;)
  474. if (shortcuts.getReference(i).isCurrentlyDown())
  475. return true;
  476. return false;
  477. }
  478. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  479. {
  480. for (int i = shortcuts.size(); --i >= 0;)
  481. if (key == shortcuts.getReference(i))
  482. return true;
  483. return false;
  484. }
  485. bool Button::keyStateChangedCallback()
  486. {
  487. if (! isEnabled())
  488. return false;
  489. const bool wasDown = isKeyDown;
  490. isKeyDown = isShortcutPressed();
  491. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  492. callbackHelper->startTimer (autoRepeatDelay);
  493. updateState();
  494. if (isEnabled() && wasDown && ! isKeyDown)
  495. {
  496. internalClickCallback (ModifierKeys::getCurrentModifiers());
  497. // (return immediately - this button may now have been deleted)
  498. return true;
  499. }
  500. return wasDown || isKeyDown;
  501. }
  502. bool Button::keyPressed (const KeyPress& key)
  503. {
  504. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  505. {
  506. triggerClick();
  507. return true;
  508. }
  509. return false;
  510. }
  511. //==============================================================================
  512. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  513. const int repeatMillisecs,
  514. const int minimumDelayInMillisecs) noexcept
  515. {
  516. autoRepeatDelay = initialDelayMillisecs;
  517. autoRepeatSpeed = repeatMillisecs;
  518. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  519. }
  520. void Button::repeatTimerCallback()
  521. {
  522. if (needsRepainting)
  523. {
  524. callbackHelper->stopTimer();
  525. updateState();
  526. needsRepainting = false;
  527. }
  528. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState() == buttonDown)))
  529. {
  530. int repeatSpeed = autoRepeatSpeed;
  531. if (autoRepeatMinimumDelay >= 0)
  532. {
  533. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  534. timeHeldDown *= timeHeldDown;
  535. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  536. }
  537. repeatSpeed = jmax (1, repeatSpeed);
  538. const uint32 now = Time::getMillisecondCounter();
  539. // if we've been blocked from repeating often enough, speed up the repeat timer to compensate..
  540. if (lastRepeatTime != 0 && (int) (now - lastRepeatTime) > repeatSpeed * 2)
  541. repeatSpeed = jmax (1, repeatSpeed / 2);
  542. lastRepeatTime = now;
  543. callbackHelper->startTimer (repeatSpeed);
  544. internalClickCallback (ModifierKeys::getCurrentModifiers());
  545. }
  546. else if (! needsToRelease)
  547. {
  548. callbackHelper->stopTimer();
  549. }
  550. }