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.

1182 lines
37KB

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