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.

700 lines
19KB

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