#!/usr/local/bin/python2.5
# -*- coding: UTF-8 -*-

# Copyright 2006-2007 (C) Raster Software Vigo (Sergio Costas)
# Copyright 2006-2007 (C) Peter Gill - win32 parts

# This file is part of DeVeDe
#
# DeVeDe is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# DeVeDe 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import stat

import pygtk # for testing GTK version number
pygtk.require ('2.0')
import gtk
import gtk.glade
import gobject
import sys
import gc
import copy
import time

import devede_other
import devede_executor
import devede_convert
import devede_dialogs

# How to add new file options:

# In the class NEWFILE, method CREATE_DEFAULT_VIDEO_PARAMETERS, add the new option
# to the SELF.FILE_PROPERTIES dictionary, setting its default value based in the
# SELF.FILE_VALUES values (the ones obtained with MPLAYER --IDENTIFY), SELF.PAL (True
# for PAL output video, False for NTSC output video) and SELF.DISCTOCREATE (DVD, VCD, SVCD
# CVD or DIVX)

# In the class FILE_PROPERTIES

# In the method GET_WIDGETS, set the parameter value in the SELF.FILE_PROPERTIES
# dictionary using the widget's current value

# In the method SET_WIDGETS, set the widget's value using the parameter value in
# SELF.FILE_PROPERTIES

# If the widget must be disabled or enabled under some circumstances (other widgets)
# set that code in method SET_FILM_BUTTONS


