# The script loads an image and compares it to a baseline
#
# Usage Arguments are:
#    -C BaselineImageToCompareWith
#    -WindowIndex n
#
# The -WindowIndex argument is optional.
#   By default the 0th render window (ie the render window displaying the axial
#   slice) is compared with the baseline. This may be overridden with
#   -WindowIndex n, which means use the nth window.. (0 Axial, 1 Sagittal, 
#       2 Coronal, 3 Volume) are the default settings.

#------------------------------------------------------
# If the input image is DICOM file, relevant DICOM tags will be printed to 
# dashboard. 

proc uniqkey { } {
     set key   [ expr { pow(2,31) + [ clock clicks ] } ]
     set key   [ string range $key end-8 end-3 ]
     set key   [ clock seconds ]$key
     return $key
}

proc sleep { ms } {
     set uniq [ uniqkey ]
     set ::__sleep__tmp__$uniq 0
     after $ms set ::__sleep__tmp__$uniq 1
     vwait ::__sleep__tmp__$uniq
     unset ::__sleep__tmp__$uniq
}


vtkVVDicomTagPrinter PrintTag
PrintTag SetFileName [lindex $argv 1] 
set dicomFile [PrintTag IsFileDicom]
if { $dicomFile } {
   PrintTag PrintTags
   }
PrintTag Delete

#------------------------------------------------------
# Load the data, take a screenshot and exit

set ApplicationName [lindex $argv 2] 
set Application [$ApplicationName ListInstances]
$Application ExitAfterLoadScriptOn
$Application PromptBeforeExitOff

set AppWindow [$Application GetNthWindow 0]

# Load the image
set imageFile [lindex $argv 1]
$AppWindow Open [lindex $argv 1]
update

$AppWindow Render
update

# Take a screenshot of all the renderwindows composed appropriately
set DataSetWidgetLayoutManager [$AppWindow GetDataSetWidgetLayoutManager]
$DataSetWidgetLayoutManager SetResolution 1 1

#----------------------------------------------------------------------------
# Organize the render widgets such that 
#       VW         IW-Coronal
#    IW-Axial    IW-Sagittal
#
set nb_widgets [$DataSetWidgetLayoutManager GetNumberOfWidgets]
if { $nb_widgets > 3 } {
  for {set i 0} {$i < $nb_widgets} {incr i} {
    set sel_frame [$DataSetWidgetLayoutManager GetNthWidget $i]
    if { $sel_frame != "" } {
      set rw [$sel_frame GetRenderWidget]
      set class [$rw GetClassName]
      if {$class == "vtkKWVolumeWidget"} {
        $DataSetWidgetLayoutManager SetWidgetPosition $sel_frame -1 -1
        $DataSetWidgetLayoutManager SetWidgetPosition $sel_frame 0 0
      }
      if {$class == "vtkKWImageWidget"} {
        set sliceOrientation [$rw GetSliceOrientationAsString]
        if {$sliceOrientation == "Axial"} {
          $DataSetWidgetLayoutManager SetWidgetPosition $sel_frame -1 -1
          $DataSetWidgetLayoutManager SetWidgetPosition $sel_frame 0 1
          $DataSetWidgetLayoutManager SelectWidget $sel_frame
        }
        if {$sliceOrientation == "Coronal"} {
          $DataSetWidgetLayoutManager SetWidgetPosition $sel_frame -1 -1
          $DataSetWidgetLayoutManager SetWidgetPosition $sel_frame 1 0
        }
        if {$sliceOrientation == "Sagittal"} {
          $DataSetWidgetLayoutManager SetWidgetPosition $sel_frame -1 -1
          $DataSetWidgetLayoutManager SetWidgetPosition $sel_frame 1 1
        }
      }
    }
  }
  $DataSetWidgetLayoutManager SetResolution 2 2
} else {
  set sel_frame [$DataSetWidgetLayoutManager GetNthWidget 0]
  if { $sel_frame != "" } {
    $DataSetWidgetLayoutManager SelectWidget $sel_frame
  }
}

sleep 2000

# Set the default w-l
set DisplayInterface [$AppWindow GetDisplayInterface]
set DataItemVolume [$AppWindow GetSelectedDataItem]

