"""
     qtgui/vectorsGui.py: CCP4MG Molecular Graphics Program
     Copyright (C) 2001-2008 University of York, CCLRC
     Copyright (C) 2009-2011 University of York

     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.
"""

from global_definitions import *
from PyQt4 import QtCore, QtGui, QtOpenGL
import MGSimpleDialog,mgWidgets,FontBrowser
import guiUtils

#-------------------------------------------------------------------
#-------------------------------------------------------------------
#-------------------------------------------------------------------
class VectorLineStyle(QtGui.QDialog):
#-------------------------------------------------------------------
#-------------------------------------------------------------------
#-------------------------------------------------------------------

  def __init__(self,parent=None,data_type='Vectors'):
    QtGui.QDialog.__init__(self,parent)
    self.data_type = data_type
    self.block_apply = 0
    self.draw()

#-------------------------------------------------------------------
  def draw(self):
#-------------------------------------------------------------------
    import mgWidgets
    import VectorsDispobj
    self.setWindowTitle(self.tr(self.data_type+' line style'))
    grid_layout = QtGui.QGridLayout()
    grid_layout.setSpacing(2)
    grid_layout.setContentsMargins(2,2,2,2)

    box = QtGui.QFrame(self)
    box.setFrameStyle(QtGui.QFrame.Box | QtGui.QFrame.Plain)
    box_layout =QtGui.QVBoxLayout()
    box_layout.addWidget(QtGui.QLabel('Vectors',self))
    line_layout =QtGui.QHBoxLayout()
    line_layout.addWidget(QtGui.QLabel('Style',self))
    self.line_style = QtGui.QComboBox(self)
    self.line_style.setEditable(0)
    self.line_style.setToolTip('Choose a drawing style for the vectors')
    for item in VectorsDispobj.VectorsDispobj.line_style_menu:
      self.line_style.addItem(item)
    line_layout.addWidget(self.line_style)
    box_layout.addLayout(line_layout)

    line_layout =QtGui.QHBoxLayout()
    line_layout.addWidget(QtGui.QLabel('Colour',self))
    self.line_colour = mgWidgets.mgColourCombo(self,browser=1)
    line_layout.addWidget(self.line_colour)
    box_layout.addLayout(line_layout)
    box_layout.addStretch(5)
    box.setLayout(box_layout)
    grid_layout.addWidget(box,0,0,1,1)

    box = QtGui.QFrame(self)
    box.setFrameStyle(QtGui.QFrame.Box | QtGui.QFrame.Plain)
    box_layout =QtGui.QVBoxLayout()
    box_layout.addWidget(QtGui.QLabel('Vector width',self))
    line_layout =QtGui.QHBoxLayout()
    line_layout.addWidget(QtGui.QLabel('Thickness (A)',self))
    self.line_width = QtGui.QSpinBox(self)
    self.line_width.setRange(1,12)
    self.line_width.setSingleStep(1)
    line_layout.addWidget(self.line_width)
    box_layout.addLayout(line_layout)

    line_layout =QtGui.QHBoxLayout()
    line_layout.addWidget(QtGui.QLabel('Cylinder radius (A)',self))
    self.cylinder_radius = QtGui.QDoubleSpinBox(self)
    self.cylinder_radius.setRange(0.1,10.0)
    self.cylinder_radius.setSingleStep(0.1)
    line_layout.addWidget(self.cylinder_radius)
    box_layout.addLayout(line_layout)
    box_layout.addStretch(5)
    box.setLayout(box_layout)
    grid_layout.addWidget(box,0,1,1,1)

    box = QtGui.QFrame(self)
    box.setFrameStyle(QtGui.QFrame.Box | QtGui.QFrame.Plain)
    box_layout =QtGui.QVBoxLayout()
    box_layout.addWidget(QtGui.QLabel('Arrow head',self))
    line_layout =QtGui.QHBoxLayout()
    line_layout.addWidget(QtGui.QLabel('At',self))
    self.arrow_head = QtGui.QComboBox(self)
    self.arrow_head.setEditable(0)
    self.arrow_head.setToolTip('Place arrow head on the vector?')
    for item in VectorsDispobj.VectorsDispobj.arrow_head_menu:
      self.arrow_head.addItem(item)
    line_layout.addWidget(self.arrow_head)
    line_layout.addWidget(QtGui.QLabel('of vector',self))
    line_layout.addStretch(5)
    box_layout.addLayout(line_layout)

    self.cone_mode = QtGui.QButtonGroup(self)
    line_layout =QtGui.QHBoxLayout()
    self.cone_mode_radius = QtGui.QRadioButton('fixed radius',self)
    self.cone_mode.addButton(self.cone_mode_radius,0)
    line_layout.addWidget(self.cone_mode_radius)
    line_layout.addStretch(5)
    self.cone_radius = QtGui.QDoubleSpinBox(self)
    self.cone_radius.setRange(0.1,10.0)
    self.cone_radius.setSingleStep(0.1)
    line_layout.addWidget(self.cone_radius)
    box_layout.addLayout(line_layout)

    line_layout =QtGui.QHBoxLayout()
    self.cone_mode_fraction = QtGui.QRadioButton('fraction of vector length',self)
    self.cone_mode.addButton(self.cone_mode_fraction,1)
    line_layout.addWidget(self.cone_mode_fraction)
    self.cone_fraction =  QtGui.QDoubleSpinBox(self)
    self.cone_fraction.setRange(0.1,1.0)
    self.cone_fraction.setSingleStep(0.05)
    line_layout.addWidget(self.cone_fraction)
    box_layout.addLayout(line_layout)
    box.setLayout(box_layout)
    grid_layout.addWidget(box,1,0,1,1)

    box = QtGui.QFrame(self)
    box.setFrameStyle(QtGui.QFrame.Box | QtGui.QFrame.Plain)
    box_layout =QtGui.QVBoxLayout()
    box_layout.addWidget(QtGui.QLabel('Dashes',self))
    self.dash_end = QtGui.QCheckBox('End with gap',self)
    box_layout.addWidget(self.dash_end)
    line_layout =QtGui.QHBoxLayout()
    line_layout.addWidget(QtGui.QLabel('Dash length',self))
    self.dash_length = QtGui.QDoubleSpinBox(self)
    self.dash_length.setRange(0.02,2.0)
    self.dash_length.setSingleStep(0.02)
    line_layout.addWidget(self.dash_length)
    box_layout.addLayout(line_layout)
    box_layout.addStretch(5)
    box.setLayout(box_layout)
    grid_layout.addWidget(box,1,1,1,1)

    box = QtGui.QFrame(self)
    box.setFrameStyle(QtGui.QFrame.Box | QtGui.QFrame.Plain)
    box_layout =QtGui.QVBoxLayout()
    box_layout.addWidget(QtGui.QLabel('Labels',self))
    line_layout =QtGui.QHBoxLayout()
    line_layout.addWidget(QtGui.QLabel('Style',self))
    self.label_mode = QtGui.QComboBox(self)
    self.label_mode.setEditable(0)
    self.label_mode.setToolTip('Choose position of labels on vectors')
    for item in VectorsDispobj.VectorsDispobj.label_mode_menu:
      self.label_mode.addItem(item)
    line_layout.addWidget(self.label_mode)
    line_layout.addStretch(5)
    line_layout.addWidget(QtGui.QLabel('Colour',self))
    self.label_colour = mgWidgets.mgColourCombo(self,browser=1)
    line_layout.addWidget(self.label_colour)
    line_layout.addStretch(5)
    box_layout.addLayout(line_layout)

    line_layout =QtGui.QHBoxLayout()
    line_layout.addWidget(QtGui.QLabel('Font',self))
    self.fontSelector = FontBrowser.MGFontSelector(self)
    line_layout.addWidget(self.fontSelector )
    box_layout.addLayout(line_layout)
    box.setLayout(box_layout)
    grid_layout.addWidget(box,2,0,1,2)

    
    dialog_buttons = QtGui.QDialogButtonBox()
    cancel_button = dialog_buttons.addButton('Close',QtGui.QDialogButtonBox.RejectRole)
    self.connect(cancel_button,QtCore.SIGNAL('clicked()'),self.close)
    grid_layout.addWidget(dialog_buttons,3,1,1,2)

    self.setLayout(grid_layout)

    self.connect(self.line_colour,QtCore.SIGNAL('currentIndexChanged(int)'),self.apply)
    self.connect(self.line_style,QtCore.SIGNAL('currentIndexChanged(int)'),self.apply)
    self.connect(self.arrow_head,QtCore.SIGNAL('currentIndexChanged(int)'),self.apply)
    self.connect(self.line_width,QtCore.SIGNAL('valueChanged(int)'),self.apply)
    self.connect(self.cylinder_radius,QtCore.SIGNAL('valueChanged(double)'),self.apply)
    self.connect(self.cone_mode,QtCore.SIGNAL('buttonClicked(int)'),self.apply)
    self.connect(self.cone_radius,QtCore.SIGNAL('valueChanged(double)'),self.apply)
    self.connect(self.cone_fraction,QtCore.SIGNAL('valueChanged(double)'),self.apply)
    self.connect(self.dash_end,QtCore.SIGNAL('stateChanged(int)'),self.apply)
    self.connect(self.dash_length,QtCore.SIGNAL('valueChanged(double)'),self.apply)
    self.connect(self.label_colour,QtCore.SIGNAL('currentIndexChanged(int)'),self.apply)
    self.connect(self.label_mode,QtCore.SIGNAL('currentIndexChanged(int)'),self.apply)
    self.connect(self.fontSelector,QtCore.SIGNAL('fontChanged'),self.applyFont)
    return 0