class newfile(devede_executor.executor):
	
	def __init__(self,pal,disctocreate):
		""" This class manages every new film added. It reads its parameters (resolution, FPS, number of
		channels...) and allows to generate the default values, both when choosing manually a file from the
		Properties window, or when dragging&dropping them into the main window """
		
		self.pal=pal
		self.disctocreate=disctocreate
		self.file_values=None
		self.file_properties=None
		
				
	def read_file_values(self,filename,check_audio):

		""" Reads the values of the video (width, heigth, fps...) and stores them
			into file_values.
		
		 	Returns (False,AUDIO) if the file is not a video (with AUDIO the number
		 	of audio tracks)
		 	
		 	Returns (True,0) if the file is a right video file """
		
		handler=''

		vrate=0
		arate=0
		width=0
		height=0
		fps=0
		length=0
		audio=0
		video=0
		audiorate=0
		aspect_ratio=1.3333333333

		# if CHECK_AUDIO is TRUE, we just check if it's an audio file

		if check_audio:
			nframes=0
		else:
			nframes=1

		if sys.platform=='win32':
			command="mplayer.exe"
		else:
			command="mplayer"
		launcher=[command, "-identify", "-ao", "null", "-vo", "null", "-frames", str(nframes), filename]
		handler=self.launch_program(launcher, win32arg=False)
	
		while True:
			linea=handler.stdout.readline()
			if linea=="":
				break
			if linea[:16]=="ID_VIDEO_BITRATE":
				vrate=int(linea[17:])
			if linea[:14]=="ID_VIDEO_WIDTH":
				width=int(linea[15:])
			if linea[:15]=="ID_VIDEO_HEIGHT":
				height=int(linea[16:])
			if linea[:15]=="ID_VIDEO_ASPECT":
				aspect_ratio=float(linea[16:])
			if linea[:12]=="ID_VIDEO_FPS":
				fps2=linea[13:]
				if ord(fps2[-1])<32:
					fps2=fps2[:-1]
				posic=linea.find(".")
				if posic==-1:
					fps=int(linea[13:])
				else:
					fps=int(linea[13:posic])
					if linea[posic+1]=="9":
						fps+=1
			if linea[:16]=="ID_AUDIO_BITRATE":
				arate=int(linea[17:])
			if linea[:13]=="ID_AUDIO_RATE":
				audiorate=int(linea[14:])
			if linea[:9]=="ID_LENGTH":
				length=int(float(linea[10:]))
			if linea[:11]=="ID_VIDEO_ID":
				video+=1
			if linea[:11]=="ID_AUDIO_ID":
				audio+=1
		handler.wait()
		
		if (video==0) or (width==0) or (height==0):
			return False,audio
		
		if aspect_ratio==0.0:
			aspect_ratio=(float(width))/(float(height))
			if aspect_ratio<(4.0/3.0):
				aspect_ratio=(4.0/3.0)
		
		self.file_values={}
		self.file_values["vrate"]=vrate
		self.file_values["arate"]=arate
		self.file_values["video_streams"]=video
		self.file_values["audio_streams"]=audio
		self.file_values["width"]=width
		self.file_values["height"]=height
		self.file_values["fps"]=fps
		self.file_values["ofps2"]=fps2
		self.file_values["length"]=length
		self.file_values["aspect_ratio"]=aspect_ratio
		self.file_values["audiorate"]=audiorate
		
		return True,0


	def get_recomended_resolution(self,vrate,arate,desired_resolution):

		""" Returns the recomended resolution for a video based in its original
			resolution and the resolution chosed by the user.
		
		 	DESIRED_RESOLUTION is a value from 0 to 5:
		 	0=auto, 1=720x480, 2=704x480, 3=480x480, 4=352x480, 5=352x240 
		 	
		 	It returns the recomended audio and video rate for that resolution,
		 	but only if the user hasn't changed them """

		if self.pal:
			nheigh1=576
			nheigh2=288
		else:
			nheigh1=480
			nheigh2=240

		if self.file_values==None:
			return 0,0,False,0,0

		if desired_resolution==0: # default resolution; we have to take the most similar resolution
			if self.disctocreate=="vcd":
				resx=352
				resy=nheigh2
			elif self.disctocreate=="cvd":
				resx=352
				resy=nheigh1
			elif self.disctocreate=="svcd":
				resx=480
				resy=nheigh1
			else: # dvd o divx
				if self.file_values["width"]<=352:
					resx=352
					if self.file_values["height"]<=nheigh2:
						resy=nheigh2
					else:
						resy=nheigh1
				else:
					resx=720
					resy=nheigh1
		elif desired_resolution==1:
			resx=720
			resy=nheigh1
		elif desired_resolution==2:
			resx=704
			resy=nheigh1
		elif desired_resolution==3:
			resx=480
			resy=nheigh1
		elif desired_resolution==4:
			resx=352
			resy=nheigh1
		elif desired_resolution==5:
			resx=352
			resy=nheigh2
	
		if (((resx==720) and (resy==nheigh1)) or (self.disctocreate=="divx")) and (self.file_values["aspect_ratio"]>=1.77):
			use_widescreen=True
		else:
			use_widescreen=False

		if (vrate==5001) or (vrate==3001) or (vrate==2001):
			if (resx>703):
				vrate=5001
			if (resx==480) or ((resx==352) and (resy==nheigh1)):
				vrate=3001
			if (resx==352) and (resy==nheigh2):
				vrate=2001
			if (self.disctocreate!="dvd") and (self.disctocreate!="divx"):
				vrate=2001
		
		if self.disctocreate=="vcd":
			vrate=1152
			arate=224

		return resx,resy,use_widescreen,vrate,arate


	def create_default_video_parameters(self,filename):

		""" This method fills the FILE_PROPERTIES property with the default values for the file.
			It returns False if the file isn't a valid video. The tuple contains the number of sound
			tracks found, so if it's different from 0, its an audio-only file. """

		if filename==None:
			return False,0

		isvideo,audio_tracks=self.read_file_values(filename,True)
		if isvideo==False:
			return False,audio_tracks
		isvideo,audio_tracks=self.read_file_values(filename,False) # get all the values in FILE_VALUES

		while filename[-1]==os.sep:
			filename=filename[:-1]
	
		nombre=filename
		while True: # get the filename without the path
			posic=nombre.find("/")
			if posic==-1:
				break
			else:
				nombre=nombre[posic+1:]
	
		# filename[0]; path[1]; width[2]; heigh[3]; length[4] (seconds); original fps[5];
		# original videorate["oarate"]; original audiorate[7];
		# final videorate[8]; final arate[9]; final width[10]; final heigh[11];
		# 0=Black bars, 1=Scale picture [12];
		# length of chapters[13]; audio delay["fps"]; final fps["arateunc"]; original audio rate (uncompressed)["oaspect"];
		# original aspect ratio[17]; final aspect ratio[18];
		# 0=full length, 1=first half, 2=second half [19];
		# Resolution: 0=auto, 1=720x480, 2=704x480, 3=480x480, 4=352x480, 5=352x240 [20]
		# extra parameters [21]

		self.file_properties={}
		self.file_properties["filename"]=nombre
		self.file_properties["path"]=filename
		self.file_properties["owidth"]=self.file_values["width"]
		self.file_properties["oheight"]=self.file_values["height"]
		self.file_properties["olength"]=self.file_values["length"]
		self.file_properties["ovrate"]=self.file_values["vrate"]/1000
		self.file_properties["oarate"]=self.file_values["arate"]/1000
		self.file_properties["arateunc"]=self.file_values["audiorate"]
		self.file_properties["oaspect"]=self.file_values["aspect_ratio"]
		 
		if self.pal:
			self.file_properties["fps"]=25
		else:
			self.file_properties["fps"]=30

		self.file_properties["ofps"]=self.file_values["fps"]
		self.file_properties["ofps2"]=self.file_values["ofps2"]
		
		self.file_properties["blackbars"]=0 # black bars, no scale
		self.file_properties["lchapters"]=5
		self.file_properties["adelay"]=0 # no audio delay
		self.file_properties["cutting"]=0 # full length
		self.file_properties["resolution"]=0 # output resolution = auto
		self.file_properties["params"]="" # no mencoder extra parameters
		self.file_properties["ismpeg"]=False
		self.file_properties["copy_audio"]=False # recompress the audio
		self.file_properties["sound51"]=False # don't use 5.1 sound
		self.file_properties["gop12"]=False # GOP of 15 or 18 by default
		self.file_properties["filesize"]=os.stat(filename)[stat.ST_SIZE]
		self.file_properties["trellis"]=True # use trellis
		self.file_properties["mbd"]=2 # maximum quality
		self.file_properties["deinterlace"]="none"
		self.file_properties["subtitles"]=""
		self.file_properties["sub_codepage"]="ISO-8859-1"
		self.file_properties["subtitles_up"]=False

		resx,resy,use_widescreen,vrate,arate=self.get_recomended_resolution(5001, 224, 0)
		self.file_properties["width"]=resx
		self.file_properties["height"]=resy
		self.file_properties["vrate"]=vrate
		self.file_properties["arate"]=arate

		if use_widescreen:
			self.file_properties["aspect"]=1.7777777
		else:
			self.file_properties["aspect"]=1.3333333
			
		return True,audio_tracks


	def split_dnd(self,data):

		""" Takes the list of files dragged into the window and returns them in a list """

		lista=[]
		item=""
		tempo=""
		mode=0
		
		for elemento in data:
			if (elemento=="\n") and (item!=""):
				if item[:8]=="file:///":
					lista.append(item[7:])
					item=""
					continue
			if ord(elemento)<32:
				continue
			if mode==0:
				if elemento=="%":
					mode=1
				else:
					item+=elemento
			elif mode==1:
				tempo=elemento
				mode=2
			else:
				mode=0
				item+=chr(int(tempo+elemento,16))
		print "Dragged files: "+str(lista)
		return lista


