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.

551 lines
25KB

  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. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  132. so that this change can be undone.
  133. @see var, getProperty, removeProperty
  134. */
  135. void setProperty (const Identifier& name, const var& newValue, UndoManager* undoManager);
  136. /** Returns true if the node contains a named property. */
  137. bool hasProperty (const Identifier& name) const;
  138. /** Removes a property from the node.
  139. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  140. so that this change can be undone.
  141. */
  142. void removeProperty (const Identifier& name, UndoManager* undoManager);
  143. /** Removes all properties from the node.
  144. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  145. so that this change can be undone.
  146. */
  147. void removeAllProperties (UndoManager* undoManager);
  148. /** Returns the total number of properties that the node contains.
  149. @see getProperty.
  150. */
  151. int getNumProperties() const;
  152. /** Returns the identifier of the property with a given index.
  153. @see getNumProperties
  154. */
  155. Identifier getPropertyName (int index) const;
  156. /** Returns a Value object that can be used to control and respond to one of the tree's properties.
  157. The Value object will maintain a reference to this tree, and will use the undo manager when
  158. it needs to change the value. Attaching a Value::Listener to the value object will provide
  159. callbacks whenever the property changes.
  160. */
  161. Value getPropertyAsValue (const Identifier& name, UndoManager* undoManager) const;
  162. //==============================================================================
  163. /** Returns the number of child nodes belonging to this one.
  164. @see getChild
  165. */
  166. int getNumChildren() const;
  167. /** Returns one of this node's child nodes.
  168. If the index is out of range, it'll return an invalid node. (See isValid() to find out
  169. whether a node is valid).
  170. */
  171. ValueTree getChild (int index) const;
  172. /** Returns the first child node with the speficied type name.
  173. If no such node is found, it'll return an invalid node. (See isValid() to find out
  174. whether a node is valid).
  175. @see getOrCreateChildWithName
  176. */
  177. ValueTree getChildWithName (const Identifier& type) const;
  178. /** Returns the first child node with the speficied type name, creating and adding
  179. a child with this name if there wasn't already one there.
  180. The only time this will return an invalid object is when the object that you're calling
  181. the method on is itself invalid.
  182. @see getChildWithName
  183. */
  184. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  185. /** Looks for the first child node that has the speficied property value.
  186. This will scan the child nodes in order, until it finds one that has property that matches
  187. the specified value.
  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. */
  191. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  192. /** Adds a child to this node.
  193. Make sure that the child is removed from any former parent node before calling this, or
  194. you'll hit an assertion.
  195. If the index is < 0 or greater than the current number of child nodes, the new node will
  196. be added at the end of the list.
  197. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  198. so that this change can be undone.
  199. */
  200. void addChild (const ValueTree& child, int index, UndoManager* undoManager);
  201. /** Removes the specified child from this node's child-list.
  202. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  203. so that this change can be undone.
  204. */
  205. void removeChild (const ValueTree& child, UndoManager* undoManager);
  206. /** Removes a child from this node's child-list.
  207. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  208. so that this change can be undone.
  209. */
  210. void removeChild (int childIndex, UndoManager* undoManager);
  211. /** Removes all child-nodes from this node.
  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 removeAllChildren (UndoManager* undoManager);
  216. /** Moves one of the children to a different index.
  217. This will move the child to a specified index, shuffling along any intervening
  218. items as required. So for example, if you have a list of { 0, 1, 2, 3, 4, 5 }, then
  219. calling move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  220. @param currentIndex the index of the item to be moved. If this isn't a
  221. valid index, then nothing will be done
  222. @param newIndex the index at which you'd like this item to end up. If this
  223. is less than zero, the value will be moved to the end
  224. of the list
  225. @param undoManager the optional UndoManager to use to store this transaction
  226. */
  227. void moveChild (int currentIndex, int newIndex, UndoManager* undoManager);
  228. /** Returns true if this node is anywhere below the specified parent node.
  229. This returns true if the node is a child-of-a-child, as well as a direct child.
  230. */
  231. bool isAChildOf (const ValueTree& possibleParent) const;
  232. /** Returns the index of a child item in this parent.
  233. If the child isn't found, this returns -1.
  234. */
  235. int indexOf (const ValueTree& child) const;
  236. /** Returns the parent node that contains this one.
  237. If the node has no parent, this will return an invalid node. (See isValid() to find out
  238. whether a node is valid).
  239. */
  240. ValueTree getParent() const;
  241. /** Returns one of this node's siblings in its parent's child list.
  242. The delta specifies how far to move through the list, so a value of 1 would return the node
  243. that follows this one, -1 would return the node before it, 0 will return this node itself, etc.
  244. If the requested position is beyond the range of available nodes, this will return ValueTree::invalid.
  245. */
  246. ValueTree getSibling (int delta) const;
  247. //==============================================================================
  248. /** Creates an XmlElement that holds a complete image of this node and all its children.
  249. If this node is invalid, this may return 0. Otherwise, the XML that is produced can
  250. be used to recreate a similar node by calling fromXml()
  251. @see fromXml
  252. */
  253. XmlElement* createXml() const;
  254. /** Tries to recreate a node from its XML representation.
  255. This isn't designed to cope with random XML data - for a sensible result, it should only
  256. be fed XML that was created by the createXml() method.
  257. */
  258. static ValueTree fromXml (const XmlElement& xml);
  259. //==============================================================================
  260. /** Stores this tree (and all its children) in a binary format.
  261. Once written, the data can be read back with readFromStream().
  262. It's much faster to load/save your tree in binary form than as XML, but
  263. obviously isn't human-readable.
  264. */
  265. void writeToStream (OutputStream& output);
  266. /** Reloads a tree from a stream that was written with writeToStream(). */
  267. static ValueTree readFromStream (InputStream& input);
  268. /** Reloads a tree from a data block that was written with writeToStream(). */
  269. static ValueTree readFromData (const void* data, size_t numBytes);
  270. //==============================================================================
  271. /** Listener class for events that happen to a ValueTree.
  272. To get events from a ValueTree, make your class implement this interface, and use
  273. ValueTree::addListener() and ValueTree::removeListener() to register it.
  274. */
  275. class JUCE_API Listener
  276. {
  277. public:
  278. /** Destructor. */
  279. virtual ~Listener() {}
  280. /** This method is called when a property of this node (or of one of its sub-nodes) has
  281. changed.
  282. The tree parameter indicates which tree has had its property changed, and the property
  283. parameter indicates the property.
  284. Note that when you register a listener to a tree, it will receive this callback for
  285. property changes in that tree, and also for any of its children, (recursively, at any depth).
  286. If your tree has sub-trees but you only want to know about changes to the top level tree,
  287. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  288. */
  289. virtual void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged,
  290. const Identifier& property) = 0;
  291. /** This method is called when a child sub-tree is added.
  292. Note that when you register a listener to a tree, it will receive this callback for
  293. child changes in both that tree and any of its children, (recursively, at any depth).
  294. If your tree has sub-trees but you only want to know about changes to the top level tree,
  295. just check the parentTree parameter to make sure it's the one that you're interested in.
  296. */
  297. virtual void valueTreeChildAdded (ValueTree& parentTree,
  298. ValueTree& childWhichHasBeenAdded) = 0;
  299. /** This method is called when a child sub-tree is removed.
  300. Note that when you register a listener to a tree, it will receive this callback for
  301. child changes in both that tree and any of its children, (recursively, at any depth).
  302. If your tree has sub-trees but you only want to know about changes to the top level tree,
  303. just check the parentTree parameter to make sure it's the one that you're interested in.
  304. */
  305. virtual void valueTreeChildRemoved (ValueTree& parentTree,
  306. ValueTree& childWhichHasBeenRemoved) = 0;
  307. /** This method is called when a tree's children have been re-shuffled.
  308. Note that when you register a listener to a tree, it will receive this callback for
  309. child changes in both that tree and any of its children, (recursively, at any depth).
  310. If your tree has sub-trees but you only want to know about changes to the top level tree,
  311. just check the parameter to make sure it's the tree that you're interested in.
  312. */
  313. virtual void valueTreeChildOrderChanged (ValueTree& parentTreeWhoseChildrenHaveMoved) = 0;
  314. /** This method is called when a tree has been added or removed from a parent node.
  315. This callback happens when the tree to which the listener was registered is added or
  316. removed from a parent. Unlike the other callbacks, it applies only to the tree to which
  317. the listener is registered, and not to any of its children.
  318. */
  319. virtual void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged) = 0;
  320. };
  321. /** Adds a listener to receive callbacks when this node is changed.
  322. The listener is added to this specific ValueTree object, and not to the shared
  323. object that it refers to. When this object is deleted, all the listeners will
  324. be lost, even if other references to the same ValueTree still exist. And if you
  325. use the operator= to make this refer to a different ValueTree, any listeners will
  326. begin listening to changes to the new tree instead of the old one.
  327. When you're adding a listener, make sure that you add it to a ValueTree instance that
  328. will last for as long as you need the listener. In general, you'd never want to add a
  329. listener to a local stack-based ValueTree, and would usually add one to a member variable.
  330. @see removeListener
  331. */
  332. void addListener (Listener* listener);
  333. /** Removes a listener that was previously added with addListener(). */
  334. void removeListener (Listener* listener);
  335. //==============================================================================
  336. /** This method uses a comparator object to sort the tree's children into order.
  337. The object provided must have a method of the form:
  338. @code
  339. int compareElements (const ValueTree& first, const ValueTree& second);
  340. @endcode
  341. ..and this method must return:
  342. - a value of < 0 if the first comes before the second
  343. - a value of 0 if the two objects are equivalent
  344. - a value of > 0 if the second comes before the first
  345. To improve performance, the compareElements() method can be declared as static or const.
  346. @param comparator the comparator to use for comparing elements.
  347. @param undoManager optional UndoManager for storing the changes
  348. @param retainOrderOfEquivalentItems if this is true, then items which the comparator says are
  349. equivalent will be kept in the order in which they currently appear in the array.
  350. This is slower to perform, but may be important in some cases. If it's false, a
  351. faster algorithm is used, but equivalent elements may be rearranged.
  352. */
  353. template <typename ElementComparator>
  354. void sort (ElementComparator& comparator, UndoManager* undoManager, bool retainOrderOfEquivalentItems)
  355. {
  356. if (object != nullptr)
  357. {
  358. ReferenceCountedArray <SharedObject> sortedList (object->children);
  359. ComparatorAdapter <ElementComparator> adapter (comparator);
  360. sortedList.sort (adapter, retainOrderOfEquivalentItems);
  361. object->reorderChildren (sortedList, undoManager);
  362. }
  363. }
  364. /** An invalid ValueTree that can be used if you need to return one as an error condition, etc.
  365. This invalid object is equivalent to ValueTree created with its default constructor.
  366. */
  367. static const ValueTree invalid;
  368. private:
  369. //==============================================================================
  370. class SetPropertyAction; friend class SetPropertyAction;
  371. class AddOrRemoveChildAction; friend class AddOrRemoveChildAction;
  372. class MoveChildAction; friend class MoveChildAction;
  373. class JUCE_API SharedObject : public SingleThreadedReferenceCountedObject
  374. {
  375. public:
  376. explicit SharedObject (const Identifier& type);
  377. SharedObject (const SharedObject& other);
  378. ~SharedObject();
  379. const Identifier type;
  380. NamedValueSet properties;
  381. ReferenceCountedArray <SharedObject> children;
  382. SortedSet <ValueTree*> valueTreesWithListeners;
  383. SharedObject* parent;
  384. void sendPropertyChangeMessage (const Identifier& property);
  385. void sendPropertyChangeMessage (ValueTree& tree, const Identifier& property);
  386. void sendChildAddedMessage (ValueTree& parent, ValueTree& child);
  387. void sendChildAddedMessage (ValueTree child);
  388. void sendChildRemovedMessage (ValueTree& parent, ValueTree& child);
  389. void sendChildRemovedMessage (ValueTree child);
  390. void sendChildOrderChangedMessage (ValueTree& parent);
  391. void sendChildOrderChangedMessage();
  392. void sendParentChangeMessage();
  393. const var& getProperty (const Identifier& name) const;
  394. var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  395. void setProperty (const Identifier& name, const var& newValue, UndoManager*);
  396. bool hasProperty (const Identifier& name) const;
  397. void removeProperty (const Identifier& name, UndoManager*);
  398. void removeAllProperties (UndoManager*);
  399. bool isAChildOf (const SharedObject* possibleParent) const;
  400. int indexOf (const ValueTree& child) const;
  401. ValueTree getChildWithName (const Identifier& type) const;
  402. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  403. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  404. void addChild (SharedObject* child, int index, UndoManager*);
  405. void removeChild (int childIndex, UndoManager*);
  406. void removeAllChildren (UndoManager*);
  407. void moveChild (int currentIndex, int newIndex, UndoManager*);
  408. void reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager*);
  409. bool isEquivalentTo (const SharedObject& other) const;
  410. XmlElement* createXml() const;
  411. private:
  412. SharedObject& operator= (const SharedObject&);
  413. JUCE_LEAK_DETECTOR (SharedObject);
  414. };
  415. template <typename ElementComparator>
  416. class ComparatorAdapter
  417. {
  418. public:
  419. ComparatorAdapter (ElementComparator& comparator_) noexcept : comparator (comparator_) {}
  420. int compareElements (SharedObject* const first, SharedObject* const second)
  421. {
  422. return comparator.compareElements (ValueTree (first), ValueTree (second));
  423. }
  424. private:
  425. ElementComparator& comparator;
  426. JUCE_DECLARE_NON_COPYABLE (ComparatorAdapter);
  427. };
  428. friend class SharedObject;
  429. typedef ReferenceCountedObjectPtr <SharedObject> SharedObjectPtr;
  430. SharedObjectPtr object;
  431. ListenerList <Listener> listeners;
  432. #if JUCE_MSVC && ! DOXYGEN
  433. public: // (workaround for VC6)
  434. #endif
  435. explicit ValueTree (SharedObject*);
  436. };
  437. #endif // __JUCE_VALUETREE_JUCEHEADER__