#############################################################################
#
# Author: Anna Omelchenko
#
# Copyright: M. Sanner TSRI
#
#############################################################################

#
#$Header: /opt/cvs/Volume/Pvv/cursorCommands.py,v 1.1.1.1 2003/05/23 18:03:19 annao Exp $
#
#$Id: cursorCommands.py,v 1.1.1.1 2003/05/23 18:03:19 annao Exp $
#

from ViewerFramework.VFCommand import Command, CommandGUI
from mglutil.gui.InputForm.Tk.gui import InputFormDescr
from mglutil.gui.BasicWidgets.Tk.customizedWidgets import ExtendedSliderWidget
import Tkinter
try:
     from Volume.Renderers.VLI import vli
except:
     pass
volGeom = None

class VLICursor(Command):

     """Command to insert a hardware generated, software controlled
     3D cursor into the volume data set being rendered. Cross-hair and
     cross-plane types of cursor are available. The cursor type and
     location can be set using the command input form.
     The X,Y,Z cursor colors are red, green and blue, respectively.
     The cursor is not visible on the volume faces(i.e. if the cursor is
     at (0,y,z) the y, z cursor components are not visible)"""
     
     def __init__(self):
          Command.__init__(self)
          self.currentSwitch = 'off'
          self.currentValues = [0, 0, 0]
          self.isDisplayed=0
          self.cursor = None

     def checkDependencies(self):
          from Volume.Renderers.VLI import vli
          
     def onAddCmdToViewer(self):
          if not volGeom.context: return
          self.cursor = volGeom.context.GetCursor()
          
     def doit(self, *args, **kw):
          if not volGeom.context:
               print "Context has not been created"
               return
          if not self.cursor:
               self.cursor = volGeom.context.GetCursor()
          switch = kw.get('switch', self.currentSwitch)
          if switch != self.currentSwitch:
               if switch == 'off':
                    self.cursor.SetAttributes(self.cursor.kDisable)
               else:
                    self.cursor.SetAttributes(self.cursor.kEnableAll) 
                    if switch == 'Planes':
                         self.cursor.SetType(self.cursor.kPlane)
                    elif switch == 'Cross-hair':
                         self.cursor.SetType(self.cursor.kCrossHair)
               self.currentSwitch = switch
          if len(args)==3:
               self.cursor.SetPosition(args[0],args[1], args[2])
               self.currentValues[0]=args[0]
               self.currentValues[1]=args[1]
               self.currentValues[2]=args[2]
          self.vf.GUI.VIEWER.Redraw()
          
     def setupUndoBefore(self, *args, **kw):
          currval = tuple(self.currentValues)
          kw['switch'] = self.currentSwitch
          self.addUndoCall(currval, kw, self.name)
     

     def __call__(self, *args, **kw):
          """None <- Cursor(X, Y, Z, switch = cursor_type)
             None <- Cursor(switch = cursor_type)
          Create a cursor.
          X,Y,Z : cursor coordinates in object
          coordinate system values;
          switch :  cursor_type, can be
          'Planes', 'Cross-hair' or 'off'.
          """

          if len(args) >0:
               if len(args)!=3:
                    raise ValueError("three cursor coordinates required")
               if self.isDisplayed:
                    ent = self.idf.entryByName
                    if args[0] != self.currentValues[0]:
                         ent['x']['widget'].set(args[0], update=0)
                    if args[1] != self.currentValues[1]:
                         ent['y']['widget'].set(args[1], update = 0)
                    if args[2] != self.currentValues[2]:
                         ent['z']['widget'].set(args[2], update = 0)
          switch = kw.get('switch')
          if switch:
               switches = ['Planes', 'Cross-hair','off']
               if switch not in switches:
                    raise ValueError("Wrong cursor type")  
          apply( self.doitWrapper, (args), kw )
               
          
     def setSwitch(self):
         val =  self.form.checkValues()
         switch = val['switch']
         #self.currentSwitch = switch
         self.doitWrapper(switch=switch)

          
     def getValue(self,value):
          val =  self.form.checkValues()
          Xpos = val['x']
          Ypos = val['y']
          Zpos = val['z']