#----------------------------------------------------------------------
  def apply(self,args):
#----------------------------------------------------------------------
    if self.block_apply: return
    self.emit(QtCore.SIGNAL('changed'),('style'))

#----------------------------------------------------------------------
  def applyFont(self,widget):
#----------------------------------------------------------------------
    if self.block_apply: return
    self.emit(QtCore.SIGNAL('changed'),('font'))

#----------------------------------------------------------------------
  def setParams(self,params):
#----------------------------------------------------------------------
    import VectorsDispobj
    #print 'VectorLineStyle.setParams',params
    self.block_apply = 1
    if params.has_key('line_colour'):
      self.line_colour.set_colour(params['line_colour'])
    if params.has_key('line_style') and VectorsDispobj.VectorsDispobj.line_style_menu.count(params['line_style']):
      self.line_style.setCurrentIndex(VectorsDispobj.VectorsDispobj.line_style_menu.index(params['line_style']))
    if params.has_key('arrow_head') and VectorsDispobj.VectorsDispobj.arrow_head_menu.count(params['arrow_head']):
      self.arrow_head.setCurrentIndex(VectorsDispobj.VectorsDispobj.arrow_head_menu.index(params['arrow_head']))
    if params.has_key('line_width'):
      self.line_width.setValue(int(params['line_width']))
    if params.has_key('cylinder_radius'):
      self.cylinder_radius.setValue(float(params['cylinder_radius']))
    if params.has_key('cone_mode'):
      if params['cone_mode']=='fraction':
        self.cone_mode_fraction.setChecked(1)
        self.cone_mode_radius.setChecked(0)
      else:
        self.cone_mode_radius.setChecked(1)
        self.cone_mode_fraction.setChecked(0)
    if params.has_key('cone_radius'):
      self.cone_radius.setValue(float(params['cone_radius']))
    if params.has_key('cone_fraction'):
      self.cone_fraction.setValue(float(params['cone_fraction']))
    if params.has_key('dash_end'):
      self.dash_end.setChecked(params['dash_end']=='gap')
    if params.has_key('dash_length'):
      self.dash_length.setValue(float(params['dash_length']))
    if params.has_key('label_colour'):
      self.label_colour.set_colour(params['label_colour'])
    if params.has_key('label_mode') and VectorsDispobj.VectorsDispobj.label_mode_menu.count(params['label_mode']):
      self.label_mode.setCurrentIndex(VectorsDispobj.VectorsDispobj.label_mode_menu.index(params['label_mode']))

      if params.has_key('font'): self.fontSelector.setParams(params['font'])
    self.block_apply = 0
    
