Sorting a ValueTree in valueTreeChildAdded() clashes with the UndoManager


#1

Hi all,

I have a parent ValueTree that contains children. They have a single property, “position”. I want the children to be sorted position-wise, so whenever a new child is added, i.e. ValueTree::Listener::valueTreeChildAdded() is fired, I sort them with a simple custom sorter.

This is OK so far. However, if I undo the operation the wrong children is removed from the parent ValueTree. I’m pretty sure this is due to the sorting operation done in valueTreeChildAdded(). If I drop that sorting, the undo performs well (but the children are obviously not sorted anymore).

The code attached below reproduces my problem. There are initially two children: child1.position=0, child2.position=1000. Then I begin an undo transaction, add another child in the middle and then I sort them: child1.position=0, child3.position=500, child2.position=1000. On undo, the expected behavior would be: child1.position=0, child2.position=1000, the actual behavior is: child1.position=0, child3.position=500.

Is sorting the ValueTree this way a bad idea?

Full code here: https://pastebin.com/LT8S832v


#2

For those interested, I managed to fix this by avoiding the sorting stage completely. In other words, instead of adding the child ValueTree at the end of its parent and then sort it, I add the child at the right position since the beginning. Instead of this:

tree.addChild(c, -1, undo);

Do this:

tree.addChild(c, [exact child index], undo);

The sorting process is now unnecessary and can be removed (and the issue is gone).

Hope it helps :wink: