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.

512 lines
23KB

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