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.

1195 lines
38KB

  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 (auto 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 (auto 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 (auto 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 (auto 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 (auto child = Ptr (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, {}));
  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 (auto 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 (auto* c : children)
  330. writeObjectToStream (output, c);
  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 (Ptr targetObject, const Identifier& propertyName,
  349. const var& newVal, const var& oldVal, bool isAdding, bool isDeleting,
  350. ValueTree::Listener* listenerToExclude = nullptr)
  351. : target (static_cast<Ptr&&> (targetObject)),
  352. name (propertyName), newValue (newVal), oldValue (oldVal),
  353. isAddingNewProperty (isAdding), isDeletingProperty (isDeleting),
  354. excludeListener (listenerToExclude)
  355. {
  356. }
  357. bool perform() override
  358. {
  359. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  360. if (isDeletingProperty)
  361. target->removeProperty (name, nullptr);
  362. else
  363. target->setProperty (name, newValue, nullptr, excludeListener);
  364. return true;
  365. }
  366. bool undo() override
  367. {
  368. if (isAddingNewProperty)
  369. target->removeProperty (name, nullptr);
  370. else
  371. target->setProperty (name, oldValue, nullptr);
  372. return true;
  373. }
  374. int getSizeInUnits() override
  375. {
  376. return (int) sizeof (*this); //xxx should be more accurate
  377. }
  378. UndoableAction* createCoalescedAction (UndoableAction* nextAction) override
  379. {
  380. if (! (isAddingNewProperty || isDeletingProperty))
  381. {
  382. if (auto* next = dynamic_cast<SetPropertyAction*> (nextAction))
  383. if (next->target == target && next->name == name
  384. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  385. return new SetPropertyAction (*target, name, next->newValue, oldValue, false, false);
  386. }
  387. return nullptr;
  388. }
  389. private:
  390. const Ptr target;
  391. const Identifier name;
  392. const var newValue;
  393. var oldValue;
  394. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  395. ValueTree::Listener* excludeListener;
  396. JUCE_DECLARE_NON_COPYABLE (SetPropertyAction)
  397. };
  398. //==============================================================================
  399. struct AddOrRemoveChildAction : public UndoableAction
  400. {
  401. AddOrRemoveChildAction (Ptr parentObject, int index, SharedObject* newChild)
  402. : target (static_cast<Ptr&&> (parentObject)),
  403. child (newChild != nullptr ? newChild : target->children.getObjectPointer (index)),
  404. childIndex (index),
  405. isDeleting (newChild == nullptr)
  406. {
  407. jassert (child != nullptr);
  408. }
  409. bool perform() override
  410. {
  411. if (isDeleting)
  412. target->removeChild (childIndex, nullptr);
  413. else
  414. target->addChild (child.get(), childIndex, nullptr);
  415. return true;
  416. }
  417. bool undo() override
  418. {
  419. if (isDeleting)
  420. {
  421. target->addChild (child.get(), childIndex, nullptr);
  422. }
  423. else
  424. {
  425. // If you hit this, it seems that your object's state is getting confused - probably
  426. // because you've interleaved some undoable and non-undoable operations?
  427. jassert (childIndex < target->children.size());
  428. target->removeChild (childIndex, nullptr);
  429. }
  430. return true;
  431. }
  432. int getSizeInUnits() override
  433. {
  434. return (int) sizeof (*this); //xxx should be more accurate
  435. }
  436. private:
  437. const Ptr target, child;
  438. const int childIndex;
  439. const bool isDeleting;
  440. JUCE_DECLARE_NON_COPYABLE (AddOrRemoveChildAction)
  441. };
  442. //==============================================================================
  443. struct MoveChildAction : public UndoableAction
  444. {
  445. MoveChildAction (Ptr parentObject, int fromIndex, int toIndex) noexcept
  446. : parent (static_cast<Ptr&&> (parentObject)), startIndex (fromIndex), endIndex (toIndex)
  447. {
  448. }
  449. bool perform() override
  450. {
  451. parent->moveChild (startIndex, endIndex, nullptr);
  452. return true;
  453. }
  454. bool undo() override
  455. {
  456. parent->moveChild (endIndex, startIndex, nullptr);
  457. return true;
  458. }
  459. int getSizeInUnits() override
  460. {
  461. return (int) sizeof (*this); //xxx should be more accurate
  462. }
  463. UndoableAction* createCoalescedAction (UndoableAction* nextAction) override
  464. {
  465. if (auto* next = dynamic_cast<MoveChildAction*> (nextAction))
  466. if (next->parent == parent && next->startIndex == endIndex)
  467. return new MoveChildAction (parent, startIndex, next->endIndex);
  468. return nullptr;
  469. }
  470. private:
  471. const Ptr parent;
  472. const int startIndex, endIndex;
  473. JUCE_DECLARE_NON_COPYABLE (MoveChildAction)
  474. };
  475. //==============================================================================
  476. const Identifier type;
  477. NamedValueSet properties;
  478. ReferenceCountedArray<SharedObject> children;
  479. SortedSet<ValueTree*> valueTreesWithListeners;
  480. SharedObject* parent = nullptr;
  481. JUCE_LEAK_DETECTOR (SharedObject)
  482. };
  483. //==============================================================================
  484. ValueTree::ValueTree() noexcept
  485. {
  486. }
  487. JUCE_DECLARE_DEPRECATED_STATIC (const ValueTree ValueTree::invalid;)
  488. ValueTree::ValueTree (const Identifier& type) : object (new ValueTree::SharedObject (type))
  489. {
  490. jassert (type.toString().isNotEmpty()); // All objects must be given a sensible type name!
  491. }
  492. ValueTree::ValueTree (const Identifier& type,
  493. std::initializer_list<NamedValueSet::NamedValue> properties,
  494. std::initializer_list<ValueTree> subTrees)
  495. : ValueTree (type)
  496. {
  497. object->properties = NamedValueSet (std::move (properties));
  498. for (auto& tree : subTrees)
  499. addChild (tree, -1, nullptr);
  500. }
  501. ValueTree::ValueTree (SharedObject::Ptr so) noexcept : object (static_cast<SharedObject::Ptr&&> (so)) {}
  502. ValueTree::ValueTree (SharedObject& so) noexcept : object (so) {}
  503. ValueTree::ValueTree (const ValueTree& other) noexcept : object (other.object)
  504. {
  505. }
  506. ValueTree& ValueTree::operator= (const ValueTree& other)
  507. {
  508. if (object != other.object)
  509. {
  510. if (listeners.isEmpty())
  511. {
  512. object = other.object;
  513. }
  514. else
  515. {
  516. if (object != nullptr)
  517. object->valueTreesWithListeners.removeValue (this);
  518. if (other.object != nullptr)
  519. other.object->valueTreesWithListeners.add (this);
  520. object = other.object;
  521. listeners.call ([this] (Listener& l) { l.valueTreeRedirected (*this); });
  522. }
  523. }
  524. return *this;
  525. }
  526. ValueTree::ValueTree (ValueTree&& other) noexcept
  527. : object (static_cast<SharedObject::Ptr&&> (other.object))
  528. {
  529. if (object != nullptr)
  530. object->valueTreesWithListeners.removeValue (&other);
  531. }
  532. ValueTree::~ValueTree()
  533. {
  534. if (! listeners.isEmpty() && object != nullptr)
  535. object->valueTreesWithListeners.removeValue (this);
  536. }
  537. bool ValueTree::operator== (const ValueTree& other) const noexcept
  538. {
  539. return object == other.object;
  540. }
  541. bool ValueTree::operator!= (const ValueTree& other) const noexcept
  542. {
  543. return object != other.object;
  544. }
  545. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  546. {
  547. return object == other.object
  548. || (object != nullptr && other.object != nullptr
  549. && object->isEquivalentTo (*other.object));
  550. }
  551. ValueTree ValueTree::createCopy() const
  552. {
  553. if (object != nullptr)
  554. return ValueTree (*new SharedObject (*object));
  555. return {};
  556. }
  557. void ValueTree::copyPropertiesFrom (const ValueTree& source, UndoManager* undoManager)
  558. {
  559. jassert (object != nullptr || source.object == nullptr); // Trying to add properties to a null ValueTree will fail!
  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. copyPropertiesFrom (source, undoManager);
  569. removeAllChildren (undoManager);
  570. if (object != nullptr && source.object != nullptr)
  571. for (auto& child : source.object->children)
  572. object->addChild (createCopyIfNotNull (child), -1, undoManager);
  573. }
  574. bool ValueTree::hasType (const Identifier& typeName) const noexcept
  575. {
  576. return object != nullptr && object->type == typeName;
  577. }
  578. Identifier ValueTree::getType() const noexcept
  579. {
  580. return object != nullptr ? object->type : Identifier();
  581. }
  582. ValueTree ValueTree::getParent() const noexcept
  583. {
  584. if (object != nullptr)
  585. if (auto p = object->parent)
  586. return ValueTree (*p);
  587. return {};
  588. }
  589. ValueTree ValueTree::getRoot() const noexcept
  590. {
  591. if (object != nullptr)
  592. return ValueTree (object->getRoot());
  593. return {};
  594. }
  595. ValueTree ValueTree::getSibling (int delta) const noexcept
  596. {
  597. if (object != nullptr)
  598. if (auto* p = object->parent)
  599. if (auto* c = p->children.getObjectPointer (p->indexOf (*this) + delta))
  600. return ValueTree (*c);
  601. return {};
  602. }
  603. static const var& getNullVarRef() noexcept
  604. {
  605. static var nullVar;
  606. return nullVar;
  607. }
  608. const var& ValueTree::operator[] (const Identifier& name) const noexcept
  609. {
  610. return object == nullptr ? getNullVarRef() : object->properties[name];
  611. }
  612. const var& ValueTree::getProperty (const Identifier& name) const noexcept
  613. {
  614. return object == nullptr ? getNullVarRef() : object->properties[name];
  615. }
  616. var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  617. {
  618. return object == nullptr ? defaultReturnValue
  619. : object->properties.getWithDefault (name, defaultReturnValue);
  620. }
  621. const var* ValueTree::getPropertyPointer (const Identifier& name) const noexcept
  622. {
  623. return object == nullptr ? nullptr
  624. : object->properties.getVarPointer (name);
  625. }
  626. ValueTree& ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* undoManager)
  627. {
  628. return setPropertyExcludingListener (nullptr, name, newValue, undoManager);
  629. }
  630. ValueTree& ValueTree::setPropertyExcludingListener (Listener* listenerToExclude, const Identifier& name,
  631. const var& newValue, UndoManager* undoManager)
  632. {
  633. jassert (name.toString().isNotEmpty()); // Must have a valid property name!
  634. jassert (object != nullptr); // Trying to add a property to a null ValueTree will fail!
  635. if (object != nullptr)
  636. object->setProperty (name, newValue, undoManager, listenerToExclude);
  637. return *this;
  638. }
  639. bool ValueTree::hasProperty (const Identifier& name) const noexcept
  640. {
  641. return object != nullptr && object->hasProperty (name);
  642. }
  643. void ValueTree::removeProperty (const Identifier& name, UndoManager* undoManager)
  644. {
  645. if (object != nullptr)
  646. object->removeProperty (name, undoManager);
  647. }
  648. void ValueTree::removeAllProperties (UndoManager* undoManager)
  649. {
  650. if (object != nullptr)
  651. object->removeAllProperties (undoManager);
  652. }
  653. int ValueTree::getNumProperties() const noexcept
  654. {
  655. return object == nullptr ? 0 : object->properties.size();
  656. }
  657. Identifier ValueTree::getPropertyName (int index) const noexcept
  658. {
  659. return object == nullptr ? Identifier()
  660. : object->properties.getName (index);
  661. }
  662. int ValueTree::getReferenceCount() const noexcept
  663. {
  664. return object != nullptr ? object->getReferenceCount() : 0;
  665. }
  666. //==============================================================================
  667. struct ValueTreePropertyValueSource : public Value::ValueSource,
  668. private ValueTree::Listener
  669. {
  670. ValueTreePropertyValueSource (const ValueTree& vt, const Identifier& prop, UndoManager* um, bool sync)
  671. : tree (vt), property (prop), undoManager (um), updateSynchronously (sync)
  672. {
  673. tree.addListener (this);
  674. }
  675. ~ValueTreePropertyValueSource()
  676. {
  677. tree.removeListener (this);
  678. }
  679. var getValue() const override { return tree[property]; }
  680. void setValue (const var& newValue) override { tree.setProperty (property, newValue, undoManager); }
  681. private:
  682. ValueTree tree;
  683. const Identifier property;
  684. UndoManager* const undoManager;
  685. const bool updateSynchronously;
  686. void valueTreePropertyChanged (ValueTree& changedTree, const Identifier& changedProperty) override
  687. {
  688. if (tree == changedTree && property == changedProperty)
  689. sendChangeMessage (updateSynchronously);
  690. }
  691. void valueTreeChildAdded (ValueTree&, ValueTree&) override {}
  692. void valueTreeChildRemoved (ValueTree&, ValueTree&, int) override {}
  693. void valueTreeChildOrderChanged (ValueTree&, int, int) override {}
  694. void valueTreeParentChanged (ValueTree&) override {}
  695. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ValueTreePropertyValueSource)
  696. };
  697. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* undoManager, bool updateSynchronously)
  698. {
  699. return Value (new ValueTreePropertyValueSource (*this, name, undoManager, updateSynchronously));
  700. }
  701. //==============================================================================
  702. int ValueTree::getNumChildren() const noexcept
  703. {
  704. return object == nullptr ? 0 : object->children.size();
  705. }
  706. ValueTree ValueTree::getChild (int index) const
  707. {
  708. if (object != nullptr)
  709. if (auto* c = object->children.getObjectPointer (index))
  710. return ValueTree (*c);
  711. return {};
  712. }
  713. ValueTree::Iterator::Iterator (const ValueTree& v, bool isEnd)
  714. : internal (v.object != nullptr ? (isEnd ? v.object->children.end() : v.object->children.begin()) : nullptr)
  715. {
  716. }
  717. ValueTree::Iterator& ValueTree::Iterator::operator++()
  718. {
  719. internal = static_cast<SharedObject**> (internal) + 1;
  720. return *this;
  721. }
  722. bool ValueTree::Iterator::operator== (const Iterator& other) const { return internal == other.internal; }
  723. bool ValueTree::Iterator::operator!= (const Iterator& other) const { return internal != other.internal; }
  724. ValueTree ValueTree::Iterator::operator*() const
  725. {
  726. return ValueTree (SharedObject::Ptr (*static_cast<SharedObject**> (internal)));
  727. }
  728. ValueTree::Iterator ValueTree::begin() const noexcept { return Iterator (*this, false); }
  729. ValueTree::Iterator ValueTree::end() const noexcept { return Iterator (*this, true); }
  730. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  731. {
  732. return object != nullptr ? object->getChildWithName (type) : ValueTree();
  733. }
  734. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  735. {
  736. return object != nullptr ? object->getOrCreateChildWithName (type, undoManager) : ValueTree();
  737. }
  738. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  739. {
  740. return object != nullptr ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree();
  741. }
  742. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const noexcept
  743. {
  744. return object != nullptr && object->isAChildOf (possibleParent.object.get());
  745. }
  746. int ValueTree::indexOf (const ValueTree& child) const noexcept
  747. {
  748. return object != nullptr ? object->indexOf (child) : -1;
  749. }
  750. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* undoManager)
  751. {
  752. jassert (object != nullptr); // Trying to add a child to a null ValueTree!
  753. if (object != nullptr)
  754. object->addChild (child.object.get(), index, undoManager);
  755. }
  756. void ValueTree::appendChild (const ValueTree& child, UndoManager* undoManager)
  757. {
  758. addChild (child, -1, undoManager);
  759. }
  760. void ValueTree::removeChild (int childIndex, UndoManager* undoManager)
  761. {
  762. if (object != nullptr)
  763. object->removeChild (childIndex, undoManager);
  764. }
  765. void ValueTree::removeChild (const ValueTree& child, UndoManager* undoManager)
  766. {
  767. if (object != nullptr)
  768. object->removeChild (object->children.indexOf (child.object), undoManager);
  769. }
  770. void ValueTree::removeAllChildren (UndoManager* undoManager)
  771. {
  772. if (object != nullptr)
  773. object->removeAllChildren (undoManager);
  774. }
  775. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  776. {
  777. if (object != nullptr)
  778. object->moveChild (currentIndex, newIndex, undoManager);
  779. }
  780. //==============================================================================
  781. void ValueTree::createListOfChildren (OwnedArray<ValueTree>& list) const
  782. {
  783. jassert (object != nullptr);
  784. for (auto* o : object->children)
  785. {
  786. jassert (o != nullptr);
  787. list.add (new ValueTree (*o));
  788. }
  789. }
  790. void ValueTree::reorderChildren (const OwnedArray<ValueTree>& newOrder, UndoManager* undoManager)
  791. {
  792. jassert (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. XmlElement* ValueTree::createXml() const
  818. {
  819. return 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. forEachXmlChildElement (xml, e)
  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. String ValueTree::toXmlString() const
  836. {
  837. std::unique_ptr<XmlElement> xml (createXml());
  838. if (xml != nullptr)
  839. return xml->createDocument ({}, false, false);
  840. return {};
  841. }
  842. //==============================================================================
  843. void ValueTree::writeToStream (OutputStream& output) const
  844. {
  845. SharedObject::writeObjectToStream (output, object.get());
  846. }
  847. ValueTree ValueTree::readFromStream (InputStream& input)
  848. {
  849. auto type = input.readString();
  850. if (type.isEmpty())
  851. return {};
  852. ValueTree v (type);
  853. auto numProps = input.readCompressedInt();
  854. if (numProps < 0)
  855. {
  856. jassertfalse; // trying to read corrupted data!
  857. return v;
  858. }
  859. for (int i = 0; i < numProps; ++i)
  860. {
  861. auto name = input.readString();
  862. if (name.isNotEmpty())
  863. v.object->properties.set (name, var::readFromStream (input));
  864. else
  865. jassertfalse; // trying to read corrupted data!
  866. }
  867. auto numChildren = input.readCompressedInt();
  868. v.object->children.ensureStorageAllocated (numChildren);
  869. for (int i = 0; i < numChildren; ++i)
  870. {
  871. auto child = readFromStream (input);
  872. if (! child.isValid())
  873. return v;
  874. v.object->children.add (child.object);
  875. child.object->parent = v.object.get();
  876. }
  877. return v;
  878. }
  879. ValueTree ValueTree::readFromData (const void* data, size_t numBytes)
  880. {
  881. MemoryInputStream in (data, numBytes, false);
  882. return readFromStream (in);
  883. }
  884. ValueTree ValueTree::readFromGZIPData (const void* data, size_t numBytes)
  885. {
  886. MemoryInputStream in (data, numBytes, false);
  887. GZIPDecompressorInputStream gzipStream (in);
  888. return readFromStream (gzipStream);
  889. }
  890. void ValueTree::Listener::valueTreeRedirected (ValueTree&) {}
  891. //==============================================================================
  892. #if JUCE_UNIT_TESTS
  893. class ValueTreeTests : public UnitTest
  894. {
  895. public:
  896. ValueTreeTests() : UnitTest ("ValueTrees", "Values") {}
  897. static String createRandomIdentifier (Random& r)
  898. {
  899. char buffer[50] = { 0 };
  900. const char chars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-:";
  901. for (int i = 1 + r.nextInt (numElementsInArray (buffer) - 2); --i >= 0;)
  902. buffer[i] = chars[r.nextInt (sizeof (chars) - 1)];
  903. String result (buffer);
  904. if (! XmlElement::isValidXmlName (result))
  905. result = createRandomIdentifier (r);
  906. return result;
  907. }
  908. static String createRandomWideCharString (Random& r)
  909. {
  910. juce_wchar buffer[50] = { 0 };
  911. for (int i = r.nextInt (numElementsInArray (buffer) - 1); --i >= 0;)
  912. {
  913. if (r.nextBool())
  914. {
  915. do
  916. {
  917. buffer[i] = (juce_wchar) (1 + r.nextInt (0x10ffff - 1));
  918. }
  919. while (! CharPointer_UTF16::canRepresent (buffer[i]));
  920. }
  921. else
  922. buffer[i] = (juce_wchar) (1 + r.nextInt (0x7e));
  923. }
  924. return CharPointer_UTF32 (buffer);
  925. }
  926. static ValueTree createRandomTree (UndoManager* undoManager, int depth, Random& r)
  927. {
  928. ValueTree v (createRandomIdentifier (r));
  929. for (int i = r.nextInt (10); --i >= 0;)
  930. {
  931. switch (r.nextInt (5))
  932. {
  933. case 0: v.setProperty (createRandomIdentifier (r), createRandomWideCharString (r), undoManager); break;
  934. case 1: v.setProperty (createRandomIdentifier (r), r.nextInt(), undoManager); break;
  935. case 2: if (depth < 5) v.addChild (createRandomTree (undoManager, depth + 1, r), r.nextInt (v.getNumChildren() + 1), undoManager); break;
  936. case 3: v.setProperty (createRandomIdentifier (r), r.nextBool(), undoManager); break;
  937. case 4: v.setProperty (createRandomIdentifier (r), r.nextDouble(), undoManager); break;
  938. default: break;
  939. }
  940. }
  941. return v;
  942. }
  943. void runTest() override
  944. {
  945. beginTest ("ValueTree");
  946. auto r = getRandom();
  947. for (int i = 10; --i >= 0;)
  948. {
  949. MemoryOutputStream mo;
  950. auto v1 = createRandomTree (nullptr, 0, r);
  951. v1.writeToStream (mo);
  952. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  953. auto v2 = ValueTree::readFromStream (mi);
  954. expect (v1.isEquivalentTo (v2));
  955. MemoryOutputStream zipped;
  956. {
  957. GZIPCompressorOutputStream zippedOut (zipped);
  958. v1.writeToStream (zippedOut);
  959. }
  960. expect (v1.isEquivalentTo (ValueTree::readFromGZIPData (zipped.getData(), zipped.getDataSize())));
  961. std::unique_ptr<XmlElement> xml1 (v1.createXml());
  962. std::unique_ptr<XmlElement> xml2 (v2.createCopy().createXml());
  963. expect (xml1->isEquivalentTo (xml2.get(), false));
  964. auto v4 = v2.createCopy();
  965. expect (v1.isEquivalentTo (v4));
  966. }
  967. }
  968. };
  969. static ValueTreeTests valueTreeTests;
  970. #endif
  971. } // namespace juce