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.

1148 lines
36KB

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