#!/usr/bin/python
#-*- coding: utf8 -*-

import gettext
import threading
import gtk
import gtk.glade
import subprocess
import os
import sys
import gtk
import tempfile
import string
from shutil import copy, move
from config import *
import preference as preference
import gobject
import re

_ = gettext.gettext

def run_process(command):
	f = subprocess.Popen(
		command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
		stderr=subprocess.PIPE, close_fds=True, shell=True)
	return f.stdout

def print_log(text, block=True):
	textview = glade.get_widget('textview1')
	buffer = textview.get_buffer()
	#buffer.delete(buffer.get_start_iter(),buffer.get_end_iter())
	if block:
		gtk.gdk.threads_enter()
		buffer.insert(buffer.get_end_iter(), text + '\n')
		match_start_mark = buffer.create_mark(
					'match_start', buffer.get_end_iter(), True)
		textview.scroll_to_mark(match_start_mark, 0, True)
		gtk.gdk.threads_leave()
	else:
		buffer.insert(buffer.get_end_iter(), text + '\n')
		match_start_mark = buffer.create_mark(
					'match_start', buffer.get_end_iter(), True)
		textview.scroll_to_mark(match_start_mark, 0, True)

def on_preference_activate(widget):
	preference.preference_activate()

def codecs_list(glade):
	codecs = ['ogg', 'mp3', 'flac', 'wav', 'ape', 'wv']
	list = glade.get_widget('codec').get_model()
	list.clear()
	map(lambda x: list.append([x]), codecs)
	st = get('codec')
	glade.get_widget('codec').set_active(st)

def varc(glade1, pathglade1, QUIET):
	global glade, pathglade, QUIET1
	glade = glade1
	pathglade = pathglade1
	QUIET1 = QUIET

def parametrs(glade):
	dic = {
		'performer': glade.get_widget('performer').get_text(),
		'bitrate': str(int(glade.get_widget('bitrate').get_value())),
		'quality': glade.get_widget('quality').get_text(),
		'album': glade.get_widget('album').get_text(),
		'date': glade.get_widget('date').get_text(),
		'genre': glade.get_widget('genre').get_text(),
		'composer': glade.get_widget('composer').get_text(),
		'level': glade.get_widget('level').get_active_text(),
		'level_n': glade.get_widget('level').get_active(),
		'bitratebtn': glade.get_widget('bitratebtn').get_active(),
		'qualitybtn': glade.get_widget('qualitybtn').get_active(),
		'VBR': glade.get_widget('VBR').get_active(),
		'bin_file': glade.get_widget('bin_file').get_text(),
		'filename': glade.get_widget('filename').get_text(),
		'codec': glade.get_widget('codec').get_active_text(),
		'codec_n': glade.get_widget('codec').get_active(),
		'folder': glade.get_widget('savefolder').get_text(),
		'same_folder': glade.get_widget('same_folder').get_active(),
		}
	return dic

def show_dialog(message):
	try: message = message.replace('<b>', '').replace('</b>', '')
	except: pass
	print message
	print_log(message, False)
	dialog = gtk.MessageDialog(parent=None,
			flags=gtk.DIALOG_MODAL, type=gtk.MESSAGE_WARNING,
			buttons=gtk.BUTTONS_OK)
	dialog.set_markup(message)
	gobject.timeout_add(10000, lambda: dialog.destroy())
	response = dialog.run()
	if not os.path.exists(get('tmpdir')):
		dialog.destroy()
		return
	clean_tmp(get('tmpdir'))
	dialog.destroy()

def set_text_progressbar1(text):
	gtk.gdk.threads_enter()
	glade.get_widget('progressbar1').set_text(text)
	preference.progressbar1.set_text(text)
	gtk.gdk.threads_leave()

def	set_fraction_progressbar1(fraction):
	gtk.gdk.threads_enter()
	glade.get_widget('progressbar1').set_fraction(fraction)
	preference.progressbar1.set_fraction(fraction)
	gtk.gdk.threads_leave()

