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.

579 lines
26KB

  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. /**
  23. A powerful tree structure that can be used to hold free-form data, and which can
  24. handle its own undo and redo behaviour.
  25. A ValueTree contains a list of named properties as var objects, and also holds
  26. any number of sub-trees.
  27. Create ValueTree objects on the stack, and don't be afraid to copy them around, as
  28. they're simply a lightweight reference to a shared data container. Creating a copy
  29. of another ValueTree simply creates a new reference to the same underlying object - to
  30. make a separate, deep copy of a tree you should explicitly call createCopy().
  31. Each ValueTree has a type name, in much the same way as an XmlElement has a tag name,
  32. and much of the structure of a ValueTree is similar to an XmlElement tree.
  33. You can convert a ValueTree to and from an XmlElement, and as long as the XML doesn't
  34. contain text elements, the conversion works well and makes a good serialisation
  35. format. They can also be serialised to a binary format, which is very fast and compact.
  36. All the methods that change data take an optional UndoManager, which will be used
  37. to track any changes to the object. For this to work, you have to be careful to
  38. consistently always use the same UndoManager for all operations to any node inside
  39. the tree.
  40. A ValueTree can only be a child of one parent at a time, so if you're moving one from
  41. one tree to another, be careful to always remove it first, before adding it. This
  42. could also mess up your undo/redo chain, so be wary! In a debug build you should hit
  43. assertions if you try to do anything dangerous, but there are still plenty of ways it
  44. could go wrong.
  45. Note that although the children in a tree have a fixed order, the properties are not
  46. guaranteed to be stored in any particular order, so don't expect that a property's index
  47. will correspond to the order in which the property was added, or that it will remain
  48. constant when other properties are added or removed.
  49. Listeners can be added to a ValueTree to be told when properies change and when
  50. nodes are added or removed.
  51. @see var, XmlElement
  52. */
  53. class JUCE_API ValueTree
  54. {
  55. public:
  56. //==============================================================================
  57. /** Creates an empty, invalid ValueTree.
  58. A ValueTree that is created with this constructor can't actually be used for anything,
  59. it's just a default 'null' ValueTree that can be returned to indicate some sort of failure.
  60. To create a real one, use the constructor that takes a string.
  61. */
  62. ValueTree() noexcept;
  63. /** Creates an empty ValueTree with the given type name.
  64. Like an XmlElement, each ValueTree node has a type, which you can access with
  65. getType() and hasType().
  66. */
  67. explicit ValueTree (const Identifier& type);
  68. /** Creates a reference to another ValueTree. */
  69. ValueTree (const ValueTree&) noexcept;
  70. /** Makes this object reference another node. */
  71. ValueTree& operator= (const ValueTree&);
  72. /** Move constructor */
  73. ValueTree (ValueTree&&) noexcept;
  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. /** Recusrively finds the highest-level parent node that contains this one.
  257. If the node has no parent, this will return itself.
  258. */
  259. ValueTree getRoot() const noexcept;
  260. /** Returns one of this node's siblings in its parent's child list.
  261. The delta specifies how far to move through the list, so a value of 1 would return the node
  262. that follows this one, -1 would return the node before it, 0 will return this node itself, etc.
  263. If the requested position is beyond the range of available nodes, this will return an empty ValueTree().
  264. */
  265. ValueTree getSibling (int delta) const noexcept;
  266. //==============================================================================
  267. struct Iterator
  268. {
  269. Iterator (const ValueTree&, bool isEnd) noexcept;
  270. Iterator& operator++() noexcept;
  271. bool operator!= (const Iterator&) const noexcept;
  272. ValueTree operator*() const;
  273. private:
  274. void* internal;
  275. };
  276. /** Returns a start iterator for the children in this tree. */
  277. Iterator begin() const noexcept;
  278. /** Returns an end iterator for the children in this tree. */
  279. Iterator end() const noexcept;
  280. //==============================================================================
  281. /** Creates an XmlElement that holds a complete image of this node and all its children.
  282. If this node is invalid, this may return nullptr. Otherwise, the XML that is produced can
  283. be used to recreate a similar node by calling fromXml().
  284. The caller must delete the object that is returned.
  285. @see fromXml
  286. */
  287. XmlElement* createXml() const;
  288. /** Tries to recreate a node from its XML representation.
  289. This isn't designed to cope with random XML data - for a sensible result, it should only
  290. be fed XML that was created by the createXml() method.
  291. */
  292. static ValueTree fromXml (const XmlElement& xml);
  293. /** This returns a string containing an XML representation of the tree.
  294. This is quite handy for debugging purposes, as it provides a quick way to view a tree.
  295. */
  296. String toXmlString() const;
  297. //==============================================================================
  298. /** Stores this tree (and all its children) in a binary format.
  299. Once written, the data can be read back with readFromStream().
  300. It's much faster to load/save your tree in binary form than as XML, but
  301. obviously isn't human-readable.
  302. */
  303. void writeToStream (OutputStream& output) const;
  304. /** Reloads a tree from a stream that was written with writeToStream(). */
  305. static ValueTree readFromStream (InputStream& input);
  306. /** Reloads a tree from a data block that was written with writeToStream(). */
  307. static ValueTree readFromData (const void* data, size_t numBytes);
  308. /** Reloads a tree from a data block that was written with writeToStream() and
  309. then zipped using GZIPCompressorOutputStream.
  310. */
  311. static ValueTree readFromGZIPData (const void* data, size_t numBytes);
  312. //==============================================================================
  313. /** Listener class for events that happen to a ValueTree.
  314. To get events from a ValueTree, make your class implement this interface, and use
  315. ValueTree::addListener() and ValueTree::removeListener() to register it.
  316. */
  317. class JUCE_API Listener
  318. {
  319. public:
  320. /** Destructor. */
  321. virtual ~Listener() {}
  322. /** This method is called when a property of this node (or of one of its sub-nodes) has
  323. changed.
  324. The tree parameter indicates which tree has had its property changed, and the property
  325. parameter indicates the property.
  326. Note that when you register a listener to a tree, it will receive this callback for
  327. property changes in that tree, and also for any of its children, (recursively, at any depth).
  328. If your tree has sub-trees but you only want to know about changes to the top level tree,
  329. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  330. */
  331. virtual void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged,
  332. const Identifier& property) = 0;
  333. /** This method is called when a child sub-tree is added.
  334. Note that when you register a listener to a tree, it will receive this callback for
  335. child changes in both that tree and any of its children, (recursively, at any depth).
  336. If your tree has sub-trees but you only want to know about changes to the top level tree,
  337. just check the parentTree parameter to make sure it's the one that you're interested in.
  338. */
  339. virtual void valueTreeChildAdded (ValueTree& parentTree,
  340. ValueTree& childWhichHasBeenAdded) = 0;
  341. /** This method is called when a child sub-tree is removed.
  342. Note that when you register a listener to a tree, it will receive this callback for
  343. child changes in both that tree and any of its children, (recursively, at any depth).
  344. If your tree has sub-trees but you only want to know about changes to the top level tree,
  345. just check the parentTree parameter to make sure it's the one that you're interested in.
  346. */
  347. virtual void valueTreeChildRemoved (ValueTree& parentTree,
  348. ValueTree& childWhichHasBeenRemoved,
  349. int indexFromWhichChildWasRemoved) = 0;
  350. /** This method is called when a tree's children have been re-shuffled.
  351. Note that when you register a listener to a tree, it will receive this callback for
  352. child changes in both that tree and any of its children, (recursively, at any depth).
  353. If your tree has sub-trees but you only want to know about changes to the top level tree,
  354. just check the parameter to make sure it's the tree that you're interested in.
  355. */
  356. virtual void valueTreeChildOrderChanged (ValueTree& parentTreeWhoseChildrenHaveMoved,
  357. int oldIndex, int newIndex) = 0;
  358. /** This method is called when a tree has been added or removed from a parent node.
  359. This callback happens when the tree to which the listener was registered is added or
  360. removed from a parent. Unlike the other callbacks, it applies only to the tree to which
  361. the listener is registered, and not to any of its children.
  362. */
  363. virtual void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged) = 0;
  364. /** This method is called when a tree is made to point to a different internal shared object.
  365. When operator= is used to make a ValueTree refer to a different object, this callback
  366. will be made.
  367. */
  368. virtual void valueTreeRedirected (ValueTree& treeWhichHasBeenChanged);
  369. };
  370. /** Adds a listener to receive callbacks when this node is changed.
  371. The listener is added to this specific ValueTree object, and not to the shared
  372. object that it refers to. When this object is deleted, all the listeners will
  373. be lost, even if other references to the same ValueTree still exist. And if you
  374. use the operator= to make this refer to a different ValueTree, any listeners will
  375. begin listening to changes to the new tree instead of the old one.
  376. When you're adding a listener, make sure that you add it to a ValueTree instance that
  377. will last for as long as you need the listener. In general, you'd never want to add a
  378. listener to a local stack-based ValueTree, and would usually add one to a member variable.
  379. @see removeListener
  380. */
  381. void addListener (Listener* listener);
  382. /** Removes a listener that was previously added with addListener(). */
  383. void removeListener (Listener* listener);
  384. /** Changes a named property of the node, but will not notify a specified listener of the change.
  385. @see setProperty
  386. */
  387. ValueTree& setPropertyExcludingListener (Listener* listenerToExclude,
  388. const Identifier& name, const var& newValue,
  389. UndoManager* undoManager);
  390. /** Causes a property-change callback to be triggered for the specified property,
  391. calling any listeners that are registered.
  392. */
  393. void sendPropertyChangeMessage (const Identifier& property);
  394. //==============================================================================
  395. /** This method uses a comparator object to sort the tree's children into order.
  396. The object provided must have a method of the form:
  397. @code
  398. int compareElements (const ValueTree& first, const ValueTree& second);
  399. @endcode
  400. ..and this method must return:
  401. - a value of < 0 if the first comes before the second
  402. - a value of 0 if the two objects are equivalent
  403. - a value of > 0 if the second comes before the first
  404. To improve performance, the compareElements() method can be declared as static or const.
  405. @param comparator the comparator to use for comparing elements.
  406. @param undoManager optional UndoManager for storing the changes
  407. @param retainOrderOfEquivalentItems if this is true, then items which the comparator says are
  408. equivalent will be kept in the order in which they currently appear in the array.
  409. This is slower to perform, but may be important in some cases. If it's false, a
  410. faster algorithm is used, but equivalent elements may be rearranged.
  411. */
  412. template <typename ElementComparator>
  413. void sort (ElementComparator& comparator, UndoManager* undoManager, bool retainOrderOfEquivalentItems)
  414. {
  415. if (object != nullptr)
  416. {
  417. OwnedArray<ValueTree> sortedList;
  418. createListOfChildren (sortedList);
  419. ComparatorAdapter<ElementComparator> adapter (comparator);
  420. sortedList.sort (adapter, retainOrderOfEquivalentItems);
  421. reorderChildren (sortedList, undoManager);
  422. }
  423. }
  424. #if JUCE_ALLOW_STATIC_NULL_VARIABLES
  425. /** An invalid ValueTree that can be used if you need to return one as an error condition, etc.
  426. This invalid object is equivalent to ValueTree created with its default constructor, but
  427. you should always prefer to avoid it and use ValueTree() or {} instead.
  428. */
  429. static const ValueTree invalid;
  430. #endif
  431. /** Returns the total number of references to the shared underlying data structure that this
  432. ValueTree is using.
  433. */
  434. int getReferenceCount() const noexcept;
  435. private:
  436. //==============================================================================
  437. JUCE_PUBLIC_IN_DLL_BUILD (class SharedObject)
  438. friend class SharedObject;
  439. ReferenceCountedObjectPtr<SharedObject> object;
  440. ListenerList<Listener> listeners;
  441. template <typename ElementComparator>
  442. struct ComparatorAdapter
  443. {
  444. ComparatorAdapter (ElementComparator& comp) noexcept : comparator (comp) {}
  445. int compareElements (const ValueTree* const first, const ValueTree* const second)
  446. {
  447. return comparator.compareElements (*first, *second);
  448. }
  449. private:
  450. ElementComparator& comparator;
  451. JUCE_DECLARE_NON_COPYABLE (ComparatorAdapter)
  452. };
  453. void createListOfChildren (OwnedArray<ValueTree>&) const;
  454. void reorderChildren (const OwnedArray<ValueTree>&, UndoManager*);
  455. explicit ValueTree (SharedObject*) noexcept;
  456. };
  457. } // namespace juce