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

import gtk
import threading
import subprocess
from string import find
import time
import sys
import gettext
import locale
import pango
import getopt
import gobject
import urllib
import re

from config import *
from decoder import *
import preference as preference

VERSION = '0.5.0'


def get_file_path_from_dnd_dropped_uri(uri):
	path = urllib.url2pathname(uri) # escape special chars
	path = path.strip('\r\n\x00') # remove \r\n and NULL
	# get the path to file
	if path.startswith('file://'): # nautilus, rox
		path = path[7:]
	elif path.startswith('file:'): # xffm
		path = path[5:]
	return path


def on_mainWindow_drag_data_received(
				widget, drag_context, x, y, selection_data, target_type, time):
	if target_type == 0:
		uri = selection_data.data.strip()
		uri_splitted = uri.split()
		thread = None
		for uri in uri_splitted:
			path = get_file_path_from_dnd_dropped_uri(uri)
			if os.path.isdir(path): # is it dir?
				thread = Searching_cue(thread=thread, folder_cue=path)
				thread.start()
			else:
				if path.endswith('.cue'):
					builder.get_object('filename').set_text(path)
					gui.bloc = True
					gui.getcuetag(path)
					gui.add_task(widget)
					gui.bloc = False


def treeview_setup_dnd(treeview):
	"""Setup a treeview to move rows using drag and drop.  """
	target_entries = [('MY_TREE_MODEL_ROW', gtk.TARGET_SAME_WIDGET, 0),
						('text/plain', 0, 1),
						('TEXT', 0, 2),
						('STRING', 0, 3), ]
	treeview.enable_model_drag_source(
		gtk.gdk.BUTTON1_MASK, target_entries, gtk.gdk.ACTION_MOVE)
	treeview.enable_model_drag_dest(target_entries, gtk.gdk.ACTION_MOVE)
	treeview.connect('drag-data-received', drag_data_received_data)
	treeview.connect('drag_data_get', drag_data_get_data)
	treeview.connect('cursor-changed', on_selection_changed)


def drag_data_get_data(treeview, context, selection, target_id, etime):
	treeselection = treeview.get_selection()


def drag_data_received_data(treeview, context, x, y, selection, info, etime):
	model_to_copy, iter_to_copy = treeview.get_selection().get_selected_rows()
	model = treeview.get_model()
	drop_info = treeview.get_dest_row_at_pos(x, y)
	if drop_info:
		path, position = drop_info
		iter = model.get_iter(path)
		if model.iter_depth(iter)is not 0:
			return
		if (position == gtk.TREE_VIEW_DROP_BEFORE
			or position == gtk.TREE_VIEW_DROP_INTO_OR_BEFORE):
			model_to_copy.move_before(model.get_iter(iter_to_copy[0]), iter)
		else:
			model_to_copy.move_after(model.get_iter(iter_to_copy[0]), iter)
	else:
		model_to_copy.move_after(model.get_iter(iter_to_copy[0]),
											model.get_iter(len(model)-1))
	for n in range(len(model)):
		model[n][0] = n + 1


def on_selection_changed(treeview):
	cursor_position = treeview.get_cursor()[0]
	if not cursor_position:
		return

	'''restore parametrs if cursor changes'''
	try:
		a = gui.bloc
	except:
		return
	gui.bloc = True
	dic = treeview.get_model()[cursor_position[0]][5]
	widget = [
		'quality', 'album', 'date', 'genre', 'composer',
		'bin_file', 'filename', 'performer']
	map(lambda x: builder.get_object(x).set_text(dic[x]), widget)
	var = [
		'bitratebtn', 'VBR',
		'same_folder', 'qualitybtn']
	map(lambda x: builder.get_object(x).set_active(dic[x]), var)
	builder.get_object('level').set_active(dic['level_n'])
	builder.get_object('codec').set_active(dic['codec_n'])
	builder.get_object('bitrate').set_value(float(dic['bitrate']))
	builder.get_object('savefolder').set_text(dic['folder'])
	gui.bloc = a

	if len(cursor_position) > 1:
		gui.renderer.set_property('editable', True)
	else:
		gui.renderer.set_property('editable', False)
		#if treeview.get_cursor()[1] is treeview.get_column(0):
			#if treeview.row_expanded(cursor_position):
				#treeview.collapse_row(cursor_position)
			#else:
				#treeview.expand_to_path(cursor_position)


