"""
     qtgui/movieGui.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.
"""
import sys
from PyQt4 import QtGui,QtCore
from global_definitions import *
import os
import mgPresentation,MGSimpleDialog,mgWidgets

#-------------------------------------------------------------------
#-------------------------------------------------------------------
#-------------------------------------------------------------------
class movieGui(mgPresentation.mgPresentation):
#-------------------------------------------------------------------
#-------------------------------------------------------------------
#-------------------------------------------------------------------
  transform_menu = ['fixed','rotate about y','rock','transform','glide to']
  transform_alias = ['fixed','rotate','rock','transform','glide']
#-------------------------------------------------------------------
  def __init__(self,parent,presentation=None):
#-------------------------------------------------------------------
    mgPresentation.mgPresentation.__init__(self,parent,presentation=presentation)

    self.setWindowTitle(self.tr("Movie editor: ")+self.presentation.identifier)
    self.dockWidget.setWindowTitle(self.tr("Movie editor: ")+self.presentation.identifier)

    self.connect(self,QtCore.SIGNAL('frameAdded'),self.updateToSnapshot)
    self.connect(self,QtCore.SIGNAL('frameDeleted'),self.updateToSnapshot)
    self.updateGlideTo()

#-------------------------------------------------------------------
  def Close(self):
#-------------------------------------------------------------------
    #print "movieGui.Close",self.findChildren(movieTransformDetailsGui)
    for win in self.findChildren(movieTransformDetailsGui):
      win.close()
    mgPresentation.mgPresentation.Close(self)

#-------------------------------------------------------------------
  def getGuiDef(self,name='',pickevent=None):
#-------------------------------------------------------------------
      #print 'getGuiDef',name
      if name == 'menus':
        return [['action',self.tr('&Action'),'aboutToShow'],['edit',self.tr('&Edit'),'aboutToShow'],['help','&Help']]
      elif name == 'action':
        return ['stop','preview','make_movie',[self.tr('Make movie in stages'),'record','compile','merge'],['Play',self.playMovieGui],'close']
      elif name == 'edit':
        return ['movie_preferences']
      elif name == 'help':
        return ['help']
      
#-------------------------------------------------------------------
  def getActionDef(self,name,**info):
#-------------------------------------------------------------------
    #print 'getActionDef',name
    import guiUtils
    if name == 'close':
      return dict ( 
        text = self.tr('Close movie editor'),
        tip = self.tr('Close this movie editor saving current status'),
        slot = self.Close  )

    if name == 'stop':
      def e(): return self.presentation.interruptable
      return dict ( 
        text = self.tr('Stop preview/recording'),
        tip = self.tr('Stop any running preview or recording'),
        slot = self.presentation.setInterrupt,
        enabled =  e )

    if name == 'preview':
      return dict ( 
        text = self.tr('Preview'),
        tip = self.tr('Preview currently selected scenes'),
        slot = guiUtils.partial(self.apply,'preview' ) )

    if name == 'make_movie':   
       return dict ( 
        text = self.tr('Make movie'),
        tip = self.tr('Make movie from currently selected scenes'),
        slot = guiUtils.partial(self.presentation.apply,'make') )

    if name == 'record':   
       return dict ( 
        text = self.tr('Record frames'),
        tip = self.tr('Record movie from currently selected scenes'),
        slot = guiUtils.partial(self.apply,'record') )

    if name == 'compile':   
       return dict ( 
        text = self.tr('Make movie scene'),
        tip = self.tr('Merge frames to make movie scene'),
        slot = guiUtils.partial(self.presentation.apply,'compile') )
     
    if name == 'merge':   
       return dict ( 
        text = self.tr('Merge movie scenes'),
        tip = self.tr('Merge movie scenes'),
        slot = guiUtils.partial(self.presentation.apply,'merge') )
        
    if name == 'play':
      return dict ( 
        text = self.tr('Play movie'),
        tip = self.tr('Play movie'),
        slot = self.playMovieGui )

    if name == 'movie_preferences':
      return dict(
        text = self.tr('Movie preferences'),
        tip = self.tr('Set preferences for this movie'),
        slot = self.preferencesGui )

    if name == 'help':
      return dict ( 
        text = self.tr('&Help'),
        tip = self.tr('Help on CCP4mg Movies'),
        slot = self.help )


    return mgPresentation.mgPresentation.getActionDef(self,name)

  def help(self):
    
    HELPBROWSER().loadMgHelp('movies.html')
  