if { $dicomFile } { 
  set WindowLevelPresetSelector [$DisplayInterface GetWindowLevelPresetSelector]
  set nb_presets [$WindowLevelPresetSelector GetNumberOfPresets]
  for {set j 0} {$j < $nb_presets} {incr j} {
    set id [$WindowLevelPresetSelector GetIdOfNthPreset $j]
    if { $id >= 0 } {
      
      # Check if this is a preset for this modality
      set volume_data [$AppWindow GetSelectedDataItem]
      if { $volume_data == "" } {
        continue
      }
      set med_prop [$volume_data GetMedicalImageProperties]
      set window [$WindowLevelPresetSelector GetPresetWindow $id]
      set level  [$WindowLevelPresetSelector GetPresetLevel  $id]
      set hasPreset [$med_prop HasWindowLevelPreset $window $level]
      if {$hasPreset == 0} {
        continue
      }
      
      $DisplayInterface WindowLevelPresetApplyCallback $id 
      break
    }
  }
  }
vtkImageData Image
$DataSetWidgetLayoutManager AppendAllWidgetsToImageData Image 1

# When we save baselines as .png (vtkTesting does that), extent information
# gets lost. These are screenshots anyway, get rid of the negative extent 
# resulting from padding in AppendAllWidgetsToImageData.
set x0 [lindex [Image GetExtent] 0]
set x1 [lindex [Image GetExtent] 1]
set y0 [lindex [Image GetExtent] 2]
set y1 [lindex [Image GetExtent] 3]
set z0 [lindex [Image GetExtent] 4]
set z1 [lindex [Image GetExtent] 5]
Image SetExtent 0 [expr $x1 - $x0] 0 [expr $y1 - $y0] 0 [expr $z1 - $z0]

# Diff with baselines
for {set i 1} {$i < [expr $argc - 1]} {incr i} {
   if {[lindex $argv $i] == "-C"} {
      source [lindex $argv [expr $i + 1]]
      $Application SetExitStatus [DiffImages Image]
   }
}

Image Delete