#----------------------------------------------------------------------
  def getParams(self):
#----------------------------------------------------------------------
    pars = {}
    import VectorsDispobj
    pars['line_colour'] = self.line_colour.get_colour()
    pars['line_style'] = VectorsDispobj.VectorsDispobj.line_style_menu[self.line_style.currentIndex()]
    pars['line_width'] = int(self.line_width.value())
    pars['cylinder_radius'] = float(self.cylinder_radius.value())
    pars['arrow_head'] = VectorsDispobj.VectorsDispobj.arrow_head_menu[self.arrow_head.currentIndex()]
    pars['cone_mode'] = ['fixed','fraction'][self.cone_mode.checkedId()]
    pars['cone_radius'] = float(self.cone_radius.value())
    pars['cone_fraction'] = float(self.cone_fraction.value())
    pars['dash_end'] = ['dash','gap'][int(self.dash_end.isChecked())]
    pars['dash_length'] = float(self.dash_length.value())
    pars['label_colour'] = self.label_colour.get_colour()
    pars['label_mode'] = VectorsDispobj.VectorsDispobj.label_mode_menu[self.label_mode.currentIndex()]

    pars.update(self.fontSelector.getParams())
    return pars


#----------------------------------------------------------------------
  def getFont(self):
#----------------------------------------------------------------------
    return self.fontSelector.getParams()
  
#-------------------------------------------------------------------
#-------------------------------------------------------------------
#-------------------------------------------------------------------
class VectorSelection(QtGui.QDialog):
#-------------------------------------------------------------------
#-------------------------------------------------------------------
#-------------------------------------------------------------------

  def __init__(self,parent=None,VectorsDataName=''):
    QtGui.QDialog.__init__(self,parent)
    self.setWindowTitle('Select vectors by tags')
    self.VectorsDataName = VectorsDataName

    self.contents = QtGui.QFrame(self)
    layout = QtGui.QVBoxLayout()
    self.contents.setLayout(layout)
    self.load()
    
    d_layout = QtGui.QVBoxLayout()
    scrollarea = QtGui.QScrollArea()
    d_layout.addWidget(scrollarea)
    scrollarea.setWidget(self.contents)
    scrollarea.setWidgetResizable(1) 
    scrollarea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)

    dialog_buttons = QtGui.QDialogButtonBox()
    apply_button = dialog_buttons.addButton(QtGui.QDialogButtonBox.Apply)
    all_button = dialog_buttons.addButton('Select all',QtGui.QDialogButtonBox.ActionRole)
    clear_button = dialog_buttons.addButton('Clear',QtGui.QDialogButtonBox.ActionRole)
    cancel_button = dialog_buttons.addButton(QtGui.QDialogButtonBox.Cancel)
    d_layout.addWidget(dialog_buttons)
    
    self.setLayout(d_layout)
    self.connect(apply_button,QtCore.SIGNAL('clicked()'),self.apply)
    self.connect(all_button,QtCore.SIGNAL('clicked()'),guiUtils.partial(self.select,'all'))
    self.connect(clear_button,QtCore.SIGNAL('clicked()'),guiUtils.partial(self.select,'clear'))   
    self.connect(cancel_button,QtCore.SIGNAL('clicked()'),self.close)