#-------------------------------------------------------------------
  def drawFrameGui(self,frame=None,id=''):
#-------------------------------------------------------------------
    # This method is reimplemented in this sub-class to
    # draw gui beneath frame pictures
    #print "movieGui.drawFrameGui",frame,id
    #frame = self.findChild(presentationFrameWidget,str(id))
    import guiUtils

    params = self.presentation.get_snapshot_details(id).get(id,{})
    snapshot_list = self.presentation.get_snapshot_list()
    #print "movieGui.drawFrameGui",frame,id,params,snapshot_list


    stack = QtGui.QStackedWidget(frame)
    stack.setObjectName('stack')

    container = QtGui.QFrame()
    layout = QtGui.QVBoxLayout()
    margin = 2
    layout.setContentsMargins(margin,margin,margin,margin)
    layout.setSpacing(margin)

    line_layout =  QtGui.QHBoxLayout()
    widget = QtGui.QLabel(self.tr('Record'),frame)
    line_layout.addWidget(widget)
    widget = QtGui.QDoubleSpinBox(frame)
    widget.setObjectName('time')
    widget.setRange(0.0,50.0)
    widget.setSingleStep(1.0)
    time = params.get('time',2.0)
    if time =='': time = 0.0
    widget.setValue(float(time))
    self.connect(widget,QtCore.SIGNAL('valueChanged(double)'),guiUtils.partial(self.updateSnapshotDetails,id))
    line_layout.addWidget(widget)
    widget = QtGui.QLabel(self.tr('secs'),frame)
    line_layout.addWidget(widget)
    line_layout.addStretch()
    layout.addLayout(line_layout)

    line_layout =  QtGui.QHBoxLayout()
    widget = QtGui.QLabel(self.tr('View'),frame)
    line_layout.addWidget(widget)
    widget = QtGui.QComboBox(frame)
    widget.setObjectName('view')
    for ii in range(0,len(movieGui.transform_menu)):
      widget.addItem(movieGui.transform_menu[ii],QtCore.QVariant(movieGui.transform_alias[ii]))
    if params.get('view','fixed') in movieGui.transform_alias:
      widget.setCurrentIndex(movieGui.transform_alias.index(params.get('view','fixed')))
    self.connect(widget,QtCore.SIGNAL('currentIndexChanged(QString)'),guiUtils.partial(self.updateFrameGui,id))
    self.connect(widget,QtCore.SIGNAL('currentIndexChanged(QString)'),guiUtils.partial(self.updateGlideTo,id))
    #self.connect(widget,QtCore.SIGNAL('currentIndexChanged(QString)'),guiUtils.partial(self.updateSnapshotDetails,id))
    line_layout.addWidget(widget)
    widget = QtGui.QComboBox(frame)
    widget.setObjectName('to_snapshot')
    widget.setVisible(0)
    if snapshot_list.count(id):
      for item in snapshot_list[snapshot_list.index(id):]:
        widget.addItem(item)
      if snapshot_list.count(params.get('to_snapshot',id)):
        widget.setCurrentIndex(snapshot_list.index(params.get('to_snapshot',id))-snapshot_list.index(id))
    self.connect(widget,QtCore.SIGNAL('currentIndexChanged(int)'),guiUtils.partial(self.updateSnapshotDetails,id))
    self.connect(widget,QtCore.SIGNAL('currentIndexChanged(int)'),guiUtils.partial(self.updateGlideTo,id))
    line_layout.addWidget(widget)
    line_layout.addStretch()
    layout.addLayout(line_layout)


    # Details button
    line_layout =  QtGui.QHBoxLayout()
    widget = QtGui.QPushButton(self.tr('Details'),frame)
    widget.setObjectName('details')
    self.connect(widget,QtCore.SIGNAL('clicked()'),guiUtils.partial(self.handleTransformDetails,id))
    line_layout.addWidget(widget)
    layout.addLayout(line_layout)

     
    container.setLayout(layout)
    stack.addWidget(container)

    # Create another layout containing a 'blank' ui
    # that will be shown if frame is glided to
    container =  QtGui.QFrame()
    layout = QtGui.QVBoxLayout()
    line_layout =  QtGui.QHBoxLayout()
    widget = QtGui.QLabel(self.tr('..glide through..'),frame)
    line_layout.addWidget(widget)
    layout.addLayout(line_layout)
    line_layout =  QtGui.QHBoxLayout()
    line_layout.addWidget(QtGui.QLabel('for time proportional  to'))
    layout.addLayout(line_layout)
    line_layout =  QtGui.QHBoxLayout()
    widget = mgWidgets.mgSlider(QtCore.Qt.Horizontal,self)
    widget.setObjectName('interpolate_time')
    widget.setRange(0.0,10.0)
    widget.setValue(1.0)
    self.connect(widget,QtCore.SIGNAL("valueChanged(double)"),guiUtils.partial(self.updateSnapshotDetails,id))
    line_layout.addWidget(widget)
    layout.addLayout(line_layout)
    container.setLayout(layout)
    stack.addWidget(container)

    stack.setCurrentIndex(0)
    
    return stack


