Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

juce_ValueTree.cpp 40KB

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