def start():

	def find_bin(path, fname):
		extention = ('ape', 'flac', 'wv', 'flake', 'wav', 'tta')
		fname = fname.split('.')[-2]
		for ext in extention:
			if not os.path.isdir(path):
				return
			for name in os.listdir(path):
				path_name = os.path.join(path, name)
				if path_name.endswith(ext) and (name.split('.')[-2] == fname):
					return path_name

	def codec_path(codec):
		path = get(codec)
		if not os.path.isfile(path):
			gtk.gdk.threads_enter()
			message = _('Codec\n <b>%s</b>\nmissing') %path
			show_dialog(message)
			glade.get_widget('stop_button').set_sensitive(False)
			gtk.gdk.threads_leave()
		else:
			return True

	def file_not_found():
		gtk.gdk.threads_enter()
		message = (_('File \n<b>%s</b>\nnot found') %bin_file)
		show_dialog(message)
		gtk.gdk.threads_leave()

	if not os.path.isdir(get('tmp_dir')):
		gtk.gdk.threads_enter()
		message = (_('Temp dir \n<b>%s</b>\nnot found') %get('tmp_dir'))
		show_dialog(message)
		glade.get_widget('stop_button').set_sensitive(False)
		gtk.gdk.threads_leave()
		return

	treeview = glade.get_widget('job queue')
	model = treeview.get_model()
	dic = model[0][6]
	folder = os.path.dirname(dic['filename'])
	all_tr = model.iter_n_children(model.get_iter(0))
	'''list tracks for decoder'''
	rowl = ''
	for n in range(model.iter_n_children(model.get_iter(0))):
		if model[0, n][3]:
			rowl += str(model[0, n][0]) + ','
	dic['trlist'] = rowl[:-1]
	dic['all_tr'] = all_tr
	for n in range(all_tr):
		if model[0, n][3]:
			dic[n+1] = model[0, n][1]
	clear_root_iter(glade)
	Conversation.job_name = '%s - %s' %(dic['performer'], dic['album'])
	gtk.gdk.threads_enter()
	glade.get_widget('stop_button').set_sensitive(True)
	progressbar2=glade.get_widget('progressbar2')
	progressbar2.set_fraction(0)
	preference.progressbar2.set_fraction(0)
	preference.progressbar2_text = '%s   in queue:%s' %(
											Conversation.job_name, len(model))
	progressbar2.set_text(preference.progressbar2_text)
	preference.progressbar2.set_text(preference.progressbar2_text)
	gtk.gdk.threads_leave()
	set_fraction_progressbar1(0)
	'''decode to tmpdir'''
	tmpdir = tempfile.mkdtemp(prefix='gcue2tracks', dir=get('tmp_dir'))
	set('tmpdir', tmpdir)
	if 'bin_files' in dic:
		'''tracks + cue'''
		for n in rowl.split(','):
			if n is '':
				break
			filename = dic['bin_files'][int(n) - 1]
			bin_file = os.path.join(folder, filename)
			if not os.path.isfile(bin_file):
				extention = ('ape', 'flac', 'wv', 'flake', 'wav', 'tta')
				if not os.path.isdir(folder):
					return
				for ext in extention:
					for name in os.listdir(folder):
						path_name = os.path.join(folder, name)
						if path_name.endswith(ext) or not ext:
							if filename.split('.')[0] in name.split('.')[0]:
								bin_file = path_name
								break
				if not bin_file:
					file_not_found()
					return
			command = "ffmpeg -y -i '%s' '%s/split-track%s.wav'" % (bin_file, tmpdir, n)
			text = _('Decoding to wav "%s" (%d/%s) ') \
				%(dic[int(n)], int(n), all_tr)
			decode_to_wav(command.encode('utf-8'), dic, text, False)
			print_log(text)
			gtk.gdk.threads_enter()
			progressbar2 = glade.get_widget('progressbar2')
			frac = progressbar2.get_fraction() +\
				2*(1.0/(2 + len(dic['trlist'].split(','))))\
				/len(dic['trlist'].split(','))
			progressbar2.set_fraction(frac)
			preference.progressbar2.set_fraction(frac)
			gtk.gdk.threads_leave()
	else:
		f = run_process('cuebreakpoints "%s" > %s/cuebreakpoints' %
			(dic['filename'], tmpdir))
		bin_file = os.path.join(folder, dic['bin_file'])
		'''file exits?'''
		if not os.path.isfile(bin_file):
			file_not_found()
			return
		print_log(_('Decoding to wav '))
		command = 'ffmpeg -y -i "%s" "%s/wav.wav"' % (bin_file, tmpdir)
		decode_to_wav(command, dic, text = _('Decoding to wav '))

		'''split tracks'''
		if Conversation.value == (_('Interrupted')):
			clean_tmp(tmpdir)
			return
		if Conversation.value == 'error':
			print 'decode error'
			print_log('decode error', False)
			clean_tmp(tmpdir)
			return
		print_log(_('split tracks  '))
		command = ('shnsplit -x "%s" '
				'-o "wav ext=wav shntool" '
				'-d "%s" '
				'-f "%s/cuebreakpoints" %s/wav.wav' %
				(dic['trlist'], tmpdir, tmpdir, tmpdir))
		process(command.encode('utf-8'), dic, True,
									text = _('split tracks  '))

	'''encoding tracks'''
	encoder(tmpdir, dic)

	'''movie encoded files'''
	a = Copy_result(tmpdir, dic)
	a = a.run()