#-------------------------------------------------------------------
  def updateFrameGui(self,id=''):
#-------------------------------------------------------------------
    '''
    User has changed the view mode in snapshot 'id'
    Update the GUI accordingly
    '''
    frame = self.findChild(mgPresentation.presentationFrameWidget,str(id))
    view = str(frame.findChild( QtGui.QComboBox, 'view').currentText())

    #frame.findChild( QtGui.QPushButton,'details').setVisible(view == 'transform')
    frame.findChild( QtGui.QComboBox,'to_snapshot').setVisible(view == 'glide to')
    # Open the details window
    #if view == 'transform': self.handleTransformDetails(id=id,transform=1)
    
    self.updateSnapshotDetails(id)

#-------------------------------------------------------------------
  def updateSnapshotDetails(self,id='',**kw):
#-------------------------------------------------------------------
    # GUI changed - update the presentation class
    if self.block_update: return
    params = self.getParams(index=id,keyList=['time','view','to_snapshot','interpolate_time'])
    #print "movieGui.updateSnapshotDetails",id,params
    self.presentation.setparams(params)
    
#-------------------------------------------------------------------
  def updateToSnapshot(self):
#-------------------------------------------------------------------
    snapshot_list=[]
    for indx in range(self.body.layout().count()-1,-1,-1):
      frame = self.body.layout().itemAt(indx).widget()
      id = str(frame.objectName())
      if id != 'insert_frame':
        snapshot_list.insert(0,id)
        widget = frame.findChild(QtGui.QComboBox,'to_snapshot')
        if hasattr(widget,"currentText") and callable(widget.currentText) and hasattr(widget,"addItem") and callable(widget.addItem) and hasattr(widget,"setCurrentIndex") and callable(widget.setCurrentIndex):
          import guiUtils
          current = str(widget.currentText())
          widget.clear()
          for item in snapshot_list: widget.addItem(item)
          if snapshot_list.count(current):
            widget.setCurrentIndex(snapshot_list.index(current))
    #print "movieGui.updateToSnapshot",snapshot_list

#-------------------------------------------------------------------
  def updateGlideTo(self,id=''):
