The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

673 lines
19KB

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