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.

556 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 category = 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. 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. /** A parameter class that maintains backwards compatibility with deprecated
  283. AudioProcessorValueTreeState functionality.
  284. Previous calls to
  285. @code
  286. createAndAddParameter (paramID1, paramName1, ...);
  287. @endcode
  288. can be replaced with
  289. @code
  290. using Parameter = AudioProcessorValueTreeState::Parameter;
  291. createAndAddParameter (std::make_unique<Parameter> (paramID1, paramName1, ...));
  292. @endcode
  293. However, a much better approach is to use the AudioProcessorValueTreeState
  294. constructor directly
  295. @code
  296. using Parameter = AudioProcessorValueTreeState::Parameter;
  297. YourAudioProcessor()
  298. : apvts (*this, &undoManager, "PARAMETERS", { std::make_unique<Parameter> (paramID1, paramName1, ...),
  299. std::make_unique<Parameter> (paramID2, paramName2, ...),
  300. ... })
  301. @endcode
  302. */
  303. class Parameter final : public AudioParameterFloat
  304. {
  305. public:
  306. Parameter (const String& parameterID,
  307. const String& parameterName,
  308. const String& labelText,
  309. NormalisableRange<float> valueRange,
  310. float defaultValue,
  311. std::function<String(float)> valueToTextFunction,
  312. std::function<float(const String&)> textToValueFunction,
  313. bool isMetaParameter = false,
  314. bool isAutomatableParameter = true,
  315. bool isDiscrete = false,
  316. AudioProcessorParameter::Category category = AudioProcessorParameter::genericParameter,
  317. bool isBoolean = false);
  318. float getDefaultValue() const override;
  319. int getNumSteps() const override;
  320. bool isMetaParameter() const override;
  321. bool isAutomatable() const override;
  322. bool isDiscrete() const override;
  323. bool isBoolean() const override;
  324. private:
  325. const float unsnappedDefault;
  326. const bool metaParameter, automatable, discrete, boolean;
  327. };
  328. //==============================================================================
  329. /** An object of this class maintains a connection between a Slider and a parameter
  330. in an AudioProcessorValueTreeState.
  331. During the lifetime of this SliderAttachment object, it keeps the two things in
  332. sync, making it easy to connect a slider to a parameter. When this object is
  333. deleted, the connection is broken. Make sure that your AudioProcessorValueTreeState
  334. and Slider aren't deleted before this object!
  335. */
  336. class JUCE_API SliderAttachment
  337. {
  338. public:
  339. SliderAttachment (AudioProcessorValueTreeState& stateToControl,
  340. const String& parameterID,
  341. Slider& sliderToControl);
  342. ~SliderAttachment();
  343. private:
  344. struct Pimpl;
  345. std::unique_ptr<Pimpl> pimpl;
  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& stateToControl,
  364. const String& parameterID,
  365. ComboBox& comboBoxToControl);
  366. ~ComboBoxAttachment();
  367. private:
  368. struct Pimpl;
  369. std::unique_ptr<Pimpl> pimpl;
  370. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComboBoxAttachment)
  371. };
  372. //==============================================================================
  373. /** An object of this class maintains a connection between a Button and a parameter
  374. in an AudioProcessorValueTreeState.
  375. During the lifetime of this ButtonAttachment object, it keeps the two things in
  376. sync, making it easy to connect a button to a parameter. When this object is
  377. deleted, the connection is broken. Make sure that your AudioProcessorValueTreeState
  378. and Button aren't deleted before this object!
  379. */
  380. class JUCE_API ButtonAttachment
  381. {
  382. public:
  383. ButtonAttachment (AudioProcessorValueTreeState& stateToControl,
  384. const String& parameterID,
  385. Button& buttonToControl);
  386. ~ButtonAttachment();
  387. private:
  388. struct Pimpl;
  389. std::unique_ptr<Pimpl> pimpl;
  390. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonAttachment)
  391. };
  392. private:
  393. //==============================================================================
  394. /** This method was introduced to allow you to use AudioProcessorValueTreeState parameters in
  395. an AudioProcessorParameterGroup, but there is now a much nicer way to achieve this.
  396. Code that looks like this
  397. @code
  398. auto paramA = apvts.createParameter ("a", "Parameter A", {}, { -100, 100 }, ...);
  399. auto paramB = apvts.createParameter ("b", "Parameter B", {}, { 0, 5 }, ...);
  400. addParameterGroup (std::make_unique<AudioProcessorParameterGroup> ("g1", "Group 1", " | ", std::move (paramA), std::move (paramB)));
  401. apvts.state = ValueTree (Identifier ("PARAMETERS"));
  402. @endcode
  403. can instead create the APVTS like this, avoiding the two-step initialization process and leveraging one of JUCE's
  404. pre-built parameter types (or your own custom type derived from RangedAudioParameter)
  405. @code
  406. using Parameter = AudioProcessorValueTreeState::Parameter;
  407. YourAudioProcessor()
  408. : apvts (*this, &undoManager, "PARAMETERS",
  409. { std::make_unique<AudioProcessorParameterGroup> ("g1", "Group 1", " | ",
  410. std::make_unique<Parameter> ("a", "Parameter A", "", NormalisableRange<float> (-100, 100), ...),
  411. std::make_unique<Parameter> ("b", "Parameter B", "", NormalisableRange<float> (0, 5), ...)) })
  412. @endcode
  413. */
  414. JUCE_DEPRECATED (std::unique_ptr<RangedAudioParameter> createParameter (const String&, const String&, const String&, NormalisableRange<float>,
  415. float, std::function<String(float)>, std::function<float(const String&)>,
  416. bool, bool, bool, AudioProcessorParameter::Category, bool));
  417. //==============================================================================
  418. class ParameterAdapter;
  419. #if JUCE_UNIT_TESTS
  420. friend struct ParameterAdapterTests;
  421. #endif
  422. void addParameterAdapter (RangedAudioParameter&);
  423. ParameterAdapter* getParameterAdapter (StringRef) const;
  424. bool flushParameterValuesToValueTree();
  425. void setNewState (ValueTree);
  426. void timerCallback() override;
  427. void valueTreePropertyChanged (ValueTree&, const Identifier&) override;
  428. void valueTreeChildAdded (ValueTree&, ValueTree&) override;
  429. void valueTreeRedirected (ValueTree&) override;
  430. void updateParameterConnectionsToChildTrees();
  431. const Identifier valueType { "PARAM" }, valuePropertyID { "value" }, idPropertyID { "id" };
  432. struct StringRefLessThan final
  433. {
  434. bool operator() (StringRef a, StringRef b) const noexcept { return a.text.compare (b.text) < 0; }
  435. };
  436. std::map<StringRef, std::unique_ptr<ParameterAdapter>, StringRefLessThan> adapterTable;
  437. CriticalSection valueTreeChanging;
  438. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorValueTreeState)
  439. };
  440. } // namespace juce