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.

675 lines
23KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. namespace juce
  20. {
  21. struct AudioProcessorValueTreeState::Parameter : public AudioProcessorParameterWithID,
  22. private ValueTree::Listener
  23. {
  24. Parameter (AudioProcessorValueTreeState& s,
  25. const String& parameterID, const String& paramName, const String& labelText,
  26. NormalisableRange<float> r, float defaultVal,
  27. std::function<String (float)> valueToText,
  28. std::function<float (const String&)> textToValue,
  29. bool meta,
  30. bool automatable,
  31. bool discrete,
  32. AudioProcessorParameter::Category category,
  33. bool boolean)
  34. : AudioProcessorParameterWithID (parameterID, paramName, labelText, category),
  35. owner (s), valueToTextFunction (valueToText), textToValueFunction (textToValue),
  36. range (r), value (defaultVal), defaultValue (defaultVal),
  37. listenersNeedCalling (true),
  38. isMetaParam (meta),
  39. isAutomatableParam (automatable),
  40. isDiscreteParam (discrete),
  41. isBooleanParam (boolean)
  42. {
  43. value = defaultValue;
  44. state.addListener (this);
  45. }
  46. ~Parameter()
  47. {
  48. // should have detached all callbacks before destroying the parameters!
  49. jassert (listeners.size() <= 1);
  50. }
  51. float getValue() const override { return range.convertTo0to1 (value); }
  52. float getDefaultValue() const override { return range.convertTo0to1 (defaultValue); }
  53. float getValueForText (const String& text) const override
  54. {
  55. return range.convertTo0to1 (textToValueFunction != nullptr ? textToValueFunction (text)
  56. : text.getFloatValue());
  57. }
  58. String getText (float v, int length) const override
  59. {
  60. return valueToTextFunction != nullptr ? valueToTextFunction (range.convertFrom0to1 (v))
  61. : AudioProcessorParameter::getText (v, length);
  62. }
  63. int getNumSteps() const override
  64. {
  65. if (range.interval > 0)
  66. return (static_cast<int> ((range.end - range.start) / range.interval) + 1);
  67. return AudioProcessor::getDefaultNumParameterSteps();
  68. }
  69. void setValue (float newValue) override
  70. {
  71. newValue = range.snapToLegalValue (range.convertFrom0to1 (newValue));
  72. if (value != newValue || listenersNeedCalling)
  73. {
  74. value = newValue;
  75. listeners.call ([=] (AudioProcessorValueTreeState::Listener& l) { l.parameterChanged (paramID, value); });
  76. listenersNeedCalling = false;
  77. needsUpdate = true;
  78. }
  79. }
  80. void setNewState (const ValueTree& v)
  81. {
  82. state = v;
  83. updateFromValueTree();
  84. }
  85. void setUnnormalisedValue (float newUnnormalisedValue)
  86. {
  87. if (value != newUnnormalisedValue)
  88. {
  89. const float newValue = range.convertTo0to1 (newUnnormalisedValue);
  90. setValueNotifyingHost (newValue);
  91. }
  92. }
  93. void updateFromValueTree()
  94. {
  95. setUnnormalisedValue (state.getProperty (owner.valuePropertyID, defaultValue));
  96. }
  97. void copyValueToValueTree()
  98. {
  99. if (auto* valueProperty = state.getPropertyPointer (owner.valuePropertyID))
  100. {
  101. if ((float) *valueProperty != value)
  102. {
  103. ScopedValueSetter<bool> svs (ignoreParameterChangedCallbacks, true);
  104. state.setProperty (owner.valuePropertyID, value, owner.undoManager);
  105. }
  106. }
  107. else
  108. {
  109. state.setProperty (owner.valuePropertyID, value, nullptr);
  110. }
  111. }
  112. void valueTreePropertyChanged (ValueTree&, const Identifier& property) override
  113. {
  114. if (ignoreParameterChangedCallbacks)
  115. return;
  116. if (property == owner.valuePropertyID)
  117. updateFromValueTree();
  118. }
  119. void valueTreeChildAdded (ValueTree&, ValueTree&) override {}
  120. void valueTreeChildRemoved (ValueTree&, ValueTree&, int) override {}
  121. void valueTreeChildOrderChanged (ValueTree&, int, int) override {}
  122. void valueTreeParentChanged (ValueTree&) override {}
  123. static Parameter* getParameterForID (AudioProcessor& processor, StringRef paramID) noexcept
  124. {
  125. for (auto* ap : processor.getParameters())
  126. {
  127. // When using this class, you must allow it to manage all the parameters in your AudioProcessor, and
  128. // not add any parameter objects of other types!
  129. jassert (dynamic_cast<Parameter*> (ap) != nullptr);
  130. auto* p = static_cast<Parameter*> (ap);
  131. if (paramID == p->paramID)
  132. return p;
  133. }
  134. return nullptr;
  135. }
  136. bool isMetaParameter() const override { return isMetaParam; }
  137. bool isAutomatable() const override { return isAutomatableParam; }
  138. bool isDiscrete() const override { return isDiscreteParam; }
  139. bool isBoolean() const override { return isBooleanParam; }
  140. AudioProcessorValueTreeState& owner;
  141. ValueTree state;
  142. ListenerList<AudioProcessorValueTreeState::Listener> listeners;
  143. std::function<String (float)> valueToTextFunction;
  144. std::function<float (const String&)> textToValueFunction;
  145. NormalisableRange<float> range;
  146. float value, defaultValue;
  147. std::atomic<bool> needsUpdate { true };
  148. bool listenersNeedCalling;
  149. const bool isMetaParam, isAutomatableParam, isDiscreteParam, isBooleanParam;
  150. bool ignoreParameterChangedCallbacks = false;
  151. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Parameter)
  152. };
  153. //==============================================================================
  154. AudioProcessorValueTreeState::AudioProcessorValueTreeState (AudioProcessor& p, UndoManager* um)
  155. : processor (p), undoManager (um)
  156. {
  157. startTimerHz (10);
  158. state.addListener (this);
  159. }
  160. AudioProcessorValueTreeState::~AudioProcessorValueTreeState() {}
  161. AudioProcessorParameterWithID* AudioProcessorValueTreeState::createAndAddParameter (const String& paramID, const String& paramName,
  162. const String& labelText, NormalisableRange<float> r,
  163. float defaultVal, std::function<String (float)> valueToTextFunction,
  164. std::function<float (const String&)> textToValueFunction,
  165. bool isMetaParameter,
  166. bool isAutomatableParameter,
  167. bool isDiscreteParameter,
  168. AudioProcessorParameter::Category category,
  169. bool isBooleanParameter)
  170. {
  171. // All parameters must be created before giving this manager a ValueTree state!
  172. jassert (! state.isValid());
  173. Parameter* p = new Parameter (*this, paramID, paramName, labelText, r,
  174. defaultVal, valueToTextFunction, textToValueFunction,
  175. isMetaParameter, isAutomatableParameter,
  176. isDiscreteParameter, category, isBooleanParameter);
  177. processor.addParameter (p);
  178. return p;
  179. }
  180. void AudioProcessorValueTreeState::addParameterListener (StringRef paramID, Listener* listener)
  181. {
  182. if (auto* p = Parameter::getParameterForID (processor, paramID))
  183. p->listeners.add (listener);
  184. }
  185. void AudioProcessorValueTreeState::removeParameterListener (StringRef paramID, Listener* listener)
  186. {
  187. if (auto* p = Parameter::getParameterForID (processor, paramID))
  188. p->listeners.remove (listener);
  189. }
  190. Value AudioProcessorValueTreeState::getParameterAsValue (StringRef paramID) const
  191. {
  192. if (auto* p = Parameter::getParameterForID (processor, paramID))
  193. return p->state.getPropertyAsValue (valuePropertyID, undoManager);
  194. return {};
  195. }
  196. NormalisableRange<float> AudioProcessorValueTreeState::getParameterRange (StringRef paramID) const noexcept
  197. {
  198. if (auto* p = Parameter::getParameterForID (processor, paramID))
  199. return p->range;
  200. return NormalisableRange<float>();
  201. }
  202. AudioProcessorParameterWithID* AudioProcessorValueTreeState::getParameter (StringRef paramID) const noexcept
  203. {
  204. return Parameter::getParameterForID (processor, paramID);
  205. }
  206. float* AudioProcessorValueTreeState::getRawParameterValue (StringRef paramID) const noexcept
  207. {
  208. if (auto* p = Parameter::getParameterForID (processor, paramID))
  209. return &(p->value);
  210. return nullptr;
  211. }
  212. ValueTree AudioProcessorValueTreeState::copyState()
  213. {
  214. ScopedLock lock (valueTreeChanging);
  215. flushParameterValuesToValueTree();
  216. return state.createCopy();
  217. }
  218. void AudioProcessorValueTreeState::replaceState (const ValueTree& newState)
  219. {
  220. ScopedLock lock (valueTreeChanging);
  221. state = newState;
  222. if (undoManager != nullptr)
  223. undoManager->clearUndoHistory();
  224. }
  225. ValueTree AudioProcessorValueTreeState::getOrCreateChildValueTree (const String& paramID)
  226. {
  227. ValueTree v (state.getChildWithProperty (idPropertyID, paramID));
  228. if (! v.isValid())
  229. {
  230. v = ValueTree (valueType);
  231. v.setProperty (idPropertyID, paramID, nullptr);
  232. state.appendChild (v, nullptr);
  233. }
  234. return v;
  235. }
  236. void AudioProcessorValueTreeState::updateParameterConnectionsToChildTrees()
  237. {
  238. ScopedLock lock (valueTreeChanging);
  239. for (auto* param : processor.getParameters())
  240. {
  241. jassert (dynamic_cast<Parameter*> (param) != nullptr);
  242. auto* p = static_cast<Parameter*> (param);
  243. p->setNewState (getOrCreateChildValueTree (p->paramID));
  244. }
  245. }
  246. void AudioProcessorValueTreeState::valueTreePropertyChanged (ValueTree& tree, const Identifier& property)
  247. {
  248. if (property == idPropertyID && tree.hasType (valueType) && tree.getParent() == state)
  249. updateParameterConnectionsToChildTrees();
  250. }
  251. void AudioProcessorValueTreeState::valueTreeChildAdded (ValueTree& parent, ValueTree& tree)
  252. {
  253. if (parent == state && tree.hasType (valueType))
  254. if (auto* param = Parameter::getParameterForID (processor, tree.getProperty (idPropertyID).toString()))
  255. param->setNewState (getOrCreateChildValueTree (param->paramID));
  256. }
  257. void AudioProcessorValueTreeState::valueTreeChildRemoved (ValueTree& parent, ValueTree& tree, int)
  258. {
  259. if (parent == state && tree.hasType (valueType))
  260. if (auto* param = Parameter::getParameterForID (processor, tree.getProperty (idPropertyID).toString()))
  261. param->setNewState (getOrCreateChildValueTree (param->paramID));
  262. }
  263. void AudioProcessorValueTreeState::valueTreeRedirected (ValueTree& v)
  264. {
  265. if (v == state)
  266. updateParameterConnectionsToChildTrees();
  267. }
  268. void AudioProcessorValueTreeState::valueTreeChildOrderChanged (ValueTree&, int, int) {}
  269. void AudioProcessorValueTreeState::valueTreeParentChanged (ValueTree&) {}
  270. bool AudioProcessorValueTreeState::flushParameterValuesToValueTree()
  271. {
  272. ScopedLock lock (valueTreeChanging);
  273. bool anythingUpdated = false;
  274. for (auto* ap : processor.getParameters())
  275. {
  276. jassert (dynamic_cast<Parameter*> (ap) != nullptr);
  277. auto* p = static_cast<Parameter*> (ap);
  278. bool needsUpdateTestValue = true;
  279. if (p->needsUpdate.compare_exchange_strong (needsUpdateTestValue, false))
  280. {
  281. p->copyValueToValueTree();
  282. anythingUpdated = true;
  283. }
  284. }
  285. return anythingUpdated;
  286. }
  287. void AudioProcessorValueTreeState::timerCallback()
  288. {
  289. auto anythingUpdated = flushParameterValuesToValueTree();
  290. startTimer (anythingUpdated ? 1000 / 50
  291. : jlimit (50, 500, getTimerInterval() + 20));
  292. }
  293. AudioProcessorValueTreeState::Listener::Listener() {}
  294. AudioProcessorValueTreeState::Listener::~Listener() {}
  295. //==============================================================================
  296. struct AttachedControlBase : public AudioProcessorValueTreeState::Listener,
  297. public AsyncUpdater
  298. {
  299. AttachedControlBase (AudioProcessorValueTreeState& s, const String& p)
  300. : state (s), paramID (p), lastValue (0)
  301. {
  302. state.addParameterListener (paramID, this);
  303. }
  304. void removeListener()
  305. {
  306. state.removeParameterListener (paramID, this);
  307. }
  308. void setNewUnnormalisedValue (float newUnnormalisedValue)
  309. {
  310. if (auto* p = state.getParameter (paramID))
  311. {
  312. const float newValue = state.getParameterRange (paramID)
  313. .convertTo0to1 (newUnnormalisedValue);
  314. if (p->getValue() != newValue)
  315. p->setValueNotifyingHost (newValue);
  316. }
  317. }
  318. void sendInitialUpdate()
  319. {
  320. if (auto* v = state.getRawParameterValue (paramID))
  321. parameterChanged (paramID, *v);
  322. }
  323. void parameterChanged (const String&, float newValue) override
  324. {
  325. lastValue = newValue;
  326. if (MessageManager::getInstance()->isThisTheMessageThread())
  327. {
  328. cancelPendingUpdate();
  329. setValue (newValue);
  330. }
  331. else
  332. {
  333. triggerAsyncUpdate();
  334. }
  335. }
  336. void beginParameterChange()
  337. {
  338. if (auto* p = state.getParameter (paramID))
  339. {
  340. if (state.undoManager != nullptr)
  341. state.undoManager->beginNewTransaction();
  342. p->beginChangeGesture();
  343. }
  344. }
  345. void endParameterChange()
  346. {
  347. if (AudioProcessorParameter* p = state.getParameter (paramID))
  348. p->endChangeGesture();
  349. }
  350. void handleAsyncUpdate() override
  351. {
  352. setValue (lastValue);
  353. }
  354. virtual void setValue (float) = 0;
  355. AudioProcessorValueTreeState& state;
  356. String paramID;
  357. float lastValue;
  358. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AttachedControlBase)
  359. };
  360. //==============================================================================
  361. struct AudioProcessorValueTreeState::SliderAttachment::Pimpl : private AttachedControlBase,
  362. private Slider::Listener
  363. {
  364. Pimpl (AudioProcessorValueTreeState& s, const String& p, Slider& sl)
  365. : AttachedControlBase (s, p), slider (sl), ignoreCallbacks (false)
  366. {
  367. NormalisableRange<float> range (state.getParameterRange (paramID));
  368. if (range.interval != 0 || range.skew != 0)
  369. {
  370. slider.setRange (range.start, range.end, range.interval);
  371. slider.setSkewFactor (range.skew, range.symmetricSkew);
  372. }
  373. else
  374. {
  375. auto convertFrom0To1Function = [range] (double currentRangeStart,
  376. double currentRangeEnd,
  377. double normalisedValue) mutable
  378. {
  379. range.start = (float) currentRangeStart;
  380. range.end = (float) currentRangeEnd;
  381. return (double) range.convertFrom0to1 ((float) normalisedValue);
  382. };
  383. auto convertTo0To1Function = [range] (double currentRangeStart,
  384. double currentRangeEnd,
  385. double mappedValue) mutable
  386. {
  387. range.start = (float) currentRangeStart;
  388. range.end = (float) currentRangeEnd;
  389. return (double) range.convertTo0to1 ((float) mappedValue);
  390. };
  391. auto snapToLegalValueFunction = [range] (double currentRangeStart,
  392. double currentRangeEnd,
  393. double valueToSnap) mutable
  394. {
  395. range.start = (float) currentRangeStart;
  396. range.end = (float) currentRangeEnd;
  397. return (double) range.snapToLegalValue ((float) valueToSnap);
  398. };
  399. slider.setNormalisableRange ({ (double) range.start, (double) range.end,
  400. convertFrom0To1Function,
  401. convertTo0To1Function,
  402. snapToLegalValueFunction });
  403. }
  404. if (auto* param = dynamic_cast<AudioProcessorValueTreeState::Parameter*> (state.getParameter (paramID)))
  405. {
  406. if (param->textToValueFunction != nullptr)
  407. slider.valueFromTextFunction = [param] (const String& text) { return (double) param->textToValueFunction (text); };
  408. if (param->valueToTextFunction != nullptr)
  409. slider.textFromValueFunction = [param] (double value) { return param->valueToTextFunction ((float) value); };
  410. slider.setDoubleClickReturnValue (true, range.convertFrom0to1 (param->getDefaultValue()));
  411. }
  412. sendInitialUpdate();
  413. slider.addListener (this);
  414. }
  415. ~Pimpl()
  416. {
  417. slider.removeListener (this);
  418. removeListener();
  419. }
  420. void setValue (float newValue) override
  421. {
  422. const ScopedLock selfCallbackLock (selfCallbackMutex);
  423. {
  424. ScopedValueSetter<bool> svs (ignoreCallbacks, true);
  425. slider.setValue (newValue, sendNotificationSync);
  426. }
  427. }
  428. void sliderValueChanged (Slider* s) override
  429. {
  430. const ScopedLock selfCallbackLock (selfCallbackMutex);
  431. if ((! ignoreCallbacks) && (! ModifierKeys::currentModifiers.isRightButtonDown()))
  432. setNewUnnormalisedValue ((float) s->getValue());
  433. }
  434. void sliderDragStarted (Slider*) override { beginParameterChange(); }
  435. void sliderDragEnded (Slider*) override { endParameterChange(); }
  436. Slider& slider;
  437. bool ignoreCallbacks;
  438. CriticalSection selfCallbackMutex;
  439. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl)
  440. };
  441. AudioProcessorValueTreeState::SliderAttachment::SliderAttachment (AudioProcessorValueTreeState& s, const String& p, Slider& sl)
  442. : pimpl (new Pimpl (s, p, sl))
  443. {
  444. }
  445. AudioProcessorValueTreeState::SliderAttachment::~SliderAttachment() {}
  446. //==============================================================================
  447. struct AudioProcessorValueTreeState::ComboBoxAttachment::Pimpl : private AttachedControlBase,
  448. private ComboBox::Listener
  449. {
  450. Pimpl (AudioProcessorValueTreeState& s, const String& p, ComboBox& c)
  451. : AttachedControlBase (s, p), combo (c), ignoreCallbacks (false)
  452. {
  453. sendInitialUpdate();
  454. combo.addListener (this);
  455. }
  456. ~Pimpl()
  457. {
  458. combo.removeListener (this);
  459. removeListener();
  460. }
  461. void setValue (float newValue) override
  462. {
  463. const ScopedLock selfCallbackLock (selfCallbackMutex);
  464. if (state.getParameter (paramID) != nullptr)
  465. {
  466. auto normValue = state.getParameterRange (paramID)
  467. .convertTo0to1 (newValue);
  468. auto index = roundToInt (normValue * (combo.getNumItems() - 1));
  469. if (index != combo.getSelectedItemIndex())
  470. {
  471. ScopedValueSetter<bool> svs (ignoreCallbacks, true);
  472. combo.setSelectedItemIndex (index, sendNotificationSync);
  473. }
  474. }
  475. }
  476. void comboBoxChanged (ComboBox*) override
  477. {
  478. const ScopedLock selfCallbackLock (selfCallbackMutex);
  479. if (! ignoreCallbacks)
  480. {
  481. if (auto* p = state.getParameter (paramID))
  482. {
  483. auto newValue = (float) combo.getSelectedItemIndex() / (combo.getNumItems() - 1);
  484. if (p->getValue() != newValue)
  485. {
  486. beginParameterChange();
  487. p->setValueNotifyingHost (newValue);
  488. endParameterChange();
  489. }
  490. }
  491. }
  492. }
  493. ComboBox& combo;
  494. bool ignoreCallbacks;
  495. CriticalSection selfCallbackMutex;
  496. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl)
  497. };
  498. AudioProcessorValueTreeState::ComboBoxAttachment::ComboBoxAttachment (AudioProcessorValueTreeState& s, const String& p, ComboBox& c)
  499. : pimpl (new Pimpl (s, p, c))
  500. {
  501. }
  502. AudioProcessorValueTreeState::ComboBoxAttachment::~ComboBoxAttachment() {}
  503. //==============================================================================
  504. struct AudioProcessorValueTreeState::ButtonAttachment::Pimpl : private AttachedControlBase,
  505. private Button::Listener
  506. {
  507. Pimpl (AudioProcessorValueTreeState& s, const String& p, Button& b)
  508. : AttachedControlBase (s, p), button (b), ignoreCallbacks (false)
  509. {
  510. sendInitialUpdate();
  511. button.addListener (this);
  512. }
  513. ~Pimpl()
  514. {
  515. button.removeListener (this);
  516. removeListener();
  517. }
  518. void setValue (float newValue) override
  519. {
  520. const ScopedLock selfCallbackLock (selfCallbackMutex);
  521. {
  522. ScopedValueSetter<bool> svs (ignoreCallbacks, true);
  523. button.setToggleState (newValue >= 0.5f, sendNotificationSync);
  524. }
  525. }
  526. void buttonClicked (Button* b) override
  527. {
  528. const ScopedLock selfCallbackLock (selfCallbackMutex);
  529. if (! ignoreCallbacks)
  530. {
  531. beginParameterChange();
  532. setNewUnnormalisedValue (b->getToggleState() ? 1.0f : 0.0f);
  533. endParameterChange();
  534. }
  535. }
  536. Button& button;
  537. bool ignoreCallbacks;
  538. CriticalSection selfCallbackMutex;
  539. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl)
  540. };
  541. AudioProcessorValueTreeState::ButtonAttachment::ButtonAttachment (AudioProcessorValueTreeState& s, const String& p, Button& b)
  542. : pimpl (new Pimpl (s, p, b))
  543. {
  544. }
  545. AudioProcessorValueTreeState::ButtonAttachment::~ButtonAttachment() {}
  546. } // namespace juce