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.

1178 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 defaultValue,
  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 category,
  33. bool isBoolean)
  34. : AudioParameterFloat (parameterID,
  35. parameterName,
  36. valueRange,
  37. defaultValue,
  38. labelText,
  39. category,
  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 (defaultValue)),
  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() noexcept { 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. }
  322. void AudioProcessorValueTreeState::valueTreePropertyChanged (ValueTree& tree, const Identifier&)
  323. {
  324. if (tree.hasType (valueType) && tree.getParent() == state)
  325. setNewState (tree);
  326. }
  327. void AudioProcessorValueTreeState::valueTreeChildAdded (ValueTree& parent, ValueTree& tree)
  328. {
  329. if (parent == state && tree.hasType (valueType))
  330. setNewState (tree);
  331. }
  332. void AudioProcessorValueTreeState::valueTreeChildRemoved (ValueTree& parent, ValueTree& tree, int)
  333. {
  334. if (parent == state && tree.hasType (valueType))
  335. setNewState (tree);
  336. }
  337. void AudioProcessorValueTreeState::valueTreeRedirected (ValueTree& v)
  338. {
  339. if (v == state)
  340. updateParameterConnectionsToChildTrees();
  341. }
  342. void AudioProcessorValueTreeState::valueTreeChildOrderChanged (ValueTree&, int, int) {}
  343. void AudioProcessorValueTreeState::valueTreeParentChanged (ValueTree&) {}
  344. bool AudioProcessorValueTreeState::flushParameterValuesToValueTree()
  345. {
  346. ScopedLock lock (valueTreeChanging);
  347. bool anyUpdated = false;
  348. for (auto& p : adapterTable)
  349. anyUpdated |= p.second->flushToTree (valuePropertyID, undoManager);
  350. return anyUpdated;
  351. }
  352. void AudioProcessorValueTreeState::timerCallback()
  353. {
  354. auto anythingUpdated = flushParameterValuesToValueTree();
  355. startTimer (anythingUpdated ? 1000 / 50
  356. : jlimit (50, 500, getTimerInterval() + 20));
  357. }
  358. //==============================================================================
  359. struct AttachedControlBase : public AudioProcessorValueTreeState::Listener,
  360. public AsyncUpdater
  361. {
  362. AttachedControlBase (AudioProcessorValueTreeState& s, const String& p)
  363. : state (s), paramID (p), lastValue (0)
  364. {
  365. state.addParameterListener (paramID, this);
  366. }
  367. void removeListener()
  368. {
  369. state.removeParameterListener (paramID, this);
  370. }
  371. void setNewDenormalisedValue (float newDenormalisedValue)
  372. {
  373. if (auto* p = state.getParameter (paramID))
  374. {
  375. const float newValue = state.getParameterRange (paramID)
  376. .convertTo0to1 (newDenormalisedValue);
  377. if (p->getValue() != newValue)
  378. p->setValueNotifyingHost (newValue);
  379. }
  380. }
  381. void sendInitialUpdate()
  382. {
  383. if (auto* v = state.getRawParameterValue (paramID))
  384. parameterChanged (paramID, *v);
  385. }
  386. void parameterChanged (const String&, float newValue) override
  387. {
  388. lastValue = newValue;
  389. if (MessageManager::getInstance()->isThisTheMessageThread())
  390. {
  391. cancelPendingUpdate();
  392. setValue (newValue);
  393. }
  394. else
  395. {
  396. triggerAsyncUpdate();
  397. }
  398. }
  399. void beginParameterChange()
  400. {
  401. if (auto* p = state.getParameter (paramID))
  402. {
  403. if (state.undoManager != nullptr)
  404. state.undoManager->beginNewTransaction();
  405. p->beginChangeGesture();
  406. }
  407. }
  408. void endParameterChange()
  409. {
  410. if (AudioProcessorParameter* p = state.getParameter (paramID))
  411. p->endChangeGesture();
  412. }
  413. void handleAsyncUpdate() override
  414. {
  415. setValue (lastValue);
  416. }
  417. virtual void setValue (float) = 0;
  418. AudioProcessorValueTreeState& state;
  419. String paramID;
  420. float lastValue;
  421. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AttachedControlBase)
  422. };
  423. //==============================================================================
  424. struct AudioProcessorValueTreeState::SliderAttachment::Pimpl : private AttachedControlBase,
  425. private Slider::Listener
  426. {
  427. Pimpl (AudioProcessorValueTreeState& s, const String& p, Slider& sl)
  428. : AttachedControlBase (s, p), slider (sl), ignoreCallbacks (false)
  429. {
  430. NormalisableRange<float> range (state.getParameterRange (paramID));
  431. if (auto* param = state.getParameterAdapter (paramID))
  432. {
  433. slider.valueFromTextFunction = [param](const String& text) { return (double) param->getDenormalisedValueForText (text); };
  434. slider.textFromValueFunction = [param](double value) { return param->getTextForDenormalisedValue ((float) value); };
  435. slider.setDoubleClickReturnValue (true, range.convertFrom0to1 (param->getParameter().getDefaultValue()));
  436. }
  437. if (range.interval != 0.0f || range.skew != 1.0f)
  438. {
  439. slider.setRange (range.start, range.end, range.interval);
  440. slider.setSkewFactor (range.skew, range.symmetricSkew);
  441. }
  442. else
  443. {
  444. auto convertFrom0To1Function = [range](double currentRangeStart,
  445. double currentRangeEnd,
  446. double normalisedValue) mutable
  447. {
  448. range.start = (float) currentRangeStart;
  449. range.end = (float) currentRangeEnd;
  450. return (double) range.convertFrom0to1 ((float) normalisedValue);
  451. };
  452. auto convertTo0To1Function = [range](double currentRangeStart,
  453. double currentRangeEnd,
  454. double mappedValue) mutable
  455. {
  456. range.start = (float) currentRangeStart;
  457. range.end = (float) currentRangeEnd;
  458. return (double) range.convertTo0to1 ((float) mappedValue);
  459. };
  460. auto snapToLegalValueFunction = [range](double currentRangeStart,
  461. double currentRangeEnd,
  462. double valueToSnap) mutable
  463. {
  464. range.start = (float) currentRangeStart;
  465. range.end = (float) currentRangeEnd;
  466. return (double) range.snapToLegalValue ((float) valueToSnap);
  467. };
  468. slider.setNormalisableRange ({ (double) range.start,
  469. (double) range.end,
  470. convertFrom0To1Function,
  471. convertTo0To1Function,
  472. snapToLegalValueFunction });
  473. }
  474. sendInitialUpdate();
  475. slider.addListener (this);
  476. }
  477. ~Pimpl()
  478. {
  479. slider.removeListener (this);
  480. removeListener();
  481. }
  482. void setValue (float newValue) override
  483. {
  484. const ScopedLock selfCallbackLock (selfCallbackMutex);
  485. {
  486. ScopedValueSetter<bool> svs (ignoreCallbacks, true);
  487. slider.setValue (newValue, sendNotificationSync);
  488. }
  489. }
  490. void sliderValueChanged (Slider* s) override
  491. {
  492. const ScopedLock selfCallbackLock (selfCallbackMutex);
  493. if ((! ignoreCallbacks) && (! ModifierKeys::currentModifiers.isRightButtonDown()))
  494. setNewDenormalisedValue ((float) s->getValue());
  495. }
  496. void sliderDragStarted (Slider*) override { beginParameterChange(); }
  497. void sliderDragEnded (Slider*) override { endParameterChange(); }
  498. Slider& slider;
  499. bool ignoreCallbacks;
  500. CriticalSection selfCallbackMutex;
  501. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl)
  502. };
  503. AudioProcessorValueTreeState::SliderAttachment::SliderAttachment (AudioProcessorValueTreeState& s, const String& p, Slider& sl)
  504. : pimpl (new Pimpl (s, p, sl))
  505. {
  506. }
  507. AudioProcessorValueTreeState::SliderAttachment::~SliderAttachment() {}
  508. //==============================================================================
  509. struct AudioProcessorValueTreeState::ComboBoxAttachment::Pimpl : private AttachedControlBase,
  510. private ComboBox::Listener
  511. {
  512. Pimpl (AudioProcessorValueTreeState& s, const String& p, ComboBox& c)
  513. : AttachedControlBase (s, p), combo (c), ignoreCallbacks (false)
  514. {
  515. sendInitialUpdate();
  516. combo.addListener (this);
  517. }
  518. ~Pimpl()
  519. {
  520. combo.removeListener (this);
  521. removeListener();
  522. }
  523. void setValue (float newValue) override
  524. {
  525. const ScopedLock selfCallbackLock (selfCallbackMutex);
  526. if (state.getParameter (paramID) != nullptr)
  527. {
  528. auto normValue = state.getParameterRange (paramID)
  529. .convertTo0to1 (newValue);
  530. auto index = roundToInt (normValue * (combo.getNumItems() - 1));
  531. if (index != combo.getSelectedItemIndex())
  532. {
  533. ScopedValueSetter<bool> svs (ignoreCallbacks, true);
  534. combo.setSelectedItemIndex (index, sendNotificationSync);
  535. }
  536. }
  537. }
  538. void comboBoxChanged (ComboBox*) override
  539. {
  540. const ScopedLock selfCallbackLock (selfCallbackMutex);
  541. if (! ignoreCallbacks)
  542. {
  543. if (auto* p = state.getParameter (paramID))
  544. {
  545. auto newValue = (float) combo.getSelectedItemIndex() / (combo.getNumItems() - 1);
  546. if (p->getValue() != newValue)
  547. {
  548. beginParameterChange();
  549. p->setValueNotifyingHost (newValue);
  550. endParameterChange();
  551. }
  552. }
  553. }
  554. }
  555. ComboBox& combo;
  556. bool ignoreCallbacks;
  557. CriticalSection selfCallbackMutex;
  558. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl)
  559. };
  560. AudioProcessorValueTreeState::ComboBoxAttachment::ComboBoxAttachment (AudioProcessorValueTreeState& s, const String& p, ComboBox& c)
  561. : pimpl (new Pimpl (s, p, c))
  562. {
  563. }
  564. AudioProcessorValueTreeState::ComboBoxAttachment::~ComboBoxAttachment() {}
  565. //==============================================================================
  566. struct AudioProcessorValueTreeState::ButtonAttachment::Pimpl : private AttachedControlBase,
  567. private Button::Listener
  568. {
  569. Pimpl (AudioProcessorValueTreeState& s, const String& p, Button& b)
  570. : AttachedControlBase (s, p), button (b), ignoreCallbacks (false)
  571. {
  572. sendInitialUpdate();
  573. button.addListener (this);
  574. }
  575. ~Pimpl()
  576. {
  577. button.removeListener (this);
  578. removeListener();
  579. }
  580. void setValue (float newValue) override
  581. {
  582. const ScopedLock selfCallbackLock (selfCallbackMutex);
  583. {
  584. ScopedValueSetter<bool> svs (ignoreCallbacks, true);
  585. button.setToggleState (newValue >= 0.5f, sendNotificationSync);
  586. }
  587. }
  588. void buttonClicked (Button* b) override
  589. {
  590. const ScopedLock selfCallbackLock (selfCallbackMutex);
  591. if (! ignoreCallbacks)
  592. {
  593. beginParameterChange();
  594. setNewDenormalisedValue (b->getToggleState() ? 1.0f : 0.0f);
  595. endParameterChange();
  596. }
  597. }
  598. Button& button;
  599. bool ignoreCallbacks;
  600. CriticalSection selfCallbackMutex;
  601. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl)
  602. };
  603. AudioProcessorValueTreeState::ButtonAttachment::ButtonAttachment (AudioProcessorValueTreeState& s, const String& p, Button& b)
  604. : pimpl (new Pimpl (s, p, b))
  605. {
  606. }
  607. AudioProcessorValueTreeState::ButtonAttachment::~ButtonAttachment() {}
  608. #if JUCE_UNIT_TESTS
  609. static struct ParameterAdapterTests final : public UnitTest
  610. {
  611. ParameterAdapterTests() : UnitTest ("Parameter Adapter") {}
  612. void runTest() override
  613. {
  614. beginTest ("The default value is returned correctly");
  615. {
  616. const auto test = [&] (NormalisableRange<float> range, float value)
  617. {
  618. AudioParameterFloat param ({}, {}, range, value, {});
  619. AudioProcessorValueTreeState::ParameterAdapter adapter (param);
  620. expectEquals (adapter.getDenormalisedDefaultValue(), value);
  621. };
  622. test ({ -100, 100 }, 0);
  623. test ({ -2.5, 12.5 }, 10);
  624. }
  625. beginTest ("Denormalised parameter values can be retrieved");
  626. {
  627. const auto test = [&](NormalisableRange<float> range, float value)
  628. {
  629. AudioParameterFloat param ({}, {}, range, {}, {});
  630. AudioProcessorValueTreeState::ParameterAdapter adapter (param);
  631. adapter.setDenormalisedValue (value);
  632. expectEquals (adapter.getDenormalisedValue(), value);
  633. expectEquals (adapter.getRawDenormalisedValue(), value);
  634. };
  635. test ({ -20, -10 }, -15);
  636. test ({ 0, 7.5 }, 2.5);
  637. }
  638. beginTest ("Floats can be converted to text");
  639. {
  640. const auto test = [&](NormalisableRange<float> range, float value, String expected)
  641. {
  642. AudioParameterFloat param ({}, {}, range, {}, {});
  643. AudioProcessorValueTreeState::ParameterAdapter adapter (param);
  644. expectEquals (adapter.getTextForDenormalisedValue (value), expected);
  645. };
  646. test ({ -100, 100 }, 0, "0.0");
  647. test ({ -2.5, 12.5 }, 10, "10.0");
  648. test ({ -20, -10 }, -15, "-15.0");
  649. test ({ 0, 7.5 }, 2.5, "2.5");
  650. }
  651. beginTest ("Text can be converted to floats");
  652. {
  653. const auto test = [&](NormalisableRange<float> range, String text, float expected)
  654. {
  655. AudioParameterFloat param ({}, {}, range, {}, {});
  656. AudioProcessorValueTreeState::ParameterAdapter adapter (param);
  657. expectEquals (adapter.getDenormalisedValueForText (text), expected);
  658. };
  659. test ({ -100, 100 }, "0.0", 0);
  660. test ({ -2.5, 12.5 }, "10.0", 10);
  661. test ({ -20, -10 }, "-15.0", -15);
  662. test ({ 0, 7.5 }, "2.5", 2.5);
  663. }
  664. }
  665. } parameterAdapterTests;
  666. namespace
  667. {
  668. template <typename ValueType>
  669. inline bool operator== (const NormalisableRange<ValueType>& a,
  670. const NormalisableRange<ValueType>& b)
  671. {
  672. return std::tie (a.start, a.end, a.interval, a.skew, a.symmetricSkew)
  673. == std::tie (b.start, b.end, b.interval, b.skew, b.symmetricSkew);
  674. }
  675. template <typename ValueType>
  676. inline bool operator!= (const NormalisableRange<ValueType>& a,
  677. const NormalisableRange<ValueType>& b)
  678. {
  679. return ! (a == b);
  680. }
  681. } // namespace
  682. static class AudioProcessorValueTreeStateTests final : public UnitTest
  683. {
  684. private:
  685. using Parameter = AudioProcessorValueTreeState::Parameter;
  686. using ParameterGroup = AudioProcessorParameterGroup;
  687. using ParameterLayout = AudioProcessorValueTreeState::ParameterLayout;
  688. class TestAudioProcessor : public AudioProcessor
  689. {
  690. public:
  691. TestAudioProcessor() = default;
  692. explicit TestAudioProcessor (ParameterLayout layout)
  693. : state (*this, nullptr, "state", std::move (layout)) {}
  694. const String getName() const override { return {}; }
  695. void prepareToPlay (double, int) override {}
  696. void releaseResources() override {}
  697. void processBlock (AudioBuffer<float>&, MidiBuffer&) override {}
  698. double getTailLengthSeconds() const override { return {}; }
  699. bool acceptsMidi() const override { return {}; }
  700. bool producesMidi() const override { return {}; }
  701. AudioProcessorEditor* createEditor() override { return {}; }
  702. bool hasEditor() const override { return {}; }
  703. int getNumPrograms() override { return 1; }
  704. int getCurrentProgram() override { return {}; }
  705. void setCurrentProgram (int) override {}
  706. const String getProgramName (int) override { return {}; }
  707. void changeProgramName (int, const String&) override {}
  708. void getStateInformation (MemoryBlock&) override {}
  709. void setStateInformation (const void*, int) override {}
  710. AudioProcessorValueTreeState state { *this, nullptr };
  711. };
  712. struct Listener final : public AudioProcessorValueTreeState::Listener
  713. {
  714. void parameterChanged (const String& idIn, float valueIn) override
  715. {
  716. id = idIn;
  717. value = valueIn;
  718. }
  719. String id;
  720. float value{};
  721. };
  722. public:
  723. AudioProcessorValueTreeStateTests() : UnitTest ("Audio Processor Value Tree State", "AudioProcessor parameters") {}
  724. void runTest() override
  725. {
  726. ScopedJuceInitialiser_GUI scopedJuceInitialiser_gui;
  727. beginTest ("After calling createAndAddParameter, the number of parameters increases by one");
  728. {
  729. TestAudioProcessor proc;
  730. proc.state.createAndAddParameter (std::make_unique<Parameter> (String(), String(), String(), NormalisableRange<float>(),
  731. 0.0f, nullptr, nullptr));
  732. expectEquals (proc.getParameters().size(), 1);
  733. }
  734. beginTest ("After creating a normal named parameter, we can later retrieve that parameter");
  735. {
  736. TestAudioProcessor proc;
  737. const auto key = "id";
  738. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  739. 0.0f, nullptr, nullptr));
  740. expect (proc.state.getParameter (key) == param);
  741. }
  742. beginTest ("After construction, the value tree has the expected format");
  743. {
  744. TestAudioProcessor proc ({
  745. std::make_unique<AudioProcessorParameterGroup> ("", "", "",
  746. std::make_unique<AudioParameterBool> ("a", "", false),
  747. std::make_unique<AudioParameterFloat> ("b", "", NormalisableRange<float>{}, 0.0f)),
  748. std::make_unique<AudioProcessorParameterGroup> ("", "", "",
  749. std::make_unique<AudioParameterInt> ("c", "", 0, 1, 0),
  750. std::make_unique<AudioParameterChoice> ("d", "", StringArray { "foo", "bar" }, 0)) });
  751. const auto valueTree = proc.state.copyState();
  752. expectEquals (valueTree.getNumChildren(), 4);
  753. for (auto child : valueTree)
  754. {
  755. expect (child.hasType ("PARAM"));
  756. expect (child.hasProperty ("id"));
  757. expect (child.hasProperty ("value"));
  758. }
  759. }
  760. beginTest ("Meta parameters can be created");
  761. {
  762. TestAudioProcessor proc;
  763. const auto key = "id";
  764. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  765. 0.0f, nullptr, nullptr, true));
  766. expect (param->isMetaParameter());
  767. }
  768. beginTest ("Automatable parameters can be created");
  769. {
  770. TestAudioProcessor proc;
  771. const auto key = "id";
  772. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  773. 0.0f, nullptr, nullptr, false, true));
  774. expect (param->isAutomatable());
  775. }
  776. beginTest ("Discrete parameters can be created");
  777. {
  778. TestAudioProcessor proc;
  779. const auto key = "id";
  780. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  781. 0.0f, nullptr, nullptr, false, false, true));
  782. expect (param->isDiscrete());
  783. }
  784. beginTest ("Custom category parameters can be created");
  785. {
  786. TestAudioProcessor proc;
  787. const auto key = "id";
  788. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  789. 0.0f, nullptr, nullptr, false, false, false,
  790. AudioProcessorParameter::Category::inputMeter));
  791. expect (param->category == AudioProcessorParameter::Category::inputMeter);
  792. }
  793. beginTest ("Boolean parameters can be created");
  794. {
  795. TestAudioProcessor proc;
  796. const auto key = "id";
  797. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  798. 0.0f, nullptr, nullptr, false, false, false,
  799. AudioProcessorParameter::Category::genericParameter, true));
  800. expect (param->isBoolean());
  801. }
  802. beginTest ("After creating a custom named parameter, we can later retrieve that parameter");
  803. {
  804. const auto key = "id";
  805. auto param = std::make_unique<AudioParameterBool> (key, "", false);
  806. const auto paramPtr = param.get();
  807. TestAudioProcessor proc (std::move (param));
  808. expect (proc.state.getParameter (key) == paramPtr);
  809. }
  810. beginTest ("After adding a normal parameter that already exists, the AudioProcessor parameters are unchanged");
  811. {
  812. TestAudioProcessor proc;
  813. const auto key = "id";
  814. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  815. 0.0f, nullptr, nullptr));
  816. proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  817. 0.0f, nullptr, nullptr));
  818. expectEquals (proc.getParameters().size(), 1);
  819. expect (proc.getParameters().getFirst() == param);
  820. }
  821. beginTest ("After setting a parameter value, that value is reflected in the state");
  822. {
  823. TestAudioProcessor proc;
  824. const auto key = "id";
  825. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  826. 0.0f, nullptr, nullptr));
  827. const auto value = 0.5f;
  828. param->setValueNotifyingHost (value);
  829. expectEquals (*proc.state.getRawParameterValue (key), value);
  830. }
  831. beginTest ("After adding an APVTS::Parameter, its value is the default value");
  832. {
  833. TestAudioProcessor proc;
  834. const auto key = "id";
  835. const auto value = 5.0f;
  836. proc.state.createAndAddParameter (std::make_unique<Parameter> (
  837. key,
  838. String(),
  839. String(),
  840. NormalisableRange<float> (0.0f, 100.0f, 10.0f),
  841. value,
  842. nullptr,
  843. nullptr));
  844. expectEquals (*proc.state.getRawParameterValue (key), value);
  845. }
  846. beginTest ("Listeners receive notifications when parameters change");
  847. {
  848. Listener listener;
  849. TestAudioProcessor proc;
  850. const auto key = "id";
  851. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  852. 0.0f, nullptr, nullptr));
  853. proc.state.addParameterListener (key, &listener);
  854. const auto value = 0.5f;
  855. param->setValueNotifyingHost (value);
  856. expectEquals (listener.id, String { key });
  857. expectEquals (listener.value, value);
  858. }
  859. beginTest ("Bool parameters have a range of 0-1");
  860. {
  861. const auto key = "id";
  862. TestAudioProcessor proc (std::make_unique<AudioParameterBool> (key, "", false));
  863. expect (proc.state.getParameterRange (key) == NormalisableRange<float> (0.0f, 1.0f, 1.0f));
  864. }
  865. beginTest ("Float parameters retain their specified range");
  866. {
  867. const auto key = "id";
  868. const auto range = NormalisableRange<float> { -100, 100, 0.7f, 0.2f, true };
  869. TestAudioProcessor proc (std::make_unique<AudioParameterFloat> (key, "", range, 0.0f));
  870. expect (proc.state.getParameterRange (key) == range);
  871. }
  872. beginTest ("Int parameters retain their specified range");
  873. {
  874. const auto key = "id";
  875. const auto min = -27;
  876. const auto max = 53;
  877. TestAudioProcessor proc (std::make_unique<AudioParameterInt> (key, "", min, max, 0));
  878. expect (proc.state.getParameterRange (key) == NormalisableRange<float> (float (min), float (max)));
  879. }
  880. beginTest ("Choice parameters retain their specified range");
  881. {
  882. const auto key = "id";
  883. const auto choices = StringArray { "", "", "" };
  884. TestAudioProcessor proc (std::make_unique<AudioParameterChoice> (key, "", choices, 0));
  885. expect (proc.state.getParameterRange (key) == NormalisableRange<float> (0.0f, (float) (choices.size() - 1)));
  886. expect (proc.state.getParameter (key)->getNumSteps() == choices.size());
  887. }
  888. beginTest ("When the parameter value is changed, normal parameter values are updated");
  889. {
  890. TestAudioProcessor proc;
  891. const auto key = "id";
  892. auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  893. 0.0f, nullptr, nullptr));
  894. proc.state.state = ValueTree { "state" };
  895. const auto newValue = 0.75f;
  896. auto value = proc.state.getParameterAsValue (key);
  897. value = newValue;
  898. expectEquals (param->getValue(), newValue);
  899. expectEquals (*proc.state.getRawParameterValue (key), newValue);
  900. }
  901. beginTest ("When the parameter value is changed, custom parameter values are updated");
  902. {
  903. const auto key = "id";
  904. const auto choices = StringArray ("foo", "bar", "baz");
  905. auto param = std::make_unique<AudioParameterChoice> (key, "", choices, 0);
  906. const auto paramPtr = param.get();
  907. TestAudioProcessor proc (std::move (param));
  908. const auto newValue = 2.0f;
  909. auto value = proc.state.getParameterAsValue (key);
  910. value = newValue;
  911. expectEquals (paramPtr->getCurrentChoiceName(), choices[int (newValue)]);
  912. expectEquals (*proc.state.getRawParameterValue (key), newValue);
  913. }
  914. beginTest ("When the parameter value is changed, listeners are notified");
  915. {
  916. Listener listener;
  917. TestAudioProcessor proc;
  918. const auto key = "id";
  919. proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  920. 0.0f, nullptr, nullptr));
  921. proc.state.addParameterListener (key, &listener);
  922. proc.state.state = ValueTree { "state" };
  923. const auto newValue = 0.75f;
  924. proc.state.getParameterAsValue (key) = newValue;
  925. expectEquals (listener.value, newValue);
  926. expectEquals (listener.id, String { key });
  927. }
  928. beginTest ("When the parameter value is changed, listeners are notified");
  929. {
  930. const auto key = "id";
  931. const auto choices = StringArray { "foo", "bar", "baz" };
  932. Listener listener;
  933. TestAudioProcessor proc (std::make_unique<AudioParameterChoice> (key, "", choices, 0));
  934. proc.state.addParameterListener (key, &listener);
  935. const auto newValue = 2.0f;
  936. proc.state.getParameterAsValue (key) = newValue;
  937. expectEquals (listener.value, newValue);
  938. expectEquals (listener.id, String (key));
  939. }
  940. }
  941. } audioProcessorValueTreeStateTests;
  942. #endif
  943. } // namespace juce