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.

570 lines
26KB

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