Briefly, my questions are:
- is it possible to change the type of a ValueTree?
- What should I do with a ValueTree that no longer points to meaningful data?
Here is a more detailed explanation:
I am writing a function which will demote this ValueTree to a grandchild position on the tree, while changing its type. It’s a bit easier to picture than to describe, so here is an XML representation:
BEFORE OPERATION:
<roottype>
<mytype property1="1" property2="2"/> // This is the element we're going to operate on.
</roottype>
AFTER OPERATION:
<roottype>
<mytype>
<newtype property1="1" property2="2"/> // operation has "moved" the element to a grandparent position, and changed its type.
</mytype>
</roottype>
Changing the type of a ValueTree seems to be more complicated than it would first appear (question 1). From what I can tell, the only way of doing it is to create a new one of the new type and then copy the properties and children across. This makes things a bit more complicated, and I’m wondering what to do with the old ValueTree once it has been copied from (question 2).
Here’s what I’ve got so far. (Note that I haven’t tested the code yet, so it might be buggy.)
void changeTypeAndMoveDown(ValueTree vtToMove&, const Identifier& newType)
{ // If this is a root ValueTree then the function isn't going to work.
jassert(vtToMove.getParent().isValid());
// We'll need to know where this ValueTree's index is in its parent.
int myIndexInParent = vtToMove.getParent().indexOf(vtToMove);
// With this information, we can remove it from its parent...
vtToMove.getParent().removeChild(myIndexInParent, nullptr);
// ...and replace it with a new ValueTree of the same type.
vtToMove.getParent().addChild(ValueTree(vtToMove.getType()), myIndexInParent, nullptr);
// We can't change the type of a ValueTree, so we'll have to create a new one...
auto movingValueTree = ValueTree(newType);
// ...and copy all of the properties and children across.
movingValueTree.copyPropertiesAndChildrenFrom(vtToMove, nullptr);
// Finally, we'll append the new ValueTree to the new child.
vtToMove.getChild(myIndexInParent).appendChild(movingValueTree, nullptr);
// Do we also need to reset the original ValueTree, since it
vtToMove = movingValueTree;
}
My question is, what should I do with vtToMove
now that its data has been copied to movingValueTree
and removed from the tree? In the example code I’m ‘resetting’ it to match the new newly created, newly typed movingValueTree
node, but I’m not sure that this is the right thing to do. If it is the right thing to do, is the old data deleted automatically, now that there aren’t any living ValueTrees pointing to it? Or should I run removeAllChildren()
and 'removeAllProperties()` first?