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
45KB

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