def notebook(widget, a, b):
	gobject.timeout_add(60, lambda: builder.get_object('start').grab_focus())


def changeg(widget):
	builder.get_object('VBR').set_sensitive(
								builder.get_object('bitratebtn').get_active())
	builder.get_object('bitrate').set_sensitive(
								builder.get_object('bitratebtn').get_active())
	builder.get_object('quality').set_sensitive(
								builder.get_object('qualitybtn').get_active())
	codecn = builder.get_object('codec').get_active_text()
	if codecn not in ['mp3', 'ogg']:
		builder.get_object('VBR').set_sensitive(False)
		builder.get_object('bitrate').set_sensitive(False)
		builder.get_object('quality').set_sensitive(False)
		return
	if codecn == 'mp3' and get('mp3advance'):
		builder.get_object('VBR').set_sensitive(True)
		builder.get_object('bitrate').set_sensitive(True)
		builder.get_object('quality').set_sensitive(True)
	if codecn == 'ogg':
		builder.get_object('bitrate').set_range(32, 500)
	else:
		builder.get_object('bitrate').set_range(32, 320)


def show_log(widget):
	show = builder.get_object('show_log').get_active()
	builder.get_object('log').set_property('visible', show)
	builder.get_object('mainWindow').resize(1, 1)
	set('show_log', show)


def job_down(widget):
	cursor_position = gui.treeview.get_cursor()[0][0]
	if cursor_position == len(gui.tree_store) - 1:
		return
	iter = gui.tree_store.get_iter(cursor_position)
	gui.tree_store.move_after(iter,
		gui.tree_store.get_iter(cursor_position + 1))
	for n in range(len(gui.tree_store)):
		gui.tree_store[n][0] = n + 1


def job_up(widget):
	cursor_position = gui.treeview.get_cursor()[0][0]
	if cursor_position == 0:
		return
	iter = gui.tree_store.get_iter(cursor_position)
	gui.tree_store.move_before(iter,
			gui.tree_store.get_iter(cursor_position - 1))
	for n in range(len(gui.tree_store)):
		gui.tree_store[n][0] = n + 1


def isutf(line):
	if get('convert_cue'):
		try:
			s = line.decode('utf-8')
		except:
			try:
				line = line.decode(get('codepage'))
			except:
				message = _('Bad codepage')
				print message
				try:
					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)
					if len(threading.enumerate()) > 1:
						return ''
					response = dialog.run()
					dialog.destroy()
				except:
					pass
				line = '							  '
	return line