#----------------------------------------------------------------------
  def load(self):
#----------------------------------------------------------------------
    dobj = data(self.VectorsDataName)
    if not dobj: return

    current = self.contents.findChildren(QtGui.QCheckBox)
    #for widget in current: widget.deleteLater()
    for widget in current: widget.close()

    #print 'VectorSelection.load', dobj.taglist
    tagList = dobj.getTagList()
    for tag in tagList:
      widget = QtGui.QCheckBox(tag,self)
      widget.setObjectName(tag)
      self.contents.layout().addWidget(widget)

#----------------------------------------------------------------------
  def select(self,mode='all'):
#----------------------------------------------------------------------
    if mode == 'all':
      checked = 1
    else:
      checked = 0
    current = self.contents.findChildren(QtGui.QCheckBox)
    for widget in current:widget.setChecked(checked)

    self.apply()
    
#----------------------------------------------------------------------
  def setSelection(self,selection=[]):
#----------------------------------------------------------------------
    if selection == 'all':
      self.select('all')
    else:
      current = self.contents.findChildren(QtGui.QCheckBox)
      for widget in current:
        if selection.count(str(widget.objectName())):
          widget.setChecked(1)
        else:
          widget.setChecked(0)

#----------------------------------------------------------------------
  def getSelection(self):
#----------------------------------------------------------------------
    selection = []
    current = self.contents.findChildren(QtGui.QCheckBox)
    for widget in current:
      if widget.isChecked(): selection.append(str(widget.objectName()))
    return selection
  
#----------------------------------------------------------------------
  def apply(self):
#----------------------------------------------------------------------
    self.emit(QtCore.SIGNAL('changed'))
    

