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.

juce_Button.cpp 18KB

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