##            self.currentValues[1]=Xpos
##            self.currentValues[2]=Ypos
##            self.currentValues[3]=Zpos
          self.doitWrapper(Xpos, Ypos, Zpos)          

     def dismiss_cb(self):
          self.idf.form.destroy()
          self.isDisplayed=0

     def setWidth(self, value):
         if not self.cursor:
               self.cursor = volGeom.context.GetCursor()
         status = self.cursor.SetWidth(int(value))
         if status != vli.kVLIOK:
              print "status SetWidth: ", status
         self.vf.GUI.VIEWER.Redraw()

     def setLength(self, value):
         if not self.cursor:
               self.cursor = volGeom.context.GetCursor()
         status = self.cursor.SetLength(int(value))
         if status != vli.kVLIOK:
              print "status SetLength: ", status
         self.vf.GUI.VIEWER.Redraw()
        
     def guiCallback(self):
          if not volGeom.volume:
               print "volume has not been loaded"
               return
          if self.isDisplayed: return
          self.isDisplayed=1
          sizeX, sizeY, sizeZ = volGeom.volume.GetSize()
          left = 10
          right = 10
          width = 200
          cursorlength = max(sizeX, sizeY, sizeZ)
          maxwidth = cursorlength+left+right
          if width < maxwidth : width = maxwidth
          idf = self.idf = InputFormDescr(title = 'Cursor')
          idf.append({'name': 'switch',
                      'widgetType': Tkinter.Radiobutton,
                      'listtext':['off','Planes', 'Cross-hair'],
                      'direction':'col',
                      'defaultValue': self.currentSwitch,
                      'wcfg': {'command':self.setSwitch},
                      'gridcfg':{'sticky':'w'}
                      })
          
          idf.append( {'name': 'x',
                       'widgetType':ExtendedSliderWidget,
                       'type':int,
                       'wcfg':{'label': 'X Position',
                               'minval':0,'maxval':sizeX,'width':width,
                               'left':left, 'right':right,
                               'incr': 1, 'init':self.currentValues[0],
                               'labelsCursorFormat':'%d', 'sliderType':'int',
                               'command':self.getValue,
                               'immediate':1,
                               'entrypackcfg':{'side':'right'}
                               },
                       'gridcfg':{'columnspan':3,'sticky':'ew'}
                       })
          idf.append( {'name': 'y',
                       'widgetType':ExtendedSliderWidget,
                       'type':int,
                       'wcfg':{'label': 'Y Position',
                               'minval':0,'maxval':sizeY,'width':width,
                               'left':left, 'right':right,
                               'incr': 1, 'init':self.currentValues[1],
                               'labelsCursorFormat':'%d', 'sliderType':'int',
                               'command':self.getValue,
                               'immediate':1,
                               'entrypackcfg':{'side':'right'}
                               },
                       'gridcfg':{'columnspan':3,'sticky':'ew'}
                       })
          idf.append( {'name': 'z',
                       'widgetType':ExtendedSliderWidget,
                       'type':int,
                       'wcfg':{'label': 'Z Position','width':width,
                               'left':left, 'right':right,
                               'minval':0,'maxval':sizeZ,
                               'incr': 1, 'init':self.currentValues[2],
                               'labelsCursorFormat':'%d', 'sliderType':'int',
                               'command':self.getValue,
                               'immediate':1,
                               'entrypackcfg':{'side':'right'}
                               },
                       'gridcfg':{'columnspan':3,'sticky':'ew'}
                       })
          idf.append({'widgetType':Tkinter.Label,
                      'wcfg': {'text': '  '},
                      'gridcfg':{'columnspan':3, 'sticky':'ew'} })

          idf.append({'widgetType': ExtendedSliderWidget,
                      'name': 'width',
                      'wcfg':{'label': 'Set Width','width':width,
                              'left':left, 'right':right,
                              'minval':1,'maxval':7,
                              'incr': 1, 'init':1,
                              'labelsCursorFormat':'%d', 'sliderType':'int',
                              'command':self.setWidth,
                              'immediate':1,
                              'entrypackcfg':{'side':'right'}
                               },
                       'gridcfg':{'columnspan':3,'sticky':'ew'}
                       })
          idf.append({'widgetType': ExtendedSliderWidget,
                      'name':'length',
                      'wcfg':{'label': 'Set Length','width':width,
                              'left':left, 'right':right,
                              'minval':1,'maxval':cursorlength,
                              'incr': 1, 'init':cursorlength,
                              'labelsCursorFormat':'%d', 'sliderType':'int',
                              'command':self.setLength,
                              'immediate':1,
                              'entrypackcfg':{'side':'right'}
                               },
                       'gridcfg':{'columnspan':3,'sticky':'ew'}
                       })
       
          idf.append({'widgetType':Tkinter.Button,
                      'wcfg': {'text': 'Dismiss',
                               'relief' : Tkinter.RAISED,
                               'borderwidth' : 3,
                               'command':self.dismiss_cb},
                      'gridcfg':{'columnspan':3,'sticky': 'ew'}, 
                      })
          
          self.form = self.vf.getUserInput(idf, modal = 0, blocking=0)
          names = ['x', 'y', 'z','width','length']
          labelfnt = ('arial', 12, 'bold')
          numfnt = ('arial', 8, 'bold')
          for name in names:
               w = idf.entryByName[name]['widget']
               w.label.configure(font=labelfnt)
               w.draw.itemconfig(w.valueLabel, font=numfnt)


commandGUI = CommandGUI()
commandNames = {'vli': 'VLICursor', 'utvolren': None}
menuName = 'Cursor'
menuIndex = 10
commandList = [{'name':'', 'cmd':None, 'gui':commandGUI}]


def initModule(viewer):
     for dict in commandList:
          if dict['name']:
               viewer.addCommand(dict['cmd'], dict['name'], dict['gui'])




