#!/usr/bin/python
#-*- coding: utf-8 -*-

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

_ = 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 = builder.get_object('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(builder):
	codecs = ['ogg', 'mp3', 'flac', 'wav', 'ape', 'wv']
	list_store = gtk.ListStore(gobject.TYPE_STRING)
	map(lambda x: list_store.append([x]), codecs)
	codec_widget = builder.get_object('codec')
	codec_widget.set_model(list_store)
	st = get('codec')
	codec_widget.set_active(st)
	cell = gtk.CellRendererText()
	codec_widget.pack_start(cell, True)
	codec_widget.add_attribute(cell, 'text', 0)

def varc(builder1, pathglade1, QUIET):
	global builder, pathglade, QUIET1
	builder = builder1
	pathglade = pathglade1
	QUIET1 = QUIET

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

def show_dialog(message):
	try: log_message = message.replace('<b>', '').replace('</b>', '')
	except: pass
	print log_message
	print_log(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()
	builder.get_object('progressbar1').set_text(text)
	preference.progressbar1.set_text(text)
	gtk.gdk.threads_leave()

def	set_fraction_progressbar1(fraction):
	gtk.gdk.threads_enter()
	builder.get_object('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 file_not_found():
		gtk.gdk.threads_enter()
		message = (_('File \n<b>%s</b>\nnot found') %bin_file)
		show_dialog(message)
		Conversation.value = 'error'
		builder.get_object('start').set_sensitive(True)
		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)
		builder.get_object('stop_button').set_sensitive(False)
		gtk.gdk.threads_leave()
		return

	treeview = builder.get_object('job queue')
	model = treeview.get_model()
	dic = model[0][5]

	# is codec exits?
	if not is_codec_exits(dic):
		return

	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][1]:
			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][1]:
			dic[n+1] = model[0, n][2]
	#clear_root_iter(glade)
	Conversation.job_name = '%s - %s' %(dic['performer'], dic['album'])
	gtk.gdk.threads_enter()
	builder.get_object('stop_button').set_sensitive(True)
	progressbar2=builder.get_object('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)
			print command
			print bin_file.replace("'", "\'")
			text = _('Decoding to wav %(filename)s (%(num)s/%(allnum)s ')\
				% {'filename': dic[int(n)], 'num': int(n), 'allnum': all_tr}
			decode_to_wav(command.encode('utf-8'), dic, text, False)
			print_log(text)
			gtk.gdk.threads_enter()
			progressbar2 = builder.get_object('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:
		"""
		create breakpoints file
		"""
		create_breakpoints(dic, 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()
	clear_root_iter()

def create_breakpoints(dic, tmpdir):
	points = ''
	myfile = '%s/cuebreakpoints' % tmpdir
	f = open(myfile, "w")
	for line in open(dic['filename']):
		u = re.search("INDEX 01 (?P<sec>\w+:\w+):(?P<msec>\w+)",line)
		if u:
			points += '%s.%s\n' %(u.group('sec'), u.group('msec'))
	points = points[points.find('\n') + 1:]
	f.write(points)
	f.close()

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

def col1_toggled_cb(cell, path, model):
	a = model[path][1] = not model[path][1]
	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))):
		model[int(path), n][1] = 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():
	treeview = builder.get_object('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:
		builder.get_object('del_task').set_sensitive(False)
	else:
		treeview.set_cursor(0)
	if len(model) == 1:
		builder.get_object('job_up').set_sensitive(False)
		builder.get_object('job_down').set_sensitive(False)
	gtk.gdk.threads_leave()

def is_codec_exits(dic):
	path = get(dic['codec'])
	if not os.path.isfile(path.encode('utf-8')):
		message = _('Codec\n <b>%s</b>\nmissing') % path
		gtk.gdk.threads_enter()
		show_dialog(message)
		gtk.gdk.threads_leave()
		Conversation.value = 'error'
		builder.get_object('start').set_sensitive(True)
		return False
	return True

def getvar(file_name, dic, trac_number):
	levels = {0: 'best', 1:'mid', 2:'fast'}
	level = levels[dic['level_n']]
	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('ape'), 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(',')
	"""
	TODO remove this
	"""
	###########################
	if 'performers' in dic:
		if dic['all_tr'] is len(dic['performers']):
			a = dic['performers']
			a.insert(0,'N/A')
			dic['performers'] = a
	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 "%(title)s" (%(track)s/%(alltrack)s)  ') % \
		{'title': title, 'track': str(n+1), 'alltrack':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 = builder.get_object('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 = builder.get_object('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:
					builder.get_object('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 = builder.get_object('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 = builder.get_object('job queue')
		model = treeview.get_model()
		while len(model) > 0:
			start()
			if Conversation.value == 'error':
				gtk.gdk.threads_enter()
				builder.get_object('progressbar1').set_text(_('Interrupted'))
				preference.progressbar1.set_text(_('Interrupted'))
				gtk.gdk.threads_leave()
				break
		gtk.gdk.threads_enter()
		builder.get_object('progressbar2').set_text('  ')
		preference.progressbar2.set_text('  ')
		builder.get_object('stop_button').set_sensitive(False)
		gtk.gdk.threads_leave()

	def stop(self):
		return Conversation.pid