class Searching_cue(threading.Thread):

	def __init__(self, thread=None, folder_cue=None):
		threading.Thread.__init__(self)
		self.thread = thread
		self.folder_cue = folder_cue

	def run(self):
		if self.thread:
			self.thread.join()
		self.bloc = True
		builder.get_object('find_cue').set_sensitive(False)
		treeview = builder.get_object('job queue')
		tree_store = treeview.get_model()
		if self.folder_cue:
			folder_cue = self.folder_cue
		else:
			folder_cue = builder.get_object('find_cue_folder').get_text()
		set('find_cue_folder', folder_cue)
		if not os.path.isdir(folder_cue):
			return
		quality = builder.get_object('quality').get_text()
		bitrate = str(int(builder.get_object('bitrate').get_value()))
		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()
		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()
		prog = re.compile(r'".+"')
		for root, dirs, files in os.walk(folder_cue):
			for name in files:
				if name.endswith('cue'):
					filename = os.path.join(root, name)
					GuiPart.folder = root
					if builder.get_object('same_folder').get_active():
						folder = root
					'''get tag from cue file'''
					dic = {
		'performer': '', 'album': '', 'date': '', 'genre': '', 'composer': '',
		'bitrate': bitrate, 'quality': quality, 'filename': filename,
		'level': level, 'level_n': level_n, 'VBR': VBR, 'codec': codec,
		'bitratebtn': bitratebtn, 'qualitybtn': qualitybtn,
		'codec_n': codec_n, 'folder': folder, 'same_folder': same_folder,
					}
					f = open(filename, 'r')
					line = f.readline()#.replace('"', '')
					result = prog.findall(line)
					if result:
						result = isutf(result[0].replace('"', ''))
					gui.bin_filename = None
					track, filename, title, performers = [], [], [], []
					while line:
						if 'TRACK' in line and 'REM' not in line:
							track.append(line.strip()[6:8])
						if 'GENRE' in line:
							dic['genre'] = line[10:-2].replace('"', '')
						if 'DATE' in line:
							dic['date'] = line.split(' ')[2][:4]
						if 'PERFORMER' in line:
							dic['performer'] = result
							performers.append(result)
						if 'COMPOSER' in line:
							dic['composer'] = result
						if 'TITLE' in line:
							if line[0]==' ':
								title.append(result)
							else:
								dic['album'] = result
						if 'FILE' in line:

							# if multitrack
							seek = f.tell()
							line1 = f.readline()
							if 'TRACK' in line1:
								filename.append(isutf(line)[5:-2].replace(
											' WAVE', '').replace('"', ''))
							f.seek(seek)

							gui.bin_filename = (isutf(line)[5:-2]).replace(
													' WAVE', '').replace('"', '')
							full_path = os.path.join(root, gui.bin_filename)
							if not os.path.isfile(full_path.encode('utf-8')):
								gui.bin_filename = gui.find_bin(root)
								if not gui.bin_filename:
									gui.bin_filename = 'None'
									message = _('Bin file not found\n<b>%s</b>') %full_path
									gtk.gdk.threads_enter()
									print message.replace('<b>', '').replace('</b>', '')
									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()
									dialog.destroy()
									gtk.gdk.threads_leave()
							dic['bin_file'] = gui.bin_filename
						line = f.readline()
						result = prog.findall(line)
						if result:
							result = isutf(result[0].replace('"', ''))
					if gui.bin_filename is None:
						f.close()
						break
					f.close()
					'''get album length'''
					if len(filename) is not 1:
						dic['bin_files'] = filename
					if len(performers) is not 1:
						dic['performers'] = performers
						for n in range(len(performers)-1):
							if performers[n] != performers[n + 1]:
								dic['performer'] = _('Various artists')
					gtk.gdk.threads_enter()
					tree_store.append(
						None, (len(tree_store) + 1, True, '%s - %s' % (
						dic['performer'], dic['album']),
						None, None, dic))
					treeview.set_cursor(len(tree_store) - 1)
					iter = tree_store.get_iter(len(tree_store) - 1)
					n = 0
					for item in title:
						n += 1
						tree_store.append(iter,
							(track[n-1], True, item, None,
							treeview.get_style().base[gtk.STATE_SELECTED].to_string(), None))
					gtk.gdk.threads_leave()
					break
		gtk.gdk.threads_enter()
		builder.get_object('del_task').set_sensitive(True)
		if len(tree_store) > 0:
			builder.get_object('start').set_sensitive(True)
		builder.get_object('start').grab_focus()
		builder.get_object('find_cue').set_sensitive(True)
		if len(tree_store) > 1:
			builder.get_object('job_up').set_sensitive(True)
			builder.get_object('job_down').set_sensitive(True)
		gtk.gdk.threads_leave()
		print 'searching cue done'
		self.bloc = False


