#!/usr/bin/env python
#
# gtkcdlabel - copyright 2009 S. Wenzler 
#
# requires pygtk and optionally python-cddb and python-id3
#
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
# ## TODO replace os.system with popen, replace gtk.glade with gtk.Builder ##

import getopt
import os,os.path
import re
import shutil
import sys
import ConfigParser
import locale

version = "1.15" # the 'floating right' release
mp3_enabled=True
cddb_enabled=True
custom_config_file=[False, False]

try:
        from ID3 import *
except:
        mp3_enabled = False
        print "WARNING: python-id3 not found - diabling MP3/ID3 support"
# end try

try:
        import CDDB, DiscID
except:
        cddb_enabled = False
        print "WARNING: python-cddb not found - diabling CDDB support"
# end try

try:
        import pygtk
        pygtk.require("2.0")
except:
        pass
# end try

try:
        import gtk
        import gtk.glade
except:
        print "ERROR:   you need to install pygtk or gtk2"
        sys.exit(1)
# end try

class py_gtkcdlabel:
        
        def __init__(self):
                
                # Set the Glade file and initialize the widget tree
                # This does not seem to work on Solaris - dunno why
                self.gladefile = os.path.dirname( sys.argv[0])+"/../share/gtkcdlabel/gtkcdlabel.glade"  
                
                if not os.path.isfile(self.gladefile):
                        self.gladefile = "/usr/share/gtkcdlabel/gtkcdlabel.glade" # default location
                # end if
                
                windowname="window1"    
                try:
                        self.wTree = gtk.glade.XML(self.gladefile,windowname) 
                        # self.wTree = gtk.glade.xml_new_from_buffer(self.glade_xml_buffer,len(self.glade_xml_buffer),windowname) 
                except:
                        print "ERROR:   Cant find gtkcdlabel.glade\n\n%s;%s" % (sys.exc_info()[0],sys.exc_info()[1])
                        print "ERROR:   Solaris users may need to change gtkcdlabel.py around row 67 manually"
                        sys.exit(1)
                # end try
                
                # Create our dictionay and connect it
                dic = { # "gtk_widget_destroy" : self.gtk_widget_destroy,
                "on_clear_textfield_clicked" : self.on_clear_textfield_clicked,
                "on_cover_bg_choice_toggled" : self.on_cover_bg_choice_toggled,
                "on_get_cddb_clicked" : self.on_get_cddb_clicked,
                "on_get_dir_clicked" : self.on_get_dir_clicked,
                "on_get_file_clicked" : self.on_get_file_clicked,
                "on_get_directorychooser_clicked" : self.on_get_directorychooser_clicked,
                "on_get_item_file_clicked" : self.on_get_item_file_clicked,
                "on_get_to_file_clicked" : self.on_get_to_file_clicked,
                "on_load_label_clicked" : self.on_load_label_clicked,
                "on_make_label_clicked" : self.on_make_label_clicked,
                "on_mp3button_clicked" : self.on_mp3button_clicked,
                "on_ornamentbutton_clicked" : self.on_ornamentbutton_clicked,
                "on_path_for_to_file_changed" : self.on_path_for_to_file_changed,
                "on_papertype_optionmenu_changed" : self.on_papertype_optionmenu_changed,
                "on_preview_clicked" : self.on_preview_clicked,
                "on_print_clicked" : self.on_print_clicked,
                "on_save_settings_clicked" : self.on_save_settings_clicked,
                "on_tray_bg_choice_toggled" : self.on_tray_bg_choice_toggled,
                "on_use_eps_toggled" : self.on_use_eps_toggled,
                "on_use_tray_toggled" : self.on_use_tray_toggled,
                "on_no_plaque_toggled" : self.on_no_plaque_toggled,
                "on_style_optionmenu_changed" : self.on_style_optionmenu_changed,
                "sensitivity_toggled" : self.sensitivity_toggled,
                "visibility_toggled" : self.visibility_toggled,
                "on_app1_delete_event" : self.on_app1_delete_event }
                self.wTree.signal_autoconnect(dic)
                
                # Load global objects 
                self.global_inline_objects()
                self.icon = gtk.gdk.pixbuf_new_from_xpm_data(self.gtkcdlabel_xpm)
                
                # Alter ui after some checks
                self.wTree.get_widget("window1").set_icon(self.icon)
                self.wTree.get_widget("window1").set_title("GTKcdlabel " + version)
                self.wTree.get_widget("plaque_colorbutton").set_color(gtk.gdk.color_parse('white'))
                
                # Disable buttons if required libraries cant be found
                if not cddb_enabled:
                        self.wTree.get_widget("get_cddb").set_sensitive(False)
                # end if
                if not mp3_enabled:
                        self.wTree.get_widget("mp3button").set_sensitive(False)
                # end if
                
                # If theres no config file present, we will search for some binaries in PATH
                if not self.load_settings(custom_config_file):
                        binaries = [("cdlabelgen_entry","cdlabelgen"),
                        ("viewer_entry","evince"),
                        ("lpr_entry","lpr"),
                        ("ogonkify_entry","ogonkify"),
                        ("convert_entry","convert")]
                        
                        for entry, binary in binaries:
                                b=self.which(binary)
                                if b:
                                        self.wTree.get_widget(entry).set_text(b)
                                # end if
                        # end for
                # end if
                
                # Finally we check if cdlabelgen is present at all
                self.check_for_cdlabelgen()
        # end def __init__
        
        # CALLBACKS
        
        def on_app1_delete_event(self, widget,event):
                w = self.wTree.get_widget("save_on_exit")
                b = self.wTree.get_widget("save_settings")
                if w.get_active():
                        self.on_save_settings_clicked(b)
                # end if
                self.cleanup()
                gtk.main_quit(event)                                    
        # end def on_app1_delete_event
        
        def on_clear_textfield_clicked(self, widget):
                w = self.wTree.get_widget("text1")
                buffer = w.get_buffer()
                buffer.set_text("")
        # end def on_clear_textfield_clicked
        
        def on_cover_bg_choice_toggled(self, widget):
                names = ( "coverxoffset", "coveryoffset" )
                if widget.get_active():
                        self.sensitize(False,names)
                else:
                        self.sensitize(True,names)
                # end if
        # end def on_cover_bg_choice_toggled
        
        def on_get_cddb_clicked(self, widget):
                year=''
                genre_name=''
                # Read CD info
                drive = self.wTree.get_widget("entry_cddb").get_text()
                try:
                        cdrom = DiscID.open(drive)
                        cdinfo = DiscID.disc_id(cdrom)
                except:
                        self.error_dialog("CDDB Error","Failed to open CDDB query device.\nDevice: '%s'\n\n%s:%s" % (drive,sys.exc_info()[0],sys.exc_info()[1]))
                        return
                # end try
                # Read album title from internet database
                try:
                        rc, album = CDDB.query(cdinfo)
                except:
                        self.error_dialog("CDDB Error","Failed to query CDDB.\nPlease check your Internet connection.\n\n%s:%s" % (sys.exc_info()[0],sys.exc_info()[1]))
                        return
                # end try
                
                if rc==200:
                        pass
                elif rc in (210,211):
                        if len(album)==1:
                                album=album[0]
                        else:
                                print "INFO:    Multiple cddb matches were found:"
                                for choice in album:
                                        print choice['title']
                                # end for
                                print "INFO:    Choosing the first one (%s)" % album[0]['title']
                                album=album[0]
                        # end if
                        
                elif rc==202:
                        self.error_dialog("CDDB Error","Did cddb query, but this CD is not listed.")
                else:
                        self.error_dialog("CDDB Error","Did cddb query, but it got an error. The return code is %d" % rc)
                # end if
                
                # Read track names
                rc, tracks = CDDB.read(album['category'], album['disc_id'])
                if not rc==210:
                        self.error_dialog("CDDB Error","CD database had an error when I tried to read track info (return code=%d)" % rc)
                # end if
                
                # Get year and genre of disc.
                if not year and tracks['DYEAR']:
                        year = tracks['DYEAR']
                # end if
                
                if not genre_name:
                        if tracks['DGENRE']:
                                genre_name = tracks['DGENRE']
                        elif album['category']:
                                genre_name = album['category']
                        # end if
                # end if
                
                try:
                        genre = findGenre(genre_name)
                except:
                        genre = 255
                # end try
                
                print
                print "INFO:    Track names for %s. (%s %s)" \
                                % (album['title'], genre_name, year)
                for track in range(0,cdinfo[1]):
                        textbuffer = self.wTree.get_widget("text1").get_buffer()
                        iter = textbuffer.get_end_iter()
                        # TODO encode?
                        textbuffer.insert(iter, "%d.\t%s\n" % (track+1, tracks["TTITLE"+`track`]))
                # end for
                
                if album['title']:
                        parsename=re.compile("(?P<artist>^.*?) / (?P<album>.*?)$")
                        m=parsename.search(album['title'])
                        if m:
                                artist_name=m.group('artist')
                                album_name=m.group('album')
                        # end if
                        album_field = self.wTree.get_widget("entry_kategori")
                        album_field2 = self.wTree.get_widget("entry_underkategory")
                        # TODO encode?
                        album_field.set_text(artist_name)
                        album_field2.set_text(album_name)
                # end if
                if genre_name:
                        album_field = self.wTree.get_widget("volume_entry")
                        # TODO encode?
                        album_field.set_text(genre_name)
                # end if
                if year:
                        self.wTree.get_widget("date_radio").set_active(True)
                        album_field = self.wTree.get_widget("date_entry")
                        # TODO encode?
                        album_field.set_text(year)
                # end if
        # end def on_get_cddb_clicked
        
        def on_get_dir_clicked(self, widget):
                ep = self.wTree.get_widget("mountpointentry").get_text()
                if ep:
                        rootdir = ep
                else:
                        rootdir = os.getenv('HOME')
                # end if
                
                path = self.show_file_selector("Select Directory",2,rootdir)
                if os.path.isdir(path):
                        textbuffer=self.wTree.get_widget("text1").get_buffer()
                        iter=self.wTree.get_widget("text1").get_buffer().get_end_iter()
                        self.tree(path, '\t',textbuffer,iter, True)
                # end if
        # end def on_get_dir_clicked
        
        def on_get_file_clicked(self, widget):
                entryname = gtk.glade.get_widget_name(widget)
                ep = widget.get_text()
                if ep:
                        rootdir = os.path.dirname(ep)
                else:
                        ps = self.wTree.get_widget("ps_entry").get_text()
                        if entryname in [ "cdlabelgen_entry","ps_entry","lpr_entry","convert_entry","viewer_entry","ogonkify_entry" ]:
                                rootdir = "/usr/"
                        elif entryname in [ "entry_tray_filename", "entry_eps_filename","entry_tray_overlay_filename" ] and ps:
                                rootdir = ps
                        elif entryname == "entry_cddb":
                                rootdir = "/dev"
                        else:
                                rootdir = os.getenv('HOME')
                        # end if
                # end if
                
                path = self.show_file_selector("Select File",1,rootdir)
                if path:
                        widget.set_text(path)
                # end if
        # end def on_get_file_clicked
        
        def on_get_directorychooser_clicked(self, widget):
                entryname = gtk.glade.get_widget_name(widget)
                ep = widget.get_text()
                if ep:
                        rootdir = ep
                else:
                        rootdir = os.getenv('HOME')
                # end if
                
                path = self.show_file_selector("Select File",2,rootdir)
                if path:
                        widget.set_text(path)
                # end if
        # end def on_get_directorychooser_clicked

        def on_load_label_clicked(self, widget):
                ep = widget.get_text()
                if ep:
                        rootdir = os.path.dirname(ep)
                else:
                        rootdir = os.getenv('HOME')
                # end if
                
                path = self.show_file_selector("Select File",1,rootdir,2)
                if path:
                        if not self.load_settings([True,path]):
                                 self.error_dialog("ERROR","Could not load gtkcdlabel file\n%s" % path)
                       # end if
                # end if
        # end def on_get_directorychooser_clicked
        
        def on_get_item_file_clicked(self, widget):
                path = self.show_file_selector("Select File",1)
                if path:
                        f = file(path)
                        textbuffer = self.wTree.get_widget("text1").get_buffer()
                        iter = textbuffer.get_end_iter()
                        # TODO encode?
                        textbuffer.insert(iter, f.read())
                        f.close()
                # end if
        # end def on_get_item_file_clicked
        
        def on_get_to_file_clicked(self, widget):
                path = self.show_file_selector("Select File",3)
                if path:
                        widget.set_text(path)
                # end if
        # end def on_get_to_file_clicked
        
        def on_make_label_clicked(self, widget):
                path_for_to_file = self.wTree.get_widget("path_for_to_file").get_text()
                if not path_for_to_file:
                        return
                # end if
                if not self.run_cdlabelgen():
                        self.cleanup()
                        return
                else:
                        if os.path.isfile(path_for_to_file) and not self.yes_no_dialog("File exists","Overwrite?"):
                                self.cleanup()
                                return
                        else:
                                try:
                                        shutil.copyfile(os.path.expanduser('~/gtkcdlabel-tmp%s.ps' % os.getpid()),path_for_to_file)
                                        self.save_extended_settings(widget,path_for_to_file)
                                except:
                                        self.error_dialog("ERROR","Could not save file to destination:\n%s\n\n%s:%s" % (path_for_to_file,sys.exc_info()[0],sys.exc_info()[1]))
                                        self.cleanup()
                                        return
                                # end try
                        # end if
                        self.info_dialog("Completed","File %s has been saved successfully"  % path_for_to_file)
                        self.cleanup()
                # end if
        # end def on_make_label_clicked

        def save_extended_settings(self, widget, path_for_to_file):
                config = ConfigParser.ConfigParser()

                list_entry = ["cdlabelgen_entry","viewer_entry","lpr_entry","ogonkify_entry","ps_entry","entry_cddb","cddbserver_entry","mountpointentry","template_entry","convert_entry" ]
                list_optionmenu = [ "papertype_optionmenu","encoding_optionmenu" ]
                list_spinbutton_int = []
                list_spinbutton_float = ["linewidth_sp","paper_offset"]
                list_radio_button = ["save_on_exit","use_ogonkify"]                        

                list_entry.extend(["entry_underkategory", "entry_kategori", "volume_entry", "date_entry", "path_for_to_file", "entry_eps_filename", "entry_tray_filename", "entry_tray_overlay_filename"])
                list_radio_button.extend(["no_date_radio", "date_radio", "clipping", "word_wrap", "no_cover_plaque", "no_plaque", "outside_foldout", "rotate_endcaps", "double_case", "use_cover_items", "use_fixed_rows", "use_fixed_columns", "use_eps", "cover_bg_choice", "use_tray", "tray_bg_choice", "use_tray_overlay"])
                list_optionmenu.extend(["style_optionmenu", "tray_bg_option"])
                list_spinbutton_int.extend(["entry_cover_items", "entry_rows", "entry_columns"])
                list_spinbutton_float.extend(["eps_scale", "coverxoffset", "coveryoffset", "tray_scale", "trayxoffset", "trayyoffset", "tray_overlay_scale", "trayoverlayxoffset", "trayoverlayyoffset"])

                # set a number of parameters TOFIX
                config.add_section("gtkcdlabel")
                for i in list_entry:
                        config.set("gtkcdlabel", i, self.wTree.get_widget(i).get_text())
                for i in list_spinbutton_float:
                        config.set("gtkcdlabel", i, locale.atof(self.wTree.get_widget(i).get_text()))
                for i in list_spinbutton_int:
                        config.set("gtkcdlabel", i, self.wTree.get_widget(i).get_text())
                # end for
                for i in list_radio_button:
                        config.set("gtkcdlabel", i, self.wTree.get_widget(i).get_active())
                # end for
                for i in list_optionmenu:
                        config.set("gtkcdlabel", i, self.wTree.get_widget(i).get_history())
                # end for
                
                # get textfield
                text = self.wTree.get_widget("text1").get_buffer()
                end = text.get_char_count()
                iter_start = text.get_iter_at_offset(0)
                iter_end = text.get_iter_at_offset(end)
                config.set("gtkcdlabel", "text1", text.get_text(iter_start,iter_end))
                
                # mark file as extendted config file
                config.set("gtkcdlabel", "extended", True)
                # write to file
                try:
                        fp = open(path_for_to_file+'.gcdl','w')
                        config.write(fp)
                        fp.close()
                except:
                        self.error_dialog("ERROR","Could not write file %s" % path_for_to_file+'.gcdl')
                # end try
        # end def save_extended_settings
        
        def on_mp3button_clicked(self, widget):
                ep = self.wTree.get_widget("mountpointentry").get_text()
                if ep:
                        rootdir = ep
                else:
                        rootdir = os.getenv('HOME')
                # end if
                
                path = self.show_file_selector("Select MP3 Directory",2,rootdir)
                textbuffer = self.wTree.get_widget("text1").get_buffer()
                iter = textbuffer.get_end_iter()
                
                for root,dirs,files in os.walk(path):
                        for name in dirs:
                                topdir=name
                                for root,dirs,files in os.walk(os.path.join(root,name)):
                                        firstmp3=0
                                        for name in files:
                                                if name.endswith(".mp3") or name.endswith(".MP3"):
                                                        if firstmp3 == 0:
                                                                # TODO encode?
                                                                textbuffer.insert(iter, '\n{#B} %s\n' % topdir)
                                                        # end if
                                                        id3info = ID3(os.path.join(root,name))
                                                        if re.search("No ID3 tag",str(id3info)):
                                                                textbuffer.insert(iter, '{#I}%d.\t%s\n' % (firstmp3+1,name))
                                                        else:
                                                                for k,v in id3info.items():
                                                                        if k == 'ARTIST':
                                                                                artist=v
                                                                        elif k == 'TITLE':
                                                                                title=v
                                                                        # end if
                                                                # end for
                                                                textbuffer.insert(iter, '{#I}%d.\t%s - %s\n' % (firstmp3+1,artist,title))
                                                        # end if
                                                        
                                                        firstmp3+=1
                                                # end if
                                        # end for
                                # end for
                        # end for
                # end for
        # end def on_mp3button_clicked
        
        def on_ornamentbutton_clicked(self, widget):
                name = gtk.glade.get_widget_name(widget)                
                if name == "italicbutton":
                        ornament = "{#I}"
                elif name == "boldbutton":
                        ornament = "{#B}"
                elif name == "italicboldbutton":
                        ornament = "{#BI}"
                elif name == "monospacedbutton":
                        ornament = "{#M}"
                elif name == "monospacedboldbutton":
                        ornament = "{#MB}"
                # end if
                
                textview = self.wTree.get_widget("text1")
                textbuffer = textview.get_buffer()
                mark = textbuffer.get_insert()
                iter = textbuffer.get_iter_at_mark(mark)
                curmark = textbuffer.create_mark("curpos", iter, False)
                textview.backward_display_line_start(iter)
                textbuffer.insert(iter, ornament)
                textview.grab_focus()
        # end def on_ornamentbutton_clicked
        
        def on_path_for_to_file_changed(self, widget):
                w = self.wTree.get_widget("path_for_to_file")
                button = self.wTree.get_widget("make_label")
                if w.get_text():
                        button.set_sensitive(True)
                else:
                        button.set_sensitive(False)
                # end if
        # end def on_path_for_to_file_changed
        
        def on_preview_clicked(self, widget):
                where_is_viewer = self.wTree.get_widget("viewer_entry").get_text()
                if not os.access(where_is_viewer, os.X_OK):
                        self.error_dialog("Error","Can not execute the Viewer")
                        return
                # end if
                if not self.check_for_cdlabelgen():
                        return
                # end if
                
                if not self.run_cdlabelgen():
                        self.cleanup()
                        return
                else:
                        gtktmpfile=os.path.expanduser('~/gtkcdlabel-tmp%s.ps' % os.getpid())
                        if os.path.isfile(gtktmpfile):
                                os.system('"'+where_is_viewer+'" '+gtktmpfile)
                        else:
                                self.error_dialog("Error","cdlabelgen could not generate a postscript file for unknown reason")
                        # end if
                        self.cleanup()
                # end if
        # end def on_preview_clicked
        
        def on_print_clicked(self, widget):
                where_is_lpr = self.wTree.get_widget("lpr_entry").get_text()
                # split arguments from printing command and check if its executable
                try:
                        lpr_command,lpr_arguments = where_is_lpr.split(" ",1)
                except:
                        lpr_command = where_is_lpr
                        lpr_arguments = ""
                        
                if not os.access(lpr_command, os.X_OK):
                        self.error_dialog("Error","Can not execute the print command")
                        return
                # end if
                if not self.check_for_cdlabelgen():
                        return
                # end if
                
                if not self.run_cdlabelgen():
                        self.cleanup()
                        return
                else:
                        gtktmpfile=os.path.expanduser('~/gtkcdlabel-tmp%s.ps' % os.getpid())
                        if os.path.isfile(gtktmpfile):
                                os.system('"'+lpr_command+'" '+lpr_arguments+' '+gtktmpfile)
                                self.info_dialog("Finished","Label has been printed")
                        else:
                                self.error_dialog("Error","cdlabelgen could not generate a postscript file for unknown reason")
                        # end if
                        self.cleanup()
                # end if
        # end def on_print_clicked
        
        def on_save_settings_clicked(self, widget):
                config = ConfigParser.ConfigParser()
                
                # set a number of parameters
                config.add_section("gtkcdlabel")
                for i in ("cdlabelgen_entry","viewer_entry","lpr_entry","ogonkify_entry","ps_entry","entry_cddb","cddbserver_entry","mountpointentry","template_entry","convert_entry"):
                        config.set("gtkcdlabel", i, self.wTree.get_widget(i).get_text())
                # end for

                # set a number of float parameters - locale save
                for i in ("linewidth_sp","paper_offset"):
                        config.set("gtkcdlabel", i, locale.atof(self.wTree.get_widget(i).get_text()))
                # end for

                config.set("gtkcdlabel", "save_on_exit", self.wTree.get_widget("save_on_exit").get_active())
                config.set("gtkcdlabel", "papertype_optionmenu", self.wTree.get_widget("papertype_optionmenu").get_history())
                config.set("gtkcdlabel", "use_ogonkify", self.wTree.get_widget("use_ogonkify").get_active())
                config.set("gtkcdlabel", "encoding_optionmenu", self.wTree.get_widget("encoding_optionmenu").get_history())
                # write to file
                try:
                        fp = open(os.path.expanduser('~/.gtkcdlabelrc'),'w')
                        config.write(fp)
                        fp.close()
                except:
                        self.error_dialog("ERROR","Could not save configuration file")
                # end try
        # end def on_save_settings_clicked
        
        def on_style_optionmenu_changed(self, widget):
                style_optionmenu =  self.wTree.get_widget("style_optionmenu").get_history()
                if style_optionmenu == 1 or style_optionmenu == 3:
                        widget.set_sensitive(True)
                else:
                        widget.set_sensitive(False)
                        widget.set_active(False)
                # end if
                
                if style_optionmenu == 4:
                        self.wTree.get_widget("double_case").set_sensitive(True)                                      
                else:
                        self.wTree.get_widget("double_case").set_active(False)                                      
                        self.wTree.get_widget("double_case").set_sensitive(False)                                      
                # end if
        # end def on_style_optionmenu_changed
        
        def on_papertype_optionmenu_changed(self, widget):
                papertype_optionmenu =  self.wTree.get_widget("papertype_optionmenu").get_history()
                if papertype_optionmenu == 2:
                        widget.set_sensitive(True)
                else:
                        widget.set_sensitive(False)
                # end if
                
                if papertype_optionmenu == 0:
                        widget.set_value(0.8)
                elif papertype_optionmenu == 1:
                        widget.set_value(1.5)
                # end if
        # end def on_papertype_optionmenu_changed
        
        def on_tray_bg_choice_toggled(self, widget):
                names = ( "trayxoffset", "trayyoffset" )
                w = self.wTree.get_widget("tray_bg_option")                                        
                if widget.get_active():
                        self.sensitize(False,names)
                        w.set_sensitive(True)
                else:
                        self.sensitize(True,names)
                        w.set_sensitive(False)
                # end if
        # end def on_tray_bg_choice_toggled
        
        def on_use_eps_toggled(self, widget):
                names = ( 'eps_scale', 'entry_eps_filename','eps_select_file','cover_bg_choice','coverxoffset','coveryoffset' )
                w = self.wTree.get_widget("cover_bg_choice")
                
                if widget.get_active():
                        self.sensitize(True,names)
                        self.on_cover_bg_choice_toggled(w)
                else:
                        self.sensitize(False,names)
                # end if
        # end def on_use_eps_toggled
        
        def on_use_tray_toggled(self, widget):
                names = (  "entry_tray_filename","tray_scale","tray_select_file","trayxoffset","trayyoffset","tray_bg_choice","tray_bg_option")
                w = self.wTree.get_widget("tray_bg_choice")                                        
                if widget.get_active():
                        self.sensitize(True,names)
                        self.on_tray_bg_choice_toggled(w)
                else:
                        self.sensitize(False,names)
                        w.set_sensitive(False)
                # end if
        # end def on_use_tray_toggled
        
        def on_no_plaque_toggled(self, widget):
                w = self.wTree.get_widget("no_plaque")                                        
                if w.get_active():
                        widget.set_active(False)
                # end if
        # end def on_no_plaque_toggled
        
        # DIALOGES
        def cdlabelgen_error(self, title, error_text):
                dialog = gtk.Dialog(title, self.wTree.get_widget("window1"), gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,(gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
                buffer = gtk.TextBuffer()
                iter = buffer.get_start_iter ()
                buffer.insert (iter, error_text)
                ced_textview = gtk.TextView()
                ced_textview.set_buffer(buffer)
                dialog.vbox.pack_start(ced_textview, True, True, 0)
                ced_textview.set_editable(False) 
                ced_textview.show()
                
                if dialog.run() == gtk.RESPONSE_ACCEPT:
                        pass
                # end if
                dialog.destroy() 
                return
        # end def cdlabelgen_error
        
        def error_dialog(self, title, label_text, message=gtk.MESSAGE_ERROR):
                dialog = gtk.MessageDialog(self.wTree.get_widget("window1"), gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,message,gtk.BUTTONS_OK, label_text)
                dialog.set_title(title)                                                                                             
                retval = False
                
                if dialog.run() == gtk.RESPONSE_OK:
                        retval = True
                # end if
                
                dialog.destroy() 
                return retval
        # end def error_dialog
        
        def info_dialog(self, title, label_text):
                return self.error_dialog(title,label_text,gtk.MESSAGE_INFO)
        # end def info_dialog
        
        def show_file_selector(self,title_name, type, rootdir=os.getenv('HOME'), filternumber=0):
                if type == 1:
                        actiontype = gtk.FILE_CHOOSER_ACTION_OPEN
                elif type == 2:
                        actiontype = gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER
                elif type == 3:
                        actiontype = gtk.FILE_CHOOSER_ACTION_SAVE
                # end if
                
                file_open = gtk.FileChooserDialog(title=title_name, parent=self.wTree.get_widget("window1"), action=actiontype, buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
                file_open.set_current_folder(rootdir)
                result = ""

                # filter
                filter = gtk.FileFilter()
                filter.set_name('All files')
                filter.add_pattern('*')
                file_open.add_filter(filter)
                if filternumber == 0:
                        file_open.set_filter(filter)
                
                filter = gtk.FileFilter()
                filter.set_name('Pictures')
                filter.add_pattern('*.eps')
                filter.add_pattern('*.jpg')
                filter.add_pattern('*.ps')
                filter.add_pattern('*.gif')
                filter.add_pattern('*.png')
                file_open.add_filter(filter)
                if filternumber == 1:
                        file_open.set_filter(filter)

                filter = gtk.FileFilter()
                filter.set_name('Label file')
                filter.add_pattern('*.gcdl')
                file_open.add_filter(filter)
                if filternumber == 2:
                        file_open.set_filter(filter)
                
                if file_open.run() == gtk.RESPONSE_OK:
                        result = file_open.get_filename()
                # end if
                file_open.destroy()
                return result
        # end def show_file_selector
        
        def yes_no_dialog(self, title, label_text):
                dialog = gtk.MessageDialog(self.wTree.get_widget("window1"), gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,gtk.MESSAGE_QUESTION,gtk.BUTTONS_YES_NO, label_text)
                dialog.set_title(title)                                                                                             
                retval = False
                
                if dialog.run() == gtk.RESPONSE_YES:
                        retval = True
                else:
                        retval = False
                # end if
                dialog.destroy() 
                return retval
        # end def yes_no_dialog
        
        # HELPERS
        def check_for_cdlabelgen(self):
                if not os.access(self.wTree.get_widget("cdlabelgen_entry").get_text(), os.X_OK):
                        self.error_dialog("ERROR","Could not find cdlabelgen.\nPlease check your settings!") 
                        return False
                else:
                        self.check_cdlabelgen_version(self.wTree.get_widget("cdlabelgen_entry").get_text())
                # end if
                return True
        # end def check_for_cdlabelgen
        
        def do_encoding(self,string):
                encoding_optionmenu =  self.wTree.get_widget("encoding_optionmenu").get_history()
                
                # no reencoding - pass utf-8
                output = string
                
                try:
                        if encoding_optionmenu == 0:
                                output = string.encode('latin-1') 
                        elif encoding_optionmenu == 1:
                                output = string.encode('iso8859-2') 
                        elif encoding_optionmenu == 2:
                                output = string.encode('iso8859-5') 
                        elif encoding_optionmenu == 3:
                                output = string.encode('iso8859-9') 
                        # end if
                except:
                        self.error_dialog("Encoding Problem","Your text input could not be re-encoded successfully.\nPlease check your encoding settings.\n\n%s:%s" % (sys.exc_info()[0],sys.exc_info()[1]))
                # end try
                return output
        # end def do_encoding
        
        def load_settings(self,file):
                config = ConfigParser.ConfigParser()

                if file[0]:
                        config_file = file[1]
                else:
                        config_file = '~/.gtkcdlabelrc'
                # end if
                
                try:
                        fp = open(os.path.expanduser(config_file),'r')
                except IOError:
                        print "INFO:    defaults loaded"                
                        return False
                # end try
                
                try:
                        config.readfp(fp)
                except:
                        print "WARNING: config file is weird"
                        return False
                # end try
                
                # older config file versions may not have all entries so we just try to get as many settings as possible
                try:
                        list_entry = [ "cdlabelgen_entry","viewer_entry","lpr_entry","ogonkify_entry","ps_entry","entry_cddb","cddbserver_entry","mountpointentry","template_entry","convert_entry" ]
                        list_optionmenu = [ "papertype_optionmenu","encoding_optionmenu" ]
                        list_spinbutton_int = []
                        list_spinbutton_float = ["linewidth_sp","paper_offset"]
                        list_radio_button = ["save_on_exit","use_ogonkify"]                        

                        # load additional settings from custom config file
                        try:
                                if config.get("gtkcdlabel", "extended") == "True":
                                        list_entry.extend([ "entry_underkategory", "entry_kategori", "volume_entry", "date_entry", "path_for_to_file", "entry_eps_filename", "entry_tray_filename", "entry_tray_overlay_filename"])
                                        list_radio_button.extend(["no_date_radio", "date_radio", "clipping", "word_wrap", "no_cover_plaque", "no_plaque", "outside_foldout", "rotate_endcaps", "double_case", "use_cover_items", "use_fixed_rows", "use_fixed_columns", "use_eps", "cover_bg_choice", "use_tray", "tray_bg_choice", "use_tray_overlay"])
                                        list_optionmenu.extend(["style_optionmenu", "tray_bg_option"])
                                        list_spinbutton_int.extend(["entry_cover_items", "entry_rows", "entry_columns"])
                                        list_spinbutton_float.extend(["eps_scale", "coverxoffset", "coveryoffset", "tray_scale", "trayxoffset", "trayyoffset", "tray_overlay_scale", "trayoverlayxoffset", "trayoverlayyoffset"])
                                        self.wTree.get_widget("text1").get_buffer().set_text(config.get("gtkcdlabel", "text1"))
                                        print "INFO:    extended config file loaded"
                                # end if
                        except:
                                pass
                        # end try

                        # set string parameters
                        for i in list_entry:
                                self.wTree.get_widget(i).set_text(config.get("gtkcdlabel", i))
                        # end for
                        
                        # set menu parameters
                        for i in list_optionmenu:
                                self.wTree.get_widget(i).set_history(int(config.get("gtkcdlabel", i)))
                        # end for

                        # set int parameters
                        for i in list_spinbutton_int:
                                self.wTree.get_widget(i).set_value(int(config.get("gtkcdlabel", i)))
                        # end for
                        
                        # set float parameters
                        for i in list_spinbutton_float:
                                self.wTree.get_widget(i).set_value(float(config.get("gtkcdlabel", i)))
                        # end for
                        
                        # set radio and check type buttons
                        for i in list_radio_button:
                                if config.get("gtkcdlabel", i) == "True":
                                        self.wTree.get_widget(i).set_active(True)
                                else:
                                        self.wTree.get_widget(i).set_active(False)
                                # end if
                        # end for
                        

                        print "INFO:    config file %s loaded" % config_file               
                except:
                        self.wTree.get_widget("save_on_exit").set_active(True)
                        print "WARNING: parsing errors in config file:\nWARNING:     -> %s\nWARNING:     -> %s" % (sys.exc_info()[0],sys.exc_info()[1])
                # end try

                if custom_config_file[0]:
                        self.wTree.get_widget("save_on_exit").set_active(False)
                # end if
                                
                fp.close()
                return True 
        # end def load_settings
        
        def sensitivity_toggled(self, widget):
                if not widget.get_property("sensitive"):
                        widget.set_sensitive(True)
                else:
                        widget.set_sensitive(False)
                # end if
        # end def sensitivity_toggled
        
        def visibility_toggled(self, widget):
                # Strange stuff - get/set_child_visible is not set up right from the beginning so we missuse sensitivity for this 
                if  not widget.get_property("sensitive"):
                        widget.show()
                        widget.set_sensitive(True)
                else:
                        widget.hide()
                        widget.set_sensitive(False)
                # end if
        # end def visibility_toggled
        
        def sensitize(self,state,names):
                for i in names:
                        w = self.wTree.get_widget(i)
                        w.set_sensitive(state)
                # end for
        # end def sensitize
        
        def colorsel_convert(self, colorbutton):
                color = colorbutton.get_color()
                r = g = b = 0.0
                if color.red: r = int(color.red / 65535.0 * 255)
                # end if
                if color.green: g = int(color.green / 65535.0 * 255)
                # end if
                if color.blue: b = int(color.blue / 65535.0 * 255)
                # end if
                return (r,b,g)
        # end def colorsel_convert
        
        # Hunts through the ID3 genres list for the index we want
        def findGenre(val):
                if val[0] in digits:
                        return int(val)
                else:
                        i=0
                        searchme=lower(val)
                # end if
                for g in ID3.genres:
                        if lower(g)==searchme: break
                        # end if
                        i=i+1
                # end for
                if i==len(ID3.genres):
                        raise ValueError, "Could not find the Genre '%s'." % val
                else:
                        return i
                # end if
        # end def findGenre
        
        # Checks the PATH for an application
        def which (self,filename,PATH=os.environ["PATH"]):
                if not PATH or PATH == '':
                        p = os.defpath
                else:
                        p = PATH
                # end if
                
                pathlist = p.split (os.pathsep)
                for path in pathlist:
                        f = os.path.join(path, filename)
                        if os.access(f, os.X_OK):
                                return f
                        # end if
                # end for
                return None
        # end def which
        
        def tree(self, dir, padding, textbuffer, iter, print_files=False):
                textbuffer.insert(iter, padding[:-1] + '+-' + os.path.basename(os.path.abspath(dir)) + '/'+'\n')
                padding = padding + ' '
                files = []
                try:
                        os.listdir(dir)
                        
                except OSError:
                        return
                # end try
                
                if print_files:
                        files = os.listdir(dir)
                else:
                        files = [x for x in os.listdir(dir) if os.path.isdir(dir + os.sep + x)]
                # end if
                count = 0
                for file in files:
                        count += 1
                        textbuffer.insert(iter, padding + '|'+'\n')
                        path = dir + os.sep + file
                        if os.path.isdir(path):
                                if count == len(files):
                                        self.tree(path, padding + ' ', textbuffer, iter, print_files)
                                else:
                                        self.tree(path, padding + '|', textbuffer, iter, print_files)
                                # end if
                        else:
                                # TODO encode?
                                textbuffer.insert(iter, padding + '+-' + file+'\n')
                        # end if
                # end for
        # end def tree
        
        def check_graphics (self, filename, number):
                fp=file(filename)
                line=fp.readline()
                # if re.search("(%!PS-Adobe|EPS)",line): JUST EPS NOT PS?!?! 
                if re.search("EPS",line):
                        # We dont need no stinkin convert - Arrr!
                        return False
                # end if
                fp.close()
                
                convertprog = self.wTree.get_widget("convert_entry").get_text()
                
                if not os.access(convertprog, os.X_OK) or not convertprog:
                        self.error_dialog("Error","You have not specified the program with which to convert images to EPS format\nIf you have the ImageMagick suite of programs then specify the path to the program convert")
                        return -1
                # end if
                
                tmpfile = os.path.expanduser('~/gtkcdlabel-tmp%s-%s.eps' % (os.getpid(),number))
                errors = os.popen('"%s" "%s" %s  2>&1' % (convertprog, filename, tmpfile))
                buffer = errors.read()
                if len(buffer) > 0 or not os.path.isfile(tmpfile):
                        self.cdlabelgen_error("convert ERROR",buffer)
                        return -1
                else:
                        print "INFO:    converted graphics file %s" %filename
                        return True
                # end if
        # end def check_graphics
        
        def save_file(self,filename):
                try:
                        f = file(filename,'w')
                except:
                        return false
                # end try
                
                text = self.wTree.get_widget("text1").get_buffer()
                end = text.get_char_count()
                iter_start = text.get_iter_at_offset(0)
                iter_end = text.get_iter_at_offset(end)
                
                f.write(self.do_encoding(text.get_text(iter_start, iter_end)))
                f.close()
                return True
        # end def save_file
        
        def shell_escape_string(self,string):
                # TODO make better escaping
                return "\'"+re.sub ('(\'|\")', '\\"', string)+"\'"
        # end def shell_escape_string
        # return "\\'".join("'" + p + "'" for p in string.split("'"))
        # return "'"+re.sub ('(\')', '\"', re.escape(string))+"'"
        
        def check_cdlabelgen_version(self,binary):
                help = os.popen('"%s" -h  2>&1' % binary)
                lines = help.read()
                i = 0
                message = "WARNING: older cdlabelgen version - disabling %s feature(s)"
                if not re.search("-n, ",lines):
                        self.wTree.get_widget("volume_entry").set_sensitive(False)                                      
                        self.wTree.get_widget("no_cover_plaque").set_sensitive(False)
                        i+=2
                elif not re.search("--create-dvd-outside",lines):
                        self.wTree.get_widget("dvd2").set_sensitive(False)                                      
                        i+=1
                elif not re.search("--double-case",lines):
                        self.wTree.get_widget("double_case").set_sensitive(False)                                      
                        self.wTree.get_widget("double_case").hide()                                      
                        i+=1
                elif not re.search("--create-dvd-inside",lines):
                        self.wTree.get_widget("dvd1").set_sensitive(False)                                      
                        i+=1
                elif not re.search("--create-cdlabel",lines):
                        self.wTree.get_widget("cd_label1").set_sensitive(False)                                 
                        i+=1
                elif not re.search("--rotate-endcaps",lines):
                        self.wTree.get_widget("rotate_endcaps").set_sensitive(False)                                    
                        self.wTree.get_widget("monospacedbutton").set_sensitive(False)                                  
                        self.wTree.get_widget("monospacedboldbutton").set_sensitive(False)                                      
                        self.wTree.get_widget("dvd3").set_sensitive(False)                                      
                        i+=4
                elif not re.search("--rows-columns",lines):
                        self.wTree.get_widget("use_fixed_columns").set_sensitive(False)
                        self.wTree.get_widget("use_fixed_rows").set_sensitive(False)
                        i+=1
                elif not re.search("--tray-overlay",lines):
                        self.wTree.get_widget("use_tray_overlay").set_sensitive(False)                                  
                        i+=1
                # end if
                if i:
                        print message % i
                # end if
        # end def check_cdlabelgen_version
        
        def cleanup(self):
                try:
                        os.unlink(os.path.expanduser('~/gtkcdlabel-tmp%s.txt' % os.getpid()))
                        os.unlink(os.path.expanduser('~/gtkcdlabel-tmp%s.ps' % os.getpid()))
                        os.unlink(os.path.expanduser('~/gtkcdlabel-tmp%s-1.eps' % os.getpid()))
                        os.unlink(os.path.expanduser('~/gtkcdlabel-tmp%s-2.eps' % os.getpid()))
                        os.unlink(os.path.expanduser('~/gtkcdlabel-tmp%s-3.eps' % os.getpid()))
                except:
                        pass
                # end try
        # end def cleanup
        
        # MAIN operation function
        def run_cdlabelgen(self):
                papertype_offset = 0.8
                cdlabeltxt = os.path.expanduser('~/gtkcdlabel-tmp%s.txt' % os.getpid())
                
                # Get all arguments for cdlabelgen
                cdlabel_arguments = ' -l %f' % self.wTree.get_widget("linewidth_sp").get_value()
                cdlabel_arguments += ' --plaque-color %d,%d,%d' % self.colorsel_convert(self.wTree.get_widget("plaque_colorbutton"))
                cdlabel_arguments += ' --text-color %d,%d,%d' % self.colorsel_convert(self.wTree.get_widget("text_colorbutton"))
                cdlabel_arguments += ' --category-color %d,%d,%d' % self.colorsel_convert(self.wTree.get_widget("category_colorbutton"))
                cdlabel_arguments += ' --subcategory-color %d,%d,%d' % self.colorsel_convert(self.wTree.get_widget("subcategory_colorbutton"))
                
                
                if self.save_file(cdlabeltxt):
                        cdlabel_arguments += ' -f %s' % cdlabeltxt 
                else:
                        self.error_dialog("Error","An error occured while saving your text input")
                        return False
                # end if
                
                template = self.wTree.get_widget("template_entry").get_text()                
                if template and os.path.isfile(template):
                        cdlabel_arguments += ' -t "%s"' % template
                # end if
                
                # Cover image
                # TODO check_graphics (eps/jpg) etc
                if self.wTree.get_widget("use_eps").get_active():
                        f = self.wTree.get_widget("entry_eps_filename").get_text()
                        if f:
                                graphic_status1 = self.check_graphics(f,1)
                                if graphic_status1 == -1:
                                        return False
                                elif graphic_status1:
                                        f = os.path.expanduser('~/gtkcdlabel-tmp%s-1.eps' % os.getpid())                                  
                                # end if
                                cdlabel_arguments += ' -e "%s"' % f
                        # end if
                        if self.wTree.get_widget("cover_bg_choice").get_active():
                                cdlabel_arguments += ' -S 0 '
                        else:
                                eps_scale = self.wTree.get_widget("eps_scale").get_value()
                                if eps_scale != 0:
                                        cdlabel_arguments += ' -S %s' % eps_scale
                                        x = self.wTree.get_widget("coverxoffset").get_value()
                                        y = self.wTree.get_widget("coveryoffset").get_value()
                                        cdlabel_arguments += ',%s,%s ' % (x,y)
                                # end if
                        # end if
                # end if
                
                # Tray image
                if self.wTree.get_widget("use_tray").get_active():
                        f = self.wTree.get_widget("entry_tray_filename").get_text()
                        if f:
                                graphic_status2 = self.check_graphics(f,2)
                                if graphic_status2 == -1:
                                        return False
                                elif graphic_status2:
                                        f = os.path.expanduser('~/gtkcdlabel-tmp%s-2.eps' % os.getpid())                                  
                                # end if
                                cdlabel_arguments += ' -E "%s"' % f
                        # end if
                        if self.wTree.get_widget("tray_bg_choice").get_active():
                                cdlabel_arguments += ' -T 0 '
                                tray_fill = self.wTree.get_widget("tray_bg_option").get_history()
                                if tray_fill == 0:
                                        cdlabel_arguments += ' -T fill1 '
                                elif tray_fill == 1:
                                        cdlabel_arguments += ' -T fill2 '
                                # end if
                        else:
                                tray_scale = self.wTree.get_widget("tray_scale").get_value()
                                if tray_scale != 0:
                                        cdlabel_arguments += ' -T %s' % tray_scale
                                        x = self.wTree.get_widget("trayxoffset").get_value()
                                        y = self.wTree.get_widget("trayyoffset").get_value()
                                        cdlabel_arguments += ',%s,%s ' % (x,y)
                                # end if
                        # end if
                # end if
                
                # Tray Overlay image
                if self.wTree.get_widget("use_tray_overlay").get_active():
                        f = self.wTree.get_widget("entry_tray_overlay_filename").get_text()
                        if f:
                                graphic_status3 = self.check_graphics(f,3)
                                if graphic_status3 == -1:
                                        return False
                                elif graphic_status3:
                                        f = os.path.expanduser('~/gtkcdlabel-tmp%s-3.eps' % os.getpid())                                  
                                # end if
                                cdlabel_arguments += ' --tray-overlay "%s"' % f
                                tray_overlay_scale = self.wTree.get_widget("tray_overlay_scale").get_value()
                                if tray_overlay_scale != 0:
                                        cdlabel_arguments += ' --tray-overlay-scaleratio %s' % tray_overlay_scale
                                        x = self.wTree.get_widget("trayoverlayxoffset").get_value()
                                        y = self.wTree.get_widget("trayoverlayyoffset").get_value()
                                        cdlabel_arguments += ',%s,%s ' % (x,y)
                                # end if
                        # end if
                # end if
                
                if self.wTree.get_widget("use_cover_items").get_active():
                        cdlabel_arguments += ' -v %d' % self.wTree.get_widget("entry_cover_items").get_value()
                # end if
                if self.wTree.get_widget("no_plaque").get_active():
                        cdlabel_arguments += ' -b'
                # end if
                if self.wTree.get_widget("no_cover_plaque").get_active():
                        cdlabel_arguments += ' -C'
                # end if
                if self.wTree.get_widget("outside_foldout").get_active():
                        cdlabel_arguments += ' -O'
                # end if
                if self.wTree.get_widget("rotate_endcaps").get_active():
                        cdlabel_arguments += ' --rotate-endcaps'
                # end if
                
                # Fixed rows/columns
                if self.wTree.get_widget("use_fixed_rows").get_active() or self.wTree.get_widget("use_fixed_columns").get_active():
                        rows = int(self.wTree.get_widget("entry_rows").get_value())
                        columns = int(self.wTree.get_widget("entry_columns").get_value())
                        if not self.wTree.get_widget("use_fixed_rows").get_active():
                                # zero means autocalc rows
                                rows = '0'
                        # end if
                        if not self.wTree.get_widget("use_fixed_columns").get_active():
                                # zero means autocalc columns
                                columns = '0'
                        # end if
                        cdlabel_arguments += ' --rows-columns %s,%s' % (  rows,columns)
                # end if
                
                # Coverstyle
                coverstyle = self.wTree.get_widget("style_optionmenu").get_history()
                if coverstyle == 0:
                        pass
                elif coverstyle == 1:
                        cdlabel_arguments += ' -m '
                elif coverstyle == 2:
                        cdlabel_arguments += ' -M '
                elif coverstyle == 3:
                        cdlabel_arguments += ' --create-dvd-inside '
                elif coverstyle == 4:
                        cdlabel_arguments += ' --create-dvd-outside '
                elif coverstyle == 5:
                        cdlabel_arguments += ' --create-dvd-outside --slim-case '
                elif coverstyle == 6:
                        cdlabel_arguments += ' --create-cdlabel '
                # end if
                
                # Paper offset
                papertype_offset = self.wTree.get_widget("paper_offset").get_value()
                p = self.wTree.get_widget("papertype_optionmenu").get_history()
                
                # Cover style dependent offset adjustment - TOFIX
                # Check for double case button checked and dvd outsie coverstyle
                if self.wTree.get_widget("double_case").get_active() and coverstyle == 4:
                        cdlabel_arguments += ' --double-case'
                        if p == 0:
                                papertype_offset = 0.25
                        elif p == 1:
                                papertype_offset = 0.8
                        # end if
                elif coverstyle == 4:
                        if p == 0:
                                papertype_offset -= 0.1
                        elif p == 1:
                                papertype_offset -= 0.3
                        # end if
                # end if
                cdlabel_arguments += ' -y "%s" ' % papertype_offset
                
                # If volume info was supplied add the CLI switch
                volume_info = self.wTree.get_widget("volume_entry").get_text()
                if volume_info:
                        cdlabel_arguments += ' -n %s' % self.shell_escape_string(self.do_encoding(volume_info))
                # end if
                
                # Word wrap or clipping, NOT both!
                if self.wTree.get_widget("word_wrap").get_active():
                        cdlabel_arguments += ' -w'
                else:
                        cdlabel_arguments += ' -p'
                # end if
                
                if self.wTree.get_widget("no_date_radio").get_active():
                        cdlabel_arguments += ' -D'
                else:
                        pass
                        cdlabel_arguments += ' -d %s' % self.do_encoding(self.shell_escape_string(self.wTree.get_widget("date_entry").get_text()))
                # end if
                
                # cdlabelgen is not UTF8 enabled!! We need to reencode this 
                cdlabel_arguments += ' -c %s' % self.do_encoding(self.shell_escape_string(self.wTree.get_widget("entry_kategori").get_text()))
                cdlabel_arguments += ' -s %s' % self.do_encoding(self.shell_escape_string(self.wTree.get_widget("entry_underkategory").get_text()))
                
                # Now check the script and run it
                cdlabelgen_script = self.wTree.get_widget("cdlabelgen_entry").get_text()    
                
                print 'INFO:    '+self.wTree.get_widget("cdlabelgen_entry").get_text()+' '+cdlabel_arguments+'\n'
                
                if os.access(cdlabelgen_script, os.X_OK):
                        tmpfile1 = os.path.expanduser('~/gtkcdlabel-tmp%d.ps' %os.getpid())
                        errors = os.popen('"%s" %s -o %s  2>&1' % (self.wTree.get_widget("cdlabelgen_entry").get_text(),cdlabel_arguments,tmpfile1))
                        buffer=errors.read()
                        
                        if len(buffer) > 0:
                                self.cdlabelgen_error("cdlabelgen ERROR", buffer)
                                return False
                        # end if
                        
                        if self.wTree.get_widget("use_ogonkify").get_active():
                                ogonki_bin = self.wTree.get_widget("ogonkify_entry").get_text()
                                if os.access(ogonki_bin, os.X_OK):
                                        shutil.copyfile(tmpfile1,tmpfile1+'.ogonki.ps')
                                        errors = os.popen('"%s" -H -eL1 %s > %s' % (self.wTree.get_widget("ogonkify_entry").get_text(),tmpfile1+'.ogonki.ps',tmpfile1) )
                                        
                                        buffer=errors.read()
                                        os.unlink(tmpfile1+'.ogonki.ps')
                                        if len(buffer) > 0:
                                                self.cdlabelgen_error("ogonkify ERROR", buffer)
                                                return False
                                        # end if
                                else:
                                        self.error_dialog("ogonkify ERROR","ogonkify can not be executed\nPath: %s" % ogonki_bin)
                                        return False
                                # end if
                        # end if
                # end if
                return True
        # end def run_cdlabelgen
        
        def global_inline_objects(self):
                self.gtkcdlabel_xpm = [
                "48 48 278 2",
                "       c None",
                ".      c #000000",
                "+      c #AA8FA8",
                "@      c #897C83",
                "#      c #836883",
                "$      c #C4B7B5",
                "%      c #BBA8B3",
                "&      c #A883A3",
                "*      c #976189",
                "=      c #444545",
                "-      c #505252",
                ";      c #716969",
                ">      c #CEB7C3",
                ",      c #8F7389",
                "'      c #CEBDB9",
                ")      c #C6AFB3",
                "!      c #B383B3",
                "~      c #AF7C89",
                "{      c #161414",
                "]      c #383A3B",
                "^      c #B99EB5",
                "/      c #9E83AC",
                "(      c #837C9C",
                "_      c #D3CAB3",
                ":      c #C3979C",
                "<      c #616161",
                "[      c #73686E",
                "}      c #4D565A",
                "|      c #977C97",
                "1      c #DACECB",
                "2      c #C4A8C6",
                "3      c #B37CB3",
                "4      c #D2AFBB",
                "5      c #969388",
                "6      c #E3D9CD",
                "7      c #4C4849",
                "8      c #443F3D",
                "9      c #655456",
                "0      c #7F7373",
                "a      c #666868",
                "b      c #9E9E9E",
                "c      c #DBC3C6",
                "d      c #E1D3D2",
                "e      c #CEA8B9",
                "f      c #C38FB9",
                "g      c #E1DDDB",
                "h      c #E5D9E5",
                "i      c #C8BBBA",
                "j      c #928284",
                "k      c #C2ADB0",
                "l      c #181415",
                "m      c #2B2326",
                "n      c #382F38",
                "o      c #2D2B2D",
                "p      c #0D0E0E",
                "q      c #9C9799",
                "r      c #CABD9C",
                "s      c #AF8FB9",
                "t      c #CA9EC6",
                "u      c #DDD3C3",
                "v      c #E1CEDB",
                "w      c #7D7279",
                "x      c #191719",
                "y      c #DBD9DA",
                "z      c #E1D3C1",
                "A      c #C8B7BA",
                "B      c #645458",
                "C      c #221F21",
                "D      c #394041",
                "E      c #737376",
                "F      c #8C8F8C",
                "G      c #AA9E9E",
                "H      c #E1CED2",
                "I      c #DBCEDB",
                "J      c #C397C1",
                "K      c #D9CAC3",
                "L      c #E9D9E4",
                "M      c #1A1818",
                "N      c #4E494B",
                "O      c #E3DDE3",
                "P      c #E1DDCD",
                "Q      c #E3E1E0",
                "R      c #E1C3C6",
                "S      c #C4A8B7",
                "T      c #998F94",
                "U      c #797C7C",
                "V      c #8F979C",
                "W      c #C8BDB9",
                "X      c #AF97B9",
                "Y      c #CAB7C8",
                "Z      c #DBCAD6",
                "`      c #EADDE3",
                " .     c #E4D9DB",
                "..     c #E8D3DD",
                "+.     c #EAD9DB",
                "@.     c #EBE1E3",
                "#.     c #CACABF",
                "$.     c #DADDE6",
                "%.     c #DDE1DF",
                "&.     c #E4E5E0",
                "*.     c #DAB7BF",     
                "=.     c #AC97A1",     
                "-.     c #898389",
                ";.     c #ACA8AA",
                ">.     c #DAC3D6",
                ",.     c #EAE1D7",
                "'.     c #EEE5DF",
                ").     c #EBE5E3",
                "!.     c #EBE5EB",
                "~.     c #EAE5D6",
                "{.     c #D2CED2",     
                "].     c #D3D9E1",
                "^.     c #DBDDDB",
                "/.     c #E7E8E6",
                "(.     c #EADDD7",
                "_.     c #D3C3C4",
                ":.     c #D3AFD6",
                "<.     c #EBE8EA",
                "[.     c #EFE5EC",
                "}.     c #BDCAD2",
                "|.     c #CED3EA",
                "1.     c #DBE1EA",
                "2.     c #ECEBE6",
                "3.     c #E8CEDB",
                "4.     c #8F6876",
                "5.     c #2F3139",
                "6.     c #4A4A4C",
                "7.     c #6E6168",
                "8.     c #BDAFC1",     
                "9.     c #F2EBEF",
                "0.     c #EDE8DE",
                "a.     c #C6CEE3",     
                "b.     c #D3D9EA",
                "c.     c #E1E5ED",
                "d.     c #BBBDB9",
                "e.     c #3C3C39",
                "f.     c #998391",
                "g.     c #7C8389",
                "h.     c #DAD3D2",
                "i.     c #F2EBE8",
                "j.     c #F0E8E0",
                "k.     c #E1CAD5",
                "l.     c #B7B7BB",
                "m.     c #D3D3E1",
                "n.     c #D0CEE0",
                "o.     c #949EBF",
                "p.     c #D2D3D2",
                "q.     c #CACED2",
                "r.     c #504A55",
                "s.     c #555759",
                "t.     c #9EA8BF",
                "u.     c #ACAFB5",
                "v.     c #EEEEEF",
                "w.     c #D2CAC6",
                "x.     c #E4D3DD",
                "y.     c #E0BDC6",
                "z.     c #D9B7DB",
                "A.     c #D9AFDB",
                "B.     c #976876",
                "C.     c #C8C3C6",
                "D.     c #C4BDC6",
                "E.     c #C6C3D2",
                "F.     c #292829",
                "G.     c #F2F0F1",
                "H.     c #3E4246",
                "I.     c #F0EEEF",
                "J.     c #E0BDDB",
                "K.     c #E1C3DB",
                "L.     c #D3C3D7",
                "M.     c #D9D3DB",
                "N.     c #F4F3F4",
                "O.     c #F1E8EA",     
                "P.     c #EEE1E5",
                "Q.     c #EEDDE3",
                "R.     c #DBD9E3",
                "S.     c #E1E1EA",
                "T.     c #E6E8EF",
                "U.     c #4A4246",
                "V.     c #F8F7F4",
                "W.     c #AFB7C1",
                "X.     c #837389",
                "Y.     c #F5EBEF",
                "Z.     c #F2EEE7",
                "`.     c #E6EBF4",
                " +     c #F3E5EF",
                ".+     c #C8AFC6",
                "++     c #BBC3CD",
                "@+     c #C8C3B5",
                "#+     c #D3BDDB",
                "$+     c #F2E8F2",
                "%+     c #EDE8F3",
                "&+     c #EBEBF4",
                "*+     c #EBE1EA",     
                "=+     c #CEB7D2",     
                "-+     c #F0E1EF",     
                ";+     c #D2CAD3",
                ">+     c #E8CAD2",
                ",+     c #BD9EC6",
                "'+     c #A89EB9",
                ")+     c #E8D3EA",
                "!+     c #868FAC",
                "~+     c #D3BDCB",
                "{+     c #BBA8C6",
                "]+     c #4A3C46",
                "^+     c #0F0D10",
                "/+     c #040305",
                "(+     c #83000B",
                "_+     c #83010B",
                ":+     c #86010E",
                "<+     c #7C0315",
                "[+     c #831125",
                "}+     c #686889",
                "|+     c #201F20",
                "1+     c #C35089",
                "2+     c #7C0005",
                "3+     c #7C0006",
                "4+     c #9C142F",
                "5+     c #C6CAD6",
                "6+     c #A81A39",
                "7+     c #D37C9C",
                "8+     c #910519",
                "9+     c #687376",
                "0+     c #CA689C",
                "a+     c #A83155",
                "b+     c #681425",
                "c+     c #685766",
                "d+     c #8F0415",
                "e+     c #ACAFC6",
                "f+     c #C36176",
                "g+     c #CE9EAC",
                "h+     c #971A39",
                "i+     c #683C46",
                "j+     c #7C0515",
                "k+     c #975789",
                "l+     c #830210",
                "m+     c #616166",
                "n+     c #4A5055",
                "o+     c #050505",
                "p+     c #141110",
                "q+     c #9E97AC",
                "r+     c #7C0715",
                "s+     c #7C0009",
                "t+     c #7C0008",
                "u+     c #A84255",
                "v+     c #505055",
                "w+     c #576166",
                "x+     c #080708",
                "y+     c #0A0908",
                "z+     c #AFA8B9",
                "A+     c #80142F",
                "B+     c #8F97B3",     
                "C+     c #BDAFA6",
                "D+     c #C183A3",
                "E+     c #9C7380",
                "F+     c #80616E",
                "G+     c #685066",     
                "H+     c #52575B",
                "I+     c #62697F",
                "J+     c #C38F9C",
                "K+     c #140F15",
                "L+     c #8C839E",
                "M+     c #5D5769",
                "N+     c #080A08",
                "O+     c #313132",
                "P+     c #6D667B",
                "Q+     c #575268",
                "R+     c #5F6477",
                "S+     c #838CAA",
                "T+     c #69707F",
                "U+     c #888E96",
                "V+     c #B7979C",
                "W+     c #9B6E79",
                "X+     c #312026",
                "Y+     c #050405",
                "Z+     c #2C2F39",
                "`+     c #343434",
                " @     c #403739",
                ".@     c #070507",
                "                                                                                                ",
                "                                                                                                ",
                "                                                                                                ",
                "                                                                                                ",
                "                        . . . . .       . . . . . . . .   . .         . .                       ",
                "                      . . . . . . .     . . . . . . . .   . .       . .                         ",
                "                    . . .         . .         . .         . .     . .                           ",
                "                    . .               + @ # # . . $ % & * . .   . .                             ",
                "                    . .         = - ; > & , # . . ' ) ! ~ . . { . .                             ",
                "                    . .     ] . . . . $ ^ / ( . . _ ) ! : . . . < . .                           ",
                "                    . . @ [ } ] = . . % ' + | . . 1 2 3 4 . . 5 6 7 . 8                         ",
                "                    . . 9 & 0 a } . . b c ^ & . . d e f c . . g h i . . j                       ",
                "                    k l . m n o . . p q r > s . . d t 4 u . . g h v w . x i                     ",
                "                  y z A B l . . C D E F G H ^ . . I J K 6 . . L H 6 v M . N O                   ",
                "                P Q P P z H R 4 S T E U V W ) X Y Z J z Q `  ...v +. .` @.@.@.g                 ",
                "              #.$.%.&.&.Q P 6 H *.4 =.U -.;.Z X ' >.R ,.'.@.L +.` @.).!.).!.~.,.{.              ",
                "              ].].].^.%.&./.~.,.(.H *.^ U V _.^ ' :.6 <.` ..L @.!.[.<.).~.,.,.,.P               ",
                "            }.|.|.].|.].].$.1.&.2.~.,.3.4.5.6.7.q 8.W $ ` [.<.9.2.0.0.'.,.~.,.(.(.K             ",
                "            a.|.|.].b.].b.$.$.$.1.c.d.e.f.;.g.q ;.d.^.9.1 h.i.j.'.'.,.,.(.+.+...3.k.            ",
                "          l.m.n.n.|.n.|.|.|.].b.].o.5.p.q.r.s.t.u.q E {.v.w.S x.H k.R y.z.*.A.:.:.A.B.          ",
                "          l.#.C.C.C.C.D.W D.D.E.C.F.;.G.U H.;.{.{.w.b F I.h.| >.J.J.J.K.K.>.J.J.J.K.2           ",
                "          C.L.w._.w._.w.{.{.m.M.M.F.^.N.q a #.&.&.%.d.;.G.<.G O.0.O.[.P.Q.Q.Q.` L L v           ",
                "          p.y R.R.^.S.$.S.S.c.T.T.U.^.V.g V W.Q /.^.l.g G.<.X.v d h @.[.O.i.Y.Z.O.O.'.          ",
                "          S.S.c.c.T.c.`.<.[.!.[. +.+@ G.V.2.h.++@+{.].v.N.8.| #+Z Z I d  . .` P.O.O.i.          ",
                "          T.T.`.T.$+[.%+%+[. +$+9.Y._.T y N.N.&+G.I.).{.;._. .Z #+L.Z Z I M.d x.h `  .          ",
                "          *+%+$+$+$+$+$+$+$+Y.O.Y.Z.Z.i.> =.W.#.q.#.=.a l.w.*+` I L.=+#+>.>.Z Z I I L.          ",
                "          n.[.*+[.-+-+-+ +[.O.j.0.0.'.P.*+S.;+m.S.0.>+% F b l.1 Z .+,+X s s '+^ % 8.X.          ",
                "          # v )+x.L L (.+.(.(.P (.` L )+h |.Y a.1./.x.) F !+b 8.w.(.Z ~+.+.+,+{+2 2 ]+          ",
                "          ^+L L ` Q.` P.,.,.~.~.(.Q.L h $.{.E.a.1.0.` ~+^ g.V G 8.w.x.d #+=+2 {+,+^ /+          ",
                "          . Y ` L ` (.,.,.Q (.+.` )+)+Z 3 $ D.a.M.(+_+:+<+[+}+F q G $ 1 H ~+.+S ,+7..           ",
                "            |+..6 6 6 6 6 z 6 d d v 1+2+3+4+E.5+;+6+6+7+8+3+3+9+F b ;.l.K 6 Z Y .+^+            ",
                "            . q y 6 6 6 6 +.x.)+v 0+2+a+d.l.++a.].6+(+>+4 =.2+b+9+g.F G ;.W K _ c+.             ",
                "              . $ #._ _ w.;+_.~+=+d+:+l.=.'+e+W.E.: 3+f+g+h+2+i+s.7.E @ f.q % G .               ",     
                "              . ^+@+_._.~+~+=+z.D.j+(+t.T q k+l+++{.l+3+l+2+[+m+6.n+s.a a X.0 o+.               ",
                "                . p+S > 4 S 2 2 8.q+2+(+r+l+s+* W.++4+t+:+u+, 7.v+H.6.s.w+7.x+.                 ",
                "                  . y+f.S S ,+{+z+t.( j+<+A+!+B+;.d.@+C+% D+E+F+v+6.H.v+U./+.                   ",
                "                  . . . G+S {+{+e+t.F U H+. I+t.u.d.@+$ S J+~ 4.c+v+e.|+. . .                   ",
                "                  . . . . K+0 e+'+q L+X.M+. I+t.u.d.#.r ) J+~ B.F+5.x+. . . .                   ",
                "                  . .     . . N+O+P+X.X.Q+. R+S+T+U+@+W C+V+W+X+Y+. . .   . .                   ",
                "                  . .     . . . . . Y+F.O+. Z+. . . `+[  @.@. . . .       . .                   ",
                "                  . .     . .     . . . . . . . . . . . . . . .   . .     . .                   ",
                "                  . .           . . .   . . . . . . . . . .       . .     . .                   ",
                "                  . .     . . . . . .     . .       . . . . . . . . .     . .                   ",
                "                  . .   . .       . .     . .       . . . .               . .                   ",
                "                  . .   . . .   . . .     . .     . .     . .     . .     . .                   ",
                "                  . .     . . . .   .     .   . . .         . . . .       . .                   ",
                "                                                                                                ",
                "                                                                                                "
                ]
        # end def global_inline_objects
# end class py_gtkcdlabel

#                self.glade_xml_buffer = """<?xml version="1.0" standalone="no"?> <!--*- mode: xml -*-->"""


##############################################################################################
if __name__ == "__main__":
        shortOptions = 'c:Vh'
        longOptions = ['help', 'version', 'config=']
        
        opts = []
        args = []
        
        def help():
                print "Usage: %s [OPTION ...]\n" %  sys.argv[0]
                print "\n\
                -h, --help              display this help and exit\n\
                -V, --version           output version information and exit\n\
                -c, --config=file       load custom configuration file\n\
                \n\
                Report bugs to <s_wenzler AT users DOT sourceforge DOT net>.\n",
        # end def help
        
        
        try:
                opts, args = getopt.getopt(sys.argv[1:], shortOptions, longOptions)
                for o, a in opts:
                        if o == "--help" or o == "-h":
                                help()
                                sys.exit(1)
                        elif o == "--version" or o == "-V":
                                print sys.argv[0], version
                                sys.exit(1)
                        elif o == "--config" or o == "-c":
                                if not os.path.isfile(a):
                                        print "ERROR:   %s is not a file" % a
                                        sys.exit(1)
                                else:
                                        custom_config_file = [True, a]
                                # end if
                        # end if
                # end for
        except getopt.GetoptError:
                help()
                sys.exit(1)
        # end try
        
        app = py_gtkcdlabel()
        gtk.main()
# end if
