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.

565 lines
25KB

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