#----------------------------------------------------------------------
#----------------------------------------------------------------------
#----------------------------------------------------------------------
class editVectorDialog(MGSimpleDialog.MGSimpleDialog):
#----------------------------------------------------------------------
#----------------------------------------------------------------------
#----------------------------------------------------------------------

        def __init__(self,parent=None,VectorsDataName='',mode=['atom','atom'],vectorId=-1):
                MGSimpleDialog.MGSimpleDialog.__init__(self,parent)
                self.VectorsDataName = VectorsDataName
                self.mode = mode
                self.vectorId=-1
		self.setWindowTitle("Edit vectors "+VectorsDataName)
                self.editTagWidget = None
                
		layout = QtGui.QVBoxLayout(self)
                layout.setSpacing(2)
                layout.setContentsMargins(2,2,2,2)
                
                self.selectVector= QtGui.QListWidget(self)
                self.selectVector.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
                self.connect(self.selectVector,QtCore.SIGNAL('currentRowChanged(int)'),self.setVectorId)
                self.loadSelectVector()


                if self.mode[0] == 'point':
                  move_frame = QtGui.QFrame()
                  line_layout = QtGui.QHBoxLayout()
                  self.move = QtGui.QCheckBox('Move vector interactively:',self)
                  self.move.setToolTip('Move vector by holding down x key and middle mouse button')
                  line_layout.addWidget(self.move)
                  line_layout.addStretch(5)
                  self.move_mode =  QtGui.QButtonGroup(self)
                  self.move_mode.setExclusive(1)
                  # button id is same as VectorsData.transform_mode code
                  bid = 1
                  for item in ['whole vector','start point','end point']:
                    b = QtGui.QRadioButton(item,self)
                    self.move_mode.addButton(b,bid)
                    bid = bid+1
                    line_layout.addWidget(b)
                  self.move_mode.button(data(self.VectorsDataName).getTransformMode()).setChecked(1)
                  line_layout.addStretch(5)
                  move_frame.setLayout(line_layout)
                  self.connect(self.move_mode,QtCore.SIGNAL('buttonReleased(int)'),self.handleMoveMode)
                  self.connect(self.move,QtCore.SIGNAL('stateChanged(int)'),self.handleMove)


                #edit_button = QtGui.QPushButton('Edit selected vector',self)
                #self.connect(edit_button,QtCore.SIGNAL('clicked()'),self.resetEditVector)
                delete_button = QtGui.QPushButton('Delete selected vector',self)
                self.connect(delete_button,QtCore.SIGNAL('clicked()'),self.deleteVector)
                new_button = QtGui.QPushButton('Create new vector',self)
                self.connect(new_button,QtCore.SIGNAL('clicked()'),self.handleNew)

                editLayout= QtGui.QGridLayout()
                editLayout.addWidget(self.selectVector,0,0,2,1)
                #editLayout.addWidget(edit_button,0,1)
                editLayout.addWidget(new_button,0,1)
                editLayout.addWidget(delete_button,1,1)
                layout.addLayout(editLayout)
                if self.mode[0] == 'point': layout.addWidget(move_frame)

        	dialog_buttons = QtGui.QDialogButtonBox()
		ok_button = dialog_buttons.addButton('Save vector and close',QtGui.QDialogButtonBox.AcceptRole)
		apply_button = dialog_buttons.addButton('Save vector',QtGui.QDialogButtonBox.ActionRole)
		cancel_button = dialog_buttons.addButton('Close',QtGui.QDialogButtonBox.RejectRole)
		help_button = dialog_buttons.addButton('Help',QtGui.QDialogButtonBox.HelpRole)
                for button in [ok_button,apply_button,cancel_button,help_button]: button.setAutoDefault(0)
		self.connect(cancel_button,QtCore.SIGNAL('clicked()'),self.Close)
		self.connect(apply_button,QtCore.SIGNAL('clicked()'),self.Apply)
		self.connect(ok_button,QtCore.SIGNAL('clicked()'),self.ApplyAndClose)
		self.connect(help_button,QtCore.SIGNAL('clicked()'),self.Help)

		startLabel = QtGui.QLabel(self.tr("Start point"))
		endLabel = QtGui.QLabel(self.tr("End point"))

                if 0:
		  startButtonGroup = QtGui.QButtonGroup(self)
		  endButtonGroup = QtGui.QButtonGroup(self)

		  self.startAtomRadio = QtGui.QRadioButton("Atom")
		  self.startCartesianRadio = QtGui.QRadioButton("Point")
		  startButtonGroup.addButton(self.startAtomRadio)
		  startButtonGroup.addButton(self.startCartesianRadio)

		  self.endAtomRadio = QtGui.QRadioButton("Atom")
		  self.endCartesianRadio = QtGui.QRadioButton("Point")
		  endButtonGroup.addButton(self.endAtomRadio)
		  endButtonGroup.addButton(self.endCartesianRadio)

		  self.connect(self.startAtomRadio,QtCore.SIGNAL("toggled(bool)"),self.setWidgetsEnabledStates)
		  self.connect(self.endAtomRadio,QtCore.SIGNAL("toggled(bool)"),self.setWidgetsEnabledStates)
		  self.connect(self.startCartesianRadio,QtCore.SIGNAL("toggled(bool)"),self.setWidgetsEnabledStates)
		  self.connect(self.endCartesianRadio,QtCore.SIGNAL("toggled(bool)"),self.setWidgetsEnabledStates)
		  self.startCartesianRadio.setChecked(1)
		  self.endCartesianRadio.setChecked(1)
		#try:
		#	self.connect(DISPLAYTABLE(),QtCore.SIGNAL("DisplayTableChanged"),self.handleDTChanged)
		#	print "done connection"
		#except:
		#	print "failed connection"

		pickerLayout = QtGui.QGridLayout()
		pickerLayout.addWidget(startLabel,0,0)
                
                if self.mode[0] == 'atom':
		  self.startAtomPicker =  mgWidgets.mgAtomPicker()
                  pickerLayout.addWidget(self.startAtomPicker,1,0)
                elif self.mode[0] == 'point':
                  self.startCartesianPicker =  mgWidgets.CartesianPicker(x=0.0,y=0.0,z=0.0)
		  pickerLayout.addWidget(self.startCartesianPicker,1,0)

                pickerLayout.addWidget(endLabel,2,0)
                if  self.mode[1] == 'atom':
		  self.endAtomPicker =  mgWidgets.mgAtomPicker()
                  pickerLayout.addWidget(self.endAtomPicker,3,0)
                elif self.mode[0] == 'point':
		  self.endCartesianPicker =  mgWidgets.CartesianPicker(x=1.0,y=0.0,z=0.0)
                  pickerLayout.addWidget(self.endCartesianPicker,3,0)

		layout.addLayout(pickerLayout)

                    

                line_layout = QtGui.QHBoxLayout()
                line_layout.addWidget(QtGui.QLabel('Add vector to group',self))
                self.tag = QtGui.QComboBox(self)
                self.tag.setMinimumContentsLength(20)
                self.tag.setEditable(1)
                self.loadTags()
                line_layout.addWidget(self.tag)
                edit_tag = QtGui.QPushButton('Group details',self)
                self.connect(edit_tag,QtCore.SIGNAL('clicked()'),self.editTags)
                line_layout.addWidget(edit_tag)
                layout.addLayout(line_layout)
                                
		editLabel = QtGui.QLabel(self.tr("Vector annotation"))
		import TextEdit
		self.editor = TextEdit.TextEditWidget()
		layout.addWidget(editLabel)
		layout.addWidget(self.editor)

		layout.addWidget(dialog_buttons)

                self.setVectorId(vectorId)

		self.setWindowFlags(QtCore.Qt.Dialog)
		#self.setModal(0)
		self.setLayout(layout)
		self.setSizeGripEnabled(0)
		self.CreateMenuEntry()


        def handleNew(self):
          self.setVectorId(-1)
          
	def handleDTChanged(self):
          self.startAtomPicker.dataCombo.clear()
          self.endAtomPicker.dataCombo.clear()
          self.startAtomPicker.dataCombo.populateMenu(object_type='MolData',parent=self.startAtomPicker)
          self.endAtomPicker.dataCombo.populateMenu(object_type='MolData',parent=self.endAtomPicker)

	def Apply(self):
          saveId = self.getVectorId()
          iV = data(self.VectorsDataName).set_vector_data(saveId,self.getParams())
          #print 'Apply initial vectorId',self.vectorId
          # Should have return index number of edited vector
          if iV>=0:
            self.redraw()
            self.loadSelectVector()
            self.loadTags()
            # Refresh
            self.setVectorId(saveId)

        def Help(self):
          HELPBROWSER().loadMgHelp('vector.html')
            
        def redraw(self):
            import rebuild
            rebuild.UpdateDisplay()
          
            
        def loadSelectVector(self):
          
          self.selectVector.blockSignals(True)
          vector_list = data(self.VectorsDataName).getVectorMenu()
          self.selectVector.clear()
          for item in vector_list:
            self.selectVector.addItem(item)
          self.selectVector.addItem('New vector.. ')
          self.selectVector.blockSignals(False)

        def deleteVector(self):
          iV = self.selectVector.currentRow()
          if iV>=0 and iV<(self.selectVector.count()-1):
            data(self.VectorsDataName).delete_vector(iV)
            self.redraw()
            self.loadSelectVector()
            self.setVectorId(iV)
            
             

        def setParams(self,params,**kw):
          #print 'setParams',params,self.mode
          params.update(kw)
          if self.mode[0]=='atom':
            if params.has_key('start_mol') and params.has_key('start_atom'):
              if params['start_mol'] and params['start_atom']:
                self.startAtomPicker.setSelection(MolData=params['start_mol'],atomName=params['start_atom'])
              else:
                self.startAtomPicker.reset()
                
          elif self.mode[0]=='point':
            if params.has_key('start_xyz'):
              pars = {}
              ii = 0
              for item in 'x','y','z':
                pars[item] = params['start_xyz'][ii]
                ii = ii + 1
              self.startCartesianPicker.setParams(pars)
            
          if self.mode[1]=='atom':
            if params.has_key('end_mol') and params.has_key('end_atom'):
              if params['end_mol'] and params['end_atom']:
                self.endAtomPicker.setSelection(MolData=params['end_mol'],atomName=params['end_atom'])
              else:
                self.endAtomPicker.reset()
          elif self.mode[1]=='point':
            if params.has_key('end_xyz'):
              pars = {}
              ii = 0
              for item in 'x','y','z':
                pars[item] = params['end_xyz'][ii]
                ii = ii + 1
              self.endCartesianPicker.setParams(pars)
              
          if params.has_key('tag'):
            import types
            if isinstance(params['tag'],types.StringType):
              iT = data(self.VectorsDataName).getTagList().count(params['tag'])
              self.tag.setCurrentIndex(iT)
            else:
              #print 'setting tag',params['tag']
              self.tag.setCurrentIndex(params['tag'])
              
          # Set the label
          if params.has_key('label'):
            self.editor.setText(params['label'])

            
        def getParams(self):
          startx=starty=startz=0.0
          endx=endy=endz=0.0
          startAtom=endAtom=startModel=endModel=None
          
          if self.mode[0]=='atom':
            startModel,startAtom=self.startAtomPicker.modelAtomPtr()
          elif self.mode[0]=='point':
            startx = float(self.startCartesianPicker.widgets["x"].text())
            starty = float(self.startCartesianPicker.widgets["y"].text())
            startz = float(self.startCartesianPicker.widgets["z"].text())
          if self.mode[1]=='atom': 
            endModel,endAtom=self.endAtomPicker.modelAtomPtr()
          elif self.mode[1] == 'point':
            endx = float(self.endCartesianPicker.widgets["x"].text())
            endy = float(self.endCartesianPicker.widgets["y"].text())
            endz = float(self.endCartesianPicker.widgets["z"].text())

        
          return {
              "start_xyz" : [startx,starty,startz],
              "end_xyz" :[endx,endy,endz],
              "start_atom" : startAtom,
              "end_atom" : endAtom,
              "start_mol" : startModel,
              "end_mol" : endModel,
              "label" : str(self.editor.textEdit.toPlainText()),
              "tag" : str(self.tag.currentText()) }

        def loadTags(self):
          #print 'loadTags'
          self.tag.clear()
          self.tag.addItem(' ')
          for label in data(self.VectorsDataName).getTagList():
            self.tag.addItem(label)


        def editTags(self):
          if not self.editTagWidget:
            self.editTagWidget = editVectorTags(self,self.VectorsDataName)
            self.connect( self.editTagWidget,QtCore.SIGNAL('changed'),self.handleChangedTags)
          self.editTagWidget.show()

        def handleChangedTags(self):
          self.loadTags()
          self.loadSelectVector()

        def getVectorId(self):
          return self.vectorId
            
        def setVectorId(self,vid):
          #print 'setVectorId vid',vid
          if vid<0 or vid>=self.selectVector.count()-1:
            # Out of range so set to 'new' vector
            self.setRow(self.selectVector.count()-1)
            import VectorsDispobj
            self.setParams(VectorsDispobj.VectorsData.initialise_vector)
            self.vectorId = -1
          else:
            self.setRow(vid)
            self.setParams(data(self.VectorsDataName).get_vector_data(vid))
            self.vectorId = vid
          data(self.VectorsDataName).setTransformVector(self.vectorId)

        def setRow(self,irow):
          if irow == self.selectVector.currentRow(): return
          self.selectVector.blockSignals(True)
          self.selectVector.setCurrentRow(irow)
          self.selectVector.blockSignals(False)
            
          
	def ApplyAndClose(self):
		self.Apply()
		self.Close()

        def handleMoveMode(self,bid):
          data(self.VectorsDataName).setTransformMode(int(bid))

        def handleMoveFromObject(self,changed):
          self.startCartesianPicker.blockSignals(True)
          self.endCartesianPicker.blockSignals(True)
          start,end = changed
          pars = {}
          ii=0
          for item in 'x','y','z':
            pars[item] = start[ii]
            ii=ii+1
          self.startCartesianPicker.setParams(pars)
          pars = {}
          ii=0
          for item in 'x','y','z':
            pars[item] = end[ii]
            ii=ii+1
          self.endCartesianPicker.setParams(pars)
          self.startCartesianPicker.blockSignals(False)
          self.endCartesianPicker.blockSignals(False)

        def handleMove(self,state):
          #if self.vectorId<0:
          #  QtGui.QMessageBox.warning(self,'Moving vector','There is no selectd vector')
          
          state = int(state == QtCore.Qt.Checked)
          DISPLAYTABLE().getDataObj(self.VectorsDataName).toggleMoving(state)
          if state == 1:
              DISPLAYTABLE().getDataObj(self.VectorsDataName).blockSignals(True)
              self.connect(DISPLAYTABLE().getDataObj(self.VectorsDataName),QtCore.SIGNAL('DataChanged'),self.handleMoveFromObject)
              DISPLAYTABLE().getDataObj(self.VectorsDataName).blockSignals(False)
          else:
              DISPLAYTABLE().getDataObj(self.VectorsDataName).blockSignals(True)
              self.disconnect(DISPLAYTABLE().getDataObj(self.VectorsDataName),QtCore.SIGNAL('DataChanged'),self.handleMoveFromObject)
              DISPLAYTABLE().getDataObj(self.VectorsDataName).blockSignals(False)
          