class Add_queue(threading.Thread):

	def __init__(self, job_name, dic):
		threading.Thread.__init__(self)
		self.job_name = job_name
		self.dic = dic

	def run(self):
		treeview = builder.get_object('job queue')
		tree_store = treeview.get_model()
		gtk.gdk.threads_enter()
		tree_store.append(
					None, (len(tree_store)+1, True, self.job_name,
					None, None, self.dic))
		treeview.set_cursor(len(tree_store) - 1)
		if len(tree_store) == 2:
			builder.get_object('job_up').set_sensitive(True)
			builder.get_object('job_down').set_sensitive(True)
		if len(threading.enumerate()) > 2:
			progressbar2=builder.get_object('progressbar2')
			text = '%s   in queue:%s' %(Conversation.job_name,len(tree_store))
			progressbar2.set_text(text)
			preference.progressbar2.set_text(text)
		gtk.gdk.threads_leave()
		"""
			get tags
		"""
		filename = builder.get_object('filename').get_text()
		path = os.path.split(filename)[0]
		f = open(filename, 'r')
		track, filename, title , performers = [], [], [], []
		line = f.readline()
		prog = re.compile(r'".+"')
		result = prog.findall(line)
		if result:
			result = isutf(result[0].replace('"', ''))
		while line:
			if 'TITLE' in line and line[0]==' ':
				title.append(result)
			line = line.replace('"', "")
			if 'TRACK' in line and 'REM' not in line:
				track.append(line.strip()[6:8])
			if 'FILE' in line:
				seek = f.tell()
				line1 = f.readline()
				if 'TRACK' in line1:
					filename.append(isutf(line)[5:-2].replace(' WAVE', ''))
				f.seek(seek)
			if 'PERFORMER' in line:
				performers.append(result)
			line = f.readline()
			result = prog.findall(line)
			if result:
				result = isutf(result[0].replace('"', ''))
		f.close()
		"""
			get album length
		"""
		n = 0
		iter = tree_store.get_iter(len(tree_store)-1)
		gtk.gdk.threads_enter()
		for item in title:
			n += 1
			tree_store.append(iter,(track[n-1], True, item, '',
				treeview.get_style().base[gtk.STATE_SELECTED].to_string(), None))
		gtk.gdk.threads_leave()
		if len(filename) != 1:
			dic = tree_store[iter][5]
			dic.update(bin_files = filename)
			tree_store[iter][5] = dic
			builder.get_object('bin_file').set_text('tracks')
		if len(performers) is not 1:
			self.dic['performers'] = performers
			for n in range(len(performers)-1):
				if performers[n] != performers[n + 1]:
					builder.get_object('performer').set_text(_('Various artists'))