def track_light(path, filename, glade):
	'''get track light'''
	filename = filename.encode('utf-8')
	path = path.encode('utf-8')
	os.chdir(path)
	f = run_process(
		'cuebreakpoints "%s"' % glade.get_widget('filename').get_text())
	fromchild = f.readline()
	list = []
	start = 0
	len1 = ''
	while fromchild:
		fromchild = fromchild.replace('\n', '')
		start, len1 = pars(fromchild, start, len1)
		list.append(len1)
		fromchild = f.readline()
	f = run_process('shnlen -q "%s/%s"' % (path, filename))
	fromchild = f.readlines()
	light = fromchild[1].strip().split(' ')[0]
	start, len1 = pars(light, start, len1)
	list.append(len1)
	return list, light

def pars(fromchild, start, len1):
	a1=string.find(fromchild, ':')
	if a1 != -1:
		min = int(fromchild[:a1])
		sec = int(fromchild[(a1+1):(a1+3)])
		dif = min*60+sec-start
		secs = str(dif-((dif/60)*60))
		if len(secs) < 2:
			secs = '0' + secs
		len1 = '%s:%s'% (str(dif/60), secs)
		start = min*60+sec
	return start, len1

def col0_edited_cb(cell, path, new_text, model):
	#print "Change '%s' to '%s'" % (model[path][1], new_text)
	model[path][1] = new_text
	return

def col1_toggled_cb(cell, path, model):
	a = model[path][3] = not model[path][3]
	treeview = glade.get_widget('job queue')
	iter = model.get_iter(path)
	s = model.iter_depth(iter)
	if s is not 0:
		return
	for n in range(model.iter_n_children(model.get_iter(path[0]))):
		model[int(path[0]), n][3] = a

def clean_tmp(tmpdir):
	for name in os.listdir(tmpdir):
		path_name = os.path.join(tmpdir, name)
		os.remove(path_name)
	os.rmdir(tmpdir)

def headerClick(TreeViewColumn, Column):
	print 'click', Column


def clear_root_iter(glade):
	treeview = glade.get_widget('job queue')
	model = treeview.get_model()
	iter_root = model.get_iter_root()
	if iter_root is None:
		return
	gtk.gdk.threads_enter()
	model.remove(iter_root)
	if len(model) ==0:
		glade.get_widget('del_task').set_sensitive(False)
	else:
		treeview.set_cursor(0)
	if len(model) == 1:
		glade.get_widget('job_up').set_sensitive(False)
		glade.get_widget('job_down').set_sensitive(False)
	gtk.gdk.threads_leave()