# Code for a VectorData server

			#if not self.target:
			#	# toPlainText should be toHtml when we are all but finished.
			#	gvd=Vectors.GVectorData(table=DISPLAYTABLE(),name='Vectors',parent=DISPLAYTABLE().GDataObjs['VectorData'],startCart=[startx,starty,startz],endCart=[endx,endy,endz],startSel=startSelection,endSel=endSelection,text=self.editor.textEdit.toPlainText())
			#	DISPLAYTABLE().addDispObj(object_type='VectorDisp',name="Vectors",parent_name =gvd.objectName())
	#	except:
		#	import sys
        	#	exc_type, exc_value = sys.exc_info()[:2]
        	#	print exc_type
        	#	print exc_value


#----------------------------------------------------------------------
#----------------------------------------------------------------------
#----------------------------------------------------------------------
class editVectorTags(MGSimpleDialog.MGSimpleDialog):
#----------------------------------------------------------------------
#----------------------------------------------------------------------
#----------------------------------------------------------------------

  def __init__(self,parent=None,VectorsDataName='',tagId=-1):
    MGSimpleDialog.MGSimpleDialog.__init__(self,parent)
    self.VectorsDataName = VectorsDataName
    self.tagId = -1
    self.setWindowTitle("Edit vectors "+VectorsDataName)
    layout = QtGui.QVBoxLayout(self)
    layout.setSpacing(2)
    layout.setContentsMargins(2,2,2,2)
                
    self.selectTag= QtGui.QListWidget(self)
    self.selectTag.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
    self.connect(self.selectTag,QtCore.SIGNAL('currentRowChanged(int)'),self.setTagId)
    self.loadSelectTag()

    delete_button = QtGui.QPushButton('Delete selected tag',self)
    self.connect(delete_button,QtCore.SIGNAL('clicked()'),self.deleteTag)
    new_button = QtGui.QPushButton('Create new tag',self)
    self.connect(new_button,QtCore.SIGNAL('clicked()'),self.handleNew)
    
    editLayout= QtGui.QGridLayout()
    editLayout.addWidget(self.selectTag,0,0,2,1)
    editLayout.addWidget(new_button,0,1)
    editLayout.addWidget(delete_button,1,1)
    layout.addLayout(editLayout)

    line_layout = QtGui.QHBoxLayout()
    line_layout.addWidget(QtGui.QLabel('Tag name',self))
    self.name = QtGui.QLineEdit(self)
    line_layout.addWidget(self.name)
    layout.addLayout(line_layout)

    line_layout = QtGui.QHBoxLayout()
    line_layout.addWidget(QtGui.QLabel('Tag annotation',self))
    layout.addLayout(line_layout)

    self.annotation =  QtGui.QTextEdit(self)
    layout.addWidget(self.annotation)


    dialog_buttons = QtGui.QDialogButtonBox()
    apply_button = dialog_buttons.addButton('Save group',QtGui.QDialogButtonBox.ActionRole)
    cancel_button = dialog_buttons.addButton('Close',QtGui.QDialogButtonBox.RejectRole)
    ok_button = dialog_buttons.addButton('Save group and close',QtGui.QDialogButtonBox.AcceptRole)
    for button in [apply_button,cancel_button,ok_button]:
      button.setAutoDefault(0)
      button.setDefault(0)
    self.connect(cancel_button,QtCore.SIGNAL('clicked()'),self.Close)
    self.connect(apply_button,QtCore.SIGNAL('clicked()'),self.Apply)
    self.connect(ok_button,QtCore.SIGNAL('clicked()'),self.ApplyAndClose)
    layout.addWidget(dialog_buttons)
    
    self.setTagId(tagId)