#-------------------------------------------------------------------
     snapshot_list= self.snapshotList()
     if len(snapshot_list)<=1: return

     # Loop over snapshot_list from index idx to end
     if id and snapshot_list.count(id):
       idx = snapshot_list.index(id)
     else:
       idx = 0

     # Note that the first frame in snapshot_list can not be glided through and
     # if this method is called with an id value then it is for a frame that has
     # a visible gui which is only possible if it is not being glided over.
     
     while idx < len(snapshot_list):
       id = snapshot_list[idx]
       frame = self.findChild(mgPresentation.presentationFrameWidget,str(id))
       frame.findChild(QtGui.QStackedWidget,'stack').setCurrentIndex(0)
       view = str(frame.findChild( QtGui.QComboBox, 'view').currentText())
       if view == 'glide to':
         to_snapshot = str(frame.findChild( QtGui.QComboBox, 'to_snapshot').currentText())
         if not snapshot_list.count(to_snapshot) or  snapshot_list.index(to_snapshot)< idx:
           # to_snapshot does not exists or is before current snapshot so reset it
           frame.findChild( QtGui.QComboBox, 'to_snapshot').setCurrentIndex(0)
         else:
           # Loop over the frames that are glided through and set the gui to 'glide through'
           while idx < snapshot_list.index(to_snapshot):
             idx = idx + 1
             id = snapshot_list[idx]
             frame = self.findChild(mgPresentation.presentationFrameWidget,str(id))
             frame.findChild(QtGui.QStackedWidget,'stack').setCurrentIndex(1) 
       idx = idx + 1

           
#-------------------------------------------------------------------
  def playMovieGui(self,info):
#-------------------------------------------------------------------
    import guiUtils
    menu,title = info
    movie_files = self.presentation.get_movie_files()
    #print "playMovieGui",movie_files,title,menu

    menu.clear()
    for item in movie_files:
      a = self.findChild(QtGui.QAction,item)
      if not a:
        a = QtGui.QAction(item,self)
        a.setObjectName(item)
        self.connect(a,QtCore.SIGNAL('triggered(bool)'),guiUtils.partial(self.playMovie,item))
      menu.addAction(a)

#-------------------------------------------------------------------
  def playMovie(self,name):
#-------------------------------------------------------------------
    image_formats_c = QtGui.QMovie.supportedFormats() 
    image_formats = []
    for im in image_formats_c:
        if not image_formats.count(str(im).lower()):
          image_formats.append(str(im))
    import os
    #print "movieGui.playMovie",name
    filename = os.path.join(self.presentation.master_dir,name)
    if os.path.exists(filename):
      name_split = os.path.splitext(name)
      if len(name_split)>1 and '.' in name_split[1] and image_formats.count(name_split[1][1:]):
        viewer =  FILEVIEWER(self.presentation.identifier)
        #print "movieGui.playMovie viewer",viewer
        # Tell viewer it is an animated gif or it will default to static
        viewer.open(filename,format='movie',title=name)
      else:
        if sys.platform == 'linux2':
          viewer =  FILEVIEWER(self.presentation.identifier)
          viewer.open(filename,format='movie_phonon',title=filename)
        else:
          QtGui.QDesktopServices.openUrl(QtCore.QUrl.fromLocalFile(filename))
    
#-------------------------------------------------------------------
  def preferencesGui(self):
#-------------------------------------------------------------------
    if not getattr(self,'preferenceGui',None):
      self.preferenceGui = moviePreferenceGui(self)
    else:
      self.preferenceGui.show()
     
#-------------------------------------------------------------------
  def handleTransformDetails(self,id,transform=0):
#-------------------------------------------------------------------
    frame = self.findChild(mgPresentation.presentationFrameWidget,str(id))
    #print "movieGui.handleTransformDetails",id,frame
    gui = frame.findChild(MGSimpleDialog.MGSimpleDialog,'transform_details')

    if not gui:
      gui = movieTransformDetailsGui(frame)
      
    gui.show()
    if transform: gui.tab.setCurrentIndex(1)

#-------------------------------------------------------------------
  def apply(self,mode=''):
#-------------------------------------------------------------------
    #print "mgPresentation.apply",mode
    self.presentation.apply(mode)
    MAINWINDOW().MGDisplayTable.update(all=1)

    

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

#-------------------------------------------------------------------
  def __init__(self,parent):