#----------------------------------------------------------------------------
# Also Display each preset on the dashboard
if { $dicomFile } {
  for {set i 0} {$i < $nb_widgets} {incr i} {
    set sel_frame [$DataSetWidgetLayoutManager GetNthWidget $i]
    if { $sel_frame != "" } {
      set rw [$sel_frame GetRenderWidget]
      set class [$rw GetClassName]
      if {$class == "vtkKWImageWidget"} {
        set sliceOrientation [$rw GetSliceOrientationAsString]
        if {$sliceOrientation == "Axial"} {
          set selected_sel_frame [$AppWindow GetSelectedSelectionFrame]
          set sel_frame_title [$sel_frame GetTitle]
          $DataSetWidgetLayoutManager SwitchWidgetCallback $sel_frame_title $selected_sel_frame
          $DataSetWidgetLayoutManager SelectWidget $sel_frame
          $DataSetWidgetLayoutManager SelectAndMaximizeWidgetCallback $sel_frame
          $AppWindow Update

          sleep 2000
          set DisplayInterface [$AppWindow GetDisplayInterface]
          set DataItemVolume [$AppWindow GetSelectedDataItem]

          set WindowLevelPresetSelector [$DisplayInterface GetWindowLevelPresetSelector]
          set nb_presets [$WindowLevelPresetSelector GetNumberOfPresets]
          for {set j 0} {$j < $nb_presets} {incr j} {
            set id [$WindowLevelPresetSelector GetIdOfNthPreset $j]
            if { $id >= 0 } {
              
              # Check if this is a preset for this modality
              set volume_data [$AppWindow GetSelectedDataItem]
              if { $volume_data == "" } {
                continue
              }
              set med_prop [$volume_data GetMedicalImageProperties]
              set window [$WindowLevelPresetSelector GetPresetWindow $id]
              set level  [$WindowLevelPresetSelector GetPresetLevel  $id]
              set hasPreset [$med_prop HasWindowLevelPreset $window $level]
              if {$hasPreset == 0} {
                continue
              }
              
              $DisplayInterface WindowLevelPresetApplyCallback $id 
              vtkImageData wlImage
              $DataSetWidgetLayoutManager AppendAllWidgetsToImageData wlImage 1
          
              # When we save baselines as .png (vtkTesting does that), extent information
              # gets lost. These are screenshots anyway, get rid of the negative extent 
              # resulting from padding in AppendAllWidgetsToImageData.
              set wlx0 [lindex [wlImage GetExtent] 0]
              set wlx1 [lindex [wlImage GetExtent] 1]
              set wly0 [lindex [wlImage GetExtent] 2]
              set wly1 [lindex [wlImage GetExtent] 3]
              set wlz0 [lindex [wlImage GetExtent] 4]
              set wlz1 [lindex [wlImage GetExtent] 5]
              wlImage SetExtent 0 [expr $wlx1 - $wlx0] 0 [expr $wly1 - $wly0] 0 [expr $wlz1 - $wlz0]
              
              set wl_preset_comment  [$WindowLevelPresetSelector GetPresetComment $id]
              set wl_preset_filename [$WindowLevelPresetSelector GetPresetFileName $id]

              vtkVVTesting Testing 
              for {set k 1} {$k < $argc} {incr k} {
                Testing AddArgument "[lindex $argv $k]"
              }
              Testing DisplayImageOnDashboard wlImage $wl_preset_filename $wl_preset_comment
              Testing Delete
              
              wlImage Delete
            }
          }
        $DataSetWidgetLayoutManager SelectAndMaximizeWidgetCallback $sel_frame
        sleep 2000
        }
      }

      if {$class == "vtkKWVolumeWidget"} {
        set selected_sel_frame [$AppWindow GetSelectedSelectionFrame]
        set sel_frame_title [$sel_frame GetTitle]
        $DataSetWidgetLayoutManager SwitchWidgetCallback $sel_frame_title $selected_sel_frame
        $DataSetWidgetLayoutManager SelectWidget $sel_frame
        $DataSetWidgetLayoutManager SelectAndMaximizeWidgetCallback $sel_frame
        $AppWindow Update

        sleep 2000
        set DisplayInterface [$AppWindow GetDisplayInterface]
        set DataItemVolume [$AppWindow GetSelectedDataItem]

        set VolumePropertyPresetSelector [$DisplayInterface GetVolumePropertyPresetSelector]
        set nb_presets [$VolumePropertyPresetSelector GetNumberOfPresets]
        for {set j 0} {$j < $nb_presets} {incr j} {
          set id [$VolumePropertyPresetSelector GetIdOfNthPreset $j]
          if { $id >= 0 } {
            set presetVis [$VolumePropertyPresetSelector GetPresetVisibility $id]
            if {$presetVis == 0} {
              continue
            }
            if {[$VolumePropertyPresetSelector GetPresetVolumeProperty $id] == ""} {
              continue
            }
            if {[$VolumePropertyPresetSelector GetPresetThumbnail $id] == ""} {
              continue
            }
            $DisplayInterface VolumeAppearancePresetApplyCallback $id 
            vtkImageData vImage
            $DataSetWidgetLayoutManager AppendAllWidgetsToImageData vImage 1
        
            # When we save baselines as .png (vtkTesting does that), extent information
            # gets lost. These are screenshots anyway, get rid of the negative extent 
            # resulting from padding in AppendAllWidgetsToImageData.
            set vx0 [lindex [vImage GetExtent] 0]
            set vx1 [lindex [vImage GetExtent] 1]
            set vy0 [lindex [vImage GetExtent] 2]
            set vy1 [lindex [vImage GetExtent] 3]
            set vz0 [lindex [vImage GetExtent] 4]
            set vz1 [lindex [vImage GetExtent] 5]
            vImage SetExtent 0 [expr $vx1 - $vx0] 0 [expr $vy1 - $vy0] 0 [expr $vz1 - $vz0]
            
            set v_preset_comment  [$VolumePropertyPresetSelector GetPresetComment $id]
            set v_preset_filename [$VolumePropertyPresetSelector GetPresetFileName $id]

            vtkVVTesting Testing 
            for {set k 1} {$k < $argc} {incr k} {
              Testing AddArgument "[lindex $argv $k]"
            }
            Testing DisplayImageOnDashboard vImage $v_preset_filename $v_preset_comment
            Testing Delete
            
            vImage Delete
          }
        }
        $DataSetWidgetLayoutManager SelectAndMaximizeWidgetCallback $sel_frame
        sleep 2000
      }    
    }
  }
}

$Application Exit
