Audio plugin host https://kx.studio/carla
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.

529 lines
24KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. #ifndef JUCE_VALUETREE_H_INCLUDED
  18. #define JUCE_VALUETREE_H_INCLUDED
  19. //==============================================================================
  20. /**
  21. A powerful tree structure that can be used to hold free-form data, and which can
  22. handle its own undo and redo behaviour.
  23. A ValueTree contains a list of named properties as var objects, and also holds
  24. any number of sub-trees.
  25. Create ValueTree objects on the stack, and don't be afraid to copy them around, as
  26. they're simply a lightweight reference to a shared data container. Creating a copy
  27. of another ValueTree simply creates a new reference to the same underlying object - to
  28. make a separate, deep copy of a tree you should explicitly call createCopy().
  29. Each ValueTree has a type name, in much the same way as an XmlElement has a tag name,
  30. and much of the structure of a ValueTree is similar to an XmlElement tree.
  31. You can convert a ValueTree to and from an XmlElement, and as long as the XML doesn't
  32. contain text elements, the conversion works well and makes a good serialisation
  33. format. They can also be serialised to a binary format, which is very fast and compact.
  34. All the methods that change data take an optional UndoManager, which will be used
  35. to track any changes to the object. For this to work, you have to be careful to
  36. consistently always use the same UndoManager for all operations to any node inside
  37. the tree.
  38. A ValueTree can only be a child of one parent at a time, so if you're moving one from
  39. one tree to another, be careful to always remove it first, before adding it. This
  40. could also mess up your undo/redo chain, so be wary! In a debug build you should hit
  41. assertions if you try to do anything dangerous, but there are still plenty of ways it
  42. could go wrong.
  43. Listeners can be added to a ValueTree to be told when properies change and when
  44. nodes are added or removed.
  45. @see var, XmlElement
  46. */
  47. class JUCE_API ValueTree
  48. {
  49. public:
  50. //==============================================================================
  51. /** Creates an empty, invalid ValueTree.
  52. A ValueTree that is created with this constructor can't actually be used for anything,
  53. it's just a default 'null' ValueTree that can be returned to indicate some sort of failure.
  54. To create a real one, use the constructor that takes a string.
  55. @see ValueTree::invalid
  56. */
  57. ValueTree() noexcept;
  58. /** Creates an empty ValueTree with the given type name.
  59. Like an XmlElement, each ValueTree node has a type, which you can access with
  60. getType() and hasType().
  61. */
  62. explicit ValueTree (Identifier type);
  63. /** Creates a reference to another ValueTree. */
  64. ValueTree (const ValueTree&);
  65. /** Makes this object reference another node. */
  66. ValueTree& operator= (const ValueTree&);
  67. #if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
  68. ValueTree (ValueTree&&) noexcept;
  69. #endif
  70. /** Destructor. */
  71. ~ValueTree();
  72. /** Returns true if both this and the other tree node refer to the same underlying structure.
  73. Note that this isn't a value comparison - two independently-created trees which
  74. contain identical data are not considered equal.
  75. */
  76. bool operator== (const ValueTree&) const noexcept;
  77. /** Returns true if this and the other node refer to different underlying structures.
  78. Note that this isn't a value comparison - two independently-created trees which
  79. contain identical data are not considered equal.
  80. */
  81. bool operator!= (const ValueTree&) const noexcept;
  82. /** Performs a deep comparison between the properties and children of two trees.
  83. If all the properties and children of the two trees are the same (recursively), this
  84. returns true.
  85. The normal operator==() only checks whether two trees refer to the same shared data
  86. structure, so use this method if you need to do a proper value comparison.
  87. */
  88. bool isEquivalentTo (const ValueTree&) const;
  89. //==============================================================================
  90. /** Returns true if this node refers to some valid data.
  91. It's hard to create an invalid node, but you might get one returned, e.g. by an out-of-range
  92. call to getChild().
  93. */
  94. bool isValid() const { return object != nullptr; }
  95. /** Returns a deep copy of this tree and all its sub-nodes. */
  96. ValueTree createCopy() const;
  97. //==============================================================================
  98. /** Returns the type of this node.
  99. The type is specified when the ValueTree is created.
  100. @see hasType
  101. */
  102. Identifier getType() const;
  103. /** Returns true if the node has this type.
  104. The comparison is case-sensitive.
  105. */
  106. bool hasType (const Identifier typeName) const;
  107. //==============================================================================
  108. /** Returns the value of a named property.
  109. If no such property has been set, this will return a void variant.
  110. You can also use operator[] to get a property.
  111. @see var, setProperty, hasProperty
  112. */
  113. const var& getProperty (const Identifier name) const;
  114. /** Returns the value of a named property, or a user-specified default if the property doesn't exist.
  115. If no such property has been set, this will return the value of defaultReturnValue.
  116. You can also use operator[] and getProperty to get a property.
  117. @see var, getProperty, setProperty, hasProperty
  118. */
  119. var getProperty (const Identifier name, const var& defaultReturnValue) const;
  120. /** Returns the value of a named property.
  121. If no such property has been set, this will return a void variant. This is the same as
  122. calling getProperty().
  123. @see getProperty
  124. */
  125. const var& operator[] (const Identifier name) const;
  126. /** Changes a named property of the node.
  127. The name identifier must not be an empty string.
  128. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  129. so that this change can be undone.
  130. @see var, getProperty, removeProperty
  131. @returns a reference to the value tree, so that you can daisy-chain calls to this method.
  132. */
  133. ValueTree& setProperty (const Identifier name, const var& newValue, UndoManager* undoManager);
  134. /** Returns true if the node contains a named property. */
  135. bool hasProperty (const Identifier name) const;
  136. /** Removes a property from the node.
  137. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  138. so that this change can be undone.
  139. */
  140. void removeProperty (const Identifier name, UndoManager* undoManager);
  141. /** Removes all properties from the node.
  142. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  143. so that this change can be undone.
  144. */
  145. void removeAllProperties (UndoManager* undoManager);
  146. /** Returns the total number of properties that the node contains.
  147. @see getProperty.
  148. */
  149. int getNumProperties() const;
  150. /** Returns the identifier of the property with a given index.
  151. @see getNumProperties
  152. */
  153. Identifier getPropertyName (int index) const;
  154. /** Returns a Value object that can be used to control and respond to one of the tree's properties.
  155. The Value object will maintain a reference to this tree, and will use the undo manager when
  156. it needs to change the value. Attaching a Value::Listener to the value object will provide
  157. callbacks whenever the property changes.
  158. */
  159. Value getPropertyAsValue (const Identifier name, UndoManager* undoManager);
  160. /** Overwrites all the properties in this tree with the properties of the source tree.
  161. Any properties that already exist will be updated; and new ones will be added, and
  162. any that are not present in the source tree will be removed.
  163. */
  164. void copyPropertiesFrom (const ValueTree& source, UndoManager* undoManager);
  165. //==============================================================================
  166. /** Returns the number of child nodes belonging to this one.
  167. @see getChild
  168. */
  169. int getNumChildren() const;
  170. /** Returns one of this node's child nodes.
  171. If the index is out of range, it'll return an invalid node. (See isValid() to find out
  172. whether a node is valid).
  173. */
  174. ValueTree getChild (int index) const;
  175. /** Returns the first child node with the speficied type name.
  176. If no such node is found, it'll return an invalid node. (See isValid() to find out
  177. whether a node is valid).
  178. @see getOrCreateChildWithName
  179. */
  180. ValueTree getChildWithName (const Identifier type) const;
  181. /** Returns the first child node with the speficied type name, creating and adding
  182. a child with this name if there wasn't already one there.
  183. The only time this will return an invalid object is when the object that you're calling
  184. the method on is itself invalid.
  185. @see getChildWithName
  186. */
  187. ValueTree getOrCreateChildWithName (const Identifier type, UndoManager* undoManager);
  188. /** Looks for the first child node that has the speficied property value.
  189. This will scan the child nodes in order, until it finds one that has property that matches
  190. the specified value.
  191. If no such node is found, it'll return an invalid node. (See isValid() to find out
  192. whether a node is valid).
  193. */
  194. ValueTree getChildWithProperty (const Identifier propertyName, const var& propertyValue) const;
  195. /** Adds a child to this node.
  196. Make sure that the child is removed from any former parent node before calling this, or
  197. you'll hit an assertion.
  198. If the index is < 0 or greater than the current number of child nodes, the new node will
  199. be added at the end of the list.
  200. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  201. so that this change can be undone.
  202. */
  203. void addChild (const ValueTree& child, int index, UndoManager* undoManager);
  204. /** Removes the specified child from this node's child-list.
  205. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  206. so that this change can be undone.
  207. */
  208. void removeChild (const ValueTree& child, UndoManager* undoManager);
  209. /** Removes a child from this node's child-list.
  210. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  211. so that this change can be undone.
  212. */
  213. void removeChild (int childIndex, UndoManager* undoManager);
  214. /** Removes all child-nodes from this node.
  215. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  216. so that this change can be undone.
  217. */
  218. void removeAllChildren (UndoManager* undoManager);
  219. /** Moves one of the children to a different index.
  220. This will move the child to a specified index, shuffling along any intervening
  221. items as required. So for example, if you have a list of { 0, 1, 2, 3, 4, 5 }, then
  222. calling move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  223. @param currentIndex the index of the item to be moved. If this isn't a
  224. valid index, then nothing will be done
  225. @param newIndex the index at which you'd like this item to end up. If this
  226. is less than zero, the value will be moved to the end
  227. of the list
  228. @param undoManager the optional UndoManager to use to store this transaction
  229. */
  230. void moveChild (int currentIndex, int newIndex, UndoManager* undoManager);
  231. /** Returns true if this node is anywhere below the specified parent node.
  232. This returns true if the node is a child-of-a-child, as well as a direct child.
  233. */
  234. bool isAChildOf (const ValueTree& possibleParent) const;
  235. /** Returns the index of a child item in this parent.
  236. If the child isn't found, this returns -1.
  237. */
  238. int indexOf (const ValueTree& child) const;
  239. /** Returns the parent node that contains this one.
  240. If the node has no parent, this will return an invalid node. (See isValid() to find out
  241. whether a node is valid).
  242. */
  243. ValueTree getParent() const;
  244. /** Returns one of this node's siblings in its parent's child list.
  245. The delta specifies how far to move through the list, so a value of 1 would return the node
  246. that follows this one, -1 would return the node before it, 0 will return this node itself, etc.
  247. If the requested position is beyond the range of available nodes, this will return ValueTree::invalid.
  248. */
  249. ValueTree getSibling (int delta) const;
  250. //==============================================================================
  251. /** Creates an XmlElement that holds a complete image of this node and all its children.
  252. If this node is invalid, this may return nullptr. Otherwise, the XML that is produced can
  253. be used to recreate a similar node by calling fromXml()
  254. @see fromXml
  255. */
  256. XmlElement* createXml() const;
  257. /** Tries to recreate a node from its XML representation.
  258. This isn't designed to cope with random XML data - for a sensible result, it should only
  259. be fed XML that was created by the createXml() method.
  260. */
  261. static ValueTree fromXml (const XmlElement& xml);
  262. /** This returns a string containing an XML representation of the tree.
  263. This is quite handy for debugging purposes, as it provides a quick way to view a tree.
  264. */
  265. String toXmlString() const;
  266. //==============================================================================
  267. /** Stores this tree (and all its children) in a binary format.
  268. Once written, the data can be read back with readFromStream().
  269. It's much faster to load/save your tree in binary form than as XML, but
  270. obviously isn't human-readable.
  271. */
  272. void writeToStream (OutputStream& output) const;
  273. /** Reloads a tree from a stream that was written with writeToStream(). */
  274. static ValueTree readFromStream (InputStream& input);
  275. /** Reloads a tree from a data block that was written with writeToStream(). */
  276. static ValueTree readFromData (const void* data, size_t numBytes);
  277. /** Reloads a tree from a data block that was written with writeToStream() and
  278. then zipped using GZIPCompressorOutputStream.
  279. */
  280. static ValueTree readFromGZIPData (const void* data, size_t numBytes);
  281. //==============================================================================
  282. /** Listener class for events that happen to a ValueTree.
  283. To get events from a ValueTree, make your class implement this interface, and use
  284. ValueTree::addListener() and ValueTree::removeListener() to register it.
  285. */
  286. class JUCE_API Listener
  287. {
  288. public:
  289. /** Destructor. */
  290. virtual ~Listener() {}
  291. /** This method is called when a property of this node (or of one of its sub-nodes) has
  292. changed.
  293. The tree parameter indicates which tree has had its property changed, and the property
  294. parameter indicates the property.
  295. Note that when you register a listener to a tree, it will receive this callback for
  296. property changes in that tree, and also for any of its children, (recursively, at any depth).
  297. If your tree has sub-trees but you only want to know about changes to the top level tree,
  298. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  299. */
  300. virtual void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged,
  301. const Identifier& property) = 0;
  302. /** This method is called when a child sub-tree is added.
  303. Note that when you register a listener to a tree, it will receive this callback for
  304. child changes in both that tree and any of its children, (recursively, at any depth).
  305. If your tree has sub-trees but you only want to know about changes to the top level tree,
  306. just check the parentTree parameter to make sure it's the one that you're interested in.
  307. */
  308. virtual void valueTreeChildAdded (ValueTree& parentTree,
  309. ValueTree& childWhichHasBeenAdded) = 0;
  310. /** This method is called when a child sub-tree is removed.
  311. Note that when you register a listener to a tree, it will receive this callback for
  312. child changes in both that tree and any of its children, (recursively, at any depth).
  313. If your tree has sub-trees but you only want to know about changes to the top level tree,
  314. just check the parentTree parameter to make sure it's the one that you're interested in.
  315. */
  316. virtual void valueTreeChildRemoved (ValueTree& parentTree,
  317. ValueTree& childWhichHasBeenRemoved) = 0;
  318. /** This method is called when a tree's children have been re-shuffled.
  319. Note that when you register a listener to a tree, it will receive this callback for
  320. child changes in both that tree and any of its children, (recursively, at any depth).
  321. If your tree has sub-trees but you only want to know about changes to the top level tree,
  322. just check the parameter to make sure it's the tree that you're interested in.
  323. */
  324. virtual void valueTreeChildOrderChanged (ValueTree& parentTreeWhoseChildrenHaveMoved) = 0;
  325. /** This method is called when a tree has been added or removed from a parent node.
  326. This callback happens when the tree to which the listener was registered is added or
  327. removed from a parent. Unlike the other callbacks, it applies only to the tree to which
  328. the listener is registered, and not to any of its children.
  329. */
  330. virtual void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged) = 0;
  331. /** This method is called when a tree is made to point to a different internal shared object.
  332. When operator= is used to make a ValueTree refer to a different object, this callback
  333. will be made.
  334. */
  335. virtual void valueTreeRedirected (ValueTree& treeWhichHasBeenChanged);
  336. };
  337. /** Adds a listener to receive callbacks when this node is changed.
  338. The listener is added to this specific ValueTree object, and not to the shared
  339. object that it refers to. When this object is deleted, all the listeners will
  340. be lost, even if other references to the same ValueTree still exist. And if you
  341. use the operator= to make this refer to a different ValueTree, any listeners will
  342. begin listening to changes to the new tree instead of the old one.
  343. When you're adding a listener, make sure that you add it to a ValueTree instance that
  344. will last for as long as you need the listener. In general, you'd never want to add a
  345. listener to a local stack-based ValueTree, and would usually add one to a member variable.
  346. @see removeListener
  347. */
  348. void addListener (Listener* listener);
  349. /** Removes a listener that was previously added with addListener(). */
  350. void removeListener (Listener* listener);
  351. /** Causes a property-change callback to be triggered for the specified property,
  352. calling any listeners that are registered.
  353. */
  354. void sendPropertyChangeMessage (const Identifier property);
  355. //==============================================================================
  356. /** This method uses a comparator object to sort the tree's children into order.
  357. The object provided must have a method of the form:
  358. @code
  359. int compareElements (const ValueTree& first, const ValueTree& second);
  360. @endcode
  361. ..and this method must return:
  362. - a value of < 0 if the first comes before the second
  363. - a value of 0 if the two objects are equivalent
  364. - a value of > 0 if the second comes before the first
  365. To improve performance, the compareElements() method can be declared as static or const.
  366. @param comparator the comparator to use for comparing elements.
  367. @param undoManager optional UndoManager for storing the changes
  368. @param retainOrderOfEquivalentItems if this is true, then items which the comparator says are
  369. equivalent will be kept in the order in which they currently appear in the array.
  370. This is slower to perform, but may be important in some cases. If it's false, a
  371. faster algorithm is used, but equivalent elements may be rearranged.
  372. */
  373. template <typename ElementComparator>
  374. void sort (ElementComparator& comparator, UndoManager* undoManager, bool retainOrderOfEquivalentItems)
  375. {
  376. if (object != nullptr)
  377. {
  378. OwnedArray<ValueTree> sortedList;
  379. createListOfChildren (sortedList);
  380. ComparatorAdapter <ElementComparator> adapter (comparator);
  381. sortedList.sort (adapter, retainOrderOfEquivalentItems);
  382. reorderChildren (sortedList, undoManager);
  383. }
  384. }
  385. /** An invalid ValueTree that can be used if you need to return one as an error condition, etc.
  386. This invalid object is equivalent to ValueTree created with its default constructor.
  387. */
  388. static const ValueTree invalid;
  389. /** Returns the total number of references to the shared underlying data structure that this
  390. ValueTree is using.
  391. */
  392. int getReferenceCount() const noexcept;
  393. private:
  394. //==============================================================================
  395. JUCE_PUBLIC_IN_DLL_BUILD (class SharedObject)
  396. friend class SharedObject;
  397. ReferenceCountedObjectPtr<SharedObject> object;
  398. ListenerList<Listener> listeners;
  399. template <typename ElementComparator>
  400. struct ComparatorAdapter
  401. {
  402. ComparatorAdapter (ElementComparator& comp) noexcept : comparator (comp) {}
  403. int compareElements (const ValueTree* const first, const ValueTree* const second)
  404. {
  405. return comparator.compareElements (*first, *second);
  406. }
  407. private:
  408. ElementComparator& comparator;
  409. JUCE_DECLARE_NON_COPYABLE (ComparatorAdapter)
  410. };
  411. void createListOfChildren (OwnedArray<ValueTree>&) const;
  412. void reorderChildren (const OwnedArray<ValueTree>&, UndoManager*);
  413. explicit ValueTree (SharedObject*);
  414. };
  415. #endif // JUCE_VALUETREE_H_INCLUDED