#-------------------------------------------------------------------
  
    MGSimpleDialog.MGSimpleDialog.__init__(self,parent)

    self.setObjectName('transform_details')
    self.setWindowTitle(self.tr('Transform details for ')+str(self.parent().objectName()))
    #self.setAttribute(QtCore.Qt.WA_DeleteOnClose)

    layout = QtGui.QVBoxLayout()
    self.tab = QtGui.QTabWidget(self)


    # --- General---
    frame = QtGui.QFrame(self)
    frame_layout = QtGui.QVBoxLayout()
    
    line_layout = QtGui.QHBoxLayout()
    widget =  QtGui.QLabel(self.tr('Rock or repeat a transform or glide..'),self)
    line_layout.addWidget(widget)
    frame_layout.addLayout(line_layout)
    line_layout = QtGui.QHBoxLayout()
    widget = QtGui.QCheckBox(self.tr('Rock back to initial position. Repeat'),self)
    widget.setObjectName('interpolate_rock')
    self.connect(widget,QtCore.SIGNAL('stateChanged(int)'),self.update)
    line_layout.addWidget(widget)
    widget = QtGui.QSpinBox(self)
    widget.setObjectName('interpolate_repeats')
    widget.setRange(1,100)
    widget.setSingleStep(1)
    self.connect(widget,QtCore.SIGNAL('valueChanged(int)'),self.update)
    line_layout.addWidget(widget)
    line_layout.addStretch(5)

    frame_layout.addLayout(line_layout)

    '''
    line_layout = QtGui.QHBoxLayout()
    widget =  QtGui.QLabel('Output movie quality for this scene',self)
    line_layout.addWidget(widget)
    frame_layout.addLayout(line_layout)
    line_layout = QtGui.QHBoxLayout()
    widget = QtGui.QCheckBox('Good quality rendering',self)
    widget.setObjectName('render_quality')
    line_layout.addWidget(widget)
    widget = QtGui.QCheckBox('Raytrace scene',self)
    widget.setObjectName('raytrace')
    line_layout.addWidget(widget)
    line_layout.addStretch(5)

    frame_layout.addLayout(line_layout)
    '''
    
    frame.setLayout(frame_layout)
    self.tab.addTab(frame,self.tr('General'))

        # -- Transform ---

    frame = QtGui.QFrame(self)
    frame_layout = QtGui.QVBoxLayout()
    
    line_layout = QtGui.QHBoxLayout()
    widget = QtGui.QLabel(self.tr('Rotation'),self)
    line_layout.addWidget(widget)
    frame_layout.addLayout(line_layout)
    line_layout = QtGui.QHBoxLayout()
    for item in ['x','y','z']:
      widget = QtGui.QLabel(item,self)
      line_layout.addWidget(widget)
      widget = QtGui.QDoubleSpinBox(self)
      widget.setObjectName('rot'+item)
      widget.setRange(-360,360)
      widget.setSingleStep(30)
      self.connect(widget,QtCore.SIGNAL('valueChanged(double)'),self.update)
      line_layout.addWidget(widget)
    line_layout.addStretch(5)
    frame_layout.addLayout(line_layout)

    
    line_layout = QtGui.QHBoxLayout()
    widget = QtGui.QLabel(self.tr('Translation'),self)
    line_layout.addWidget(widget)
    frame_layout.addLayout(line_layout)
    line_layout = QtGui.QHBoxLayout()
    frame_layout.addLayout(line_layout)
    for item in ['x','y','z','zoom']:
      widget = QtGui.QLabel(item,self)
      line_layout.addWidget(widget)
      widget = QtGui.QDoubleSpinBox(self)
      widget.setObjectName(item)
      widget.setRange(0,100)
      widget.setSingleStep(1)
      self.connect(widget,QtCore.SIGNAL('valueChanged(double)'),self.update)
      line_layout.addWidget(widget)
    frame_layout.addLayout(line_layout)

    frame.setLayout(frame_layout)
    self.tab.addTab(frame,self.tr('Specify transform'))

    # -- Rock --
    
    frame = QtGui.QFrame(self)
    frame_layout = QtGui.QVBoxLayout()

    line_layout = QtGui.QHBoxLayout()
    widget = QtGui.QLabel(self.tr('Rock angle'),self)
    line_layout.addWidget(widget)
    widget = QtGui.QSpinBox(self)
    widget.setRange(0,360)
    widget.setSingleStep(5)
    widget.setObjectName('rock_angle')
    self.connect(widget,QtCore.SIGNAL('valueChanged(int)'),self.update)
    line_layout.addWidget(widget) 
    widget = QtGui.QLabel(self.tr('period'),self)
    line_layout.addWidget(widget)
    widget = QtGui.QDoubleSpinBox(self)
    widget.setObjectName('rock_period')
    widget.setRange(0.0,20.0)
    widget.setSingleStep(0.5)
    self.connect(widget,QtCore.SIGNAL('valueChanged(double)'),self.update)
    line_layout.addWidget(widget)
    widget = QtGui.QLabel(self.tr('secs'),self)
    line_layout.addWidget(widget)
    line_layout.addStretch(5)

    frame_layout.addLayout(line_layout)
    
    frame.setLayout(frame_layout)
    self.tab.addTab(frame,self.tr('Rock options'))


    # -- glide options ----

    frame = QtGui.QFrame(self)
    frame_layout = QtGui.QVBoxLayout()

    line_layout = QtGui.QHBoxLayout()
    widget = QtGui.QLabel(self.tr('Ramp speed at start and end of glide'),self)
    line_layout.addWidget(widget)
    frame_layout.addLayout(line_layout)

    line_layout = QtGui.QHBoxLayout()
    widget = QtGui.QSpinBox(self)
    widget.setObjectName('ramp_start')
    widget.setRange(0,100)
    widget.setSingleStep(1)
    self.connect(widget,QtCore.SIGNAL('valueChanged(int)'),self.update)
    line_layout.addWidget(widget)
    widget = QtGui.QLabel(self.tr('frames at start'),self)
    line_layout.addWidget(widget)
    widget = QtGui.QSpinBox(self)
    widget.setObjectName('ramp_end')
    widget.setRange(0,100)
    widget.setSingleStep(1)
    self.connect(widget,QtCore.SIGNAL('valueChanged(int)'),self.update)
    line_layout.addWidget(widget)
    widget = QtGui.QLabel(self.tr('frames at end'),self)
    line_layout.addWidget(widget)
    line_layout.addStretch(5)
    frame_layout.addLayout(line_layout)

    frame.setLayout(frame_layout)
    self.tab.addTab(frame,self.tr('Glide options'))
   
    layout.addWidget(self.tab)
    self.setLayout(layout)

    id = str(self.parent().objectName())
    params = self.parent().presentationGui.presentation.get_snapshot_details(id)
    if params.has_key(id): self.setParams(params[id])