def getvar(file_name, dic, trac_number):
	level = dic['level']
	codec = dic['codec']
	title = dic[int(trac_number)]
	if 'performers' in dic:
		performer = dic['performers'][int(trac_number)]
	else:performer = dic['performer']

	if codec =='flac':
		arg = '%s -T TITLE="%s" -T ALBUM="%s" -T TRACKNUMBER=%s \
		-T ARTIST="%s" -T GENRE="%s" -T DATE="%s" \
		-T DESCRIPTION="gCue2tracks" -T COMPOSER="%s" ' % (
		get('flac'), title, dic['album'], trac_number,
		performer, dic['genre'],
		dic['date'], dic['composer'])
		if level =='mid':
			arg += '-5 '
		else:
			arg += '--%s ' %level

	if codec =='ogg':
		arg = '%s -a "%s" -d "%s" -G "%s" -l "%s" -N "%s" -t "%s" -c "%s"' % (
				get('ogg'), performer, dic['date'], dic['genre'],
				 dic['album'], trac_number, title, 'DESCRIPTION=gCue2tracks')

		if dic['bitratebtn']:
			if dic['VBR']:
				arg += ' -b %s ' %dic['bitrate']
			else:
				arg += ' --managed -b %s -M %s ' % (dic['bitrate'], dic['bitrate'])
		else:
			arg += ' -q %s ' %dic['quality']

	if codec =='mp3':
		arg = '%s --id3v2-only --ta "%s" --tt "%s" --tl "%s" --ty "%s" --tc "%s" \
			--tn "%s/%s" --tg "%s" --nohist' % (get('mp3'),
			performer, title, dic['album'], dic['date'], 'gCue2tracks',
			trac_number, dic['all_tr'], dic['genre'])
		if get('mp3advance'):
			if dic['bitratebtn']:
				if dic['VBR']:
					arg += ' -v -B %s -q %s ' % (dic['bitrate'], dic['quality'])
				else:
					arg += ' -b %s -q %s ' % (dic['bitrate'], dic['quality'])
		else:
			if dic['bitratebtn']:
				if dic['VBR']:
					arg += ' -v -B %s ' %dic['bitrate']
				else:
					arg += ' -b %s ' %dic['bitrate']
			else:
				arg += ' -q %s ' %dic['quality']

	if codec =='wv':
		arg = '%s -w "Title=%s" -w "Artist=%s" -w "Album=%s" '\
			'-w "Track=%s/%s" -w "Composer=%s" -w "Comment=gCue2tracks" '\
			'-w "Year=%s" -w "Genre=%s" ' % (
			get('wavpack'), title, performer, dic['album'],
			trac_number, dic['all_tr'], dic['composer'],
			dic['date'], dic['genre'])
		if level =='fast':
			arg +='-f '
		if level =='best':
			arg +='-hh '
		if level =='mid':
			arg +='-h '

	if codec =='ape':
		arg = '%s %s %s ' % (get('mac'), file_name, file_name + '.ape')
		if level =='fast':
			arg +='-c1000 '
		if level =='best':
			arg +='-c4000 '
		if level =='mid':
			arg +='-c2000 '
		return arg

	arg += file_name
	return arg

def encoder(tmpdir, dic):
	codec = dic['codec']
	if codec =='wav':
		return
	if Conversation.value == (_('Interrupted')):
		return
	if Conversation.value == 'error':
		print 'split error'
		print_log('split error', False)
		return
	tmp_file_list = []
	tr_list = dic['trlist'].split(',')
	tr_to_enc = str(len(tr_list))
	print 'start encode'
	print_log('start encode')

	# search tracks
	for name in os.listdir(tmpdir):
		if name.startswith('split-track'):
			file_name = os.path.join(tmpdir, name)
			tmp_file_list.append(file_name)
	tmp_file_list.sort()

	n = 0
	for file_name in tmp_file_list:
		trac_number = tr_list[n]
		title = dic[int(trac_number)]
		text = _('Encoding "%s" (%s/%s)  ') % (title, str(n+1), tr_to_enc)
		print text
		print_log(text)
		command = getvar(file_name, dic, trac_number).replace('`', '\`')
		print command
		print_log(command)
		if codec =='wv':
			process(command, dic, text = text)
		process(command, dic, True, text = text)
		if Conversation.value == 'error' or Conversation.value == (_('Interrupted')):
			return
		n +=1

def process(command, dic, progr = None, text = ''):

	def ss(a, b, n, fraction):
		b += a
		if a == '%':
			c = (b[-7:-1]).split(' ')
			try:
				c[-1] = c[-1].replace(',', '.').replace('[', '').replace('(', '')
			except:
				pass
			try:
				n = float(c[-1])
			except:
				pass
			b = '0000000'

		progres = n/100.0
		if progres > fraction:
			set_fraction_progressbar1(progres)
			prog_text = '%s%s%s' %(text, str(n), '%')
			set_text_progressbar1(prog_text)
			#preference.progressbar2.set_text(preference.progressbar2_text)
			fraction = progres
		if progres < fraction:
			set_fraction_progressbar1(0)
			fraction = 0
		return b, n, fraction


	if Conversation.value == (_('Interrupted')):
		return
	if Conversation.value == 'error':
		print ' error'
		return
	fraction = 0
	all_tr = dic['all_tr']
	tr_to_enc = len(dic['trlist'].split(','))
	set_text_progressbar1(text)
	progressbar2 = glade.get_widget('progressbar2')
	try:
		Conversation.value = 'in process'
		proc1 = subprocess.Popen(command, stdin=subprocess.PIPE,
				stdout=subprocess.PIPE, stderr=subprocess.PIPE,
				close_fds=True, shell=True)
		Conversation.pid = proc1.pid
		n = 0
		b = '0000000'
		while proc1.poll() == None:
			b, n, fraction = ss(proc1.stderr.read(1), b, n, fraction)
		while proc1.stderr.read(1):
			b, n, fraction = ss(proc1.stderr.read(1), b, n, fraction)
		if proc1.poll() not in [256, 0, -1]:
			set_fraction_progressbar1(0.0)
			if proc1.poll() == 9:
				set_text_progressbar1(_('Interrupted'))
				Conversation.value = (_('Interrupted'))
			else:
				set_text_progressbar1(_('Error'))
				Conversation.value = 'error'
		elif proc1.poll()==0:
			if progr:
				gtk.gdk.threads_enter()
				frac = progressbar2.get_fraction() +(1.0/(2 + tr_to_enc))
				progressbar2.set_fraction(frac)
				preference.progressbar2.set_fraction(frac)
				gtk.gdk.threads_leave()
			set_fraction_progressbar1(0)
			Conversation.value = 'complete'
	except:
		preference.trayicon.set_tooltip('error')
		Conversation.value = 'error'
		print 'error in ' + self.getName() + command
		print_log('error in ' + self.getName() + command)