class GuiPart:

	def __init__(self):

		def insert_one_tag_into_buffer(buffer, name, *params):
			tag = gtk.TextTag(name)
			while(params):
				tag.set_property(params[0], params[1])
				params = params[2:]
			table = buffer.get_tag_table()
			table.add(tag)

		self.bloc = True
		dic = {'on_mainWindow_destroy': self.endApplication,
				'onf': self.onf, 'start_recomp': self.start_recomp,
				'bsave': self.bsave, 'stop': self.stop,
				'on_about1_activate': self.on_about_activate,
				'codec_changed': self.codec_changed,
				'changeg': changeg, 'sync': self.sync,
				'show_log': show_log, 'note-book': notebook,
				'on_preference_activate': on_preference_activate,
				'add_task': self.add_task, 'del_task': self.del_task,
				'job_down': job_down, 'job_up': job_up,
				'find_cue': self.find_cue, 'find_cue_dialog': self.find_cue_dialog,
				'on_mainWindow_drag_data_received': on_mainWindow_drag_data_received}
		builder.connect_signals(dic)
		del dic
		bitrait = builder.get_object('bitrate')
		'''read config'''
		bitrait.set_value(get('bitrait'))
		builder.get_object('quality').set_text(get('quality'))
		builder.get_object('savefolder').set_text(get('savepath'))
		builder.get_object('find_cue_folder').set_text(get('find_cue_folder'))

		levels = ['best', 'mid', 'fast']
		list_store = gtk.ListStore(gobject.TYPE_STRING)
		map(lambda x: list_store.append([x]), levels)
		levels_widget = builder.get_object('level')
		levels_widget.set_model(list_store)
		st = get('level')
		levels_widget.set_active(st)
		cell = gtk.CellRendererText()
		levels_widget.pack_start(cell, True)
		levels_widget.add_attribute(cell, 'text', 0)


		widget = [
			'same_folder', 'show_log', 'level', 'qualitybtn', 'VBR']
		map(lambda x: set(x, builder.get_object(x).set_active(get(x))), widget)
		codecs_list(builder)
		if builder.get_object('codec').get_active_text() == 'ogg':
			bitrait.set_range(32, 500)
		GuiPart.textview = builder.get_object('textview1')
		buffer=GuiPart.textview.get_buffer()
		insert_one_tag_into_buffer(buffer, 'bold', 'weight', pango.WEIGHT_BOLD)
		builder.get_object('log').set_property('visible', get('show_log'))
		win = builder.get_object('mainWindow')
		win.set_property('skip-taskbar-hint', get('show_in_taskbar'))
		win.drag_dest_set(gtk.DEST_DEFAULT_ALL,
								[('text/uri-list', 0, 0)], gtk.gdk.ACTION_MOVE)
		#win.reshow_with_initial_size()
		'''first build'''
		self.treeview = builder.get_object('job queue')
		self.treeview.set_rules_hint(True)
		self.treeview.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
		self.tree_store = self.treeview.get_model()
		self.tree_store = gtk.TreeStore(str, 'gboolean',str, str, str,
														gobject.TYPE_PYOBJECT)

		TARGETS = [
					('MY_TREE_MODEL_ROW', gtk.TARGET_SAME_WIDGET, 0),
					('text/plain', 0, 1),
					('TEXT', 0, 2),
					('STRING', 0, 3),
					]

		self.treeview.set_model(self.tree_store)
		treeview_setup_dnd(self.treeview)
		renderer0 = gtk.CellRendererText()
		column = gtk.TreeViewColumn('', renderer0, text=0)
		self.renderer = gtk.CellRendererText()
		self.renderer.set_properties(
								xalign=0, editable=True)
		self.renderer.connect('edited', col0_edited_cb, self.tree_store)
		self.renderer1 = gtk.CellRendererToggle()
		self.renderer1.set_properties(
							xalign=1.0, activatable=True)
		self.renderer1.connect('toggled', col1_toggled_cb, self.tree_store)
		column1 = gtk.TreeViewColumn('', self.renderer1)
		column1.add_attribute(self.renderer1, 'active', 1)
		column1.set_clickable(True)
		column0 = gtk.TreeViewColumn(_('Track name'), self.renderer, text=2)
		column0.add_attribute(self.renderer, 'foreground', 4)
		column.add_attribute(renderer0, 'foreground', 4)
		column0.set_resizable(True)
		column1.set_resizable(False)
		self.treeview.append_column(column)
		self.treeview.append_column(column1)
		self.treeview.append_column(column0)
		if ARGS:
			filename = ARGS[-1]
			if os.path.isdir(filename): # is it dir?
				thread = Searching_cue(thread=None, folder_cue=filename)
				thread.start()
				self.bloc = False
				return
			if not os.path.isfile(filename):
				print _('Wrong filename or folder'), filename
				self.bloc = False
				return
			path = os.path.split(filename)[0]
			builder.get_object('filename').set_text(filename)
			builder.get_object('start').set_sensitive(True)
			gtk.gdk.threads_enter()
			self.getcuetag(filename)
			gtk.gdk.threads_leave()
			self.add_task(self)
		self.bloc = False

	def on_about_activate(self, widget):
		"""
			about gcue2tracks
		"""
		if  os.path.isfile('/usr/share/common-licenses/GPL-2'):
			fd = open('/usr/share/common-licenses/GPL-2')
			text = fd.read()
			fd.close()
		else:
			text = "This program 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 2 \
of the License, or (at your option) any later version. \
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 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 ."
		pathglade = os.path.join(workdir, 'ui/aboutdialog.glade')
 		builder.add_from_file(pathglade)
 		about = builder.get_object('aboutdialog1')
		about.set_license(text)
		about.set_wrap_license(True)
		about.set_comments(
			'GTK+ Version: %s\nPyGTK Version: %s'
			% (self.tuple2str(gtk.gtk_version),
			self.tuple2str(gtk.pygtk_version)))
		about.set_website('http://trac-hg.assembla.com/gCue2tracks/wiki')
		about.set_version(VERSION)
		authors = []
		author = 'gCue2tracks: \n\tFomin Denis (fominde@gmail.com)'
		authors.append(author)
		authors.append(
		'\n%s\n\tOleg N. Stadnik (mail@lokee.rv.ua)\
		\n\tgoogle moogle\n\tEvgen \n\tLe Gluon du Net' %_('THANKS:'))
		about.set_authors(authors)
		#about.set_artists('graf designer')
		for button in about.action_area.get_children():
			if button.get_property('label') == gtk.STOCK_CLOSE:
				button.connect('clicked', lambda x: about.hide())
		about.show()

	def tuple2str(self, tuple_):
		str_ = ''
		for num in tuple_:
			str_ += str(num) + '.'
		return str_[0:-1]

	def codec_changed(self, widget):
		if builder.get_object('codec').get_active_text() == 'mp3':
			is_bitratebtn = builder.get_object('bitratebtn').get_active()
			builder.get_object('VBR').set_sensitive(is_bitratebtn)
			builder.get_object('bitrate').set_sensitive(is_bitratebtn)
			is_qualitybtn = builder.get_object('qualitybtn').get_active()
			builder.get_object('qualitybtn').set_active(is_qualitybtn)
			builder.get_object('quality').set_sensitive(is_qualitybtn)
			builder.get_object('bitrate').set_range(32, 320)
			builder.get_object('level').set_sensitive(False)
			builder.get_object('bitratebtn').set_sensitive(True)
			builder.get_object('qualitybtn').set_sensitive(True)
			if get('mp3advance'):
				builder.get_object('quality').set_sensitive(True)
			return
		if builder.get_object('codec').get_active_text() == 'ogg':
			builder.get_object('qualitybtn').set_active(get('qualitybtn'))
			builder.get_object('VBR').set_sensitive(
				not builder.get_object('qualitybtn').get_active())
			builder.get_object('bitrate').set_sensitive(
				not builder.get_object('qualitybtn').get_active())
			builder.get_object('level').set_sensitive(False)
			builder.get_object('bitrate').set_range(32, 500)
			builder.get_object('bitratebtn').set_sensitive(True)
			builder.get_object('qualitybtn').set_sensitive(True)
			builder.get_object('quality').set_sensitive(
				builder.get_object('qualitybtn').get_active())
			return
		widget = [
			'VBR', 'bitrate', 'quality', 'bitratebtn', 'qualitybtn']
		map(lambda x: builder.get_object(x).set_sensitive(False), widget)
		builder.get_object('level').set_sensitive(True)

	def sync(self, widget):
		if not self.bloc:
			cursor = self.treeview.get_cursor()
			if len(builder.get_object('job queue').get_model()) < 1:
				cursor = ((0, 0), 0)
				return
			treeview = builder.get_object('job queue')
			model = treeview.get_model()
			dic = model[cursor[0]][5]
			dic.update(parametrs(builder).items())
			model[cursor[0]][5] = dic

	def find_cue_dialog(self, widget):
		dialog = gtk.FileChooserDialog(_('Select folder'), None,
						gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
						(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
						gtk.STOCK_OPEN, gtk.RESPONSE_OK))
		dialog.set_default_response(gtk.RESPONSE_OK)
		if not os.path.exists(get('open_folder')):
			set('open_folder', os.path.expanduser('~'))
		dialog.set_current_folder(get('open_folder'))
		response = dialog.run()
		if response == gtk.RESPONSE_OK:
			builder.get_object('find_cue_folder').set_text(dialog.get_filename())
		dialog.destroy()

	def onf(self, widget):
		"""open file dialog"""
		dialog = gtk.FileChooserDialog(_('Open'), None,
						gtk.FILE_CHOOSER_ACTION_OPEN,
						(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
						gtk.STOCK_OPEN, gtk.RESPONSE_OK))

		dialog.set_default_response(gtk.RESPONSE_OK)
		if not os.path.exists(get('open_folder')):
			set('open_folder', os.path.expanduser('~'))
		dialog.set_current_folder(get('open_folder'))
		try:
			dialog.set_icon_from_file('/usr/share/pixmaps/gCue2tracks.png')
		except:
			pass
		filter = gtk.FileFilter()
		filter.set_name('Cue')
		filter.add_pattern('*.cue')
		dialog.add_filter(filter)
		filter = gtk.FileFilter()
		filter.set_name(_('All files'))
		filter.add_pattern('*')
		dialog.add_filter(filter)
		response = dialog.run()
		if response == gtk.RESPONSE_OK:
			self.bloc = True
			self.filename = dialog.get_filename()
			builder.get_object('filename').set_text(self.filename)
			if builder.get_object('same_folder').get_active():
				builder.get_object('savefolder').set_text(dialog.get_current_folder())
			self.getcuetag()
			self.bloc = False
			if builder.get_object('bin_file').get_text() is '':
				dialog.destroy()
				message = _('Bin file not found\n<b>%s</b>') %''
				show_dialog(message)
				return
			self.add_task(self)
			builder.get_object('start').set_sensitive(True)
			builder.get_object('start').grab_focus()
		dialog.destroy()

	def getcuetag(self, filename = None):
		'''get tag from cue file'''
		if filename is None:
			if not os.path.isfile(self.filename):
				return
			path = os.path.split(self.filename)[0]
			f = open(self.filename, 'r')
		else:
			path = os.path.split(filename)[0]
			f = open(filename, 'r')
			if builder.get_object('same_folder').get_active():
				builder.get_object('savefolder').set_text(path)
		fields = ['genre', 'date', 'performer', 'album', 'composer']
		map(lambda x: builder.get_object(x).set_text(''), fields)
		line = f.readline()#.replace('"','')
		prog = re.compile(r'".+"')
		result = prog.findall(line)
		if result:
			result = isutf(result[0].replace('"', ''))
		while line:
			if 'TRACK' in line:
				break
			if 'GENRE' in line:
				builder.get_object('genre').set_text(line[10:-2].replace('"', ''))
			if 'DATE' in line:
				builder.get_object('date').set_text(line.split(' ')[2][:4])
			if 'PERFORMER' in line:
				builder.get_object('performer').set_text(result)
			if 'COMPOSER' in line:
				builder.get_object('composer').set_text(result)
			if 'TITLE' in line:
				builder.get_object('album').set_text(result)
			if 'FILE' in line:
				a = (isutf(line)[5:-2]).replace(' WAVE', '').replace('"', '')
				full_path = os.path.join(path, a)
				if not os.path.isfile(full_path.encode('utf-8')):
					a = self.find_bin(path)
					if not a:
						a = 'None'
						message = _('Bin file not found\n<b>%s</b>') %full_path
						builder.get_object('bin_file').set_text('tracks')
						show_dialog(message)
				builder.get_object('bin_file').set_text(a)
			line = f.readline()#.replace('"','')
			result = prog.findall(line)
			if result:
				result = isutf(result[0].replace('"', ''))
		f.close()

	def find_cue(self, widget):
		thread = Searching_cue()
		thread.start()

	def find_bin(self, path):
		extention = ('ape', 'flac', 'wv', 'flake', 'wav', 'tta')
		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) or not ext:
					path_name = os.path.split(path_name)
					return path_name[-1].decode('utf8')

	def bsave(self, widget):

		def dialogdestroy(widget):
			dialog.destroy()

		def bsaveok(widget):
			path = dialog.get_filename().decode(sys.getfilesystemencoding())
			builder.get_object('savefolder').set_text(path)
			set('save_folder', path)
			dialog.destroy()

		pathglade = os.path.join(workdir, 'ui/filechooserdialog.glade')
		builder.add_from_file(pathglade)
		dialog = builder.get_object('filechooserdialog1')
		dic = {'bsave_cancel': dialogdestroy, 'bsave_ok': bsaveok}
		builder.connect_signals(dic)
		#dialog = Tree.get_widget('filechooserdialog1')
		if not os.path.exists(get('open_folder')):
			set('save_folder', os.path.expanduser('~'))
		dialog.set_current_folder(get('save_folder'))
		response = dialog.show()

	def add_task(self, widget):
		dic = parametrs(builder)
		if len(threading.enumerate()) == 1:
			builder.get_object('start').set_sensitive(True)
		self.add_queue = Add_queue('%s - %s' % (dic['performer'], dic['album']), dic)
		self.add_queue.start()
		builder.get_object('del_task').set_sensitive(True)

	def del_task(self, widget):
		selection = self.treeview.get_selection()
		model, selected = selection.get_selected_rows()
		iters = [model.get_iter(path) for path in selected]
		cursor_position = self.treeview.get_cursor()[0]
		if len(cursor_position) > 1:
			return
		if len(model) == 1:
			builder.get_object('del_task').set_sensitive(False)
		if iters:
			for iter in iters:
				model.remove(iter)
			for n in range(len(model)):
				model[n][0] = n + 1
			if len(model) != 0:
				self.treeview.set_cursor(0)
			if len(model) == 1:
				builder.get_object('job_up').set_sensitive(False)
				builder.get_object('job_down').set_sensitive(False)
		if len(model) == 0:
			builder.get_object('start').set_sensitive(False)
		if len(threading.enumerate()) > 1:
			progressbar2=builder.get_object('progressbar2')
			text = '%s   in queue:%s' %(Conversation.job_name, len(model))
			progressbar2.set_text(text)
			preference.progressbar2.set_text(text)

	def start_recomp(self, widget):
		builder.get_object('start').set_sensitive(False)
		start_thread = Conversation()
		start_thread.start()

	def stop(self, widget):
		builder.get_object('stop_button').set_sensitive(False)
		treads = threading.enumerate()
		a = treads[1].stop()
		Conversation.value = (_('Interrupted'))
		if a:
			try:
				os.kill(a, 9)
			except:
				pass
		if len(builder.get_object('job queue').get_model()) > 0:
			builder.get_object('start').set_sensitive(True)

	def endApplication(self, widget):
		if len(threading.enumerate()) > 1:
			self.stop(None)
			clean_tmp(get('tmpdir'))
		widget = [
			'same_folder', 'codec', 'level', 'bitratebtn', 'qualitybtn', 'VBR']
		map(lambda x: set(x, builder.get_object(x).get_active()), widget)
		set('savepath', builder.get_object('savefolder').get_text())
		set('quality', builder.get_object('quality').get_text())
		set('bitrait', builder.get_object('bitrate').get_value())
		write()
		gtk.main_quit()