#-------------------------------------------------------------------
  def getParams(self,**kw):
#-------------------------------------------------------------------
    import presentation
    params = MGSimpleDialog.MGSimpleDialog.getParams(self,presentation.presentation.default_details)
    params['transform'] = []
    for key in ['rotx','roty','rotz','x','y','z','zoom']:
      params['transform'].append(float(self.findChild(QtGui.QDoubleSpinBox,key).value()))
    #print "getParams",params
    return params

#-------------------------------------------------------------------
  def setParams(self,params={}):
#-------------------------------------------------------------------
    #print "movieTransformDetailsGui.setParams",params
    MGSimpleDialog.MGSimpleDialog.setParams(self,params)
    ii = 0
    if params.has_key('transform'):
      for key in ['rotx','roty','rotz','x','y','z','zoom']:
        self.findChild(QtGui.QDoubleSpinBox,key).setValue(params['transform'][ii])
        ii = ii + 1

        
#-------------------------------------------------------------------
  def update(self):
#-------------------------------------------------------------------
    params = self.getParams()
    #print "movieTransformDetailsGui.update params",params
    self.parent().presentationGui.presentation.handle_movie_details(index=str(self.parent().objectName()),params=params)


class FFMPEGSizeValidator(QtGui.QValidator):
	def __init__(self,parent=None):
		QtGui.QValidator.__init__(self,parent)
	def fixup(self,input):
		v = int(input.toAscii())
		vnew = (v+7)/8 * 8
		input.replace(0,len(input),str(vnew))
	def validate(self,input,pos):
		return (QtGui.QValidator.Intermediate,pos)

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

  def __init__(self,parent=None):
    QtGui.QDialog.__init__(self,parent)
    self.setWindowTitle(self.tr("Movie preferences ")+self.parent().presentation.identifier)

    layout = QtGui.QVBoxLayout()

    line_layout =  QtGui.QHBoxLayout()
    line_layout.addWidget(QtGui.QLabel(self.tr('Frame rate')))
    self.frame_rate = mgWidgets.RestrictedSpinBox(self)
    self.frame_rate.setRange(1,100)
    self.frame_rate.setSingleStep(5)
    line_layout.addWidget(self.frame_rate)
    line_layout.addStretch(5)
    layout.addLayout(line_layout)

    line_layout =  QtGui.QHBoxLayout()
    line_layout.addWidget(QtGui.QLabel(self.tr('Frame width')))
    self.frame_width = mgWidgets.RoundToMultipleSpin(self)
    #self.frame_width.setMultiple(8)
    self.frame_width.setRange(32,5000)
    self.frame_width.setSingleStep(16)
    line_layout.addWidget(self.frame_width)
    layout.addLayout(line_layout)
    line_layout.addWidget(QtGui.QLabel(self.tr('height')))
    self.frame_height = mgWidgets.RoundToMultipleSpin(self)
    #self.frame_height.setMultiple(8)
    self.frame_height.setRange(32,5000)
    self.frame_height.setSingleStep(16)
    line_layout.addWidget(self.frame_height)
    line_layout.addStretch(5)
    layout.addLayout(line_layout)

    line_layout =  QtGui.QHBoxLayout()
    line_layout.addWidget(QtGui.QLabel(self.tr('Encoder quality')))
    self.encoder_quality = QtGui.QSlider(QtCore.Qt.Horizontal)
    self.encoder_quality.setValue(100)
    line_layout.addWidget(self.encoder_quality)
    layout.addLayout(line_layout)

    line_layout =  QtGui.QHBoxLayout()
    self.render_quality = QtGui.QCheckBox(self.tr('Create higher quality snapshot'),self)
    line_layout.addWidget(self.render_quality)
    line_layout.addStretch(5)
    layout.addLayout(line_layout)
    
    line_layout =  QtGui.QHBoxLayout()
    self.true_transparency = QtGui.QCheckBox(self.tr('Use true transparency (slow!)'),self)
    line_layout.addWidget(self.true_transparency)
    line_layout.addStretch(5)
    layout.addLayout(line_layout)

    line_layout =  QtGui.QHBoxLayout()
    self.do_render = QtGui.QCheckBox(self.tr('User renderer (slow!)'),self)
    line_layout.addWidget(self.do_render)
    line_layout.addStretch(5)
    layout.addLayout(line_layout)

    line_layout =  QtGui.QHBoxLayout()
    self.scale_fonts_and_images = QtGui.QCheckBox(self.tr('Scale fonts and images'),self)
    line_layout.addWidget(self.scale_fonts_and_images)
    line_layout.addStretch(5)
    layout.addLayout(line_layout)

    
    line_layout =  QtGui.QHBoxLayout()
    line_layout.addWidget(QtGui.QLabel(self.tr('Create movie file with extension')))
    self.movie_ext = QtGui.QComboBox(self)
    for item in self.parent().presentation.movie_ext_menu:
      self.movie_ext.addItem(item)
    line_layout.addWidget(self.movie_ext)
    line_layout.addStretch(5)
    layout.addLayout(line_layout)
    
    line_layout =  QtGui.QHBoxLayout()
    line_layout.addWidget(QtGui.QLabel(self.tr('Use movie encoder program')))
    self.movie_encoder = QtGui.QComboBox(self)
    for item in self.parent().presentation.movie_encoder_menu:
      self.movie_encoder.addItem(item)
    line_layout.addWidget(self.movie_encoder)
    line_layout.addStretch(5)
    layout.addLayout(line_layout)
    self.connect(self.movie_encoder,QtCore.SIGNAL("currentIndexChanged ( const QString &)"),self.setAllowedValues)

    dialog_buttons = QtGui.QDialogButtonBox()
    apply_button = dialog_buttons.addButton(self.tr('Apply'),QtGui.QDialogButtonBox.ApplyRole)
    cancel_button = dialog_buttons.addButton(self.tr('Close'),QtGui.QDialogButtonBox.RejectRole)
    self.connect(apply_button,QtCore.SIGNAL('clicked()'),self.Apply)
    self.connect(cancel_button,QtCore.SIGNAL('clicked()'),self.close)
    layout.addWidget(dialog_buttons)
    
    self.setLayout(layout)
    self.setParams(self.parent().presentation.getparams())
    self.setAllowedValues()
    self.Apply()
    self.show()

