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.

1181 lines
44KB

  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. //==============================================================================
  22. AudioProcessorValueTreeState::Parameter::Parameter (const String& parameterID,
  23. const String& parameterName,
  24. const String& labelText,
  25. NormalisableRange<float> valueRange,
  26. float defaultParameterValue,
  27. std::function<String(float)> valueToTextFunction,
  28. std::function<float(const String&)> textToValueFunction,
  29. bool isMetaParameter,
  30. bool isAutomatableParameter,
  31. bool isDiscrete,
  32. AudioProcessorParameter::Category parameterCategory,
  33. bool isBoolean)
  34. : AudioParameterFloat (parameterID,
  35. parameterName,
  36. valueRange,
  37. defaultParameterValue,
  38. labelText,
  39. parameterCategory,
  40. valueToTextFunction == nullptr ? std::function<String(float v, int)>()
  41. : [valueToTextFunction](float v, int) { return valueToTextFunction (v); },
  42. std::move (textToValueFunction)),
  43. unsnappedDefault (valueRange.convertTo0to1 (defaultParameterValue)),
  44. metaParameter (isMetaParameter),
  45. automatable (isAutomatableParameter),
  46. discrete (isDiscrete),
  47. boolean (isBoolean)
  48. {
  49. }
  50. float AudioProcessorValueTreeState::Parameter::getDefaultValue() const { return unsnappedDefault; }
  51. int AudioProcessorValueTreeState::Parameter::getNumSteps() const { return RangedAudioParameter::getNumSteps(); }
  52. bool AudioProcessorValueTreeState::Parameter::isMetaParameter() const { return metaParameter; }
  53. bool AudioProcessorValueTreeState::Parameter::isAutomatable() const { return automatable; }
  54. bool AudioProcessorValueTreeState::Parameter::isDiscrete() const { return discrete; }
  55. bool AudioProcessorValueTreeState::Parameter::isBoolean() const { return boolean; }
  56. //==============================================================================
  57. class AudioProcessorValueTreeState::ParameterAdapter : private AudioProcessorParameter::Listener
  58. {
  59. private:
  60. using Listener = AudioProcessorValueTreeState::Listener;
  61. public:
  62. explicit ParameterAdapter (RangedAudioParameter& parameterIn)
  63. : parameter (parameterIn),
  64. // For legacy reasons, the unnormalised value should *not* be snapped on construction
  65. unnormalisedValue (getRange().convertFrom0to1 (parameter.getDefaultValue()))
  66. {
  67. parameter.addListener (this);
  68. }
  69. ~ParameterAdapter() override { parameter.removeListener (this); }
  70. void addListener (Listener* l) { listeners.add (l); }
  71. void removeListener (Listener* l) { listeners.remove (l); }
  72. RangedAudioParameter& getParameter() { return parameter; }
  73. const RangedAudioParameter& getParameter() const { return parameter; }
  74. const NormalisableRange<float>& getRange() const { return parameter.getNormalisableRange(); }
  75. float getDenormalisedDefaultValue() const { return denormalise (parameter.getDefaultValue()); }
  76. void setDenormalisedValue (float value)
  77. {
  78. if (value == unnormalisedValue)
  79. return;
  80. setNormalisedValue (normalise (value));
  81. }
  82. float getDenormalisedValueForText (const String& text) const
  83. {
  84. return denormalise (parameter.getValueForText (text));
  85. }
  86. String getTextForDenormalisedValue (float value) const
  87. {
  88. return parameter.getText (normalise (value), 0);
  89. }
  90. float getDenormalisedValue() const { return unnormalisedValue; }
  91. float& getRawDenormalisedValue() { return unnormalisedValue; }
  92. bool flushToTree (const Identifier& key, UndoManager* um)
  93. {
  94. auto needsUpdateTestValue = true;
  95. if (! needsUpdate.compare_exchange_strong (needsUpdateTestValue, false))
  96. return false;
  97. if (auto valueProperty = tree.getPropertyPointer (key))
  98. {
  99. if ((float) *valueProperty != unnormalisedValue)
  100. {
  101. ScopedValueSetter<bool> svs (ignoreParameterChangedCallbacks, true);
  102. tree.setProperty (key, unnormalisedValue, um);
  103. }
  104. }
  105. else
  106. {
  107. tree.setProperty (key, unnormalisedValue, nullptr);
  108. }
  109. return true;
  110. }
  111. ValueTree tree;
  112. private:
  113. void parameterGestureChanged (int, bool) override {}
  114. void parameterValueChanged (int, float) override
  115. {
  116. const auto newValue = denormalise (parameter.getValue());
  117. if (unnormalisedValue == newValue && ! listenersNeedCalling)
  118. return;
  119. unnormalisedValue = newValue;
  120. listeners.call ([=](Listener& l) { l.parameterChanged (parameter.paramID, unnormalisedValue); });
  121. listenersNeedCalling = false;
  122. needsUpdate = true;
  123. }
  124. float denormalise (float normalised) const
  125. {
  126. return getParameter().convertFrom0to1 (normalised);
  127. }
  128. float normalise (float denormalised) const
  129. {
  130. return getParameter().convertTo0to1 (denormalised);
  131. }
  132. void setNormalisedValue (float value)
  133. {
  134. if (ignoreParameterChangedCallbacks)
  135. return;
  136. parameter.setValueNotifyingHost (value);
  137. }
  138. RangedAudioParameter& parameter;
  139. ListenerList<Listener> listeners;
  140. float unnormalisedValue{};
  141. std::atomic<bool> needsUpdate { true };
  142. bool listenersNeedCalling { true }, ignoreParameterChangedCallbacks { false };
  143. };
  144. //==============================================================================
  145. AudioProcessorValueTreeState::AudioProcessorValueTreeState (AudioProcessor& processorToConnectTo,
  146. UndoManager* undoManagerToUse,
  147. const Identifier& valueTreeType,
  148. ParameterLayout parameterLayout)
  149. : AudioProcessorValueTreeState (processorToConnectTo, undoManagerToUse)
  150. {
  151. struct PushBackVisitor : ParameterLayout::Visitor
  152. {
  153. explicit PushBackVisitor (AudioProcessorValueTreeState& stateIn)
  154. : state (&stateIn) {}
  155. void visit (std::unique_ptr<RangedAudioParameter> param) const override
  156. {
  157. if (param == nullptr)
  158. {
  159. jassertfalse;
  160. return;
  161. }
  162. state->addParameterAdapter (*param);
  163. state->processor.addParameter (param.release());
  164. }
  165. void visit (std::unique_ptr<AudioProcessorParameterGroup> group) const override
  166. {
  167. if (group == nullptr)
  168. {
  169. jassertfalse;
  170. return;
  171. }
  172. for (const auto param : group->getParameters (true))
  173. {
  174. if (const auto rangedParam = dynamic_cast<RangedAudioParameter*> (param))
  175. {
  176. state->addParameterAdapter (*rangedParam);
  177. }
  178. else
  179. {
  180. // If you hit this assertion then you are attempting to add a parameter that is
  181. // not derived from RangedAudioParameter to the AudioProcessorValueTreeState.
  182. jassertfalse;
  183. }
  184. }
  185. state->processor.addParameterGroup (move (group));
  186. }
  187. AudioProcessorValueTreeState* state;
  188. };
  189. for (auto& item : parameterLayout.parameters)
  190. item->accept (PushBackVisitor (*this));
  191. state = ValueTree (valueTreeType);
  192. }
  193. AudioProcessorValueTreeState::AudioProcessorValueTreeState (AudioProcessor& p, UndoManager* um)
  194. : processor (p), undoManager (um)
  195. {
  196. startTimerHz (10);
  197. state.addListener (this);
  198. }
  199. AudioProcessorValueTreeState::~AudioProcessorValueTreeState() {}
  200. //==============================================================================
  201. RangedAudioParameter* AudioProcessorValueTreeState::createAndAddParameter (const String& paramID,
  202. const String& paramName,
  203. const String& labelText,
  204. NormalisableRange<float> range,
  205. float defaultVal,
  206. std::function<String(float)> valueToTextFunction,
  207. std::function<float(const String&)> textToValueFunction,
  208. bool isMetaParameter,
  209. bool isAutomatableParameter,
  210. bool isDiscreteParameter,
  211. AudioProcessorParameter::Category category,
  212. bool isBooleanParameter)
  213. {
  214. return createAndAddParameter (std::make_unique<Parameter> (paramID,
  215. paramName,
  216. labelText,
  217. range,
  218. defaultVal,
  219. std::move (valueToTextFunction),
  220. std::move (textToValueFunction),
  221. isMetaParameter,
  222. isAutomatableParameter,
  223. isDiscreteParameter,
  224. category,
  225. isBooleanParameter));
  226. }
  227. RangedAudioParameter* AudioProcessorValueTreeState::createAndAddParameter (std::unique_ptr<RangedAudioParameter> param)
  228. {
  229. // All parameters must be created before giving this manager a ValueTree state!
  230. jassert (! state.isValid());
  231. if (getParameter (param->paramID) != nullptr)
  232. return nullptr;
  233. addParameterAdapter (*param);
  234. processor.addParameter (param.get());
  235. return param.release();
  236. }
  237. //==============================================================================
  238. void AudioProcessorValueTreeState::addParameterAdapter (RangedAudioParameter& param)
  239. {
  240. adapterTable.emplace (param.paramID, std::make_unique<ParameterAdapter> (param));
  241. }
  242. AudioProcessorValueTreeState::ParameterAdapter* AudioProcessorValueTreeState::getParameterAdapter (StringRef paramID) const
  243. {
  244. auto it = adapterTable.find (paramID);
  245. return it == adapterTable.end() ? nullptr : it->second.get();
  246. }
  247. void AudioProcessorValueTreeState::addParameterListener (StringRef paramID, Listener* listener)
  248. {
  249. if (auto* p = getParameterAdapter (paramID))
  250. p->addListener (listener);
  251. }
  252. void AudioProcessorValueTreeState::removeParameterListener (StringRef paramID, Listener* listener)
  253. {
  254. if (auto* p = getParameterAdapter (paramID))
  255. p->removeListener (listener);
  256. }
  257. Value AudioProcessorValueTreeState::getParameterAsValue (StringRef paramID) const
  258. {
  259. if (auto* adapter = getParameterAdapter (paramID))
  260. if (adapter->tree.isValid())
  261. return adapter->tree.getPropertyAsValue (valuePropertyID, undoManager);
  262. return {};
  263. }
  264. NormalisableRange<float> AudioProcessorValueTreeState::getParameterRange (StringRef paramID) const noexcept
  265. {
  266. if (auto* p = getParameterAdapter (paramID))
  267. return p->getRange();
  268. return {};
  269. }
  270. RangedAudioParameter* AudioProcessorValueTreeState::getParameter (StringRef paramID) const noexcept
  271. {
  272. if (auto adapter = getParameterAdapter (paramID))
  273. return &adapter->getParameter();
  274. return nullptr;
  275. }
  276. float* AudioProcessorValueTreeState::getRawParameterValue (StringRef paramID) const noexcept
  277. {
  278. if (auto* p = getParameterAdapter (paramID))
  279. return &p->getRawDenormalisedValue();
  280. return nullptr;
  281. }
  282. ValueTree AudioProcessorValueTreeState::copyState()
  283. {
  284. ScopedLock lock (valueTreeChanging);
  285. flushParameterValuesToValueTree();
  286. return state.createCopy();
  287. }
  288. void AudioProcessorValueTreeState::replaceState (const ValueTree& newState)
  289. {
  290. ScopedLock lock (valueTreeChanging);
  291. state = newState;
  292. if (undoManager != nullptr)
  293. undoManager->clearUndoHistory();
  294. }
  295. void AudioProcessorValueTreeState::setNewState (ValueTree vt)
  296. {
  297. jassert (vt.getParent() == state);
  298. if (auto* p = getParameterAdapter (vt.getProperty (idPropertyID).toString()))
  299. {
  300. p->tree = vt;
  301. p->setDenormalisedValue (p->tree.getProperty (valuePropertyID, p->getDenormalisedDefaultValue()));
  302. }
  303. }
  304. void AudioProcessorValueTreeState::updateParameterConnectionsToChildTrees()
  305. {
  306. ScopedLock lock (valueTreeChanging);
  307. for (auto& p : adapterTable)
  308. p.second->tree = ValueTree();
  309. for (const auto& child : state)
  310. setNewState (child);
  311. for (auto& p : adapterTable)
  312. {
  313. auto& adapter = *p.second;
  314. if (! adapter.tree.isValid())
  315. {
  316. adapter.tree = ValueTree (valueType);
  317. adapter.tree.setProperty (idPropertyID, adapter.getParameter().paramID, nullptr);
  318. state.appendChild (adapter.tree, nullptr);
  319. }
  320. }
  321. flushParameterValuesToValueTree();
  322. }
  323. void AudioProcessorValueTreeState::valueTreePropertyChanged (ValueTree& tree, const Identifier&)
  324. {
  325. if (tree.hasType (valueType) && tree.getParent() == state)
  326. setNewState (tree);
  327. }
  328. void AudioProcessorValueTreeState::valueTreeChildAdded (ValueTree& parent, ValueTree& tree)
  329. {
  330. if (parent == state && tree.hasType (valueType))
  331. setNewState (tree);
  332. }
  333. void AudioProcessorValueTreeState::valueTreeRedirected (ValueTree& v)
  334. {
  335. if (v == state)
  336. updateParameterConnectionsToChildTrees();
  337. }
  338. bool AudioProcessorValueTreeState::flushParameterValuesToValueTree()
  339. {
  340. ScopedLock lock (valueTreeChanging);
  341. bool anyUpdated = false;
  342. for (auto& p : adapterTable)
  343. anyUpdated |= p.second->flushToTree (valuePropertyID, undoManager);
  344. return anyUpdated;
  345. }
  346. void AudioProcessorValueTreeState::timerCallback()
  347. {
  348. auto anythingUpdated = flushParameterValuesToValueTree();
  349. startTimer (anythingUpdated ? 1000 / 50
  350. : jlimit (50, 500, getTimerInterval() + 20));
  351. }
  352. //==============================================================================
  353. struct AttachedControlBase : public AudioProcessorValueTreeState::Listener,
  354. public AsyncUpdater
  355. {
  356. AttachedControlBase (AudioProcessorValueTreeState& s, const String& p)
  357. : state (s), paramID (p), lastValue (0)
  358. {
  359. state.addParameterListener (paramID, this);
  360. }
  361. void removeListener()
  362. {
  363. state.removeParameterListener (paramID, this);
  364. }
  365. void setNewDenormalisedValue (float newDenormalisedValue)
  366. {
  367. if (auto* p = state.getParameter (paramID))
  368. {
  369. const float newValue = state.getParameterRange (paramID)
  370. .convertTo0to1 (newDenormalisedValue);
  371. if (p->getValue() != newValue)
  372. p->setValueNotifyingHost (newValue);
  373. }
  374. }
  375. void sendInitialUpdate()
  376. {
  377. if (auto* v = state.getRawParameterValue (paramID))
  378. parameterChanged (paramID, *v);
  379. }
  380. void parameterChanged (const String&, float newValue) override
  381. {
  382. lastValue = newValue;
  383. if (MessageManager::getInstance()->isThisTheMessageThread())
  384. {
  385. cancelPendingUpdate();
  386. setValue (newValue);
  387. }
  388. else
  389. {
  390. triggerAsyncUpdate();
  391. }
  392. }
  393. void beginParameterChange()
  394. {
  395. if (auto* p = state.getParameter (paramID))
  396. {
  397. if (state.undoManager != nullptr)
  398. state.undoManager->beginNewTransaction();
  399. p->beginChangeGesture();
  400. }
  401. }
  402. void endParameterChange()
  403. {
  404. if (AudioProcessorParameter* p = state.getParameter (paramID))
  405. p->endChangeGesture();
  406. }
  407. void handleAsyncUpdate() override
  408. {
  409. setValue (lastValue);
  410. }
  411. virtual void setValue (float) = 0;
  412. AudioProcessorValueTreeState& state;
  413. String paramID;
  414. float lastValue;
  415. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AttachedControlBase)
  416. };
  417. //==============================================================================
  418. struct AudioProcessorValueTreeState::SliderAttachment::Pimpl : private AttachedControlBase,
  419. private Slider::Listener
  420. {
  421. Pimpl (AudioProcessorValueTreeState& s, const String& p, Slider& sl)
  422. : AttachedControlBase (s, p), slider (sl), ignoreCallbacks (false)
  423. {
  424. NormalisableRange<float> range (state.getParameterRange (paramID));
  425. if (auto* param = state.getParameterAdapter (paramID))
  426. {
  427. slider.valueFromTextFunction = [param](const String& text) { return (double) param->getDenormalisedValueForText (text); };
  428. slider.textFromValueFunction = [param](double value) { return param->getTextForDenormalisedValue ((float) value); };
  429. slider.setDoubleClickReturnValue (true, range.convertFrom0to1 (param->getParameter().getDefaultValue()));
  430. }
  431. auto convertFrom0To1Function = [range](double currentRangeStart,
  432. double currentRangeEnd,
  433. double normalisedValue) mutable
  434. {
  435. range.start = (float) currentRangeStart;
  436. range.end = (float) currentRangeEnd;
  437. return (double) range.convertFrom0to1 ((float) normalisedValue);
  438. };
  439. auto convertTo0To1Function = [range](double currentRangeStart,
  440. double currentRangeEnd,
  441. double mappedValue) mutable
  442. {
  443. range.start = (float) currentRangeStart;
  444. range.end = (float) currentRangeEnd;
  445. return (double) range.convertTo0to1 ((float) mappedValue);
  446. };
  447. auto snapToLegalValueFunction = [range](double currentRangeStart,
  448. double currentRangeEnd,
  449. double valueToSnap) mutable
  450. {
  451. range.start = (float) currentRangeStart;
  452. range.end = (float) currentRangeEnd;
  453. return (double) range.snapToLegalValue ((float) valueToSnap);
  454. };
  455. NormalisableRange<double> newRange { (double) range.start,
  456. (double) range.end,
  457. convertFrom0To1Function,
  458. convertTo0To1Function,
  459. snapToLegalValueFunction };
  460. newRange.interval = (double) range.interval;
  461. newRange.skew = (double) range.skew;
  462. slider.setNormalisableRange (newRange);
  463. sendInitialUpdate();
  464. slider.addListener (this);
  465. }
  466. ~Pimpl() override
  467. {
  468. slider.removeListener (this);
  469. removeListener();
  470. }
  471. void setValue (float newValue) override
  472. {
  473. const ScopedLock selfCallbackLock (selfCallbackMutex);
  474. {
  475. ScopedValueSetter<bool> svs (ignoreCallbacks, true);
  476. slider.setValue (newValue, sendNotificationSync);
  477. }
  478. }
  479. void sliderValueChanged (Slider* s) override
  480. {
  481. const ScopedLock selfCallbackLock (selfCallbackMutex);
  482. if ((! ignoreCallbacks) && (! ModifierKeys::currentModifiers.isRightButtonDown()))
  483. setNewDenormalisedValue ((float) s->getValue());
  484. }
  485. void sliderDragStarted (Slider*) override { beginParameterChange(); }
  486. void sliderDragEnded (Slider*) override { endParameterChange(); }
  487. Slider& slider;
  488. bool ignoreCallbacks;
  489. CriticalSection selfCallbackMutex;
  490. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl)
  491. };
  492. AudioProcessorValueTreeState::SliderAttachment::SliderAttachment (AudioProcessorValueTreeState& s, const String& p, Slider& sl)
  493. : pimpl (new Pimpl (s, p, sl))
  494. {
  495. }
  496. AudioProcessorValueTreeState::SliderAttachment::~SliderAttachment() {}
  497. //==============================================================================
  498. struct AudioProcessorValueTreeState::ComboBoxAttachment::Pimpl : private AttachedControlBase,
  499. private ComboBox::Listener
  500. {
  501. Pimpl (AudioProcessorValueTreeState& s, const String& p, ComboBox& c)
  502. : AttachedControlBase (s, p), combo (c), ignoreCallbacks (false)
  503. {
  504. sendInitialUpdate();
  505. combo.addListener (this);
  506. }
  507. ~Pimpl() override
  508. {
  509. combo.removeListener (this);
  510. removeListener();
  511. }
  512. void setValue (float newValue) override
  513. {
  514. const ScopedLock selfCallbackLock (selfCallbackMutex);
  515. if (state.getParameter (paramID) != nullptr)
  516. {
  517. auto normValue = state.getParameterRange (paramID)
  518. .convertTo0to1 (newValue);
  519. auto index = roundToInt (normValue * (combo.getNumItems() - 1));
  520. if (index != combo.getSelectedItemIndex())
  521. {
  522. ScopedValueSetter<bool> svs (ignoreCallbacks, true);
  523. combo.setSelectedItemIndex (index, sendNotificationSync);
  524. }
  525. }
  526. }
  527. void comboBoxChanged (ComboBox*) override
  528. {
  529. const ScopedLock selfCallbackLock (selfCallbackMutex);
  530. if (! ignoreCallbacks)
  531. {
  532. if (auto* p = state.getParameter (paramID))
  533. {
  534. auto newValue = (float) combo.getSelectedItemIndex() / (combo.getNumItems() - 1);
  535. if (p->getValue() != newValue)
  536. {
  537. beginParameterChange();
  538. p->setValueNotifyingHost (newValue);
  539. endParameterChange();
  540. }
  541. }
  542. }
  543. }
  544. ComboBox& combo;
  545. bool ignoreCallbacks;
  546. CriticalSection selfCallbackMutex;
  547. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl)
  548. };
  549. AudioProcessorValueTreeState::ComboBoxAttachment::ComboBoxAttachment (AudioProcessorValueTreeState& s, const String& p, ComboBox& c)
  550. : pimpl (new Pimpl (s, p, c))
  551. {
  552. }
  553. AudioProcessorValueTreeState::ComboBoxAttachment::~ComboBoxAttachment() {}
  554. //==============================================================================
  555. struct AudioProcessorValueTreeState::ButtonAttachment::Pimpl : private AttachedControlBase,
  556. private Button::Listener
  557. {
  558. Pimpl (AudioProcessorValueTreeState& s, const String& p, Button& b)
  559. : AttachedControlBase (s, p), button (b), ignoreCallbacks (false)
  560. {
  561. sendInitialUpdate();
  562. button.addListener (this);
  563. }
  564. ~Pimpl() override
  565. {
  566. button.removeListener (this);
  567. removeListener();
  568. }
  569. void setValue (float newValue) override
  570. {
  571. const ScopedLock selfCallbackLock (selfCallbackMutex);
  572. {
  573. ScopedValueSetter<bool> svs (ignoreCallbacks, true);
  574. button.setToggleState (newValue >= 0.5f, sendNotificationSync);
  575. }
  576. }
  577. void buttonClicked (Button* b) override
  578. {
  579. const ScopedLock selfCallbackLock (selfCallbackMutex);
  580. if (! ignoreCallbacks)
  581. {
  582. beginParameterChange();
  583. setNewDenormalisedValue (b->getToggleState() ? 1.0f : 0.0f);
  584. endParameterChange();
  585. }
  586. }
  587. Button& button;
  588. bool ignoreCallbacks;
  589. CriticalSection selfCallbackMutex;
  590. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl)
  591. };
  592. AudioProcessorValueTreeState::ButtonAttachment::ButtonAttachment (AudioProcessorValueTreeState& s, const String& p, Button& b)
  593. : pimpl (new Pimpl (s, p, b))
  594. {
  595. }
  596. AudioProcessorValueTreeState::ButtonAttachment::~ButtonAttachment() {}
  597. //==============================================================================
  598. //==============================================================================
  599. #if JUCE_UNIT_TESTS
  600. struct ParameterAdapterTests : public UnitTest
  601. {
  602. ParameterAdapterTests()
  603. : UnitTest ("Parameter Adapter", UnitTestCategories::audioProcessorParameters)
  604. {}
  605. void runTest() override
  606. {
  607. beginTest ("The default value is returned correctly");
  608. {
  609. const auto test = [&] (NormalisableRange<float> range, float value)
  610. {
  611. AudioParameterFloat param ({}, {}, range, value, {});
  612. AudioProcessorValueTreeState::ParameterAdapter adapter (param);
  613. expectEquals (adapter.getDenormalisedDefaultValue(), value);
  614. };
  615. test ({ -100, 100 }, 0);
  616. test ({ -2.5, 12.5 }, 10);
  617. }
  618. beginTest ("Denormalised parameter values can be retrieved");
  619. {
  620. const auto test = [&](NormalisableRange<float> range, float value)
  621. {
  622. AudioParameterFloat param ({}, {}, range, {}, {});
  623. AudioProcessorValueTreeState::ParameterAdapter adapter (param);
  624. adapter.setDenormalisedValue (value);
  625. expectEquals (adapter.getDenormalisedValue(), value);
  626. expectEquals (adapter.getRawDenormalisedValue(), value);
  627. };
  628. test ({ -20, -10 }, -15);
  629. test ({ 0, 7.5 }, 2.5);
  630. }
  631. beginTest ("Floats can be converted to text");
  632. {
  633. const auto test = [&](NormalisableRange<float> range, float value, String expected)
  634. {
  635. AudioParameterFloat param ({}, {}, range, {}, {});
  636. AudioProcessorValueTreeState::ParameterAdapter adapter (param);
  637. expectEquals (adapter.getTextForDenormalisedValue (value), expected);
  638. };
  639. test ({ -100, 100 }, 0, "0.0000000");
  640. test ({ -2.5, 12.5 }, 10, "10.0000000");
  641. test ({ -20, -10 }, -15, "-15.0000000");
  642. test ({ 0, 7.5 }, 2.5, "2.5000000");
  643. }
  644. beginTest ("Text can be converted to floats");
  645. {
  646. const auto test = [&](NormalisableRange<float> range, String text, float expected)
  647. {
  648. AudioParameterFloat param ({}, {}, range, {}, {});
  649. AudioProcessorValueTreeState::ParameterAdapter adapter (param);
  650. expectEquals (adapter.getDenormalisedValueForText (text), expected);
  651. };
  652. test ({ -100, 100 }, "0.0", 0);
  653. test ({ -2.5, 12.5 }, "10.0", 10);
  654. test ({ -20, -10 }, "-15.0", -15);
  655. test ({ 0, 7.5 }, "2.5", 2.5);
  656. }
  657. }
  658. };
  659. static ParameterAdapterTests parameterAdapterTests;
  660. namespace
  661. {
  662. template <typename ValueType>
  663. inline bool operator== (const NormalisableRange<ValueType>& a,
  664. const NormalisableRange<ValueType>& b)
  665. {
  666. return std::tie (a.start, a.end, a.interval, a.skew, a.symmetricSkew)
  667. == std::tie (b.start, b.end, b.interval, b.skew, b.symmetricSkew);
  668. }
  669. template <typename ValueType>
  670. inline bool operator!= (const NormalisableRange<ValueType>& a,
  671. const NormalisableRange<ValueType>& b)
  672. {
  673. return ! (a == b);
  674. }
  675. } // namespace
  676. class AudioProcessorValueTreeStateTests : public UnitTest
  677. {
  678. private:
  679. using Parameter = AudioProcessorValueTreeState::Parameter;
  680. using ParameterGroup = AudioProcessorParameterGroup;
  681. using ParameterLayout = AudioProcessorValueTreeState::ParameterLayout;
  682. class TestAudioProcessor : public AudioProcessor
  683. {
  684. public:
  685. TestAudioProcessor() = default;
  686. explicit TestAudioProcessor (ParameterLayout layout)
  687. : state (*this, nullptr, "state", std::move (layout)) {}
  688. const String getName() const override { return {}; }
  689. void prepareToPlay (double, int) override {}
  690. void releaseResources() override {}
  691. void processBlock (AudioBuffer<float>&, MidiBuffer&) override {}
  692. double getTailLengthSeconds() const override { return {}; }
  693. bool acceptsMidi() const override { return {}; }
  694. bool producesMidi() const override { return {}; }
  695. AudioProcessorEditor* createEditor() override { return {}; }
  696. bool hasEditor() const override { return {}; }
  697. int getNumPrograms() override { return 1; }
  698. int getCurrentProgram() override { return {}; }
  699. void setCurrentProgram (int) override {}
  700. const String getProgramName (int) override { return {}; }
  701. void changeProgramName (int, const String&) override {}
  702. void getStateInformation (MemoryBlock&) override {}
  703. void setStateInformation (const void*, int) override {}
  704. AudioProcessorValueTreeState state { *this, nullptr };
  705. };
  706. struct Listener final : public AudioProcessorValueTreeState::Listener
  707. {
  708. void parameterChanged (const String& idIn, float valueIn) override
  709. {
  710. id = idIn;
  711. value = valueIn;
  712. }
  713. String id;
  714. float value{};
  715. };
  716. public:
  717. AudioProcessorValueTreeStateTests()
  718. : UnitTest ("Audio Processor Value Tree State", UnitTestCategories::audioProcessorParameters)
  719. {}
  720. void runTest() override
  721. {
  722. ScopedJuceInitialiser_GUI scopedJuceInitialiser_gui;
  723. beginTest ("After calling createAndAddParameter, the number of parameters increases by one");
  724. {
  725. TestAudioProcessor proc;
  726. proc.state.createAndAddParameter (std::make_unique<Parameter> (String(), String(), String(), NormalisableRange<float>(),
  727. 0.0f, nullptr, nullptr));
  728. expectEquals (proc.getParameters().size(), 1);
  729. }
  730. beginTest ("After creating a normal named parameter, we can later retrieve that parameter");
  731. {
  732. TestAudioProcessor proc;
  733. const auto key = "id";
  734. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  735. 0.0f, nullptr, nullptr));
  736. expect (proc.state.getParameter (key) == param);
  737. }
  738. beginTest ("After construction, the value tree has the expected format");
  739. {
  740. TestAudioProcessor proc ({
  741. std::make_unique<AudioProcessorParameterGroup> ("", "", "",
  742. std::make_unique<AudioParameterBool> ("a", "", false),
  743. std::make_unique<AudioParameterFloat> ("b", "", NormalisableRange<float>{}, 0.0f)),
  744. std::make_unique<AudioProcessorParameterGroup> ("", "", "",
  745. std::make_unique<AudioParameterInt> ("c", "", 0, 1, 0),
  746. std::make_unique<AudioParameterChoice> ("d", "", StringArray { "foo", "bar" }, 0)) });
  747. const auto valueTree = proc.state.copyState();
  748. expectEquals (valueTree.getNumChildren(), 4);
  749. for (auto child : valueTree)
  750. {
  751. expect (child.hasType ("PARAM"));
  752. expect (child.hasProperty ("id"));
  753. expect (child.hasProperty ("value"));
  754. }
  755. }
  756. beginTest ("Meta parameters can be created");
  757. {
  758. TestAudioProcessor proc;
  759. const auto key = "id";
  760. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  761. 0.0f, nullptr, nullptr, true));
  762. expect (param->isMetaParameter());
  763. }
  764. beginTest ("Automatable parameters can be created");
  765. {
  766. TestAudioProcessor proc;
  767. const auto key = "id";
  768. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  769. 0.0f, nullptr, nullptr, false, true));
  770. expect (param->isAutomatable());
  771. }
  772. beginTest ("Discrete parameters can be created");
  773. {
  774. TestAudioProcessor proc;
  775. const auto key = "id";
  776. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  777. 0.0f, nullptr, nullptr, false, false, true));
  778. expect (param->isDiscrete());
  779. }
  780. beginTest ("Custom category parameters can be created");
  781. {
  782. TestAudioProcessor proc;
  783. const auto key = "id";
  784. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  785. 0.0f, nullptr, nullptr, false, false, false,
  786. AudioProcessorParameter::Category::inputMeter));
  787. expect (param->category == AudioProcessorParameter::Category::inputMeter);
  788. }
  789. beginTest ("Boolean parameters can be created");
  790. {
  791. TestAudioProcessor proc;
  792. const auto key = "id";
  793. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  794. 0.0f, nullptr, nullptr, false, false, false,
  795. AudioProcessorParameter::Category::genericParameter, true));
  796. expect (param->isBoolean());
  797. }
  798. beginTest ("After creating a custom named parameter, we can later retrieve that parameter");
  799. {
  800. const auto key = "id";
  801. auto param = std::make_unique<AudioParameterBool> (key, "", false);
  802. const auto paramPtr = param.get();
  803. TestAudioProcessor proc (std::move (param));
  804. expect (proc.state.getParameter (key) == paramPtr);
  805. }
  806. beginTest ("After adding a normal parameter that already exists, the AudioProcessor parameters are unchanged");
  807. {
  808. TestAudioProcessor proc;
  809. const auto key = "id";
  810. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  811. 0.0f, nullptr, nullptr));
  812. proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  813. 0.0f, nullptr, nullptr));
  814. expectEquals (proc.getParameters().size(), 1);
  815. expect (proc.getParameters().getFirst() == param);
  816. }
  817. beginTest ("After setting a parameter value, that value is reflected in the state");
  818. {
  819. TestAudioProcessor proc;
  820. const auto key = "id";
  821. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  822. 0.0f, nullptr, nullptr));
  823. const auto value = 0.5f;
  824. param->setValueNotifyingHost (value);
  825. expectEquals (*proc.state.getRawParameterValue (key), value);
  826. }
  827. beginTest ("After adding an APVTS::Parameter, its value is the default value");
  828. {
  829. TestAudioProcessor proc;
  830. const auto key = "id";
  831. const auto value = 5.0f;
  832. proc.state.createAndAddParameter (std::make_unique<Parameter> (
  833. key,
  834. String(),
  835. String(),
  836. NormalisableRange<float> (0.0f, 100.0f, 10.0f),
  837. value,
  838. nullptr,
  839. nullptr));
  840. expectEquals (*proc.state.getRawParameterValue (key), value);
  841. }
  842. beginTest ("Listeners receive notifications when parameters change");
  843. {
  844. Listener listener;
  845. TestAudioProcessor proc;
  846. const auto key = "id";
  847. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  848. 0.0f, nullptr, nullptr));
  849. proc.state.addParameterListener (key, &listener);
  850. const auto value = 0.5f;
  851. param->setValueNotifyingHost (value);
  852. expectEquals (listener.id, String { key });
  853. expectEquals (listener.value, value);
  854. }
  855. beginTest ("Bool parameters have a range of 0-1");
  856. {
  857. const auto key = "id";
  858. TestAudioProcessor proc (std::make_unique<AudioParameterBool> (key, "", false));
  859. expect (proc.state.getParameterRange (key) == NormalisableRange<float> (0.0f, 1.0f, 1.0f));
  860. }
  861. beginTest ("Float parameters retain their specified range");
  862. {
  863. const auto key = "id";
  864. const auto range = NormalisableRange<float> { -100, 100, 0.7f, 0.2f, true };
  865. TestAudioProcessor proc (std::make_unique<AudioParameterFloat> (key, "", range, 0.0f));
  866. expect (proc.state.getParameterRange (key) == range);
  867. }
  868. beginTest ("Int parameters retain their specified range");
  869. {
  870. const auto key = "id";
  871. const auto min = -27;
  872. const auto max = 53;
  873. TestAudioProcessor proc (std::make_unique<AudioParameterInt> (key, "", min, max, 0));
  874. expect (proc.state.getParameterRange (key) == NormalisableRange<float> (float (min), float (max), 1.0f));
  875. }
  876. beginTest ("Choice parameters retain their specified range");
  877. {
  878. const auto key = "id";
  879. const auto choices = StringArray { "", "", "" };
  880. TestAudioProcessor proc (std::make_unique<AudioParameterChoice> (key, "", choices, 0));
  881. expect (proc.state.getParameterRange (key) == NormalisableRange<float> (0.0f, (float) (choices.size() - 1), 1.0f));
  882. expect (proc.state.getParameter (key)->getNumSteps() == choices.size());
  883. }
  884. beginTest ("When the parameter value is changed, normal parameter values are updated");
  885. {
  886. TestAudioProcessor proc;
  887. const auto key = "id";
  888. const auto initialValue = 0.2f;
  889. auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  890. initialValue, nullptr, nullptr));
  891. proc.state.state = ValueTree { "state" };
  892. auto value = proc.state.getParameterAsValue (key);
  893. expectEquals (float (value.getValue()), initialValue);
  894. const auto newValue = 0.75f;
  895. value = newValue;
  896. expectEquals (param->getValue(), newValue);
  897. expectEquals (*proc.state.getRawParameterValue (key), newValue);
  898. }
  899. beginTest ("When the parameter value is changed, custom parameter values are updated");
  900. {
  901. const auto key = "id";
  902. const auto choices = StringArray ("foo", "bar", "baz");
  903. auto param = std::make_unique<AudioParameterChoice> (key, "", choices, 0);
  904. const auto paramPtr = param.get();
  905. TestAudioProcessor proc (std::move (param));
  906. const auto newValue = 2.0f;
  907. auto value = proc.state.getParameterAsValue (key);
  908. value = newValue;
  909. expectEquals (paramPtr->getCurrentChoiceName(), choices[int (newValue)]);
  910. expectEquals (*proc.state.getRawParameterValue (key), newValue);
  911. }
  912. beginTest ("When the parameter value is changed, listeners are notified");
  913. {
  914. Listener listener;
  915. TestAudioProcessor proc;
  916. const auto key = "id";
  917. proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  918. 0.0f, nullptr, nullptr));
  919. proc.state.addParameterListener (key, &listener);
  920. proc.state.state = ValueTree { "state" };
  921. const auto newValue = 0.75f;
  922. proc.state.getParameterAsValue (key) = newValue;
  923. expectEquals (listener.value, newValue);
  924. expectEquals (listener.id, String { key });
  925. }
  926. beginTest ("When the parameter value is changed, listeners are notified");
  927. {
  928. const auto key = "id";
  929. const auto choices = StringArray { "foo", "bar", "baz" };
  930. Listener listener;
  931. TestAudioProcessor proc (std::make_unique<AudioParameterChoice> (key, "", choices, 0));
  932. proc.state.addParameterListener (key, &listener);
  933. const auto newValue = 2.0f;
  934. proc.state.getParameterAsValue (key) = newValue;
  935. expectEquals (listener.value, newValue);
  936. expectEquals (listener.id, String (key));
  937. }
  938. }
  939. };
  940. static AudioProcessorValueTreeStateTests audioProcessorValueTreeStateTests;
  941. #endif
  942. } // namespace juce