#----------------------------------------------------------------------
  def ApplyAndClose(self):
#----------------------------------------------------------------------
    self.Apply(1)
    
#----------------------------------------------------------------------
  def Apply(self,close=0):
#----------------------------------------------------------------------
    #print 'editVectorTags.Apply',close
    target = data(self.VectorsDataName)
    name = str(self.name.text())
    annotation = str(self.annotation.document().toPlainText())
    taglist = target.getTagList()
    if self.tagId<0:
      if name and not taglist.count(name):
        target.edit_tag(-1,name,annotation)
      else:
        QtGui.QMessageBox.warning(self,'Creating new tag','Enter a unique name for the new tag')
        return
    else:
      if name and (name == taglist[self.tagId] or not taglist.count(name)):
         target.edit_tag(self.tagId,name,annotation)
      else:
         QtGui.QMessageBox.warning(self,'Editing tag','Enter a unique name for the new tag')
         return
       
    self.loadSelectTag()
    self.emit(QtCore.SIGNAL('changed'))
    if close: self.Close()

  def handleNew(self):
    self.setTagId(-1)

    
#----------------------------------------------------------------------
  def deleteTag(self):
#----------------------------------------------------------------------
    data(self.VectorsDataName).delete_tag(self.tagId)
    self.loadSelectTag()
    self.setTagId(-1)
    self.emit(QtCore.SIGNAL('changed'))

