Friday, December 13, 2013

Extracting tcl treeview items

I wanted to validate treeview items after doing operations on them, like add, delete. I created 2 function to extract the items and dump into a file, next i was able to compare the extracted file with the expected values

#this function dumps the 1st level in the tree to a file
proc dumpTreeDataTags { file } {
global treeControl
    set file_writer [open $file  w+]
foreach id [$treeControl item children root] {
   set data [$treeControl item tag names $id]
   puts $file_writer $data
}
    close $file_writer
}

#this function dumps all the tree data, file is appended. File must be cleared before calling this function
proc dumpAllTreeDataTags { file { item root} } {
    global treeControl
foreach id [$treeControl item children $item] {
   set file_writer [open $file  a+]
   set data [$treeControl item tag names $id]
   puts $file_writer $data
   close $file_writer
   dumpAllTreeDataTags $file $id
}
}

Explaining the functions:
The first one, i am extracting the first level only, and saving to the file, the file is opened in write mode, and replaced every time the function is called.
The second function is using recursion to iterate starting from the root node, through the children, and then calling the function again for each children, and so on. File is opened in append mode, so that when called in recursion, the previous data written to the file is not lost