"""
     pygl/glevent.py: CCP4MG Molecular Graphics Program
     Copyright (C) 2001-2008 University of York, CCLRC

     This library is free software: you can redistribute it and/or
     modify it under the terms of the GNU Lesser General Public License
     version 3, modified in accordance with the provisions of the 
     license to address the requirements of UK law.
 
     You should have received a copy of the modified GNU Lesser General 
     Public License along with this library.  If not, copies may be 
     downloaded from http://www.ccp4.ac.uk/ccp4license.php
 
     This program is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     GNU Lesser General Public License for more details.
"""


import Queue
from keys import *
import time, threading

class GLEvent:

   bindings_order = ['rotate-xy','rotate-z','translate-xy','translate-z',
                     'object-rotate-xy','object-rotate-z','object-translate-xy',
                     'object-translate-z','zoom', 'clip-width','utility-1','utility-2',
                     'utility-3','utility-4' ]
   LEFT_MOTION=3       
   MIDDLE_MOTION=5    
   RIGHT_MOTION=4    
   CCP4mg_bindings = {
        'rotate-xy' : [LEFT_MOTION,0,0,''],
        'rotate-z' : [LEFT_MOTION,1,0,''],
        'translate-xy' : [MIDDLE_MOTION,0,0,''],
        'translate-z' : [MIDDLE_MOTION,0,0,'z'],
        'object-rotate-xy' : [LEFT_MOTION,0,1,''],
        'object-rotate-z' : [LEFT_MOTION,1,1,''],
        'object-translate-xy' : [MIDDLE_MOTION,0,1,''],
        'object-translate-z' : [MIDDLE_MOTION,1,1,''],
        'zoom' :  [MIDDLE_MOTION,1,0,''],
        'clip-width' :  [MIDDLE_MOTION,0,0,'h'],
        'utility-1' : [RIGHT_MOTION,0,0,''],
        'utility-2' : [RIGHT_MOTION,1,0,''],
        'utility-3' : [RIGHT_MOTION,0,1,''],
        'utility-4' : [RIGHT_MOTION,1,1,''] }
   
   Coot_bindings = {
        'rotate-xy' : [LEFT_MOTION,0,0,''],
        'rotate-z' : [RIGHT_MOTION,1,1,''],
        'translate-xy' : [LEFT_MOTION,0,1,''],
        'translate-z' : [RIGHT_MOTION,0,1,'z'],
        'object-rotate-xy' : [LEFT_MOTION,0,0,'f'],
        'object-rotate-z' : [RIGHT_MOTION,1,1,'f'],
        'object-translate-xy' : [LEFT_MOTION,0,1,'f'],
        'object-translate-z' : [RIGHT_MOTION,0,1,'f'],
        'zoom' :  [RIGHT_MOTION,0,0,''],
        'clip-width' :  [RIGHT_MOTION,0,1,''],
        'utility-1' : [RIGHT_MOTION,0,0,'z'],
        'utility-2' : [RIGHT_MOTION,0,0,'x'],
        'utility-3' : [RIGHT_MOTION,0,0,'c'],
        'utility-4' : [RIGHT_MOTION,0,0,'v'] }


   def __init__(self,glthread):
     self.glthread = glthread
     self.mods = []
     self.firstevent = 1
     self.interruptq = None
     
     #Rotate/translate via keyboard
     self.ACCELERATOR_KEY = self.glthread.SHIFT
     self.X_ROT_KEY = [key_a,key_A,key_q,key_Q]
     self.Y_ROT_KEY = [key_o,key_O,key_p,key_P]
     self.Z_ROT_KEY = [key_w,key_W,key_e,key_E]
     self.ROT_ANGLE=[1.0,3.0,-1.0,-3.0]
     self.UtilityFunction1 = self.ResizeRubberBand
     self.UtilityFunction2 = self.Dummy
     self.UtilityFunction3 = self.Dummy
     self.UtilityFunction4 = self.Dummy
     self.selected_symm = -1
 
     self.zoom_inc = 0.5

     self.set_bindings (clear=1,reset=1)

     self.create_binding_lookup()

   def create_binding_lookup (self):
     import string
     self.lookup = {}
     for action,bind in self.bindings.items():
       if not self.lookup.has_key(bind[0]):
         self.lookup[bind[0]] = {}
       if not self.lookup[bind[0]].has_key(bind[1]):
         self.lookup[bind[0]][bind[1]] = {}
       if not self.lookup[bind[0]][bind[1]].has_key(bind[2]):
         self.lookup[bind[0]][bind[1]][bind[2]] = {}
       if bind[3] != '' :
         i = string.lowercase.index(bind[3])
         self.lookup[bind[0]][bind[1]][bind[2]][97+i]=action
       else: 
         self.lookup[bind[0]][bind[1]][bind[2]][0]=action
     #print "lookup",self.lookup

   def get_bindings(self):
     pars = {}
     for key,value in self.bindings.items(): pars[key] = value
     return pars
  
   def set_bindings(self,new_bindings={},clear=0,reset=0):
     if clear: self.bindings = {}
     if reset:
       for key,value in GLEvent.CCP4mg_bindings.items():
         self.bindings[key] = value
         
     for key,value in new_bindings.items():
       self.bindings[key] = value
     self.create_binding_lookup()
     
   def registerqueue(self,jq='',interrupt=''):
     if jq: self.jq= jq
     if interrupt: self.interruptq = interrupt
     
   def registermods(self,mods):
     self.mods = mods

   def glevent(self,job):
     """
     Function to deal with keyboard/mouse events that are
     just concerned with the graphics stuff.
     """

     if job[0] == self.glthread.MENU:
         self.jobtypeold = job[0]
         xyz = job[4]
         near = job[5]
         far = job[6]
         xyzbox = job[7]
         action = job[1]
         if action == self.glthread.CENTRE_ON_PRIMITIVE:
           text_label = job[8]
           self.findprimitive(xyzbox,near,far,do_label=0,do_centre=1,text_label=text_label)
         if action == self.glthread.LABEL_PRIMITIVE:
           text_label = job[8]
           self.findprimitive(xyzbox,near,far,text_label=text_label)
         
     if job[0] == self.glthread.MOUSE:

         binfo = job[1]
         button = binfo["button"]
         state = binfo["state"]

         if(state==0):
           self.glthread.draw_simple = 1
         else:
           self.glthread.draw_simple = 0

         x = binfo["x"]
         y = binfo["y"]
         self.oldx = x
         self.oldy = y
         near = self.glthread.NEAR
         far = self.glthread.FAR
         xyzbox = binfo["xyzbox"]

         if(state==2):
           self.findprimitive(xyzbox,near,far,do_label=1,do_centre=1,do_zoom=1)

         if state == 1 and button == 2 and self.jobtypeold == job[0]:
            screenx = binfo["screenx"]
            screeny = binfo["screeny"]

            mod = self.findprimitive(xyzbox,near,far,do_label=0,do_centre=0,return_label=1)
            if mod:
              node1 = mod.line[0]
              node2 = mod.line[1]
              cmd = 'atom_picking.atom_picking.insts.post_graphics_popup(' +\
                   str(screenx)+','+str(screeny)+',"'+repr(mod)+'",' + \
                   str(node1) +',' +str(node2) +')'
              self.jq.put(['COMMAND',cmd] )
            else:
              #print "general pick"
              self.jq.put(['COMMAND', \
              'atom_picking.atom_picking.insts.post_graphics_popup('\
                   +str(screenx)+','+str(screeny)+')' ])
         elif state == 1:

            if self.jobtypeold == job[0]:
              self.findprimitive(xyzbox,near,far)

         self.jobtypeold = job[0]

     if job[0] == self.glthread.SPECIAL:
         key = job[1]
         x = job[2] 
         y = job[3]
         if self.glthread.modifiers[self.ACCELERATOR_KEY]>0:
           move = 1.0
         else:
           move = 0.1
         if key == self.glthread.keyleft:
            self.glthread.move_camera(-move,0.0,0.0)
            for mod in self.mods:
             mod.SetupSymmetry(self.glthread.rpos,self.glthread.extents)
             if mod.obj.IsAnchored():
               mod.obj.move(move,0,0)
         if key == self.glthread.keyright:
            self.glthread.move_camera(move,0.0,0.0)
            for mod in self.mods:
             mod.SetupSymmetry(self.glthread.rpos,self.glthread.extents)
             if mod.obj.IsAnchored():
               mod.obj.move(-move,0,0)
         if key == self.glthread.keyup:
            self.glthread.move_camera(0.0,-move,0.0)
            for mod in self.mods:
             mod.SetupSymmetry(self.glthread.rpos,self.glthread.extents)
             if mod.obj.IsAnchored():
               mod.obj.move(0,move,0)
         if key == self.glthread.keydown:
            self.glthread.move_camera(0.0,move,0.0)
            for mod in self.mods:
             mod.SetupSymmetry(self.glthread.rpos,self.glthread.extents)
             if mod.obj.IsAnchored():
               mod.obj.move(0,-move,0)
         self.oldx = x
         self.oldy = y
         self.jobtypeold = job[0]

     if job[0] == self.glthread.KEYBOARD:
         key = job[1]
         x = job[2] 
         y = job[3]
  
         # Rotation keys          
         if self.Z_ROT_KEY.count(key):
            rot = self.ROT_ANGLE[self.Z_ROT_KEY.index(key)]
            #if self.glthread.modifiers[self.ACCELERATOR_KEY]>0:rot=rot*3.0
            self.glthread.rotate_camera((0.0,0.0,rot))
         elif self.Y_ROT_KEY.count(key):
            rot = self.ROT_ANGLE[self.Y_ROT_KEY.index(key)]
            #if self.glthread.modifiers[self.ACCELERATOR_KEY]>0:rot=rot*3.0
            self.glthread.rotate_camera((0.0,-rot,0.0))
         elif self.X_ROT_KEY.count(key):
            rot = self.ROT_ANGLE[self.X_ROT_KEY.index(key)]
            #if self.glthread.modifiers[self.ACCELERATOR_KEY]>0:rot=rot*3.0
            self.glthread.rotate_camera((rot,0.0,0.0))

         elif key == key_esc:
            if self.interruptq: self.interruptq.put('INTERRUPT')
         elif key == key_a:
            if self.glthread.modifiers[self.glthread.ALT] > 0:
              planes = []
              planes.extend(self.glthread.get_rubber_band_planes())
              planes.extend(self.glthread.get_clipping_planes())
              self.FindPrimitivesInVolume(planes)
         elif key == key_eq:
            self.glthread.zoom_camera(-self.zoom_inc)
         elif key == key_minus:
            self.glthread.zoom_camera(self.zoom_inc)
         elif key == key_com:
            self.glthread.MoveSlab(-0.5)
            self.jq.put(['COMMAND','DT().viewmenu.handle_clip_planes(update="1")'])
         elif key == key_stop:
            self.glthread.MoveSlab(0.5)
            self.jq.put(['COMMAND','DT().viewmenu.handle_clip_planes(update="1")'])
         elif key == key_lt:
            self.glthread.ExpandSlab(-0.5)
            self.jq.put(['COMMAND','DT().viewmenu.handle_clip_planes(update="1")'])
         elif key == key_gt:
            self.glthread.ExpandSlab(0.5)
            self.jq.put(['COMMAND','DT().viewmenu.handle_clip_planes(update="1")'])
         elif key == key_m:
            self.glthread.UnDefineSlab()

         #elif key == key_M:
         #  ideally set slab to small width about focus residue
         self.oldx = x
         self.oldy = y
         self.jobtypeold = job[0]

     if job[0] == self.glthread.KEYBOARD_UP:
         key = job[1]
         x = job[2] 
         y = job[3]
         binfo = job[5]
         #print "binfo",binfo
         screenx = binfo["screenx"]
         screeny = binfo["screeny"]
         #cmd =  'COMMAND','atom_picking.atom_picking.insts.handle_keyboard_input(key='+str(key)+',xy=['+str(x)+','+str(y)+'],screen=['+str(screenx)+','+str(screeny)+'])'
         #print "glevent KEYBOARD_UP",key,x,y,screenx,screeny
         if key == key_space:
            if self.glthread.modifiers[self.glthread.SHIFT]:
              self.jq.put(['COMMAND','DT().centre.next_residue(-1)'])
            else:
              self.jq.put(['COMMAND','DT().centre.next_residue()'])
         else:
            self.jq.put(['COMMAND','atom_picking.atom_picking.insts.handle_keyboard_input(key='+str(key)+',xy=['+str(x)+','+str(y)+'],screen=['+str(screenx)+','+str(screeny)+'])'])
         self.oldx = x
         self.oldy = y
         self.jobtypeold = job[0]

     if [self.glthread.LEFT_MOTION,self.glthread.MIDDLE_MOTION,
         self.glthread.RIGHT_MOTION].count(job[0])>0:
       #print "handling", job[0], job[1]
       binfo=job[1]
       if binfo.has_key('key_presses') and binfo['key_presses'].count(1):
         k = binfo['key_presses'].index(1)
         if k<97 or k>122: k=0
       else:
         k=0
       action = ''
       shift = self.glthread.modifiers[self.glthread.SHIFT]
       ctrl = self.glthread.modifiers[self.glthread.CTRL]
       if self.lookup.has_key(job[0]):
         a1 = self.lookup[job[0]]
         if a1.has_key(shift):
           a2 = a1[shift]
           if a2.has_key(ctrl):
             a3 = a2[ctrl]
             if a3.has_key(k):
               action = a3[k]
               
       #print "action",action   
       if not action: 
         job.pop()
         return

       x = binfo["x"]
       y = binfo["y"]
       if self.firstevent > 0:
          self.firstevent = 0
          self.oldx = x
          self.oldy = y

       if action == 'rotate-xy':
          dx = binfo["dx"]
          dy = binfo["dy"]
          #print "dx,dy",dx,dy
          self.glthread.rotate_camera((dy*self.glthread.rotscaley,dx*self.glthread.rotscalex,0.0))
       elif action == 'rotate-z':
          x = binfo["x"]
          y = binfo["y"]
          dx = binfo["dx"]
          dy = binfo["dy"]
          if(x<self.glthread.win_w/3):
            self.glthread.rotate_camera((0,0,dy*self.glthread.rotscaley))
          elif(x>self.glthread.win_w*2/3):
            self.glthread.rotate_camera((0,0,-dy*self.glthread.rotscaley))
          if(y<self.glthread.win_h/3):
            self.glthread.rotate_camera((0,0,-dx*self.glthread.rotscalex))
          elif(y>self.glthread.win_h*2/3):
            self.glthread.rotate_camera((0,0,dx*self.glthread.rotscalex))
       elif action == 'translate-xy':
          dx = binfo["dx"]
          dy = binfo["dy"]
          xmove = dx*self.glthread.movescalex
          ymove = dy*self.glthread.movescaley
          zmove = 0.0
          self.glthread.move_camera(xmove,ymove,zmove)
          for mod in self.mods:
             mod.SetupSymmetry(self.glthread.rpos,self.glthread.extents)
             if mod.obj.IsAnchored(): mod.obj.move(-xmove,-ymove,-zmove)
       elif action == 'translate-z':
          xmove = 0.0
          ymove = 0.0
          zmove = binfo["dy"]
          self.glthread.move_camera(xmove,ymove,zmove)
          for mod in self.mods:
             mod.SetupSymmetry(self.glthread.rpos,self.glthread.extents)
             if mod.obj.IsAnchored(): mod.obj.move(-xmove,-ymove,-zmove)
       elif action == 'zoom':
          self.glthread.zoom_camera(-binfo["dy"])
       elif action == 'clip-width':
          delta=binfo["dy"]
          self.glthread.ExpandSlab(delta)
          self.jq.put(['COMMAND','DT().viewmenu.handle_clip_planes(update="1")'])
       elif action == 'object-rotate-xy':
          dx = binfo["dx"]
          dy = binfo["dy"]
          self.jq.put(['COMMAND', \
              '#FLUSH atom_picking.atom_picking.insts.move_object(rotx='\
                   +str(dx)+',roty='+str(dy)+')' ])

          self.mods[self.selected_model].obj.rotate(dy*self.glthread.rotscaley,-dx*self.glthread.rotscalex,0.0)
       elif action == 'object-rotate-z':
          dy = binfo["dy"]
          self.jq.put(['COMMAND', \
              '#FLUSH atom_picking.atom_picking.insts.move_object(rotz='+str(-dy)+')'])
       elif action == 'object-translate-xy':
         """
         Send signal to atom_picking.move_object for it to forward
         the request to move an object to the currently selected
         moving object
         """
         dx = binfo["dx"]
         dy = binfo["dy"]
         self.jq.put(['COMMAND', \
              '#FLUSH atom_picking.atom_picking.insts.move_object(dx='\
                   +str(dx)+',dy='+str(dy)+')' ])
       elif action == 'object-translate-z':
          dy = binfo["dy"]
          self.jq.put(['COMMAND', \
           '#FLUSH atom_picking.atom_picking.insts.move_object(dz='+str(-dy)+')'])
       elif action == 'utility-1':
         print "to utility-1"
         self.UtilityFunction1(binfo,job[0])
       elif action == 'utility-2':
         self.UtilityFunction2(binfo,job[0])
       elif action == 'utility-3':
         self.UtilityFunction3(binfo,job[0])
       elif action == 'utility-4':
         self.UtilityFunction4(binfo,job[0])

       self.oldx = x
       self.oldy = y
       self.jobtypeold = job[0]

     if job[0] == self.glthread.WHEEL_UP:
         self.jobtypeold = job[0]
         self.glthread.zoom_camera(self.zoom_inc)

     if job[0] == self.glthread.WHEEL_DOWN:
         self.jobtypeold = job[0]
         self.glthread.zoom_camera(-self.zoom_inc)

     if job[0] == self.glthread.JOYSTICK_AXIS:
        binfo = job[1]
        x = binfo["x"]
        y = binfo["y"]
        buttons = binfo["joybuttons"]
        self.glthread.rotate_camera((y*self.glthread.joyscaley,x*self.glthread.joyscalex,0.0))

     job.pop()

   def FindPrimitivesInVolume(self,planes):

      """
      Determine which primitives are inside a volume
      defined by arbitrary numbers of planes.
      """

      for mod in self.mods:
       ninbox = 0
       obj = mod.obj
       if obj.visible > 0:
          import pygl_coord
          contained_volume = pygl_coord.Volume()
          for plane in planes:
             contained_volume.AddPlane(plane)

          """
          Atom/molecule stuff should disappear ...
          """
          selected_atoms = mod.GetAtomsInVolume(contained_volume)
          print selected_atoms

          for at in selected_atoms:
             label = at.GetAtomID()[0]
             import cprim
             tl = cprim.Text(pygl_coord.Cartesian(at.x,at.y,at.z),label,pygl_coord.Cartesian(at.x,at.y,at.z))
             tl.thisown = 0 # Makes sure it isn't deleted when this function ends.
             mod.obj.add_text_primitive(tl)

          if len(selected_atoms) > 0:
            #print "rebuilding"
            obj.rebuild()

   def movetextprim(self,xyzbox,near,far,quat,dx,dy,dz):

      for i in range(len(self.mods)):
        obj = self.mods[i].obj
        if obj.visible > 0:
          neartextprim = obj.findtextprimitive(xyzbox,near,far)
          if neartextprim != None:
             break 
          else:
             return
      obj.MoveTextPrimitiveInWindowCoords(neartextprim,dx,dy,dz,quat.dval)

   def Dummy (self,binfo,jobtype):
     pass
  
   def ResizeRubberBand(self,binfo,jobtype):
      x = binfo["x"]
      y = binfo["y"]
      print "ResizeRubberBand", self.jobtypeold, jobtype
      if self.jobtypeold != jobtype:
        self.glthread.set_rubber_band_start(x,y)
      else:
        self.glthread.set_rubber_band_end(x,y)


   def findprimitive(self,xyzbox,near,far,do_label=1,do_centre=0,return_label=0,text_label="",lines=0,do_zoom=0):
      """
      Search through all models' primitives to find out which
      one has been selected.
      """

      clicked_line_dists = []

      label = ""
      if len(self.mods)<=0: return None
      for i in range(len(self.mods)):
        obj = self.mods[i].obj
        if obj.visible > 0:
         self.mods[i].GetClickedLinesAndPoints(xyzbox,near,far,self.glthread.draw_symmetry)
         clicked_line_dists.append(self.mods[i].line[2])
        else:
         clicked_line_dists.append(100000)

         
      min_dist = min(clicked_line_dists)
      #print "clicked_line_dists",clicked_line_dists,"min_dist",min_dist
      if min_dist > 0.5: return None
      clicked_line_idx = clicked_line_dists.index(min_dist)
      self.selected_model = clicked_line_idx

      mod = self.mods[clicked_line_idx]
      obj = mod.obj
      self.selected_symm  = mod.line[3]


      if return_label:
        if mod.line[2]<0.5:
          return mod
        else:
          return None
       
      if do_label == 1 or do_centre==1:
        #mod = self.findprimitive(xyzbox,near,far,do_label=0,do_centre=0,return_label=1)
        if mod.line[2]<0.5:
          node1 = mod.line[0]
          node2 = mod.line[1]

          at = mod.AddLabel(text_label)
          if at:
            cmd = 'atom_picking.atom_picking.insts.handle_application_pick("' +\
                   repr(mod)+'",'+ str(node1) +',' +str(node2) +',focus='+str(do_centre)+')'
            #print "findprimitive cmd",cmd
            self.jq.put(['COMMAND',cmd] )
          #if lines:
          #  mod.AddLineLabel()

      if do_centre == 1:
            # Need to transform coords by mod.obj.GetSymmetryMatrix(mod.line[3])            print "doing centre"
            if lines:
              """
              I think GUI pop-up somehow stops us ever getting here.
              """
              linecoords = mod.ClickedLineCoords()
              if linecoords:
                p1 = pygl_coord.Cartesian(linecoords[0][0],linecoords[0][1],linecoords[0][2])
                p2 = pygl_coord.Cartesian(linecoords[1][0],linecoords[1][1],linecoords[1][2])
                p = p1.MidPoint(p1,p2)
                self.centre_on(p.get_x(),p.get_y(),p.get_z(),obj,zoom=do_zoom)
              else:
                coords = mod.ClickedPrimitiveCoords()
                if coords:
                  self.centre_on((coords[0],coords[1],coords[2]),obj,zoom=do_zoom)
            else:
              coords = mod.ClickedPrimitiveCoords()
              if coords:
                self.centre_on((coords[0],coords[1],coords[2]),obj,zoom=do_zoom)
                
            self.selected_model = i
      else:
        obj.rebuild()


   def centre_on(self,o_in,obj=None,zoom=0,radius='',quick=0,plane=None,plane_up=None):
       x,y,z = o_in
       if self.selected_symm > -1 and obj:
          import pygl_coord
          cmat = obj.GetSymmetryMatrix(self.selected_symm)
          mat = pygl_coord.matrixPtr(cmat)
          cart = mat * pygl_coord.Cartesian(o_in)
          x = cart.get_x()
          y = cart.get_y()
          z = cart.get_z()
       if obj:
         import list
         primoriginrot = list.list(obj.rotate_point(x,y,z),3)
         oo = list.list(obj.get_origin(),3)
         position = (-oo[0]-primoriginrot[0],-oo[1]-primoriginrot[1],-oo[2]-primoriginrot[2])
       else:
         position = (-x,-y,-z)
       if threading.currentThread()._Thread__name == self.glthread._Thread__name:
         cmd = 'build.build.insts.glthread.set_camera_origin(o_in=(' + str(position[0]) + ',' + str(position[1]) + ',' + str(position[2]) + '),radius="'+str(radius)+'",zoom=' + str(zoom) + ')'
         self.jq.put(['COMMAND',cmd] )
                
       else:
         self.glthread.set_camera_origin(o_in=position,radius=radius,zoom=zoom,plane=plane,plane_up=plane_up)
       self.update_anchored(position=position)

   def update_anchored(self,position=[]):
      for mod in self.mods:
         if mod.obj.IsAnchored():
           mod.CentreOn((-position[0],-position[1],-position[2]))
           mod.build_primitives()