def decode_to_wav(command, dic, text='', use_pbar=True):
	if Conversation.value == (_('Interrupted')):
		return
	if Conversation.value == 'error':
		print ' error'
		return
	fraction = 0
	all_tr = dic['all_tr']
	tr_to_enc = len(dic['trlist'].split(','))
	set_text_progressbar1(text)
	progressbar2 = glade.get_widget('progressbar2')
	Conversation.value = 'in process'
	proc1 = subprocess.Popen(command, stdin=subprocess.PIPE,
			stdout=subprocess.PIPE, stderr=subprocess.PIPE,
			close_fds=True, shell=True)
	Conversation.pid = proc1.pid
	a = ''
	while proc1.poll() == None:
		b = proc1.stderr.read(1)
		if b == '\r':
			#a =  'Duration: N/A, bitrate: N/A'
			u = re.search("Duration: (?P<name>.*?),",a)
			if u:
				u = u.group('name').split(':')
				if u[0] == 'N/A':
					duration = 0
					break
				duration = (int(u[0]) * 60 + int(u[1])) * 60 + \
													int(u[2].split('.')[0])
				break
		a += b
	while proc1.poll() == None:
		b = proc1.stderr.read(1)
		if b == '\r':
			u = re.search('time\s{0,}=\s{0,}(?P<time>\d+\.\d+)\s{1,}bitrate', a)
			if u:
				time = float(u.group('time').split('.')[0])
				if duration == 0:
					glade.get_widget('progressbar1').pulse()
				else:
					progres = time/duration
					set_fraction_progressbar1(progres)
					prog_text = '%s%s%s' %(text, str(int(progres*100)), '%')
					set_text_progressbar1(prog_text)
				a = ""
		a += b
	if proc1.poll() not in [256, 0, -1]:
		set_fraction_progressbar1(0.0)
		if proc1.poll() == 9:
			set_text_progressbar1(_('Interrupted'))
			Conversation.value = (_('Interrupted'))
		else:
			set_text_progressbar1(_('Error'))
			Conversation.value = 'error'
	elif proc1.poll()==0:
		if use_pbar:
			gtk.gdk.threads_enter()
			frac = progressbar2.get_fraction() +(1.0/(2 + tr_to_enc))
			progressbar2.set_fraction(frac)
			preference.progressbar2.set_fraction(frac)
			gtk.gdk.threads_leave()
		set_fraction_progressbar1(0)
		Conversation.value = 'complete'