#-------------------------------------------------------------------
  def setAllowedValues(self,**kw):
#-------------------------------------------------------------------
	if 1:#try:
		ci =  self.movie_encoder.currentIndex()
		enc = self.parent().presentation.movie_encoder_alias[ci]
		formats =  self.parent().presentation.movie_encoder_formats[enc]
		multiple =  self.parent().presentation.movie_encoder_size_multiple[enc]
		fps =  self.parent().presentation.movie_encoder_fps[enc]
		self.frame_width.setMultiple(multiple)
		self.frame_height.setMultiple(multiple)
		self.frame_height.setSingleStep(16)
		self.frame_width.setSingleStep(16)
		self.frame_width.fixValue()
		self.frame_height.fixValue()
		self.movie_ext.clear()
		for item in formats:
			if self.parent().presentation.movie_ext_menu.count(item)>0:
				self.movie_ext.addItem(item)
		self.movie_ext.setCurrentIndex(0)
		self.frame_rate.setRestriction(fps)
		if len(fps)>0:
			self.frame_rate.setRange(min(fps),max(fps))
		else:
			self.frame_rate.setRange(1,100)
			
	else:#except:
		pass

#-------------------------------------------------------------------
  def getParams(self):
#-------------------------------------------------------------------
    params = {
      'encoder_quality' : int(self.encoder_quality.value()),
      'frame_rate' : int(self.frame_rate.value()),
      'frame_size' : [int(self.frame_width.value()),int(self.frame_height.value())],
      'render_quality' : int(self.render_quality.isChecked()),
      'true_transparency' : int(self.true_transparency.isChecked()),
      'do_render' : int(self.do_render.isChecked()),
      'scale_fonts_and_images' : int(self.scale_fonts_and_images.isChecked()),
      'movie_encoder' : self.parent().presentation.movie_encoder_alias[self.movie_encoder.currentIndex()],
      'movie_ext' : str(self.movie_ext.currentText().toAscii())
      }
    #print 'moviePreferenceGui.getParams',params
    return params
    