#----------------------------------------------------------------------
  def loadSelectTag(self):
#----------------------------------------------------------------------
    self.selectTag.blockSignals(True)
    taglist = data(self.VectorsDataName).getTagList()
    self.selectTag.clear()
    for item in taglist:
      self.selectTag.addItem(item)
    self.selectTag.addItem('New tag..')
    self.selectTag.blockSignals(False)
  

#----------------------------------------------------------------------
  def setTagId(self,vid):
#----------------------------------------------------------------------
    #print 'setTagId vid',vid
    if vid<0 or vid>=self.selectTag.count()-1:
      # Out of range so set to 'new' vector
      self.setRow(self.selectTag.count()-1)
      self.name.setText('')
      self.annotation.document().clear()
      self.tagId = -1
    else:
      self.setRow(vid)
      name,annotation = data(self.VectorsDataName).get_tag(vid)
      self.name.setText(name)
      self.annotation.document().setPlainText(QtCore.QString(annotation))
      self.tagId = vid


#----------------------------------------------------------------------
  def setRow(self,irow):
#----------------------------------------------------------------------
    if irow == self.selectTag.currentRow(): return
    self.selectTag.blockSignals(True)
    self.selectTag.setCurrentRow(irow)
    self.selectTag.blockSignals(False)
            
