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.

666 lines
18KB

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