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.

667 lines
18KB

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