gtk.gdk.threads_init()
APP = 'gCue2tracks'
DIR = '/usr/share/locale'
locale.setlocale(locale.LC_ALL, '')
_ = gettext.gettext
gettext.textdomain(APP)

if os.path.dirname(sys.argv[0]) != '/usr/bin':
	workdir = os.getcwd()
else:
	workdir = '/usr/share/gcue2tracks'
set('workdir', workdir)

builder = gtk.Builder()
builder.set_translation_domain(APP)
pathglade = os.path.join(workdir, 'ui/main.glade')
builder.add_from_file(pathglade)
set('builder', builder)
QUIET = None

longargs = 'help quiet output'
try:
	opts, args = getopt.getopt(sys.argv[1:], 'hqo:', longargs.split())
	ARGS = args
except getopt.GetoptError, err:
		print str(err)
		sys.exit(2)

for o, a in opts:
	if o in ('-h', '--help'):
		print 'gCue2tracks [--help] [--quiet] inputfile [...]'
		sys.exit()
	if o in ('-q', '--quiet'):
		print 'will be done later :-)'
		QUIET = True
	if o in ('-o', '--output'):
		print a


gui = GuiPart()
varc(builder, pathglade, QUIET)
gtk.gdk.threads_enter()
preference.systray(builder)
gtk.main()
gtk.gdk.threads_leave()