class Copy_result():

	def __init__(self, tmpdir, dic):
		self.tmpdir = tmpdir
		self.dic = dic

	def run(self):
		if Conversation.value == (_('Interrupted')):
			clean_tmp(self.tmpdir)
			return
		if Conversation.value == 'error':
			print 'cleaning temp'
			print_log('cleaning temp')
			clean_tmp(self.tmpdir)
			return
		print 'start copy file'
		print_log('start copy file')
		if self.dic['codec'] =='mp3' and get('mp3_utf'):
			# 'python-mutagen'
			set_text_progressbar1(_('Convert tag to UTF-8'))
			for root, dirs, files in os.walk(self.tmpdir):
				for f in files:
					if f.endswith('mp3'):
						conv = 'mid3iconv -e UTF-8 "%s/%s"' % (root, f)
						proc1 = subprocess.Popen(conv, shell=True)
						os.waitpid(proc1.pid, 0)

		dic = {
			'%A': self.dic['album'],
			'%a': 'Album disc number',
			'%P': self.dic['performer'],
			'%D': self.dic['date'],
			'%G': self.dic['genre'],
			'%t': 'Track title',
			'%p': self.dic['performer'],
			'%g': self.dic['genre'],
			'%n': '%name',
			'%N': 'Track number'}
		if self.dic['date'] is '':
			dic['%D'] = 'unknown'
		format = get('format')
		for n in dic:
			try:
				format = format.replace(n, dic[n])
			except:
				pass
		newdir = format[:format.rfind('/')]
		try:
			set_text_progressbar1(_('Create folder'))
			newdir = self.dic['folder'] + newdir
			os.makedirs(newdir)
		except OSError, (errno, strerror):
			if errno == 13:
				print 'OSError(%s): %s' % (errno, strerror)
				print_log('OSError(%s): %s   can\'t create new dir "%s"' % (
													errno, strerror, newdir))
				clean_tmp(self.tmpdir)
				return

		newname_ = format[format.rfind('/') + 1:]
		tr_list = self.dic['trlist'].split(',')
		tmp_file_list = []
		for name in os.listdir(self.tmpdir):
			if name.endswith(self.dic['codec']) and name.startswith('split'):
				tmp_file_list.append(name)
		tmp_file_list.sort()

		os.chdir(self.tmpdir)
		n = 0
		filtr = re.compile(r"[?\\*:><\"\|]") # filename filter ?  \ * : >< " |
		filename_filter = get('filename_filter')
		for file_name in tmp_file_list:
			self.trac_number = tr_list[n]
			self.title = self.dic[int(self.trac_number)]
			try:
				newname = newname_.replace('Track title', self.title)
				newname = newname.replace('%name', str(int(self.trac_number)))
			except:
				pass
			try:
				newname = newname.replace('Track number', self.trac_number)
			except:
				pass
			newname += '.%s' %self.dic['codec']
			# replace ? / \ * : >< " | in filenames
			if '/' in newname:
				newname = newname.replace('/', '_')
			if filename_filter:
				newname = filtr.sub('_', newname)

			os.rename(file_name, newname)
			set_text_progressbar1(_('Taging and copy %s' %newname))
			print newname, '=>> ' + newdir
			print_log(newname, '=>> ' + newdir)
			move(newname, newdir)
			n += 1

		if get('copy_image') and self.dic['filename'] != newdir:
			'''copy image files '''
			set_text_progressbar1(_('Copy image files '))
			import mimetypes
			copy_from = os.path.dirname(self.dic['filename'])
			mimetypes.init()
			for root, dirs, files in os.walk(copy_from):
				for name in dirs:
					if name not in newdir:
						try:
							os.mkdir(os.path.join(newdir, name))
						except OSError, (errno, strerror):
							pass#print 'OSError(%s): %s (%s)' \
							#% (errno, strerror, os.path.join(newdir, name))
				for name in files:
					filetype = mimetypes.guess_type(name)[0]
					if type(filetype) is str:
						filetype = filetype.split('/')[0]
						if filetype =='image':
							try:
								copy(
										os.path.join(root, name),
										newdir + root.replace(copy_from, ''))
							except:
								pass
			for root, dirs, files in os.walk(newdir):
				for name in dirs:
					if os.listdir(os.path.join(root, name)) == []:
						os.rmdir(os.path.join(root, name))
		set_text_progressbar1(_('Complete'))
		del dic
		clean_tmp(self.tmpdir)
		progressbar2=glade.get_widget('progressbar2')
		gtk.gdk.threads_enter()
		progressbar2.set_fraction(1)
		preference.progressbar2.set_fraction(1)
		gtk.gdk.threads_leave()


class Conversation(threading.Thread):

	def __init__(self):
		threading.Thread.__init__(self)
		Conversation.value = None

	def run(self):
		treeview = glade.get_widget('job queue')
		model = treeview.get_model()
		while len(model) > 0:
			start()
			if Conversation.value == (_('Interrupted')):
				print Conversation.value
				break
		gtk.gdk.threads_enter()
		glade.get_widget('progressbar2').set_text('  ')
		preference.progressbar2.set_text('  ')
		glade.get_widget('stop_button').set_sensitive(False)
		gtk.gdk.threads_leave()

	def stop(self):
		return Conversation.pid
