private void AddChildrenNodesToTreeNodeInternal(ICollection<TreeNode> childrenNodes, bool clearChildrenCollection, bool onlyInsertNew)
{
Debug.Assert(!this.AutomationElementTreeControl.InvokeRequired, "this method can run only on IUThread!");
//this is used to mark which node is new (and will be inserted) and
//which is obsolete(and will be removed)
bool[] newNodeFlags = new bool[childrenNodes.Count]; //true means new
bool[] obsoleteNodesFlags = new bool[this.TreeNode.Nodes.Count]; //true means obsolete
//lets mark all new children nodes new
for (int k = 0; k < newNodeFlags.Length; k++)
newNodeFlags[k] = true;
//lets mark all old children nodes obsolete
for (int k = 0; k < obsoleteNodesFlags.Length; k++)
obsoleteNodesFlags[k] = true;
//if we are not going to clear the collection and we have some old and some new nodes
if (!clearChildrenCollection && childrenNodes.Count > 0 && this.TreeNode.Nodes.Count > 0)
{
//lets compare old nodes with new nodes and set flags which nodes should be inserted and which
//should be removed
int i = 0;
foreach (TreeNode newNode in childrenNodes)
{
AutomationElement newElement = TreeHelper.GetNodeElement(newNode);
for (int j = 0; j < this.TreeNode.Nodes.Count; j++)
{
TreeNode oldNode = this.TreeNode.Nodes[j];
AutomationElement oldElement = TreeHelper.GetNodeElement(oldNode);
if (newElement == oldElement)
{
newNodeFlags[i] = false;
obsoleteNodesFlags[j] = false;
}
}
i++;
}
}
if (!onlyInsertNew)
{
//lets remove all obsolete nodes
for (int i = 0, j = 0; i < obsoleteNodesFlags.Length; i++, j++)
{
//i is used to iterate thru flags array
//j is used to iterate thru nodes collection
if (obsoleteNodesFlags[i] || clearChildrenCollection)
{
//this will decrement index of all nodes after j-node
this.TreeNode.Nodes[j].Remove();
j--;
}
}
}
//lets go and insert new nodes
int l = 0;
foreach (TreeNode newNode in childrenNodes)
{
if (newNodeFlags[l])
{
this.TreeNode.Nodes.Insert(Math.Max(0, Math.Min(l, this.TreeNode.Nodes.Count - 1)), newNode);
}
l++;
}
}