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.

1171 lines
37KB

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