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.

552 lines
25KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 6 technical preview.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For this technical preview, this file is not subject to commercial licensing.
  8. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  9. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  10. DISCLAIMED.
  11. ==============================================================================
  12. */
  13. namespace juce
  14. {
  15. /**
  16. This class contains a ValueTree that is used to manage an AudioProcessor's entire state.
  17. It has its own internal class of parameter object that is linked to values
  18. within its ValueTree, and which are each identified by a string ID.
  19. You can get access to the underlying ValueTree object via the state member variable,
  20. so you can add extra properties to it as necessary.
  21. It also provides some utility child classes for connecting parameters directly to
  22. GUI controls like sliders.
  23. The favoured constructor of this class takes a collection of RangedAudioParameters or
  24. AudioProcessorParameterGroups of RangedAudioParameters and adds them to the attached
  25. AudioProcessor directly.
  26. The deprecated way of using this class is as follows:
  27. 1) Create an AudioProcessorValueTreeState, and give it some parameters using createAndAddParameter().
  28. 2) Initialise the state member variable with a type name.
  29. The deprecated constructor will be removed from the API in a future version of JUCE!
  30. @tags{Audio}
  31. */
  32. class JUCE_API AudioProcessorValueTreeState : private Timer,
  33. private ValueTree::Listener
  34. {
  35. public:
  36. //==============================================================================
  37. /** A class to contain a set of RangedAudioParameters and AudioProcessorParameterGroups
  38. containing RangedAudioParameters.
  39. This class is used in the AudioProcessorValueTreeState constructor to allow
  40. arbitrarily grouped RangedAudioParameters to be passed to an AudioProcessor.
  41. */
  42. class JUCE_API ParameterLayout final
  43. {
  44. private:
  45. //==============================================================================
  46. template <typename It>
  47. using ValidIfIterator = decltype (std::next (std::declval<It>()));
  48. public:
  49. //==============================================================================
  50. template <typename... Items>
  51. ParameterLayout (std::unique_ptr<Items>... items) { add (std::move (items)...); }
  52. template <typename It, typename = ValidIfIterator<It>>
  53. ParameterLayout (It begin, It end) { add (begin, end); }
  54. template <typename... Items>
  55. void add (std::unique_ptr<Items>... items)
  56. {
  57. parameters.reserve (parameters.size() + sizeof... (items));
  58. // We can replace this with some nicer code once generic lambdas become available. A
  59. // sequential context like an array initialiser is required to ensure we get the correct
  60. // order from the parameter pack.
  61. int unused[] { (parameters.emplace_back (MakeContents() (std::move (items))), 0)... };
  62. ignoreUnused (unused);
  63. }
  64. template <typename It, typename = ValidIfIterator<It>>
  65. void add (It begin, It end)
  66. {
  67. parameters.reserve (parameters.size() + std::size_t (std::distance (begin, end)));
  68. std::transform (std::make_move_iterator (begin),
  69. std::make_move_iterator (end),
  70. std::back_inserter (parameters),
  71. MakeContents());
  72. }
  73. ParameterLayout (const ParameterLayout& other) = delete;
  74. ParameterLayout (ParameterLayout&& other) noexcept { swap (other); }
  75. ParameterLayout& operator= (const ParameterLayout& other) = delete;
  76. ParameterLayout& operator= (ParameterLayout&& other) noexcept { swap (other); return *this; }
  77. void swap (ParameterLayout& other) noexcept { std::swap (other.parameters, parameters); }
  78. private:
  79. //==============================================================================
  80. struct Visitor
  81. {
  82. virtual ~Visitor() = default;
  83. // If you have a compiler error telling you that there is no matching
  84. // member function to call for 'visit', then you are probably attempting
  85. // to add a parameter that is not derived from RangedAudioParameter to
  86. // the AudioProcessorValueTreeState.
  87. virtual void visit (std::unique_ptr<RangedAudioParameter>) const = 0;
  88. virtual void visit (std::unique_ptr<AudioProcessorParameterGroup>) const = 0;
  89. };
  90. struct ParameterStorageBase
  91. {
  92. virtual ~ParameterStorageBase() = default;
  93. virtual void accept (const Visitor& visitor) = 0;
  94. };
  95. template <typename Contents>
  96. struct ParameterStorage : ParameterStorageBase
  97. {
  98. explicit ParameterStorage (std::unique_ptr<Contents> input) : contents (std::move (input)) {}
  99. void accept (const Visitor& visitor) override { visitor.visit (std::move (contents)); }
  100. std::unique_ptr<Contents> contents;
  101. };
  102. struct MakeContents final
  103. {
  104. template <typename Item>
  105. std::unique_ptr<ParameterStorageBase> operator() (std::unique_ptr<Item> item) const
  106. {
  107. return std::unique_ptr<ParameterStorageBase> (new ParameterStorage<Item> (std::move (item)));
  108. }
  109. };
  110. void add() {}
  111. friend class AudioProcessorValueTreeState;
  112. std::vector<std::unique_ptr<ParameterStorageBase>> parameters;
  113. };
  114. //==============================================================================
  115. /** Creates a state object for a given processor, and sets up all the parameters
  116. that will control that processor.
  117. You should *not* assign a new ValueTree to the state, or call
  118. createAndAddParameter, after using this constructor.
  119. Note that each AudioProcessorValueTreeState should be attached to only one
  120. processor, and must have the same lifetime as the processor, as they will
  121. have dependencies on each other.
  122. The ParameterLayout parameter has a set of constructors that allow you to
  123. add multiple RangedAudioParameters and AudioProcessorParameterGroups containing
  124. RangedAudioParameters to the AudioProcessorValueTreeState inside this constructor.
  125. @code
  126. YourAudioProcessor()
  127. : apvts (*this, &undoManager, "PARAMETERS",
  128. { std::make_unique<AudioParameterFloat> ("a", "Parameter A", NormalisableRange<float> (-100.0f, 100.0f), 0),
  129. std::make_unique<AudioParameterInt> ("b", "Parameter B", 0, 5, 2) })
  130. @endcode
  131. To add parameters programatically you can call `add` repeatedly on a
  132. ParameterLayout instance:
  133. @code
  134. AudioProcessorValueTreeState::ParameterLayout createParameterLayout()
  135. {
  136. AudioProcessorValueTreeState::ParameterLayout layout;
  137. for (int i = 1; i < 9; ++i)
  138. layout.add (std::make_unique<AudioParameterInt> (String (i), String (i), 0, i, 0));
  139. return layout;
  140. }
  141. YourAudioProcessor()
  142. : apvts (*this, &undoManager, "PARAMETERS", createParameterLayout())
  143. {
  144. }
  145. @endcode
  146. @param processorToConnectTo The Processor that will be managed by this object
  147. @param undoManagerToUse An optional UndoManager to use; pass nullptr if no UndoManager is required
  148. @param valueTreeType The identifier used to initialise the internal ValueTree
  149. @param parameterLayout An object that holds all parameters and parameter groups that the
  150. AudioProcessor should use.
  151. */
  152. AudioProcessorValueTreeState (AudioProcessor& processorToConnectTo,
  153. UndoManager* undoManagerToUse,
  154. const Identifier& valueTreeType,
  155. ParameterLayout parameterLayout);
  156. /** This constructor is discouraged and will be deprecated in a future version of JUCE!
  157. Use the other constructor instead.
  158. Creates a state object for a given processor.
  159. The UndoManager is optional and can be a nullptr. After creating your state object,
  160. you should add parameters with the createAndAddParameter() method. Note that each
  161. AudioProcessorValueTreeState should be attached to only one processor, and must have
  162. the same lifetime as the processor, as they will have dependencies on each other.
  163. */
  164. AudioProcessorValueTreeState (AudioProcessor& processorToConnectTo, UndoManager* undoManagerToUse);
  165. /** Destructor. */
  166. ~AudioProcessorValueTreeState() override;
  167. //==============================================================================
  168. /** This function is deprecated and will be removed in a future version of JUCE!
  169. Previous calls to
  170. @code
  171. createAndAddParameter (paramID1, paramName1, ...);
  172. @endcode
  173. can be replaced with
  174. @code
  175. using Parameter = AudioProcessorValueTreeState::Parameter;
  176. createAndAddParameter (std::make_unique<Parameter> (paramID1, paramName1, ...));
  177. @endcode
  178. However, a much better approach is to use the AudioProcessorValueTreeState
  179. constructor directly
  180. @code
  181. using Parameter = AudioProcessorValueTreeState::Parameter;
  182. YourAudioProcessor()
  183. : apvts (*this, &undoManager, "PARAMETERS", { std::make_unique<Parameter> (paramID1, paramName1, ...),
  184. std::make_unique<Parameter> (paramID2, paramName2, ...),
  185. ... })
  186. @endcode
  187. @see AudioProcessorValueTreeState::AudioProcessorValueTreeState
  188. This function creates and returns a new parameter object for controlling a
  189. parameter with the given ID.
  190. Calling this will create and add a special type of AudioProcessorParameter to the
  191. AudioProcessor to which this state is attached.
  192. */
  193. JUCE_DEPRECATED (RangedAudioParameter* createAndAddParameter (const String& parameterID,
  194. const String& parameterName,
  195. const String& labelText,
  196. NormalisableRange<float> valueRange,
  197. float defaultValue,
  198. std::function<String(float)> valueToTextFunction,
  199. std::function<float(const String&)> textToValueFunction,
  200. bool isMetaParameter = false,
  201. bool isAutomatableParameter = true,
  202. bool isDiscrete = false,
  203. AudioProcessorParameter::Category parameterCategory = AudioProcessorParameter::genericParameter,
  204. bool isBoolean = false));
  205. /** This function adds a parameter to the attached AudioProcessor and that parameter will
  206. be managed by this AudioProcessorValueTreeState object.
  207. */
  208. RangedAudioParameter* createAndAddParameter (std::unique_ptr<RangedAudioParameter> parameter);
  209. //==============================================================================
  210. /** Returns a parameter by its ID string. */
  211. RangedAudioParameter* getParameter (StringRef parameterID) const noexcept;
  212. /** Returns a pointer to a floating point representation of a particular parameter which a realtime
  213. process can read to find out its current value.
  214. Note that calling this method from within AudioProcessorValueTreeState::Listener::parameterChanged()
  215. is not guaranteed to return an up-to-date value for the parameter.
  216. */
  217. std::atomic<float>* getRawParameterValue (StringRef parameterID) const noexcept;
  218. //==============================================================================
  219. /** A listener class that can be attached to an AudioProcessorValueTreeState.
  220. Use AudioProcessorValueTreeState::addParameterListener() to register a callback.
  221. */
  222. struct JUCE_API Listener
  223. {
  224. virtual ~Listener() = default;
  225. /** This callback method is called by the AudioProcessorValueTreeState when a parameter changes.
  226. Within this call, retrieving the value of the parameter that has changed via the getRawParameterValue()
  227. or getParameter() methods is not guaranteed to return the up-to-date value. If you need this you should
  228. instead use the newValue parameter.
  229. */
  230. virtual void parameterChanged (const String& parameterID, float newValue) = 0;
  231. };
  232. /** Attaches a callback to one of the parameters, which will be called when the parameter changes. */
  233. void addParameterListener (StringRef parameterID, Listener* listener);
  234. /** Removes a callback that was previously added with addParameterCallback(). */
  235. void removeParameterListener (StringRef parameterID, Listener* listener);
  236. //==============================================================================
  237. /** Returns a Value object that can be used to control a particular parameter. */
  238. Value getParameterAsValue (StringRef parameterID) const;
  239. /** Returns the range that was set when the given parameter was created. */
  240. NormalisableRange<float> getParameterRange (StringRef parameterID) const noexcept;
  241. //==============================================================================
  242. /** Returns a copy of the state value tree.
  243. The AudioProcessorValueTreeState's ValueTree is updated internally on the
  244. message thread, but there may be cases when you may want to access the state
  245. from a different thread (getStateInformation is a good example). This method
  246. flushes all pending audio parameter value updates and returns a copy of the
  247. state in a thread safe way.
  248. Note: This method uses locks to synchronise thread access, so whilst it is
  249. thread-safe, it is not realtime-safe. Do not call this method from within
  250. your audio processing code!
  251. */
  252. ValueTree copyState();
  253. /** Replaces the state value tree.
  254. The AudioProcessorValueTreeState's ValueTree is updated internally on the
  255. message thread, but there may be cases when you may want to modify the state
  256. from a different thread (setStateInformation is a good example). This method
  257. allows you to replace the state in a thread safe way.
  258. Note: This method uses locks to synchronise thread access, so whilst it is
  259. thread-safe, it is not realtime-safe. Do not call this method from within
  260. your audio processing code!
  261. */
  262. void replaceState (const ValueTree& newState);
  263. //==============================================================================
  264. /** A reference to the processor with which this state is associated. */
  265. AudioProcessor& processor;
  266. /** The state of the whole processor.
  267. This must be initialised after all calls to createAndAddParameter().
  268. You can replace this with your own ValueTree object, and can add properties and
  269. children to the tree. This class will automatically add children for each of the
  270. parameter objects that are created by createAndAddParameter().
  271. */
  272. ValueTree state;
  273. /** Provides access to the undo manager that this object is using. */
  274. UndoManager* const undoManager;
  275. private:
  276. //==============================================================================
  277. class ParameterAdapter;
  278. public:
  279. //==============================================================================
  280. /** A parameter class that maintains backwards compatibility with deprecated
  281. AudioProcessorValueTreeState functionality.
  282. Previous calls to
  283. @code
  284. createAndAddParameter (paramID1, paramName1, ...);
  285. @endcode
  286. can be replaced with
  287. @code
  288. using Parameter = AudioProcessorValueTreeState::Parameter;
  289. createAndAddParameter (std::make_unique<Parameter> (paramID1, paramName1, ...));
  290. @endcode
  291. However, a much better approach is to use the AudioProcessorValueTreeState
  292. constructor directly
  293. @code
  294. using Parameter = AudioProcessorValueTreeState::Parameter;
  295. YourAudioProcessor()
  296. : apvts (*this, &undoManager, "PARAMETERS", { std::make_unique<Parameter> (paramID1, paramName1, ...),
  297. std::make_unique<Parameter> (paramID2, paramName2, ...),
  298. ... })
  299. @endcode
  300. */
  301. class Parameter final : public AudioParameterFloat
  302. {
  303. public:
  304. Parameter (const String& parameterID,
  305. const String& parameterName,
  306. const String& labelText,
  307. NormalisableRange<float> valueRange,
  308. float defaultValue,
  309. std::function<String(float)> valueToTextFunction,
  310. std::function<float(const String&)> textToValueFunction,
  311. bool isMetaParameter = false,
  312. bool isAutomatableParameter = true,
  313. bool isDiscrete = false,
  314. AudioProcessorParameter::Category parameterCategory = AudioProcessorParameter::genericParameter,
  315. bool isBoolean = false);
  316. float getDefaultValue() const override;
  317. int getNumSteps() const override;
  318. bool isMetaParameter() const override;
  319. bool isAutomatable() const override;
  320. bool isDiscrete() const override;
  321. bool isBoolean() const override;
  322. private:
  323. void valueChanged (float) override;
  324. std::function<void()> onValueChanged;
  325. const float unsnappedDefault;
  326. const bool metaParameter, automatable, discrete, boolean;
  327. std::atomic<float> lastValue { -1.0f };
  328. friend class AudioProcessorValueTreeState::ParameterAdapter;
  329. };
  330. //==============================================================================
  331. /** An object of this class maintains a connection between a Slider and a parameter
  332. in an AudioProcessorValueTreeState.
  333. During the lifetime of this SliderAttachment object, it keeps the two things in
  334. sync, making it easy to connect a slider to a parameter. When this object is
  335. deleted, the connection is broken. Make sure that your AudioProcessorValueTreeState
  336. and Slider aren't deleted before this object!
  337. */
  338. class JUCE_API SliderAttachment
  339. {
  340. public:
  341. SliderAttachment (AudioProcessorValueTreeState& stateToUse,
  342. const String& parameterID,
  343. Slider& slider);
  344. private:
  345. std::unique_ptr<SliderParameterAttachment> attachment;
  346. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderAttachment)
  347. };
  348. //==============================================================================
  349. /** An object of this class maintains a connection between a ComboBox and a parameter
  350. in an AudioProcessorValueTreeState.
  351. Combobox items will be spaced linearly across the range of the parameter. For
  352. example if the range is specified by NormalisableRange<float> (-0.5f, 0.5f, 0.5f)
  353. and you add three items then the first will be mapped to a value of -0.5, the
  354. second to 0, and the third to 0.5.
  355. During the lifetime of this ComboBoxAttachment object, it keeps the two things in
  356. sync, making it easy to connect a combo box to a parameter. When this object is
  357. deleted, the connection is broken. Make sure that your AudioProcessorValueTreeState
  358. and ComboBox aren't deleted before this object!
  359. */
  360. class JUCE_API ComboBoxAttachment
  361. {
  362. public:
  363. ComboBoxAttachment (AudioProcessorValueTreeState& stateToUse,
  364. const String& parameterID,
  365. ComboBox& combo);
  366. private:
  367. std::unique_ptr<ComboBoxParameterAttachment> attachment;
  368. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComboBoxAttachment)
  369. };
  370. //==============================================================================
  371. /** An object of this class maintains a connection between a Button and a parameter
  372. in an AudioProcessorValueTreeState.
  373. During the lifetime of this ButtonAttachment object, it keeps the two things in
  374. sync, making it easy to connect a button to a parameter. When this object is
  375. deleted, the connection is broken. Make sure that your AudioProcessorValueTreeState
  376. and Button aren't deleted before this object!
  377. */
  378. class JUCE_API ButtonAttachment
  379. {
  380. public:
  381. ButtonAttachment (AudioProcessorValueTreeState& stateToUse,
  382. const String& parameterID,
  383. Button& button);
  384. private:
  385. std::unique_ptr<ButtonParameterAttachment> attachment;
  386. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonAttachment)
  387. };
  388. private:
  389. //==============================================================================
  390. /** This method was introduced to allow you to use AudioProcessorValueTreeState parameters in
  391. an AudioProcessorParameterGroup, but there is now a much nicer way to achieve this.
  392. Code that looks like this
  393. @code
  394. auto paramA = apvts.createParameter ("a", "Parameter A", {}, { -100, 100 }, ...);
  395. auto paramB = apvts.createParameter ("b", "Parameter B", {}, { 0, 5 }, ...);
  396. addParameterGroup (std::make_unique<AudioProcessorParameterGroup> ("g1", "Group 1", " | ", std::move (paramA), std::move (paramB)));
  397. apvts.state = ValueTree (Identifier ("PARAMETERS"));
  398. @endcode
  399. can instead create the APVTS like this, avoiding the two-step initialization process and leveraging one of JUCE's
  400. pre-built parameter types (or your own custom type derived from RangedAudioParameter)
  401. @code
  402. using Parameter = AudioProcessorValueTreeState::Parameter;
  403. YourAudioProcessor()
  404. : apvts (*this, &undoManager, "PARAMETERS",
  405. { std::make_unique<AudioProcessorParameterGroup> ("g1", "Group 1", " | ",
  406. std::make_unique<Parameter> ("a", "Parameter A", "", NormalisableRange<float> (-100, 100), ...),
  407. std::make_unique<Parameter> ("b", "Parameter B", "", NormalisableRange<float> (0, 5), ...)) })
  408. @endcode
  409. */
  410. JUCE_DEPRECATED (std::unique_ptr<RangedAudioParameter> createParameter (const String&, const String&, const String&, NormalisableRange<float>,
  411. float, std::function<String(float)>, std::function<float(const String&)>,
  412. bool, bool, bool, AudioProcessorParameter::Category, bool));
  413. //==============================================================================
  414. #if JUCE_UNIT_TESTS
  415. friend struct ParameterAdapterTests;
  416. #endif
  417. void addParameterAdapter (RangedAudioParameter&);
  418. ParameterAdapter* getParameterAdapter (StringRef) const;
  419. bool flushParameterValuesToValueTree();
  420. void setNewState (ValueTree);
  421. void timerCallback() override;
  422. void valueTreePropertyChanged (ValueTree&, const Identifier&) override;
  423. void valueTreeChildAdded (ValueTree&, ValueTree&) override;
  424. void valueTreeRedirected (ValueTree&) override;
  425. void updateParameterConnectionsToChildTrees();
  426. const Identifier valueType { "PARAM" }, valuePropertyID { "value" }, idPropertyID { "id" };
  427. struct StringRefLessThan final
  428. {
  429. bool operator() (StringRef a, StringRef b) const noexcept { return a.text.compare (b.text) < 0; }
  430. };
  431. std::map<StringRef, std::unique_ptr<ParameterAdapter>, StringRefLessThan> adapterTable;
  432. CriticalSection valueTreeChanging;
  433. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorValueTreeState)
  434. };
  435. } // namespace juce