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.

689 lines
19KB

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