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.

1258 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 == *this)
  559. return;
  560. if (source.object == nullptr)
  561. removeAllProperties (undoManager);
  562. else if (object != nullptr)
  563. object->copyPropertiesFrom (*(source.object), undoManager);
  564. }
  565. void ValueTree::copyPropertiesAndChildrenFrom (const ValueTree& source, UndoManager* undoManager)
  566. {
  567. jassert (object != nullptr || source.object == nullptr); // Trying to copy to a null ValueTree will fail!
  568. if (source == *this)
  569. return;
  570. copyPropertiesFrom (source, undoManager);
  571. removeAllChildren (undoManager);
  572. if (object != nullptr && source.object != nullptr)
  573. for (auto& child : source.object->children)
  574. object->addChild (createCopyIfNotNull (child), -1, undoManager);
  575. }
  576. bool ValueTree::hasType (const Identifier& typeName) const noexcept
  577. {
  578. return object != nullptr && object->type == typeName;
  579. }
  580. Identifier ValueTree::getType() const noexcept
  581. {
  582. return object != nullptr ? object->type : Identifier();
  583. }
  584. ValueTree ValueTree::getParent() const noexcept
  585. {
  586. if (object != nullptr)
  587. if (auto p = object->parent)
  588. return ValueTree (*p);
  589. return {};
  590. }
  591. ValueTree ValueTree::getRoot() const noexcept
  592. {
  593. if (object != nullptr)
  594. return ValueTree (object->getRoot());
  595. return {};
  596. }
  597. ValueTree ValueTree::getSibling (int delta) const noexcept
  598. {
  599. if (object != nullptr)
  600. if (auto* p = object->parent)
  601. if (auto* c = p->children.getObjectPointer (p->indexOf (*this) + delta))
  602. return ValueTree (*c);
  603. return {};
  604. }
  605. static const var& getNullVarRef() noexcept
  606. {
  607. static var nullVar;
  608. return nullVar;
  609. }
  610. const var& ValueTree::operator[] (const Identifier& name) const noexcept
  611. {
  612. return object == nullptr ? getNullVarRef() : object->properties[name];
  613. }
  614. const var& ValueTree::getProperty (const Identifier& name) const noexcept
  615. {
  616. return object == nullptr ? getNullVarRef() : object->properties[name];
  617. }
  618. var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  619. {
  620. return object == nullptr ? defaultReturnValue
  621. : object->properties.getWithDefault (name, defaultReturnValue);
  622. }
  623. const var* ValueTree::getPropertyPointer (const Identifier& name) const noexcept
  624. {
  625. return object == nullptr ? nullptr
  626. : object->properties.getVarPointer (name);
  627. }
  628. ValueTree& ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* undoManager)
  629. {
  630. return setPropertyExcludingListener (nullptr, name, newValue, undoManager);
  631. }
  632. ValueTree& ValueTree::setPropertyExcludingListener (Listener* listenerToExclude, const Identifier& name,
  633. const var& newValue, UndoManager* undoManager)
  634. {
  635. jassert (name.toString().isNotEmpty()); // Must have a valid property name!
  636. jassert (object != nullptr); // Trying to add a property to a null ValueTree will fail!
  637. if (object != nullptr)
  638. object->setProperty (name, newValue, undoManager, listenerToExclude);
  639. return *this;
  640. }
  641. bool ValueTree::hasProperty (const Identifier& name) const noexcept
  642. {
  643. return object != nullptr && object->hasProperty (name);
  644. }
  645. void ValueTree::removeProperty (const Identifier& name, UndoManager* undoManager)
  646. {
  647. if (object != nullptr)
  648. object->removeProperty (name, undoManager);
  649. }
  650. void ValueTree::removeAllProperties (UndoManager* undoManager)
  651. {
  652. if (object != nullptr)
  653. object->removeAllProperties (undoManager);
  654. }
  655. int ValueTree::getNumProperties() const noexcept
  656. {
  657. return object == nullptr ? 0 : object->properties.size();
  658. }
  659. Identifier ValueTree::getPropertyName (int index) const noexcept
  660. {
  661. return object == nullptr ? Identifier()
  662. : object->properties.getName (index);
  663. }
  664. int ValueTree::getReferenceCount() const noexcept
  665. {
  666. return object != nullptr ? object->getReferenceCount() : 0;
  667. }
  668. //==============================================================================
  669. struct ValueTreePropertyValueSource : public Value::ValueSource,
  670. private ValueTree::Listener
  671. {
  672. ValueTreePropertyValueSource (const ValueTree& vt, const Identifier& prop, UndoManager* um, bool sync)
  673. : tree (vt), property (prop), undoManager (um), updateSynchronously (sync)
  674. {
  675. tree.addListener (this);
  676. }
  677. ~ValueTreePropertyValueSource() override
  678. {
  679. tree.removeListener (this);
  680. }
  681. var getValue() const override { return tree[property]; }
  682. void setValue (const var& newValue) override { tree.setProperty (property, newValue, undoManager); }
  683. private:
  684. ValueTree tree;
  685. const Identifier property;
  686. UndoManager* const undoManager;
  687. const bool updateSynchronously;
  688. void valueTreePropertyChanged (ValueTree& changedTree, const Identifier& changedProperty) override
  689. {
  690. if (tree == changedTree && property == changedProperty)
  691. sendChangeMessage (updateSynchronously);
  692. }
  693. void valueTreeChildAdded (ValueTree&, ValueTree&) override {}
  694. void valueTreeChildRemoved (ValueTree&, ValueTree&, int) override {}
  695. void valueTreeChildOrderChanged (ValueTree&, int, int) override {}
  696. void valueTreeParentChanged (ValueTree&) override {}
  697. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ValueTreePropertyValueSource)
  698. };
  699. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* undoManager, bool updateSynchronously)
  700. {
  701. return Value (new ValueTreePropertyValueSource (*this, name, undoManager, updateSynchronously));
  702. }
  703. //==============================================================================
  704. int ValueTree::getNumChildren() const noexcept
  705. {
  706. return object == nullptr ? 0 : object->children.size();
  707. }
  708. ValueTree ValueTree::getChild (int index) const
  709. {
  710. if (object != nullptr)
  711. if (auto* c = object->children.getObjectPointer (index))
  712. return ValueTree (*c);
  713. return {};
  714. }
  715. ValueTree::Iterator::Iterator (const ValueTree& v, bool isEnd)
  716. : internal (v.object != nullptr ? (isEnd ? v.object->children.end() : v.object->children.begin()) : nullptr)
  717. {
  718. }
  719. ValueTree::Iterator& ValueTree::Iterator::operator++()
  720. {
  721. internal = static_cast<SharedObject**> (internal) + 1;
  722. return *this;
  723. }
  724. bool ValueTree::Iterator::operator== (const Iterator& other) const { return internal == other.internal; }
  725. bool ValueTree::Iterator::operator!= (const Iterator& other) const { return internal != other.internal; }
  726. ValueTree ValueTree::Iterator::operator*() const
  727. {
  728. return ValueTree (SharedObject::Ptr (*static_cast<SharedObject**> (internal)));
  729. }
  730. ValueTree::Iterator ValueTree::begin() const noexcept { return Iterator (*this, false); }
  731. ValueTree::Iterator ValueTree::end() const noexcept { return Iterator (*this, true); }
  732. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  733. {
  734. return object != nullptr ? object->getChildWithName (type) : ValueTree();
  735. }
  736. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  737. {
  738. return object != nullptr ? object->getOrCreateChildWithName (type, undoManager) : ValueTree();
  739. }
  740. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  741. {
  742. return object != nullptr ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree();
  743. }
  744. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const noexcept
  745. {
  746. return object != nullptr && object->isAChildOf (possibleParent.object.get());
  747. }
  748. int ValueTree::indexOf (const ValueTree& child) const noexcept
  749. {
  750. return object != nullptr ? object->indexOf (child) : -1;
  751. }
  752. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* undoManager)
  753. {
  754. jassert (object != nullptr); // Trying to add a child to a null ValueTree!
  755. if (object != nullptr)
  756. object->addChild (child.object.get(), index, undoManager);
  757. }
  758. void ValueTree::appendChild (const ValueTree& child, UndoManager* undoManager)
  759. {
  760. addChild (child, -1, undoManager);
  761. }
  762. void ValueTree::removeChild (int childIndex, UndoManager* undoManager)
  763. {
  764. if (object != nullptr)
  765. object->removeChild (childIndex, undoManager);
  766. }
  767. void ValueTree::removeChild (const ValueTree& child, UndoManager* undoManager)
  768. {
  769. if (object != nullptr)
  770. object->removeChild (object->children.indexOf (child.object), undoManager);
  771. }
  772. void ValueTree::removeAllChildren (UndoManager* undoManager)
  773. {
  774. if (object != nullptr)
  775. object->removeAllChildren (undoManager);
  776. }
  777. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  778. {
  779. if (object != nullptr)
  780. object->moveChild (currentIndex, newIndex, undoManager);
  781. }
  782. //==============================================================================
  783. void ValueTree::createListOfChildren (OwnedArray<ValueTree>& list) const
  784. {
  785. if (object != nullptr)
  786. for (auto* o : object->children)
  787. if (o != nullptr)
  788. list.add (new ValueTree (*o));
  789. }
  790. void ValueTree::reorderChildren (const OwnedArray<ValueTree>& newOrder, UndoManager* undoManager)
  791. {
  792. if (object != nullptr)
  793. object->reorderChildren (newOrder, undoManager);
  794. }
  795. //==============================================================================
  796. void ValueTree::addListener (Listener* listener)
  797. {
  798. if (listener != nullptr)
  799. {
  800. if (listeners.isEmpty() && object != nullptr)
  801. object->valueTreesWithListeners.add (this);
  802. listeners.add (listener);
  803. }
  804. }
  805. void ValueTree::removeListener (Listener* listener)
  806. {
  807. listeners.remove (listener);
  808. if (listeners.isEmpty() && object != nullptr)
  809. object->valueTreesWithListeners.removeValue (this);
  810. }
  811. void ValueTree::sendPropertyChangeMessage (const Identifier& property)
  812. {
  813. if (object != nullptr)
  814. object->sendPropertyChangeMessage (property);
  815. }
  816. //==============================================================================
  817. std::unique_ptr<XmlElement> ValueTree::createXml() const
  818. {
  819. return std::unique_ptr<XmlElement> (object != nullptr ? object->createXml() : nullptr);
  820. }
  821. ValueTree ValueTree::fromXml (const XmlElement& xml)
  822. {
  823. if (! xml.isTextElement())
  824. {
  825. ValueTree v (xml.getTagName());
  826. v.object->properties.setFromXmlAttributes (xml);
  827. for (auto* e : xml.getChildIterator())
  828. v.appendChild (fromXml (*e), nullptr);
  829. return v;
  830. }
  831. // ValueTrees don't have any equivalent to XML text elements!
  832. jassertfalse;
  833. return {};
  834. }
  835. ValueTree ValueTree::fromXml (const String& xmlText)
  836. {
  837. if (auto xml = parseXML (xmlText))
  838. return fromXml (*xml);
  839. return {};
  840. }
  841. String ValueTree::toXmlString (const XmlElement::TextFormat& format) const
  842. {
  843. if (auto xml = createXml())
  844. return xml->toString (format);
  845. return {};
  846. }
  847. //==============================================================================
  848. void ValueTree::writeToStream (OutputStream& output) const
  849. {
  850. SharedObject::writeObjectToStream (output, object.get());
  851. }
  852. ValueTree ValueTree::readFromStream (InputStream& input)
  853. {
  854. auto type = input.readString();
  855. if (type.isEmpty())
  856. return {};
  857. ValueTree v (type);
  858. auto numProps = input.readCompressedInt();
  859. if (numProps < 0)
  860. {
  861. jassertfalse; // trying to read corrupted data!
  862. return v;
  863. }
  864. for (int i = 0; i < numProps; ++i)
  865. {
  866. auto name = input.readString();
  867. if (name.isNotEmpty())
  868. v.object->properties.set (name, var::readFromStream (input));
  869. else
  870. jassertfalse; // trying to read corrupted data!
  871. }
  872. auto numChildren = input.readCompressedInt();
  873. v.object->children.ensureStorageAllocated (numChildren);
  874. for (int i = 0; i < numChildren; ++i)
  875. {
  876. auto child = readFromStream (input);
  877. if (! child.isValid())
  878. return v;
  879. v.object->children.add (child.object);
  880. child.object->parent = v.object.get();
  881. }
  882. return v;
  883. }
  884. ValueTree ValueTree::readFromData (const void* data, size_t numBytes)
  885. {
  886. MemoryInputStream in (data, numBytes, false);
  887. return readFromStream (in);
  888. }
  889. ValueTree ValueTree::readFromGZIPData (const void* data, size_t numBytes)
  890. {
  891. MemoryInputStream in (data, numBytes, false);
  892. GZIPDecompressorInputStream gzipStream (in);
  893. return readFromStream (gzipStream);
  894. }
  895. void ValueTree::Listener::valueTreePropertyChanged (ValueTree&, const Identifier&) {}
  896. void ValueTree::Listener::valueTreeChildAdded (ValueTree&, ValueTree&) {}
  897. void ValueTree::Listener::valueTreeChildRemoved (ValueTree&, ValueTree&, int) {}
  898. void ValueTree::Listener::valueTreeChildOrderChanged (ValueTree&, int, int) {}
  899. void ValueTree::Listener::valueTreeParentChanged (ValueTree&) {}
  900. void ValueTree::Listener::valueTreeRedirected (ValueTree&) {}
  901. //==============================================================================
  902. #if JUCE_ALLOW_STATIC_NULL_VARIABLES
  903. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  904. JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4996)
  905. const ValueTree ValueTree::invalid;
  906. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  907. JUCE_END_IGNORE_WARNINGS_MSVC
  908. #endif
  909. //==============================================================================
  910. //==============================================================================
  911. #if JUCE_UNIT_TESTS
  912. class ValueTreeTests : public UnitTest
  913. {
  914. public:
  915. ValueTreeTests()
  916. : UnitTest ("ValueTrees", UnitTestCategories::values)
  917. {}
  918. static String createRandomIdentifier (Random& r)
  919. {
  920. char buffer[50] = { 0 };
  921. const char chars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-:";
  922. for (int i = 1 + r.nextInt (numElementsInArray (buffer) - 2); --i >= 0;)
  923. buffer[i] = chars[r.nextInt (sizeof (chars) - 1)];
  924. String result (buffer);
  925. if (! XmlElement::isValidXmlName (result))
  926. result = createRandomIdentifier (r);
  927. return result;
  928. }
  929. static String createRandomWideCharString (Random& r)
  930. {
  931. juce_wchar buffer[50] = { 0 };
  932. for (int i = r.nextInt (numElementsInArray (buffer) - 1); --i >= 0;)
  933. {
  934. if (r.nextBool())
  935. {
  936. do
  937. {
  938. buffer[i] = (juce_wchar) (1 + r.nextInt (0x10ffff - 1));
  939. }
  940. while (! CharPointer_UTF16::canRepresent (buffer[i]));
  941. }
  942. else
  943. buffer[i] = (juce_wchar) (1 + r.nextInt (0x7e));
  944. }
  945. return CharPointer_UTF32 (buffer);
  946. }
  947. static ValueTree createRandomTree (UndoManager* undoManager, int depth, Random& r)
  948. {
  949. ValueTree v (createRandomIdentifier (r));
  950. for (int i = r.nextInt (10); --i >= 0;)
  951. {
  952. switch (r.nextInt (5))
  953. {
  954. case 0: v.setProperty (createRandomIdentifier (r), createRandomWideCharString (r), undoManager); break;
  955. case 1: v.setProperty (createRandomIdentifier (r), r.nextInt(), undoManager); break;
  956. case 2: if (depth < 5) v.addChild (createRandomTree (undoManager, depth + 1, r), r.nextInt (v.getNumChildren() + 1), undoManager); break;
  957. case 3: v.setProperty (createRandomIdentifier (r), r.nextBool(), undoManager); break;
  958. case 4: v.setProperty (createRandomIdentifier (r), r.nextDouble(), undoManager); break;
  959. default: break;
  960. }
  961. }
  962. return v;
  963. }
  964. void runTest() override
  965. {
  966. {
  967. beginTest ("ValueTree");
  968. auto r = getRandom();
  969. for (int i = 10; --i >= 0;)
  970. {
  971. MemoryOutputStream mo;
  972. auto v1 = createRandomTree (nullptr, 0, r);
  973. v1.writeToStream (mo);
  974. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  975. auto v2 = ValueTree::readFromStream (mi);
  976. expect (v1.isEquivalentTo (v2));
  977. MemoryOutputStream zipped;
  978. {
  979. GZIPCompressorOutputStream zippedOut (zipped);
  980. v1.writeToStream (zippedOut);
  981. }
  982. expect (v1.isEquivalentTo (ValueTree::readFromGZIPData (zipped.getData(), zipped.getDataSize())));
  983. auto xml1 = v1.createXml();
  984. auto xml2 = v2.createCopy().createXml();
  985. expect (xml1->isEquivalentTo (xml2.get(), false));
  986. auto v4 = v2.createCopy();
  987. expect (v1.isEquivalentTo (v4));
  988. }
  989. }
  990. {
  991. beginTest ("Float formatting");
  992. ValueTree testVT ("Test");
  993. Identifier number ("number");
  994. std::map<double, String> tests;
  995. tests[1] = "1.0";
  996. tests[1.1] = "1.1";
  997. tests[1.01] = "1.01";
  998. tests[0.76378] = "0.76378";
  999. tests[-10] = "-10.0";
  1000. tests[10.01] = "10.01";
  1001. tests[0.0123] = "0.0123";
  1002. tests[-3.7e-27] = "-3.7e-27";
  1003. tests[1e+40] = "1.0e40";
  1004. tests[-12345678901234567.0] = "-1.234567890123457e16";
  1005. tests[192000] = "192000.0";
  1006. tests[1234567] = "1.234567e6";
  1007. tests[0.00006] = "0.00006";
  1008. tests[0.000006] = "6.0e-6";
  1009. for (auto& test : tests)
  1010. {
  1011. testVT.setProperty (number, test.first, nullptr);
  1012. auto lines = StringArray::fromLines (testVT.toXmlString());
  1013. lines.removeEmptyStrings();
  1014. auto numLines = lines.size();
  1015. expect (numLines > 1);
  1016. expectEquals (lines[numLines - 1], "<Test number=\"" + test.second + "\"/>");
  1017. }
  1018. }
  1019. }
  1020. };
  1021. static ValueTreeTests valueTreeTests;
  1022. #endif
  1023. } // namespace juce