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.

1252 lines
40KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  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 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. namespace juce
  19. {
  20. class ValueTree::SharedObject : public ReferenceCountedObject
  21. {
  22. public:
  23. using Ptr = ReferenceCountedObjectPtr<SharedObject>;
  24. explicit SharedObject (const Identifier& t) noexcept : type (t) {}
  25. SharedObject (const SharedObject& other)
  26. : ReferenceCountedObject(), type (other.type), properties (other.properties)
  27. {
  28. for (auto* c : other.children)
  29. {
  30. auto* child = new SharedObject (*c);
  31. child->parent = this;
  32. children.add (child);
  33. }
  34. }
  35. SharedObject& operator= (const SharedObject&) = delete;
  36. ~SharedObject()
  37. {
  38. jassert (parent == nullptr); // this should never happen unless something isn't obeying the ref-counting!
  39. for (auto i = children.size(); --i >= 0;)
  40. {
  41. const Ptr c (children.getObjectPointerUnchecked (i));
  42. c->parent = nullptr;
  43. children.remove (i);
  44. c->sendParentChangeMessage();
  45. }
  46. }
  47. SharedObject& getRoot() noexcept
  48. {
  49. return parent == nullptr ? *this : parent->getRoot();
  50. }
  51. template <typename Function>
  52. void callListeners (ValueTree::Listener* listenerToExclude, Function fn) const
  53. {
  54. auto numListeners = valueTreesWithListeners.size();
  55. if (numListeners == 1)
  56. {
  57. valueTreesWithListeners.getUnchecked (0)->listeners.callExcluding (listenerToExclude, fn);
  58. }
  59. else if (numListeners > 0)
  60. {
  61. auto listenersCopy = valueTreesWithListeners;
  62. for (int i = 0; i < numListeners; ++i)
  63. {
  64. auto* v = listenersCopy.getUnchecked (i);
  65. if (i == 0 || valueTreesWithListeners.contains (v))
  66. v->listeners.callExcluding (listenerToExclude, fn);
  67. }
  68. }
  69. }
  70. template <typename Function>
  71. void callListenersForAllParents (ValueTree::Listener* listenerToExclude, Function fn) const
  72. {
  73. for (auto* t = this; t != nullptr; t = t->parent)
  74. t->callListeners (listenerToExclude, fn);
  75. }
  76. void sendPropertyChangeMessage (const Identifier& property, ValueTree::Listener* listenerToExclude = nullptr)
  77. {
  78. ValueTree tree (*this);
  79. callListenersForAllParents (listenerToExclude, [&] (Listener& l) { l.valueTreePropertyChanged (tree, property); });
  80. }
  81. void sendChildAddedMessage (ValueTree child)
  82. {
  83. ValueTree tree (*this);
  84. callListenersForAllParents (nullptr, [&] (Listener& l) { l.valueTreeChildAdded (tree, child); });
  85. }
  86. void sendChildRemovedMessage (ValueTree child, int index)
  87. {
  88. ValueTree tree (*this);
  89. callListenersForAllParents (nullptr, [=, &tree, &child] (Listener& l) { l.valueTreeChildRemoved (tree, child, index); });
  90. }
  91. void sendChildOrderChangedMessage (int oldIndex, int newIndex)
  92. {
  93. ValueTree tree (*this);
  94. callListenersForAllParents (nullptr, [=, &tree] (Listener& l) { l.valueTreeChildOrderChanged (tree, oldIndex, newIndex); });
  95. }
  96. void sendParentChangeMessage()
  97. {
  98. ValueTree tree (*this);
  99. for (auto j = children.size(); --j >= 0;)
  100. if (auto* child = children.getObjectPointer (j))
  101. child->sendParentChangeMessage();
  102. callListeners (nullptr, [&] (Listener& l) { l.valueTreeParentChanged (tree); });
  103. }
  104. void setProperty (const Identifier& name, const var& newValue, UndoManager* undoManager,
  105. ValueTree::Listener* listenerToExclude = nullptr)
  106. {
  107. if (undoManager == nullptr)
  108. {
  109. if (properties.set (name, newValue))
  110. sendPropertyChangeMessage (name, listenerToExclude);
  111. }
  112. else
  113. {
  114. if (auto* existingValue = properties.getVarPointer (name))
  115. {
  116. if (*existingValue != newValue)
  117. undoManager->perform (new SetPropertyAction (*this, name, newValue, *existingValue,
  118. false, false, listenerToExclude));
  119. }
  120. else
  121. {
  122. undoManager->perform (new SetPropertyAction (*this, name, newValue, {},
  123. 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* 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* 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 (auto 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* undoManager)
  163. {
  164. for (auto 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* 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* 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 (int childIndex, UndoManager* undoManager)
  242. {
  243. if (auto child = Ptr (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, {}));
  255. }
  256. }
  257. }
  258. void removeAllChildren (UndoManager* 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. auto 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 (auto 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 (auto* c : children)
  329. writeObjectToStream (output, c);
  330. }
  331. static void writeObjectToStream (OutputStream& output, const SharedObject* object)
  332. {
  333. if (object != nullptr)
  334. {
  335. object->writeToStream (output);
  336. }
  337. else
  338. {
  339. output.writeString ({});
  340. output.writeCompressedInt (0);
  341. output.writeCompressedInt (0);
  342. }
  343. }
  344. //==============================================================================
  345. struct SetPropertyAction : public UndoableAction
  346. {
  347. SetPropertyAction (Ptr targetObject, const Identifier& propertyName,
  348. const var& newVal, const var& oldVal, bool isAdding, bool isDeleting,
  349. ValueTree::Listener* listenerToExclude = nullptr)
  350. : target (std::move (targetObject)),
  351. 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 (Ptr parentObject, int index, SharedObject* newChild)
  401. : target (std::move (parentObject)),
  402. child (newChild != nullptr ? newChild : target->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.get(), childIndex, nullptr);
  414. return true;
  415. }
  416. bool undo() override
  417. {
  418. if (isDeleting)
  419. {
  420. target->addChild (child.get(), 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 (Ptr parentObject, int fromIndex, int toIndex) noexcept
  445. : parent (std::move (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. ValueTree::ValueTree (const Identifier& type) : object (new ValueTree::SharedObject (type))
  487. {
  488. jassert (type.toString().isNotEmpty()); // All objects must be given a sensible type name!
  489. }
  490. ValueTree::ValueTree (const Identifier& type,
  491. std::initializer_list<NamedValueSet::NamedValue> properties,
  492. std::initializer_list<ValueTree> subTrees)
  493. : ValueTree (type)
  494. {
  495. object->properties = NamedValueSet (std::move (properties));
  496. for (auto& tree : subTrees)
  497. addChild (tree, -1, nullptr);
  498. }
  499. ValueTree::ValueTree (SharedObject::Ptr so) noexcept : object (std::move (so)) {}
  500. ValueTree::ValueTree (SharedObject& so) noexcept : object (so) {}
  501. ValueTree::ValueTree (const ValueTree& other) noexcept : object (other.object)
  502. {
  503. }
  504. ValueTree& ValueTree::operator= (const ValueTree& other)
  505. {
  506. if (object != other.object)
  507. {
  508. if (listeners.isEmpty())
  509. {
  510. object = other.object;
  511. }
  512. else
  513. {
  514. if (object != nullptr)
  515. object->valueTreesWithListeners.removeValue (this);
  516. if (other.object != nullptr)
  517. other.object->valueTreesWithListeners.add (this);
  518. object = other.object;
  519. listeners.call ([this] (Listener& l) { l.valueTreeRedirected (*this); });
  520. }
  521. }
  522. return *this;
  523. }
  524. ValueTree::ValueTree (ValueTree&& other) noexcept
  525. : object (std::move (other.object))
  526. {
  527. if (object != nullptr)
  528. object->valueTreesWithListeners.removeValue (&other);
  529. }
  530. ValueTree::~ValueTree()
  531. {
  532. if (! listeners.isEmpty() && object != nullptr)
  533. object->valueTreesWithListeners.removeValue (this);
  534. }
  535. bool ValueTree::operator== (const ValueTree& other) const noexcept
  536. {
  537. return object == other.object;
  538. }
  539. bool ValueTree::operator!= (const ValueTree& other) const noexcept
  540. {
  541. return object != other.object;
  542. }
  543. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  544. {
  545. return object == other.object
  546. || (object != nullptr && other.object != nullptr
  547. && object->isEquivalentTo (*other.object));
  548. }
  549. ValueTree ValueTree::createCopy() const
  550. {
  551. if (object != nullptr)
  552. return ValueTree (*new SharedObject (*object));
  553. return {};
  554. }
  555. void ValueTree::copyPropertiesFrom (const ValueTree& source, UndoManager* undoManager)
  556. {
  557. jassert (object != nullptr || source.object == nullptr); // Trying to add properties to a null ValueTree will fail!
  558. if (source.object == nullptr)
  559. removeAllProperties (undoManager);
  560. else if (object != nullptr)
  561. object->copyPropertiesFrom (*(source.object), undoManager);
  562. }
  563. void ValueTree::copyPropertiesAndChildrenFrom (const ValueTree& source, UndoManager* undoManager)
  564. {
  565. jassert (object != nullptr || source.object == nullptr); // Trying to copy to a null ValueTree will fail!
  566. copyPropertiesFrom (source, undoManager);
  567. removeAllChildren (undoManager);
  568. if (object != nullptr && source.object != nullptr)
  569. for (auto& child : source.object->children)
  570. object->addChild (createCopyIfNotNull (child), -1, undoManager);
  571. }
  572. bool ValueTree::hasType (const Identifier& typeName) const noexcept
  573. {
  574. return object != nullptr && object->type == typeName;
  575. }
  576. Identifier ValueTree::getType() const noexcept
  577. {
  578. return object != nullptr ? object->type : Identifier();
  579. }
  580. ValueTree ValueTree::getParent() const noexcept
  581. {
  582. if (object != nullptr)
  583. if (auto p = object->parent)
  584. return ValueTree (*p);
  585. return {};
  586. }
  587. ValueTree ValueTree::getRoot() const noexcept
  588. {
  589. if (object != nullptr)
  590. return ValueTree (object->getRoot());
  591. return {};
  592. }
  593. ValueTree ValueTree::getSibling (int delta) const noexcept
  594. {
  595. if (object != nullptr)
  596. if (auto* p = object->parent)
  597. if (auto* c = p->children.getObjectPointer (p->indexOf (*this) + delta))
  598. return ValueTree (*c);
  599. return {};
  600. }
  601. static const var& getNullVarRef() noexcept
  602. {
  603. static var nullVar;
  604. return nullVar;
  605. }
  606. const var& ValueTree::operator[] (const Identifier& name) const noexcept
  607. {
  608. return object == nullptr ? getNullVarRef() : object->properties[name];
  609. }
  610. const var& ValueTree::getProperty (const Identifier& name) const noexcept
  611. {
  612. return object == nullptr ? getNullVarRef() : object->properties[name];
  613. }
  614. var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  615. {
  616. return object == nullptr ? defaultReturnValue
  617. : object->properties.getWithDefault (name, defaultReturnValue);
  618. }
  619. const var* ValueTree::getPropertyPointer (const Identifier& name) const noexcept
  620. {
  621. return object == nullptr ? nullptr
  622. : object->properties.getVarPointer (name);
  623. }
  624. ValueTree& ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* undoManager)
  625. {
  626. return setPropertyExcludingListener (nullptr, name, newValue, undoManager);
  627. }
  628. ValueTree& ValueTree::setPropertyExcludingListener (Listener* listenerToExclude, const Identifier& name,
  629. const var& newValue, UndoManager* undoManager)
  630. {
  631. jassert (name.toString().isNotEmpty()); // Must have a valid property name!
  632. jassert (object != nullptr); // Trying to add a property to a null ValueTree will fail!
  633. if (object != nullptr)
  634. object->setProperty (name, newValue, undoManager, listenerToExclude);
  635. return *this;
  636. }
  637. bool ValueTree::hasProperty (const Identifier& name) const noexcept
  638. {
  639. return object != nullptr && object->hasProperty (name);
  640. }
  641. void ValueTree::removeProperty (const Identifier& name, UndoManager* undoManager)
  642. {
  643. if (object != nullptr)
  644. object->removeProperty (name, undoManager);
  645. }
  646. void ValueTree::removeAllProperties (UndoManager* undoManager)
  647. {
  648. if (object != nullptr)
  649. object->removeAllProperties (undoManager);
  650. }
  651. int ValueTree::getNumProperties() const noexcept
  652. {
  653. return object == nullptr ? 0 : object->properties.size();
  654. }
  655. Identifier ValueTree::getPropertyName (int index) const noexcept
  656. {
  657. return object == nullptr ? Identifier()
  658. : object->properties.getName (index);
  659. }
  660. int ValueTree::getReferenceCount() const noexcept
  661. {
  662. return object != nullptr ? object->getReferenceCount() : 0;
  663. }
  664. //==============================================================================
  665. struct ValueTreePropertyValueSource : public Value::ValueSource,
  666. private ValueTree::Listener
  667. {
  668. ValueTreePropertyValueSource (const ValueTree& vt, const Identifier& prop, UndoManager* um, bool sync)
  669. : tree (vt), property (prop), undoManager (um), updateSynchronously (sync)
  670. {
  671. tree.addListener (this);
  672. }
  673. ~ValueTreePropertyValueSource() override
  674. {
  675. tree.removeListener (this);
  676. }
  677. var getValue() const override { return tree[property]; }
  678. void setValue (const var& newValue) override { tree.setProperty (property, newValue, undoManager); }
  679. private:
  680. ValueTree tree;
  681. const Identifier property;
  682. UndoManager* const undoManager;
  683. const bool updateSynchronously;
  684. void valueTreePropertyChanged (ValueTree& changedTree, const Identifier& changedProperty) override
  685. {
  686. if (tree == changedTree && property == changedProperty)
  687. sendChangeMessage (updateSynchronously);
  688. }
  689. void valueTreeChildAdded (ValueTree&, ValueTree&) override {}
  690. void valueTreeChildRemoved (ValueTree&, ValueTree&, int) override {}
  691. void valueTreeChildOrderChanged (ValueTree&, int, int) override {}
  692. void valueTreeParentChanged (ValueTree&) override {}
  693. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ValueTreePropertyValueSource)
  694. };
  695. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* undoManager, bool updateSynchronously)
  696. {
  697. return Value (new ValueTreePropertyValueSource (*this, name, undoManager, updateSynchronously));
  698. }
  699. //==============================================================================
  700. int ValueTree::getNumChildren() const noexcept
  701. {
  702. return object == nullptr ? 0 : object->children.size();
  703. }
  704. ValueTree ValueTree::getChild (int index) const
  705. {
  706. if (object != nullptr)
  707. if (auto* c = object->children.getObjectPointer (index))
  708. return ValueTree (*c);
  709. return {};
  710. }
  711. ValueTree::Iterator::Iterator (const ValueTree& v, bool isEnd)
  712. : internal (v.object != nullptr ? (isEnd ? v.object->children.end() : v.object->children.begin()) : nullptr)
  713. {
  714. }
  715. ValueTree::Iterator& ValueTree::Iterator::operator++()
  716. {
  717. internal = static_cast<SharedObject**> (internal) + 1;
  718. return *this;
  719. }
  720. bool ValueTree::Iterator::operator== (const Iterator& other) const { return internal == other.internal; }
  721. bool ValueTree::Iterator::operator!= (const Iterator& other) const { return internal != other.internal; }
  722. ValueTree ValueTree::Iterator::operator*() const
  723. {
  724. return ValueTree (SharedObject::Ptr (*static_cast<SharedObject**> (internal)));
  725. }
  726. ValueTree::Iterator ValueTree::begin() const noexcept { return Iterator (*this, false); }
  727. ValueTree::Iterator ValueTree::end() const noexcept { return Iterator (*this, true); }
  728. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  729. {
  730. return object != nullptr ? object->getChildWithName (type) : ValueTree();
  731. }
  732. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  733. {
  734. return object != nullptr ? object->getOrCreateChildWithName (type, undoManager) : ValueTree();
  735. }
  736. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  737. {
  738. return object != nullptr ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree();
  739. }
  740. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const noexcept
  741. {
  742. return object != nullptr && object->isAChildOf (possibleParent.object.get());
  743. }
  744. int ValueTree::indexOf (const ValueTree& child) const noexcept
  745. {
  746. return object != nullptr ? object->indexOf (child) : -1;
  747. }
  748. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* undoManager)
  749. {
  750. jassert (object != nullptr); // Trying to add a child to a null ValueTree!
  751. if (object != nullptr)
  752. object->addChild (child.object.get(), index, undoManager);
  753. }
  754. void ValueTree::appendChild (const ValueTree& child, UndoManager* undoManager)
  755. {
  756. addChild (child, -1, undoManager);
  757. }
  758. void ValueTree::removeChild (int childIndex, UndoManager* undoManager)
  759. {
  760. if (object != nullptr)
  761. object->removeChild (childIndex, undoManager);
  762. }
  763. void ValueTree::removeChild (const ValueTree& child, UndoManager* undoManager)
  764. {
  765. if (object != nullptr)
  766. object->removeChild (object->children.indexOf (child.object), undoManager);
  767. }
  768. void ValueTree::removeAllChildren (UndoManager* undoManager)
  769. {
  770. if (object != nullptr)
  771. object->removeAllChildren (undoManager);
  772. }
  773. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  774. {
  775. if (object != nullptr)
  776. object->moveChild (currentIndex, newIndex, undoManager);
  777. }
  778. //==============================================================================
  779. void ValueTree::createListOfChildren (OwnedArray<ValueTree>& list) const
  780. {
  781. if (object != nullptr)
  782. for (auto* o : object->children)
  783. if (o != nullptr)
  784. list.add (new ValueTree (*o));
  785. }
  786. void ValueTree::reorderChildren (const OwnedArray<ValueTree>& newOrder, UndoManager* undoManager)
  787. {
  788. if (object != nullptr)
  789. object->reorderChildren (newOrder, undoManager);
  790. }
  791. //==============================================================================
  792. void ValueTree::addListener (Listener* listener)
  793. {
  794. if (listener != nullptr)
  795. {
  796. if (listeners.isEmpty() && object != nullptr)
  797. object->valueTreesWithListeners.add (this);
  798. listeners.add (listener);
  799. }
  800. }
  801. void ValueTree::removeListener (Listener* listener)
  802. {
  803. listeners.remove (listener);
  804. if (listeners.isEmpty() && object != nullptr)
  805. object->valueTreesWithListeners.removeValue (this);
  806. }
  807. void ValueTree::sendPropertyChangeMessage (const Identifier& property)
  808. {
  809. if (object != nullptr)
  810. object->sendPropertyChangeMessage (property);
  811. }
  812. //==============================================================================
  813. std::unique_ptr<XmlElement> ValueTree::createXml() const
  814. {
  815. return std::unique_ptr<XmlElement> (object != nullptr ? object->createXml() : nullptr);
  816. }
  817. ValueTree ValueTree::fromXml (const XmlElement& xml)
  818. {
  819. if (! xml.isTextElement())
  820. {
  821. ValueTree v (xml.getTagName());
  822. v.object->properties.setFromXmlAttributes (xml);
  823. for (auto* e : xml.getChildIterator())
  824. v.appendChild (fromXml (*e), nullptr);
  825. return v;
  826. }
  827. // ValueTrees don't have any equivalent to XML text elements!
  828. jassertfalse;
  829. return {};
  830. }
  831. ValueTree ValueTree::fromXml (const String& xmlText)
  832. {
  833. if (auto xml = parseXML (xmlText))
  834. return fromXml (*xml);
  835. return {};
  836. }
  837. String ValueTree::toXmlString (const XmlElement::TextFormat& format) const
  838. {
  839. if (auto xml = createXml())
  840. return xml->toString (format);
  841. return {};
  842. }
  843. //==============================================================================
  844. void ValueTree::writeToStream (OutputStream& output) const
  845. {
  846. SharedObject::writeObjectToStream (output, object.get());
  847. }
  848. ValueTree ValueTree::readFromStream (InputStream& input)
  849. {
  850. auto type = input.readString();
  851. if (type.isEmpty())
  852. return {};
  853. ValueTree v (type);
  854. auto numProps = input.readCompressedInt();
  855. if (numProps < 0)
  856. {
  857. jassertfalse; // trying to read corrupted data!
  858. return v;
  859. }
  860. for (int i = 0; i < numProps; ++i)
  861. {
  862. auto name = input.readString();
  863. if (name.isNotEmpty())
  864. v.object->properties.set (name, var::readFromStream (input));
  865. else
  866. jassertfalse; // trying to read corrupted data!
  867. }
  868. auto numChildren = input.readCompressedInt();
  869. v.object->children.ensureStorageAllocated (numChildren);
  870. for (int i = 0; i < numChildren; ++i)
  871. {
  872. auto child = readFromStream (input);
  873. if (! child.isValid())
  874. return v;
  875. v.object->children.add (child.object);
  876. child.object->parent = v.object.get();
  877. }
  878. return v;
  879. }
  880. ValueTree ValueTree::readFromData (const void* data, size_t numBytes)
  881. {
  882. MemoryInputStream in (data, numBytes, false);
  883. return readFromStream (in);
  884. }
  885. ValueTree ValueTree::readFromGZIPData (const void* data, size_t numBytes)
  886. {
  887. MemoryInputStream in (data, numBytes, false);
  888. GZIPDecompressorInputStream gzipStream (in);
  889. return readFromStream (gzipStream);
  890. }
  891. void ValueTree::Listener::valueTreePropertyChanged (ValueTree&, const Identifier&) {}
  892. void ValueTree::Listener::valueTreeChildAdded (ValueTree&, ValueTree&) {}
  893. void ValueTree::Listener::valueTreeChildRemoved (ValueTree&, ValueTree&, int) {}
  894. void ValueTree::Listener::valueTreeChildOrderChanged (ValueTree&, int, int) {}
  895. void ValueTree::Listener::valueTreeParentChanged (ValueTree&) {}
  896. void ValueTree::Listener::valueTreeRedirected (ValueTree&) {}
  897. //==============================================================================
  898. #if JUCE_ALLOW_STATIC_NULL_VARIABLES
  899. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  900. JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4996)
  901. const ValueTree ValueTree::invalid;
  902. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  903. JUCE_END_IGNORE_WARNINGS_MSVC
  904. #endif
  905. //==============================================================================
  906. //==============================================================================
  907. #if JUCE_UNIT_TESTS
  908. class ValueTreeTests : public UnitTest
  909. {
  910. public:
  911. ValueTreeTests()
  912. : UnitTest ("ValueTrees", UnitTestCategories::values)
  913. {}
  914. static String createRandomIdentifier (Random& r)
  915. {
  916. char buffer[50] = { 0 };
  917. const char chars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-:";
  918. for (int i = 1 + r.nextInt (numElementsInArray (buffer) - 2); --i >= 0;)
  919. buffer[i] = chars[r.nextInt (sizeof (chars) - 1)];
  920. String result (buffer);
  921. if (! XmlElement::isValidXmlName (result))
  922. result = createRandomIdentifier (r);
  923. return result;
  924. }
  925. static String createRandomWideCharString (Random& r)
  926. {
  927. juce_wchar buffer[50] = { 0 };
  928. for (int i = r.nextInt (numElementsInArray (buffer) - 1); --i >= 0;)
  929. {
  930. if (r.nextBool())
  931. {
  932. do
  933. {
  934. buffer[i] = (juce_wchar) (1 + r.nextInt (0x10ffff - 1));
  935. }
  936. while (! CharPointer_UTF16::canRepresent (buffer[i]));
  937. }
  938. else
  939. buffer[i] = (juce_wchar) (1 + r.nextInt (0x7e));
  940. }
  941. return CharPointer_UTF32 (buffer);
  942. }
  943. static ValueTree createRandomTree (UndoManager* undoManager, int depth, Random& r)
  944. {
  945. ValueTree v (createRandomIdentifier (r));
  946. for (int i = r.nextInt (10); --i >= 0;)
  947. {
  948. switch (r.nextInt (5))
  949. {
  950. case 0: v.setProperty (createRandomIdentifier (r), createRandomWideCharString (r), undoManager); break;
  951. case 1: v.setProperty (createRandomIdentifier (r), r.nextInt(), undoManager); break;
  952. case 2: if (depth < 5) v.addChild (createRandomTree (undoManager, depth + 1, r), r.nextInt (v.getNumChildren() + 1), undoManager); break;
  953. case 3: v.setProperty (createRandomIdentifier (r), r.nextBool(), undoManager); break;
  954. case 4: v.setProperty (createRandomIdentifier (r), r.nextDouble(), undoManager); break;
  955. default: break;
  956. }
  957. }
  958. return v;
  959. }
  960. void runTest() override
  961. {
  962. {
  963. beginTest ("ValueTree");
  964. auto r = getRandom();
  965. for (int i = 10; --i >= 0;)
  966. {
  967. MemoryOutputStream mo;
  968. auto v1 = createRandomTree (nullptr, 0, r);
  969. v1.writeToStream (mo);
  970. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  971. auto v2 = ValueTree::readFromStream (mi);
  972. expect (v1.isEquivalentTo (v2));
  973. MemoryOutputStream zipped;
  974. {
  975. GZIPCompressorOutputStream zippedOut (zipped);
  976. v1.writeToStream (zippedOut);
  977. }
  978. expect (v1.isEquivalentTo (ValueTree::readFromGZIPData (zipped.getData(), zipped.getDataSize())));
  979. auto xml1 = v1.createXml();
  980. auto xml2 = v2.createCopy().createXml();
  981. expect (xml1->isEquivalentTo (xml2.get(), false));
  982. auto v4 = v2.createCopy();
  983. expect (v1.isEquivalentTo (v4));
  984. }
  985. }
  986. {
  987. beginTest ("Float formatting");
  988. ValueTree testVT ("Test");
  989. Identifier number ("number");
  990. std::map<double, String> tests;
  991. tests[1] = "1.0";
  992. tests[1.1] = "1.1";
  993. tests[1.01] = "1.01";
  994. tests[0.76378] = "0.76378";
  995. tests[-10] = "-10.0";
  996. tests[10.01] = "10.01";
  997. tests[0.0123] = "0.0123";
  998. tests[-3.7e-27] = "-3.7e-27";
  999. tests[1e+40] = "1.0e40";
  1000. tests[-12345678901234567.0] = "-1.234567890123457e16";
  1001. tests[192000] = "192000.0";
  1002. tests[1234567] = "1.234567e6";
  1003. tests[0.00006] = "0.00006";
  1004. tests[0.000006] = "6.0e-6";
  1005. for (auto& test : tests)
  1006. {
  1007. testVT.setProperty (number, test.first, nullptr);
  1008. auto lines = StringArray::fromLines (testVT.toXmlString());
  1009. lines.removeEmptyStrings();
  1010. auto numLines = lines.size();
  1011. expect (numLines > 1);
  1012. expectEquals (lines[numLines - 1], "<Test number=\"" + test.second + "\"/>");
  1013. }
  1014. }
  1015. }
  1016. };
  1017. static ValueTreeTests valueTreeTests;
  1018. #endif
  1019. } // namespace juce