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.

1152 lines
36KB

  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. class ValueTree::SharedObject : public ReferenceCountedObject
  22. {
  23. public:
  24. typedef ReferenceCountedObjectPtr<SharedObject> Ptr;
  25. explicit SharedObject (const Identifier& t) noexcept : type (t)
  26. {
  27. }
  28. SharedObject (const SharedObject& other)
  29. : ReferenceCountedObject(), type (other.type), properties (other.properties)
  30. {
  31. for (int i = 0; i < other.children.size(); ++i)
  32. {
  33. auto child = new SharedObject (*other.children.getObjectPointerUnchecked(i));
  34. child->parent = this;
  35. children.add (child);
  36. }
  37. }
  38. ~SharedObject()
  39. {
  40. jassert (parent == nullptr); // this should never happen unless something isn't obeying the ref-counting!
  41. for (int i = children.size(); --i >= 0;)
  42. {
  43. const Ptr c (children.getObjectPointerUnchecked(i));
  44. c->parent = nullptr;
  45. children.remove (i);
  46. c->sendParentChangeMessage();
  47. }
  48. }
  49. SharedObject* getRoot() noexcept
  50. {
  51. return parent == nullptr ? this : parent->getRoot();
  52. }
  53. template <typename Function>
  54. void callListeners (Function fn) const
  55. {
  56. auto numListeners = valueTreesWithListeners.size();
  57. if (numListeners == 1)
  58. {
  59. fn (valueTreesWithListeners.getUnchecked(0)->listeners);
  60. }
  61. else if (numListeners > 0)
  62. {
  63. auto listenersCopy = valueTreesWithListeners;
  64. for (int i = 0; i < numListeners; ++i)
  65. {
  66. auto* v = listenersCopy.getUnchecked(i);
  67. if (i == 0 || valueTreesWithListeners.contains (v))
  68. fn (v->listeners);
  69. }
  70. }
  71. }
  72. template <typename Function>
  73. void callListenersForAllParents (Function fn) const
  74. {
  75. for (auto* t = this; t != nullptr; t = t->parent)
  76. t->callListeners (fn);
  77. }
  78. void sendPropertyChangeMessage (const Identifier& property, ValueTree::Listener* listenerToExclude = nullptr)
  79. {
  80. ValueTree tree (this);
  81. callListenersForAllParents ([&] (ListenerList<Listener>& list) { list.callExcluding (listenerToExclude, &ValueTree::Listener::valueTreePropertyChanged, tree, property); });
  82. }
  83. void sendChildAddedMessage (ValueTree child)
  84. {
  85. ValueTree tree (this);
  86. callListenersForAllParents ([&] (ListenerList<Listener>& list) { list.call (&ValueTree::Listener::valueTreeChildAdded, tree, child); });
  87. }
  88. void sendChildRemovedMessage (ValueTree child, int index)
  89. {
  90. ValueTree tree (this);
  91. callListenersForAllParents ([=, &tree, &child] (ListenerList<Listener>& list) { list.call (&ValueTree::Listener::valueTreeChildRemoved, tree, child, index); });
  92. }
  93. void sendChildOrderChangedMessage (int oldIndex, int newIndex)
  94. {
  95. ValueTree tree (this);
  96. callListenersForAllParents ([=, &tree] (ListenerList<Listener>& list) { list.call (&ValueTree::Listener::valueTreeChildOrderChanged, tree, oldIndex, newIndex); });
  97. }
  98. void sendParentChangeMessage()
  99. {
  100. ValueTree tree (this);
  101. for (int j = children.size(); --j >= 0;)
  102. if (auto* child = children.getObjectPointer (j))
  103. child->sendParentChangeMessage();
  104. callListeners ([&] (ListenerList<Listener>& list) { list.call (&ValueTree::Listener::valueTreeParentChanged, tree); });
  105. }
  106. void setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager,
  107. ValueTree::Listener* listenerToExclude = nullptr)
  108. {
  109. if (undoManager == nullptr)
  110. {
  111. if (properties.set (name, newValue))
  112. sendPropertyChangeMessage (name, listenerToExclude);
  113. }
  114. else
  115. {
  116. if (auto* existingValue = properties.getVarPointer (name))
  117. {
  118. if (*existingValue != newValue)
  119. undoManager->perform (new SetPropertyAction (this, name, newValue, *existingValue, false, false, listenerToExclude));
  120. }
  121. else
  122. {
  123. undoManager->perform (new SetPropertyAction (this, name, newValue, {}, true, false, listenerToExclude));
  124. }
  125. }
  126. }
  127. bool hasProperty (const Identifier& name) const noexcept
  128. {
  129. return properties.contains (name);
  130. }
  131. void removeProperty (const Identifier& name, UndoManager* const undoManager)
  132. {
  133. if (undoManager == nullptr)
  134. {
  135. if (properties.remove (name))
  136. sendPropertyChangeMessage (name);
  137. }
  138. else
  139. {
  140. if (properties.contains (name))
  141. undoManager->perform (new SetPropertyAction (this, name, {}, properties [name], false, true));
  142. }
  143. }
  144. void removeAllProperties (UndoManager* const undoManager)
  145. {
  146. if (undoManager == nullptr)
  147. {
  148. while (properties.size() > 0)
  149. {
  150. auto name = properties.getName (properties.size() - 1);
  151. properties.remove (name);
  152. sendPropertyChangeMessage (name);
  153. }
  154. }
  155. else
  156. {
  157. for (int i = properties.size(); --i >= 0;)
  158. undoManager->perform (new SetPropertyAction (this, properties.getName(i), {},
  159. properties.getValueAt(i), false, true));
  160. }
  161. }
  162. void copyPropertiesFrom (const SharedObject& source, UndoManager* const undoManager)
  163. {
  164. for (int i = properties.size(); --i >= 0;)
  165. if (! source.properties.contains (properties.getName (i)))
  166. removeProperty (properties.getName (i), undoManager);
  167. for (int i = 0; i < source.properties.size(); ++i)
  168. setProperty (source.properties.getName(i), source.properties.getValueAt(i), undoManager);
  169. }
  170. ValueTree getChildWithName (const Identifier& typeToMatch) const
  171. {
  172. for (auto* s : children)
  173. if (s->type == typeToMatch)
  174. return ValueTree (s);
  175. return {};
  176. }
  177. ValueTree getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  178. {
  179. for (auto* s : children)
  180. if (s->type == typeToMatch)
  181. return ValueTree (s);
  182. auto newObject = new SharedObject (typeToMatch);
  183. addChild (newObject, -1, undoManager);
  184. return ValueTree (newObject);
  185. }
  186. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  187. {
  188. for (auto* s : children)
  189. if (s->properties[propertyName] == propertyValue)
  190. return ValueTree (s);
  191. return {};
  192. }
  193. bool isAChildOf (const SharedObject* const possibleParent) const noexcept
  194. {
  195. for (auto* p = parent; p != nullptr; p = p->parent)
  196. if (p == possibleParent)
  197. return true;
  198. return false;
  199. }
  200. int indexOf (const ValueTree& child) const noexcept
  201. {
  202. return children.indexOf (child.object);
  203. }
  204. void addChild (SharedObject* child, int index, UndoManager* const undoManager)
  205. {
  206. if (child != nullptr && child->parent != this)
  207. {
  208. if (child != this && ! isAChildOf (child))
  209. {
  210. // You should always make sure that a child is removed from its previous parent before
  211. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  212. // undomanager should be used when removing it from its current parent..
  213. jassert (child->parent == nullptr);
  214. if (child->parent != nullptr)
  215. {
  216. jassert (child->parent->children.indexOf (child) >= 0);
  217. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  218. }
  219. if (undoManager == nullptr)
  220. {
  221. children.insert (index, child);
  222. child->parent = this;
  223. sendChildAddedMessage (ValueTree (child));
  224. child->sendParentChangeMessage();
  225. }
  226. else
  227. {
  228. if (! isPositiveAndBelow (index, children.size()))
  229. index = children.size();
  230. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  231. }
  232. }
  233. else
  234. {
  235. // You're attempting to create a recursive loop! A node
  236. // can't be a child of one of its own children!
  237. jassertfalse;
  238. }
  239. }
  240. }
  241. void removeChild (const int childIndex, UndoManager* const undoManager)
  242. {
  243. if (const Ptr child = children.getObjectPointer (childIndex))
  244. {
  245. if (undoManager == nullptr)
  246. {
  247. children.remove (childIndex);
  248. child->parent = nullptr;
  249. sendChildRemovedMessage (ValueTree (child), childIndex);
  250. child->sendParentChangeMessage();
  251. }
  252. else
  253. {
  254. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, nullptr));
  255. }
  256. }
  257. }
  258. void removeAllChildren (UndoManager* const undoManager)
  259. {
  260. while (children.size() > 0)
  261. removeChild (children.size() - 1, undoManager);
  262. }
  263. void moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  264. {
  265. // The source index must be a valid index!
  266. jassert (isPositiveAndBelow (currentIndex, children.size()));
  267. if (currentIndex != newIndex
  268. && isPositiveAndBelow (currentIndex, children.size()))
  269. {
  270. if (undoManager == nullptr)
  271. {
  272. children.move (currentIndex, newIndex);
  273. sendChildOrderChangedMessage (currentIndex, newIndex);
  274. }
  275. else
  276. {
  277. if (! isPositiveAndBelow (newIndex, children.size()))
  278. newIndex = children.size() - 1;
  279. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  280. }
  281. }
  282. }
  283. void reorderChildren (const OwnedArray<ValueTree>& newOrder, UndoManager* undoManager)
  284. {
  285. jassert (newOrder.size() == children.size());
  286. for (int i = 0; i < children.size(); ++i)
  287. {
  288. auto* child = newOrder.getUnchecked(i)->object.get();
  289. if (children.getObjectPointerUnchecked (i) != child)
  290. {
  291. const int oldIndex = children.indexOf (child);
  292. jassert (oldIndex >= 0);
  293. moveChild (oldIndex, i, undoManager);
  294. }
  295. }
  296. }
  297. bool isEquivalentTo (const SharedObject& other) const noexcept
  298. {
  299. if (type != other.type
  300. || properties.size() != other.properties.size()
  301. || children.size() != other.children.size()
  302. || properties != other.properties)
  303. return false;
  304. for (int i = 0; i < children.size(); ++i)
  305. if (! children.getObjectPointerUnchecked(i)->isEquivalentTo (*other.children.getObjectPointerUnchecked(i)))
  306. return false;
  307. return true;
  308. }
  309. XmlElement* createXml() const
  310. {
  311. auto xml = new XmlElement (type);
  312. properties.copyToXmlAttributes (*xml);
  313. // (NB: it's faster to add nodes to XML elements in reverse order)
  314. for (int i = children.size(); --i >= 0;)
  315. xml->prependChildElement (children.getObjectPointerUnchecked(i)->createXml());
  316. return xml;
  317. }
  318. void writeToStream (OutputStream& output) const
  319. {
  320. output.writeString (type.toString());
  321. output.writeCompressedInt (properties.size());
  322. for (int j = 0; j < properties.size(); ++j)
  323. {
  324. output.writeString (properties.getName (j).toString());
  325. properties.getValueAt(j).writeToStream (output);
  326. }
  327. output.writeCompressedInt (children.size());
  328. for (int i = 0; i < children.size(); ++i)
  329. writeObjectToStream (output, children.getObjectPointerUnchecked(i));
  330. }
  331. static void writeObjectToStream (OutputStream& output, const SharedObject* const object)
  332. {
  333. if (object != nullptr)
  334. {
  335. object->writeToStream (output);
  336. }
  337. else
  338. {
  339. output.writeString (String());
  340. output.writeCompressedInt (0);
  341. output.writeCompressedInt (0);
  342. }
  343. }
  344. //==============================================================================
  345. struct SetPropertyAction : public UndoableAction
  346. {
  347. SetPropertyAction (SharedObject* const so, const Identifier& propertyName,
  348. const var& newVal, const var& oldVal, bool isAdding, bool isDeleting,
  349. ValueTree::Listener* listenerToExclude = nullptr)
  350. : target (so), name (propertyName), newValue (newVal), oldValue (oldVal),
  351. isAddingNewProperty (isAdding), isDeletingProperty (isDeleting),
  352. excludeListener (listenerToExclude)
  353. {
  354. }
  355. bool perform() override
  356. {
  357. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  358. if (isDeletingProperty)
  359. target->removeProperty (name, nullptr);
  360. else
  361. target->setProperty (name, newValue, nullptr, excludeListener);
  362. return true;
  363. }
  364. bool undo() override
  365. {
  366. if (isAddingNewProperty)
  367. target->removeProperty (name, nullptr);
  368. else
  369. target->setProperty (name, oldValue, nullptr);
  370. return true;
  371. }
  372. int getSizeInUnits() override
  373. {
  374. return (int) sizeof (*this); //xxx should be more accurate
  375. }
  376. UndoableAction* createCoalescedAction (UndoableAction* nextAction) override
  377. {
  378. if (! (isAddingNewProperty || isDeletingProperty))
  379. {
  380. if (SetPropertyAction* const next = dynamic_cast<SetPropertyAction*> (nextAction))
  381. if (next->target == target && next->name == name
  382. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  383. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  384. }
  385. return nullptr;
  386. }
  387. private:
  388. const Ptr target;
  389. const Identifier name;
  390. const var newValue;
  391. var oldValue;
  392. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  393. ValueTree::Listener* excludeListener;
  394. JUCE_DECLARE_NON_COPYABLE (SetPropertyAction)
  395. };
  396. //==============================================================================
  397. struct AddOrRemoveChildAction : public UndoableAction
  398. {
  399. AddOrRemoveChildAction (SharedObject* parentObject, int index, SharedObject* newChild)
  400. : target (parentObject),
  401. child (newChild != nullptr ? newChild : parentObject->children.getObjectPointer (index)),
  402. childIndex (index),
  403. isDeleting (newChild == nullptr)
  404. {
  405. jassert (child != nullptr);
  406. }
  407. bool perform() override
  408. {
  409. if (isDeleting)
  410. target->removeChild (childIndex, nullptr);
  411. else
  412. target->addChild (child, childIndex, nullptr);
  413. return true;
  414. }
  415. bool undo() override
  416. {
  417. if (isDeleting)
  418. {
  419. target->addChild (child, childIndex, nullptr);
  420. }
  421. else
  422. {
  423. // If you hit this, it seems that your object's state is getting confused - probably
  424. // because you've interleaved some undoable and non-undoable operations?
  425. jassert (childIndex < target->children.size());
  426. target->removeChild (childIndex, nullptr);
  427. }
  428. return true;
  429. }
  430. int getSizeInUnits() override
  431. {
  432. return (int) sizeof (*this); //xxx should be more accurate
  433. }
  434. private:
  435. const Ptr target, child;
  436. const int childIndex;
  437. const bool isDeleting;
  438. JUCE_DECLARE_NON_COPYABLE (AddOrRemoveChildAction)
  439. };
  440. //==============================================================================
  441. struct MoveChildAction : public UndoableAction
  442. {
  443. MoveChildAction (SharedObject* parentObject, int fromIndex, int toIndex) noexcept
  444. : parent (parentObject), startIndex (fromIndex), endIndex (toIndex)
  445. {
  446. }
  447. bool perform() override
  448. {
  449. parent->moveChild (startIndex, endIndex, nullptr);
  450. return true;
  451. }
  452. bool undo() override
  453. {
  454. parent->moveChild (endIndex, startIndex, nullptr);
  455. return true;
  456. }
  457. int getSizeInUnits() override
  458. {
  459. return (int) sizeof (*this); //xxx should be more accurate
  460. }
  461. UndoableAction* createCoalescedAction (UndoableAction* nextAction) override
  462. {
  463. if (auto* next = dynamic_cast<MoveChildAction*> (nextAction))
  464. if (next->parent == parent && next->startIndex == endIndex)
  465. return new MoveChildAction (parent, startIndex, next->endIndex);
  466. return nullptr;
  467. }
  468. private:
  469. const Ptr parent;
  470. const int startIndex, endIndex;
  471. JUCE_DECLARE_NON_COPYABLE (MoveChildAction)
  472. };
  473. //==============================================================================
  474. const Identifier type;
  475. NamedValueSet properties;
  476. ReferenceCountedArray<SharedObject> children;
  477. SortedSet<ValueTree*> valueTreesWithListeners;
  478. SharedObject* parent = nullptr;
  479. private:
  480. SharedObject& operator= (const SharedObject&);
  481. JUCE_LEAK_DETECTOR (SharedObject)
  482. };
  483. //==============================================================================
  484. ValueTree::ValueTree() noexcept
  485. {
  486. }
  487. #if JUCE_ALLOW_STATIC_NULL_VARIABLES
  488. const ValueTree ValueTree::invalid;
  489. #endif
  490. ValueTree::ValueTree (const Identifier& type) : object (new ValueTree::SharedObject (type))
  491. {
  492. jassert (type.toString().isNotEmpty()); // All objects must be given a sensible type name!
  493. }
  494. ValueTree::ValueTree (SharedObject* so) noexcept : object (so)
  495. {
  496. }
  497. ValueTree::ValueTree (const ValueTree& other) noexcept : object (other.object)
  498. {
  499. }
  500. ValueTree& ValueTree::operator= (const ValueTree& other)
  501. {
  502. if (object != other.object)
  503. {
  504. if (listeners.isEmpty())
  505. {
  506. object = other.object;
  507. }
  508. else
  509. {
  510. if (object != nullptr)
  511. object->valueTreesWithListeners.removeValue (this);
  512. if (other.object != nullptr)
  513. other.object->valueTreesWithListeners.add (this);
  514. object = other.object;
  515. listeners.call (&ValueTree::Listener::valueTreeRedirected, *this);
  516. }
  517. }
  518. return *this;
  519. }
  520. ValueTree::ValueTree (ValueTree&& other) noexcept
  521. : object (static_cast<SharedObject::Ptr&&> (other.object))
  522. {
  523. }
  524. ValueTree::~ValueTree()
  525. {
  526. if (listeners.size() > 0 && object != nullptr)
  527. object->valueTreesWithListeners.removeValue (this);
  528. }
  529. bool ValueTree::operator== (const ValueTree& other) const noexcept
  530. {
  531. return object == other.object;
  532. }
  533. bool ValueTree::operator!= (const ValueTree& other) const noexcept
  534. {
  535. return object != other.object;
  536. }
  537. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  538. {
  539. return object == other.object
  540. || (object != nullptr && other.object != nullptr
  541. && object->isEquivalentTo (*other.object));
  542. }
  543. ValueTree ValueTree::createCopy() const
  544. {
  545. return ValueTree (createCopyIfNotNull (object.get()));
  546. }
  547. bool ValueTree::hasType (const Identifier& typeName) const noexcept
  548. {
  549. return object != nullptr && object->type == typeName;
  550. }
  551. Identifier ValueTree::getType() const noexcept
  552. {
  553. return object != nullptr ? object->type : Identifier();
  554. }
  555. ValueTree ValueTree::getParent() const noexcept
  556. {
  557. return ValueTree (object != nullptr ? object->parent
  558. : static_cast<SharedObject*> (nullptr));
  559. }
  560. ValueTree ValueTree::getRoot() const noexcept
  561. {
  562. return ValueTree (object != nullptr ? object->getRoot()
  563. : static_cast<SharedObject*> (nullptr));
  564. }
  565. ValueTree ValueTree::getSibling (const int delta) const noexcept
  566. {
  567. if (object == nullptr || object->parent == nullptr)
  568. return {};
  569. const int index = object->parent->indexOf (*this) + delta;
  570. return ValueTree (object->parent->children.getObjectPointer (index));
  571. }
  572. static const var& getNullVarRef() noexcept
  573. {
  574. #if JUCE_ALLOW_STATIC_NULL_VARIABLES
  575. return var::null;
  576. #else
  577. static var nullVar;
  578. return nullVar;
  579. #endif
  580. }
  581. const var& ValueTree::operator[] (const Identifier& name) const noexcept
  582. {
  583. return object == nullptr ? getNullVarRef() : object->properties[name];
  584. }
  585. const var& ValueTree::getProperty (const Identifier& name) const noexcept
  586. {
  587. return object == nullptr ? getNullVarRef() : object->properties[name];
  588. }
  589. var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  590. {
  591. return object == nullptr ? defaultReturnValue
  592. : object->properties.getWithDefault (name, defaultReturnValue);
  593. }
  594. const var* ValueTree::getPropertyPointer (const Identifier& name) const noexcept
  595. {
  596. return object == nullptr ? nullptr
  597. : object->properties.getVarPointer (name);
  598. }
  599. ValueTree& ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* undoManager)
  600. {
  601. return setPropertyExcludingListener (nullptr, name, newValue, undoManager);
  602. }
  603. ValueTree& ValueTree::setPropertyExcludingListener (Listener* listenerToExclude, const Identifier& name, const var& newValue, UndoManager* undoManager)
  604. {
  605. jassert (name.toString().isNotEmpty()); // Must have a valid property name!
  606. jassert (object != nullptr); // Trying to add a property to a null ValueTree will fail!
  607. if (object != nullptr)
  608. object->setProperty (name, newValue, undoManager, listenerToExclude);
  609. return *this;
  610. }
  611. bool ValueTree::hasProperty (const Identifier& name) const noexcept
  612. {
  613. return object != nullptr && object->hasProperty (name);
  614. }
  615. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  616. {
  617. if (object != nullptr)
  618. object->removeProperty (name, undoManager);
  619. }
  620. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  621. {
  622. if (object != nullptr)
  623. object->removeAllProperties (undoManager);
  624. }
  625. int ValueTree::getNumProperties() const noexcept
  626. {
  627. return object == nullptr ? 0 : object->properties.size();
  628. }
  629. Identifier ValueTree::getPropertyName (const int index) const noexcept
  630. {
  631. return object == nullptr ? Identifier()
  632. : object->properties.getName (index);
  633. }
  634. void ValueTree::copyPropertiesFrom (const ValueTree& source, UndoManager* const undoManager)
  635. {
  636. jassert (object != nullptr || source.object == nullptr); // Trying to add properties to a null ValueTree will fail!
  637. if (source.object == nullptr)
  638. removeAllProperties (undoManager);
  639. else if (object != nullptr)
  640. object->copyPropertiesFrom (*(source.object), undoManager);
  641. }
  642. int ValueTree::getReferenceCount() const noexcept
  643. {
  644. return object != nullptr ? object->getReferenceCount() : 0;
  645. }
  646. //==============================================================================
  647. class ValueTreePropertyValueSource : public Value::ValueSource,
  648. private ValueTree::Listener
  649. {
  650. public:
  651. ValueTreePropertyValueSource (const ValueTree& vt, const Identifier& prop, UndoManager* um)
  652. : tree (vt), property (prop), undoManager (um)
  653. {
  654. tree.addListener (this);
  655. }
  656. ~ValueTreePropertyValueSource()
  657. {
  658. tree.removeListener (this);
  659. }
  660. var getValue() const override { return tree [property]; }
  661. void setValue (const var& newValue) override { tree.setProperty (property, newValue, undoManager); }
  662. private:
  663. ValueTree tree;
  664. const Identifier property;
  665. UndoManager* const undoManager;
  666. void valueTreePropertyChanged (ValueTree& changedTree, const Identifier& changedProperty) override
  667. {
  668. if (tree == changedTree && property == changedProperty)
  669. sendChangeMessage (false);
  670. }
  671. void valueTreeChildAdded (ValueTree&, ValueTree&) override {}
  672. void valueTreeChildRemoved (ValueTree&, ValueTree&, int) override {}
  673. void valueTreeChildOrderChanged (ValueTree&, int, int) override {}
  674. void valueTreeParentChanged (ValueTree&) override {}
  675. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ValueTreePropertyValueSource)
  676. };
  677. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager)
  678. {
  679. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  680. }
  681. //==============================================================================
  682. int ValueTree::getNumChildren() const noexcept
  683. {
  684. return object == nullptr ? 0 : object->children.size();
  685. }
  686. ValueTree ValueTree::getChild (int index) const
  687. {
  688. return ValueTree (object != nullptr ? object->children.getObjectPointer (index)
  689. : static_cast<SharedObject*> (nullptr));
  690. }
  691. ValueTree::Iterator::Iterator (const ValueTree& v, bool isEnd) noexcept
  692. : internal (v.object != nullptr ? (isEnd ? v.object->children.end() : v.object->children.begin()) : nullptr)
  693. {}
  694. ValueTree::Iterator& ValueTree::Iterator::operator++() noexcept
  695. {
  696. internal = static_cast<SharedObject**> (internal) + 1;
  697. return *this;
  698. }
  699. bool ValueTree::Iterator::operator!= (const Iterator& other) const noexcept
  700. {
  701. return internal != other.internal;
  702. }
  703. ValueTree ValueTree::Iterator::operator*() const
  704. {
  705. return ValueTree (*static_cast<SharedObject**> (internal));
  706. }
  707. ValueTree::Iterator ValueTree::begin() const noexcept { return Iterator (*this, false); }
  708. ValueTree::Iterator ValueTree::end() const noexcept { return Iterator (*this, true); }
  709. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  710. {
  711. return object != nullptr ? object->getChildWithName (type) : ValueTree();
  712. }
  713. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  714. {
  715. return object != nullptr ? object->getOrCreateChildWithName (type, undoManager) : ValueTree();
  716. }
  717. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  718. {
  719. return object != nullptr ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree();
  720. }
  721. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const noexcept
  722. {
  723. return object != nullptr && object->isAChildOf (possibleParent.object);
  724. }
  725. int ValueTree::indexOf (const ValueTree& child) const noexcept
  726. {
  727. return object != nullptr ? object->indexOf (child) : -1;
  728. }
  729. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  730. {
  731. jassert (object != nullptr); // Trying to add a child to a null ValueTree!
  732. if (object != nullptr)
  733. object->addChild (child.object, index, undoManager);
  734. }
  735. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  736. {
  737. if (object != nullptr)
  738. object->removeChild (childIndex, undoManager);
  739. }
  740. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  741. {
  742. if (object != nullptr)
  743. object->removeChild (object->children.indexOf (child.object), undoManager);
  744. }
  745. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  746. {
  747. if (object != nullptr)
  748. object->removeAllChildren (undoManager);
  749. }
  750. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  751. {
  752. if (object != nullptr)
  753. object->moveChild (currentIndex, newIndex, undoManager);
  754. }
  755. //==============================================================================
  756. void ValueTree::createListOfChildren (OwnedArray<ValueTree>& list) const
  757. {
  758. jassert (object != nullptr);
  759. for (int i = 0; i < object->children.size(); ++i)
  760. list.add (new ValueTree (object->children.getObjectPointerUnchecked(i)));
  761. }
  762. void ValueTree::reorderChildren (const OwnedArray<ValueTree>& newOrder, UndoManager* undoManager)
  763. {
  764. jassert (object != nullptr);
  765. object->reorderChildren (newOrder, undoManager);
  766. }
  767. //==============================================================================
  768. void ValueTree::addListener (Listener* listener)
  769. {
  770. if (listener != nullptr)
  771. {
  772. if (listeners.isEmpty() && object != nullptr)
  773. object->valueTreesWithListeners.add (this);
  774. listeners.add (listener);
  775. }
  776. }
  777. void ValueTree::removeListener (Listener* listener)
  778. {
  779. listeners.remove (listener);
  780. if (listeners.isEmpty() && object != nullptr)
  781. object->valueTreesWithListeners.removeValue (this);
  782. }
  783. void ValueTree::sendPropertyChangeMessage (const Identifier& property)
  784. {
  785. if (object != nullptr)
  786. object->sendPropertyChangeMessage (property);
  787. }
  788. //==============================================================================
  789. XmlElement* ValueTree::createXml() const
  790. {
  791. return object != nullptr ? object->createXml() : nullptr;
  792. }
  793. ValueTree ValueTree::fromXml (const XmlElement& xml)
  794. {
  795. if (! xml.isTextElement())
  796. {
  797. ValueTree v (xml.getTagName());
  798. v.object->properties.setFromXmlAttributes (xml);
  799. forEachXmlChildElement (xml, e)
  800. v.addChild (fromXml (*e), -1, nullptr);
  801. return v;
  802. }
  803. // ValueTrees don't have any equivalent to XML text elements!
  804. jassertfalse;
  805. return {};
  806. }
  807. String ValueTree::toXmlString() const
  808. {
  809. const ScopedPointer<XmlElement> xml (createXml());
  810. return xml != nullptr ? xml->createDocument (StringRef()) : String();
  811. }
  812. //==============================================================================
  813. void ValueTree::writeToStream (OutputStream& output) const
  814. {
  815. SharedObject::writeObjectToStream (output, object);
  816. }
  817. ValueTree ValueTree::readFromStream (InputStream& input)
  818. {
  819. auto type = input.readString();
  820. if (type.isEmpty())
  821. return {};
  822. ValueTree v (type);
  823. const int numProps = input.readCompressedInt();
  824. if (numProps < 0)
  825. {
  826. jassertfalse; // trying to read corrupted data!
  827. return v;
  828. }
  829. for (int i = 0; i < numProps; ++i)
  830. {
  831. const String name (input.readString());
  832. if (name.isNotEmpty())
  833. {
  834. const var value (var::readFromStream (input));
  835. v.object->properties.set (name, value);
  836. }
  837. else
  838. {
  839. jassertfalse; // trying to read corrupted data!
  840. }
  841. }
  842. const int numChildren = input.readCompressedInt();
  843. v.object->children.ensureStorageAllocated (numChildren);
  844. for (int i = 0; i < numChildren; ++i)
  845. {
  846. ValueTree child (readFromStream (input));
  847. if (! child.isValid())
  848. return v;
  849. v.object->children.add (child.object);
  850. child.object->parent = v.object;
  851. }
  852. return v;
  853. }
  854. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  855. {
  856. MemoryInputStream in (data, numBytes, false);
  857. return readFromStream (in);
  858. }
  859. ValueTree ValueTree::readFromGZIPData (const void* const data, const size_t numBytes)
  860. {
  861. MemoryInputStream in (data, numBytes, false);
  862. GZIPDecompressorInputStream gzipStream (in);
  863. return readFromStream (gzipStream);
  864. }
  865. void ValueTree::Listener::valueTreeRedirected (ValueTree&) {}
  866. //==============================================================================
  867. #if JUCE_UNIT_TESTS
  868. class ValueTreeTests : public UnitTest
  869. {
  870. public:
  871. ValueTreeTests() : UnitTest ("ValueTrees", "Values") {}
  872. static String createRandomIdentifier (Random& r)
  873. {
  874. char buffer[50] = { 0 };
  875. const char chars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-:";
  876. for (int i = 1 + r.nextInt (numElementsInArray (buffer) - 2); --i >= 0;)
  877. buffer[i] = chars [r.nextInt (sizeof (chars) - 1)];
  878. String result (buffer);
  879. if (! XmlElement::isValidXmlName (result))
  880. result = createRandomIdentifier (r);
  881. return result;
  882. }
  883. static String createRandomWideCharString (Random& r)
  884. {
  885. juce_wchar buffer[50] = { 0 };
  886. for (int i = r.nextInt (numElementsInArray (buffer) - 1); --i >= 0;)
  887. {
  888. if (r.nextBool())
  889. {
  890. do
  891. {
  892. buffer[i] = (juce_wchar) (1 + r.nextInt (0x10ffff - 1));
  893. }
  894. while (! CharPointer_UTF16::canRepresent (buffer[i]));
  895. }
  896. else
  897. buffer[i] = (juce_wchar) (1 + r.nextInt (0x7e));
  898. }
  899. return CharPointer_UTF32 (buffer);
  900. }
  901. static ValueTree createRandomTree (UndoManager* undoManager, int depth, Random& r)
  902. {
  903. ValueTree v (createRandomIdentifier (r));
  904. for (int i = r.nextInt (10); --i >= 0;)
  905. {
  906. switch (r.nextInt (5))
  907. {
  908. case 0: v.setProperty (createRandomIdentifier (r), createRandomWideCharString (r), undoManager); break;
  909. case 1: v.setProperty (createRandomIdentifier (r), r.nextInt(), undoManager); break;
  910. case 2: if (depth < 5) v.addChild (createRandomTree (undoManager, depth + 1, r), r.nextInt (v.getNumChildren() + 1), undoManager); break;
  911. case 3: v.setProperty (createRandomIdentifier (r), r.nextBool(), undoManager); break;
  912. case 4: v.setProperty (createRandomIdentifier (r), r.nextDouble(), undoManager); break;
  913. default: break;
  914. }
  915. }
  916. return v;
  917. }
  918. void runTest() override
  919. {
  920. beginTest ("ValueTree");
  921. Random r = getRandom();
  922. for (int i = 10; --i >= 0;)
  923. {
  924. MemoryOutputStream mo;
  925. ValueTree v1 (createRandomTree (nullptr, 0, r));
  926. v1.writeToStream (mo);
  927. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  928. ValueTree v2 = ValueTree::readFromStream (mi);
  929. expect (v1.isEquivalentTo (v2));
  930. ScopedPointer<XmlElement> xml1 (v1.createXml());
  931. ScopedPointer<XmlElement> xml2 (v2.createCopy().createXml());
  932. expect (xml1->isEquivalentTo (xml2, false));
  933. ValueTree v4 = v2.createCopy();
  934. expect (v1.isEquivalentTo (v4));
  935. }
  936. }
  937. };
  938. static ValueTreeTests valueTreeTests;
  939. #endif
  940. } // namespace juce