##################################################################################


class file_properties(newfile):

	""" This class manages the properties window, where the user can choose the properties
		of each video file """
	
	# public methods	
	
	def __init__(self,global_vars,title,chapter,structure,callback_refresh):
		
		newfile.__init__(self,global_vars["PAL"],global_vars["disctocreate"])
		self.gladefile=global_vars["gladefile"]
		self.global_vars=global_vars
		self.title=title
		self.chapter=chapter
		self.structure=structure
		self.callback_refresh=callback_refresh
		
		self.tree=gtk.glade.XML(self.gladefile,"wfile",domain="devede")
		self.tree.signal_autoconnect(self)
		self.window=self.tree.get_widget("wfile")
		self.window.show()
		self.window.drag_dest_set(gtk.DEST_DEFAULT_MOTION | gtk.DEST_DEFAULT_HIGHLIGHT | gtk.DEST_DEFAULT_DROP,[ ( "text/plain", 0, 80 ) ],gtk.gdk.ACTION_COPY)
		w = self.tree.get_widget("expander_advanced")
		w.set_expanded(self.global_vars["expand_advanced"])
		w = self.tree.get_widget("subtitles_frame")
		if (self.disctocreate == "divx"):
			w.hide()
		else:
			w.show()
		
		w1 = self.tree.get_widget("subtitles_label")
		w2 = self.tree.get_widget("frame_special")
		w3 = self.tree.get_widget("gop12")
		if (self.disctocreate == "divx"):
			w1.show()
			w2.hide()
			w3.hide()
		else:
			w1.hide()
			w2.show()
			w3.show()
		
		w = self.tree.get_widget("frame_division") # SPLIT THE FILES IN CHAPTERS FOR EASY SEEKING
		if (self.disctocreate == "dvd"):
			w.show()
		else:
			w.hide()
		
		self.set_resolution()
		self.change_file=False
		if (self.chapter!=-1): # we want to modify a chapter
			the_chapter=structure[title][chapter]
			print "Chequeo "+str(the_chapter["path"])
			isvideo,audio_tracks=self.read_file_values(the_chapter["path"],True)
			if isvideo==True:
				self.read_file_values(the_chapter["path"],False) # get all the values in FILE_VALUES
				self.file_properties=copy.deepcopy(the_chapter)
				self.change_file=True # we are changing the file name manually
				w=self.tree.get_widget("moviefile")
				print "Pongo nombre por propiedades"
				w.set_filename(self.file_properties["path"])
			else:
				self.chapter=-1
		w=self.tree.get_widget("moviefile")
		self.file_filter_videos=gtk.FileFilter()
		self.file_filter_videos.set_name(_("Video files"))
		self.file_filter_videos.add_mime_type("video/*")
		self.file_filter_all=gtk.FileFilter()
		self.file_filter_all.set_name(_("All files"))
		self.file_filter_all.add_pattern("*")
		print "Anado filtro"
		w.add_filter(self.file_filter_videos)
		print "Anado filtro"
		w.add_filter(self.file_filter_all)
		self.set_widgets()
		if (self.chapter!=-1): # we want to modify a chapter
			self.set_global_values()
		self.set_film_buttons()
		if (self.chapter!=-1): # we want to modify a chapter
			w=self.tree.get_widget("fileaccept")
			w.set_sensitive(True)
			w=self.tree.get_widget("preview_film")
			w.set_sensitive(True)
		
		print "Fin"


	# help methods


	def get_desired_resolution(self):
		
		""" Returns the resolution desired by the user as a single number """
		
		if (self.tree.get_widget("res720x480").get_active()):
			return 1
		if (self.tree.get_widget("res704x480").get_active()):
			return 2
		if (self.tree.get_widget("res480x480").get_active()):
			return 3
		if (self.tree.get_widget("res352x480").get_active()):
			return 4
		if (self.tree.get_widget("res352x240").get_active()):
			return 5
		return 0


	def adjust_resolution(self):
		
		""" Sets the final resolution and bitrate based on the original resolution and the
			desired one by the user """
		
		if self.file_properties==None:
			return
		
		w1=self.tree.get_widget("video_rate")
		vrate=w1.get_value()
		w2=self.tree.get_widget("audio_rate")
		arate=w2.get_value()
		resx,resy,use_widescreen,vrate,arate=self.get_recomended_resolution(vrate, arate, self.get_desired_resolution())
		self.file_properties["width"]=resx
		self.file_properties["height"]=resy
		w1.set_value(vrate)
		w2.set_value(arate)
		w=self.tree.get_widget("aspect_ratio")
		if ((resx!=720) or ((resy!=480) and (resy!=576))):
			w.set_active(False)

		if w.get_active():
			self.file_properties["aspect"]=1.7777777
		else:
			self.file_properties["aspect"]=1.3333333
			

	def get_widgets(self):
		
		""" Fills the file_properties list with the values expressed in the widgets """
		
		w=self.tree.get_widget("subtitles_chooser")
		subt=w.get_filename()
		if (subt==None) or (subt==""):
			self.file_properties["subtitles"]=""
		else:
			self.file_properties["subtitles"]=subt

		w=self.tree.get_widget("blackbars")
		if w.get_active():
			self.file_properties["blackbars"]=0
		else:
			self.file_properties["blackbars"]=1
	
		w=self.tree.get_widget("trell")
		self.file_properties["trellis"]=w.get_active()
	
		self.file_properties["mbd"]=0
		w=self.tree.get_widget("mbd1")
		if w.get_active():
			self.file_properties["mbd"]=1
		w=self.tree.get_widget("mbd2")
		if w.get_active():
			self.file_properties["mbd"]=2
		
		self.file_properties["deinterlace"]="none"
		w=self.tree.get_widget("deinterlace_lb")
		if w.get_active():
			self.file_properties["deinterlace"]="lb"
		w=self.tree.get_widget("deinterlace_md")
		if w.get_active():
			self.file_properties["deinterlace"]="md"
		w=self.tree.get_widget("deinterlace_fd")
		if w.get_active():
			self.file_properties["deinterlace"]="fd"
		
		w=self.tree.get_widget("ismpeg")
		self.file_properties["ismpeg"]=w.get_active()

		w=self.tree.get_widget("copy_audio")
		self.file_properties["copy_audio"]=w.get_active()

		w=self.tree.get_widget("sound51")
		self.file_properties["sound51"]=w.get_active()

		w=self.tree.get_widget("gop12")
		self.file_properties["gop12"]=w.get_active()

		w=self.tree.get_widget("do_chapters")
		if w.get_active():
			w=self.tree.get_widget("chapter_long")
			self.file_properties["lchapters"]=w.get_value()
		else:
			self.file_properties["lchapters"]=0
	
		w=self.tree.get_widget("audiodelay")
		self.file_properties["adelay"]=float(w.get_value())
		
		w=self.tree.get_widget("video_rate")
		self.file_properties["vrate"]=int(w.get_value())
		w=self.tree.get_widget("audio_rate")
		self.file_properties["arate"]=int(w.get_value())
	
		w=self.tree.get_widget("full_length")
		if w.get_active():
			self.file_properties["cutting"]=0
		else:
			w=self.tree.get_widget("first_half")
			if w.get_active():
				self.file_properties["cutting"]=1
			else:
				self.file_properties["cutting"]=2

		w=self.tree.get_widget("video_pal")
		if w.get_active():
			self.file_properties["fps"]=25
			self.global_vars["PAL"]=True
		else:
			self.file_properties["fps"]=30
			self.global_vars["PAL"]=False

		w=self.tree.get_widget("aspect_ratio")
	
		if (self.disctocreate=="dvd") or (self.disctocreate=="divx"):
			if w.get_active():
				self.file_properties["aspect"]=1.77777777
			else:
				self.file_properties["aspect"]=1.33333333
		else:
			self.file_properties["aspect"]=1.33333333

		w=self.tree.get_widget("sub_codepage")
		self.file_properties["sub_codepage"]=w.child.get_text()
		w=self.tree.get_widget("sub_up")
		self.file_properties["subtitles_up"]=w.get_active()

		self.file_properties["resolution"]=self.get_desired_resolution()
	
		w=self.tree.get_widget("custom_params")
		self.file_properties["params"]=w.get_text()


	# Callbacks
		
	def on_filecancel_clicked(self,widget):

		w=self.tree.get_widget("expander_advanced")
		self.global_vars["expand_advanced"]=w.get_expanded()
		self.window.destroy()
		self.window=None
		gc.collect()


	def on_fileaccept_clicked(self,widget):
		
		w=self.tree.get_widget("expander_advanced")
		self.global_vars["expand_advanced"]=w.get_expanded()
		self.get_widgets()
		if self.chapter==-1: # add this file as a new chapter
			self.structure[self.title].append(self.file_properties)
		else:
			self.structure[self.title][self.chapter]=self.file_properties
		self.window.destroy()
		self.window=None
		(self.callback_refresh)()
		gc.collect()


	def on_wfile_delete_event(self,widget,arg2):
		self.window.destroy()
		self.window=None
		gc.collect()
		return True


	def on_wfile_destroy_event(self,widget,arg2):
		self.window.destroy()
		self.window=None
		gc.collect()
	
	
	def on_clear_subtitles_clicked(self,widget):
		
		""" clears the subtitle filechooser """
		
		w=self.tree.get_widget("subtitles_chooser")
		w.unselect_all()
	

	def on_moviefile_file_set(self,widget):
		
		w=self.tree.get_widget("moviefile")
		filename=widget.get_filename()
		
		print "File changed to "+str(filename)
		
		if (filename==None) or (filename==""):
			return
		
		if self.change_file:
			self.change_file=False
			return
		
		fine,tracks=self.create_default_video_parameters(filename)
		if fine==False: # it's not a video file
			if tracks==0: # it's not a multimedia file
				devede_dialogs.show_error(_("File doesn't seem to be a video file."))
			else:
				devede_dialogs.show_error(_("File seems to be an audio file."))
		self.set_widgets()
		self.set_global_values()
		self.set_film_buttons()


	def on_video_pal_toggled(self,widget):
		
		""" Detects the change in the option PAL/NTSC """
		
		w=self.tree.get_widget("video_pal")
		self.pal=w.get_active()
		self.set_resolution()
		self.adjust_resolution()
		self.set_global_values()


	def on_res_toggled(self,widget):
		
		self.adjust_resolution()
		self.set_global_values()


	def on_length_toggled(self,widget):
		
		self.set_global_values()


	def on_video_rate_value_changed(self,widget):
		self.set_global_values()
		

	def on_audio_rate_value_changed(self,widget):
		self.set_global_values()


	def on_aspect_ratio_toggled(self,widget):
		
		if self.file_properties==None:
			return
		
		w=self.tree.get_widget("aspect_ratio")
		if w.get_active()==False:
			return
		self.set_resolution()
		if (self.file_properties["width"]!=720) or ((self.file_properties["height"]!=480) and(self.file_properties["height"]!=576)):
			w=self.tree.get_widget("res720x480")
			w.set_active(True)


	def on_ismpeg_toggled(self,widget):
		
		self.set_film_buttons()
		self.set_global_values()


	def on_copy_audio_toggled(self,widget):
		
		self.set_film_buttons()
		self.set_global_values()


	def on_sound51_toggled(self,widget):

		self.set_film_buttons()
		self.set_global_values()


	def on_preview_film_clicked(self,widget):

		self.get_widgets()
		self.global_vars["erase_temporary_files"]=True
		self.global_vars["number_actions"]=1
		tmp_structure=[["",self.file_properties]]
		converter=devede_convert.create_all(self.gladefile,tmp_structure,self.global_vars,self.callback)
		self.global_vars["temp_folder"]=converter.preview(self.global_vars["temp_folder"])
		print "Temp folder changed to "+str(self.global_vars["temp_folder"])


	def callback(self):
		
		""" This method is called after a preview """
		
		return None # do nothing


	def draganddrop(self,widget,drag_context, x, y, selection, info, time):

		""" Manages the Drag&Drop in the property window """

		lista=self.split_dnd(selection.data)

		if len(lista)==0:
			return

		if len(lista)>1:
			self.show_error(_("Please, add only one file each time."))
			return

		w=self.tree.get_widget("moviefile")
		print "Adding "+str(lista[0])
		w.set_filename(str(lista[0]))


	# data visualization methods


	def set_resolution(self):

		""" Sets the labels with the rigth resolution values, depending
		if the user selected PAL/SECAM or NTSC """

		if self.pal:
			res1="288"
			res2="576"
		else:
			res1="240"
			res2="480"

		w=self.tree.get_widget("res720x480")
		w.set_label("720x"+res2)
		w=self.tree.get_widget("res704x480")
		w.set_label("704x"+res2)
		w=self.tree.get_widget("res480x480")
		w.set_label("480x"+res2)
		w=self.tree.get_widget("res352x480")
		w.set_label("352x"+res2)
		w=self.tree.get_widget("res352x240")
		w.set_label("352x"+res1)


	def set_widgets(self):
		
		""" sets the widgets to the values specificated in SELF.FILE_PROPERTIES """

		if self.disctocreate=="vcd":
			w=self.tree.get_widget("video_rate")
			w.set_value(1152)
			w=self.tree.get_widget("audio_rate")
			w.set_value(224)
		elif (self.disctocreate=="svcd") or (self.disctocreate=="cvd"):
			w=self.tree.get_widget("video_rate")
			w.set_range(600,2375)
			w=self.tree.get_widget("audio_rate")
			w.set_range(64,384)
		else:
			w=self.tree.get_widget("video_rate")
			w.set_range(500,8000)
			w=self.tree.get_widget("audio_rate")
			w.set_range(128,448)

		w=self.tree.get_widget("subtitles_chooser")
		w.unselect_all()

		if self.file_properties==None:
			return

		w=self.tree.get_widget("aspect_ratio")
		if (self.disctocreate=="dvd") or (self.disctocreate=="divx"):
			w.set_sensitive(True)
			if self.file_properties["aspect"]>1.6:
				w.set_active(True)
			else:
				w.set_active(False)
		else:
			w.set_sensitive(False)

		if self.file_properties["resolution"]==0: # auto resolution
			w=self.tree.get_widget("resauto")
		elif self.file_properties["resolution"]==1: # 720x480
			w=self.tree.get_widget("res720x480")
		elif self.file_properties["resolution"]==2: # 704x480
			w=self.tree.get_widget("res704x480")
		elif self.file_properties["resolution"]==3: # 480x480
			w=self.tree.get_widget("res480x480")
		elif self.file_properties["resolution"]==4: # 352x480
			w=self.tree.get_widget("res352x480")
		else:
			w=self.tree.get_widget("res352x240")
	
		w.set_active(True)
	
		w=self.tree.get_widget("trell")
		w.set_active(self.file_properties["trellis"])
	
		if self.file_properties["mbd"]==0:
			w=self.tree.get_widget("mbd")
		elif self.file_properties["mbd"]==1:
			w=self.tree.get_widget("mbd1")
		else:
			w=self.tree.get_widget("mbd2")
		w.set_active(True)
	
		if self.file_properties["deinterlace"]=="none":
			w=self.tree.get_widget("deinterlace")
		else:
			w=self.tree.get_widget("deinterlace_"+self.file_properties["deinterlace"])
		w.set_active(True)
	
		w=self.tree.get_widget("ismpeg")
		w.set_active(self.file_properties["ismpeg"])

		w=self.tree.get_widget("copy_audio")
		w.set_active(self.file_properties["copy_audio"])
	
		w=self.tree.get_widget("sound51")
		w.set_active(self.file_properties["sound51"])
		
		w=self.tree.get_widget("gop12")
		w.set_active(self.file_properties["gop12"])
	
		w=self.tree.get_widget("custom_params")
		w.set_text(self.file_properties["params"])
	
		vrate=self.tree.get_widget("video_rate")
		vrate.set_value(self.file_properties["vrate"])
		arate=self.tree.get_widget("audio_rate")
		arate.set_value(self.file_properties["arate"])
		w=self.tree.get_widget("audiodelay")
		w.set_value(self.file_properties["adelay"])
		if self.file_properties["blackbars"]==0:
			w=self.tree.get_widget("blackbars")
		else:
			w=self.tree.get_widget("scalepict")
		w.set_active(True)
		
		w=self.tree.get_widget("do_chapters")
		if self.file_properties["lchapters"]==0:
			w.set_active(False)
			w=self.tree.get_widget("chapter_long")
			w.set_sensitive(False)
		else:
			w.set_active(True)
			w=self.tree.get_widget("chapter_long")
			w.set_sensitive(True)
			w.set_value(self.file_properties["lchapters"])
		
		if self.file_properties["fps"]==25:
			w=self.tree.get_widget("video_pal")
		else:
			w=self.tree.get_widget("video_ntsc")
		w.set_active(True)
	
		if self.file_properties["cutting"]==0:
			w=self.tree.get_widget("full_length")
		elif self.file_properties["cutting"]==1:
			w=self.tree.get_widget("first_half")
		else:
			w=self.tree.get_widget("second_half")
		w.set_active(True)
	
		if self.file_properties["subtitles"]!="":
			w=self.tree.get_widget("subtitles_chooser")
			w.set_filename(self.file_properties["subtitles"])
		
		w=self.tree.get_widget("sub_codepage")
		w.child.set_text(self.file_properties["sub_codepage"])
		w=self.tree.get_widget("sub_up")
		w.set_active(self.file_properties["subtitles_up"])

	
	def set_film_buttons(self):

		""" Enables or disables all the buttons, based in the current disk type and other widgets """

		w1=self.tree.get_widget("fileaccept")
		w=self.tree.get_widget("moviefile")
		cfile=w.get_filename()
		print "cojo nombre en Set film Buttons: "+str(cfile)
		w=self.tree.get_widget("preview_film")
		if (cfile=="") or (cfile==None):
			w.set_sensitive(False)
			w1.set_sensitive(False)
		else:
			w.set_sensitive(True)
			w1.set_sensitive(True)

		w=self.tree.get_widget("ismpeg")
		if w.get_active():
			grupo2=False
		else:
			grupo2=True

		w=self.tree.get_widget("copy_audio")
		if w.get_active():
			copy_audio=False
		else:
			copy_audio=grupo2

		if (self.disctocreate!="dvd") and (self.disctocreate!="divx"):
			w.set_active(False)
			w.set_sensitive(False)
			sound51=False
		else:
			w.set_sensitive(grupo2)
			sound51=grupo2

		if self.disctocreate =="vcd":
			grupo1=False
		else:
			grupo1=grupo2
		
		if (self.disctocreate=="dvd") or (self.disctocreate=="divx"):
			w=self.tree.get_widget("sound51")
			if w.get_active():
				w=self.tree.get_widget("audio_rate")
				w.set_range(384,448)		
			else:
				w=self.tree.get_widget("audio_rate")
				w.set_range(128,448)

		grupo3=grupo2
		try:
			if self.file_properties["olength"]<60:
				grupo3=False
		except:
			grupo3=False

		w=self.tree.get_widget("video_rate")
		w.set_sensitive(grupo1)
		w=self.tree.get_widget("audio_rate")
		w.set_sensitive(grupo1 and copy_audio)
		w=self.tree.get_widget("gop12")
		w.set_sensitive(grupo2)
		w=self.tree.get_widget("sound51")
		if not(grupo1 and copy_audio):
			w.set_active(False)
		w.set_sensitive(sound51 and copy_audio)
		w=self.tree.get_widget("resauto")
		w.set_sensitive(grupo1)
		w=self.tree.get_widget("res352x240")
		w.set_sensitive(grupo1)
		w=self.tree.get_widget("res352x480")
		w.set_sensitive(grupo1)
		w=self.tree.get_widget("res480x480")
		w.set_sensitive(grupo1)
		w=self.tree.get_widget("res704x480")
		w.set_sensitive(grupo1)
		w=self.tree.get_widget("res720x480")
		w.set_sensitive(grupo1)
	
		w=self.tree.get_widget("full_length")
		w.set_sensitive(grupo3)
		w=self.tree.get_widget("first_half")
		w.set_sensitive(grupo3)
		w=self.tree.get_widget("second_half")
		w.set_sensitive(grupo3)
		w=self.tree.get_widget("video_pal")
		w.set_sensitive(grupo2)
		w=self.tree.get_widget("video_ntsc")
		w.set_sensitive(grupo2)
		w=self.tree.get_widget("audiodelay")
		w.set_sensitive(copy_audio)
		w=self.tree.get_widget("blackbars")
		w.set_sensitive(grupo2)
		w=self.tree.get_widget("scalepict")
		w.set_sensitive(grupo2)
		w=self.tree.get_widget("custom_params")
		w.set_sensitive(grupo2)
		w=self.tree.get_widget("trell")
		w.set_sensitive(grupo2)
		w=self.tree.get_widget("mbd")
		w.set_sensitive(grupo2)
		w=self.tree.get_widget("mbd1")
		w.set_sensitive(grupo2)
		w=self.tree.get_widget("mbd2")
		w.set_sensitive(grupo2)
		w=self.tree.get_widget("deinterlace")
		w.set_sensitive(grupo2)
		w=self.tree.get_widget("deinterlace_lb")
		w.set_sensitive(grupo2)
		w=self.tree.get_widget("deinterlace_md")
		w.set_sensitive(grupo2)
		w=self.tree.get_widget("deinterlace_fd")
		w.set_sensitive(grupo2)
		w=self.tree.get_widget("aspect_ratio")
		if (self.disctocreate == "dvd") or (self.disctocreate == "divx"):
			w.set_sensitive(grupo2)
		else:
			w.set_sensitive(False)


	def set_global_values(self):

		""" Repaints all the data about the current film, recalculating
			the size needed and other params """
		
		if self.file_properties==None:
			empty=True
		else:
			empty=False
	
		w=self.tree.get_widget("o_size2")
		if empty:
			w.set_text("")
		else:
			w.set_text(str(self.file_properties["owidth"])+"x"+str(self.file_properties["oheight"]))

		w=self.tree.get_widget("leng2")
		if empty:
			w.set_text("")
		else:
			w.set_text(str(self.file_properties["olength"]))
		
		w=self.tree.get_widget("fps")
		if empty:
			w.set_text("")
		else:
			w.set_text(str(self.file_properties["ofps"]))

		w=self.tree.get_widget("vrate2")
		if empty:
			w.set_text("")
		else:
			w.set_text(str(self.file_properties["ovrate"]))

		w=self.tree.get_widget("arate2")
		if empty:
			w.set_text("")
		else:
			w.set_text(str(self.file_properties["oarate"]))
	
		w=self.tree.get_widget("video_rate")
		vrate=w.get_value()
		w=self.tree.get_widget("audio_rate")
		arate=w.get_value()
	
		w=self.tree.get_widget("full_length")
		if w.get_active():
			divide=False
		else:
			divide=True
		
		w=self.tree.get_widget("eleng2")
		if empty:
			w.set_text("")
		else:
			w2=self.tree.get_widget("ismpeg")
			if w2.get_active():
				l=int(self.file_properties["filesize"]/1000000)
			else:
				l=int(((vrate+arate)*self.file_properties["olength"])/8000)
				if divide:
					l/=2
				w.set_text(str(l))
		
		w=self.tree.get_widget("f_size2")
		if empty:
			w.set_text("")
		else:
			w.set_text(str(self.file_properties["width"])+"x"+str(self.file_properties["height"]))		