#-------------------------------------------------------------------
  def setParams(self,params):
#-------------------------------------------------------------------
    #print 'moviePreferenceGui.setParams',params
    if params.has_key('frame_rate'): self.frame_rate.setValue(int(params['frame_rate']))
    if params.has_key('encoder_quality'): self.encoder_quality.setValue(int(params['encoder_quality']))
    if params.has_key('frame_size'):
      self.frame_width.setValue(int(params['frame_size'][0]))
      self.frame_height.setValue(int(params['frame_size'][1]))
    if params.has_key('render_quality'): self.render_quality.setChecked(int(params['render_quality']))
    if params.has_key('true_transparency'): self.true_transparency.setChecked(int(params['true_transparency']))
    if params.has_key('do_render'): self.do_render.setChecked(int(params['do_render']))
    if params.has_key('scale_fonts_and_images'): self.scale_fonts_and_images.setChecked(int(params['scale_fonts_and_images']))
    if params.has_key('movie_encoder') and self.parent().presentation.movie_encoder_alias.count(params['movie_encoder']):
       self.movie_encoder.setCurrentIndex(self.parent().presentation.movie_encoder_alias.index(params['movie_encoder']))
      
    if params.has_key('movie_ext') and self.parent().presentation.movie_ext_menu.count(params['movie_ext']):
       self.movie_ext.setCurrentIndex(self.parent().presentation.movie_ext_menu.index(params['movie_ext']))

 
#-------------------------------------------------------------------
  def Apply(self):
#-------------------------------------------------------------------
    self.parent().presentation.set_movie_params(params=self.getParams())
