#!/usr/bin/env python
# -*- coding: latin-1 -*-
    
#----------------------------------------------------------------------
# Program: stylus-toolbox - A toolbox for Epson Stylus inkjet printers
# Desc:    Stylus Toolbox is a GTK+ GUI front-end for Gutenprint's 
#          escputil printer utility.
# Author:  Rob A. Shinn

# Legal:   Copyright © 2006 Rob A. Shinn. All rights reserved.
#          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.
#----------------------------------------------------------------------

import sys
import os
import re
import gtk
import gobject

from ConfigParser import *
from pexpect import *
from GladeWindow import *
from errno import *

install_prefix="/usr"


#----------------------------------------------------------------------
# class for parsing and storage of configuration data
#----------------------------------------------------------------------
class conf(ConfigParser):
	def __init__(self,defaults=None):
	        # initialize attributes ...
	 	self.sFilename=''   # location of .stylus-toolbox.conf
		self.sRawDevice=''  # raw printer device 
		self.sModel='Auto'  # *short* Gutenprint/escputil model name
		self.fNewUSB=True   # printer uses 'packet mode' 
	  	self.sEscputilProg='/usr/bin/escputil' # location of escputil
                # ... and call our ancestor
		ConfigParser.__init__(self,defaults)	
	def write(self,f):
		ConfigParser.write(self,f)
		f.close()	
		
config=conf() 

#----------------------------------------------------------------------
# class for the main window 
#----------------------------------------------------------------------
class stylusToolboxMain(GladeWindow):
    def __init__(self):

        ''' '''
    	self.cellview1=None
    	self.cellview2=None
    	self.cellview3=None
    	self.cellview4=None
    	self.cellview5=None
    	self.cellview6=None
    	self.cellview7=None
    	self.cellview8=None
	self.fModelsPopulated=False
	self.lstModelList=None
	#self.child=None
        self.init()

    def init(self):

        filename = install_prefix+'/share/stylus-toolbox/stylus-toolbox.glade'

        widget_list = [
            'wndToolbox',
            'btnClean',
            'btnAlign',
            'btnPrint',
            'btnRefresh',
            'btnClose',
	    'proBlack',
	    'proCyan',
	    'proMagenta',
	    'proYellow',
	    'proLightMagenta',
	    'proLightCyan',
            'wndStep1',
            'btnStep1Cancel',
            'btnStep1Forward',
            'wndStep2',
            'btnStep2Cancel',
            'btnStep2Back',
            'btnStep2Forward',
            'wndStep3',
            'btnStep3Cancel',
            'btnStep3Back',
            'btnStep3Forward',
            'wndStep4',
            'btnStep4Cancel',
            'btnStep4Back',
            'btnStep4Forward',
            'wndStep5',
            'btnStep5Cancel',
            'btnStep5FowardButton',
            'wndStep6',
            'btnStep6Cancel',
            'btnStep6Back',
            'btnStep6Forward',
            'wndStep7',
            'btnStep7Cancel',
            'btnStep7Back',
            'btnStep7Forward',
            'wndStep8',
            'btnStep8Close',
	    'vbox4',
	    'vbox5',
	    'vbox8',
	    'vbox10',
	    'vbox12',
	    'vbox14',
	    'vbox16',
	    'vbox19',
	    'cellview1',
	    'cellview2',
	    'cellview3',
	    'cellview4',
	    'cellview5',
	    'cellview6',
	    'cellview7',
	    'cellview8',
            'lblBlue',
            'lblRed',
	    'lblStep1Msg',
	    'lblMsgStep8',
	    'radSave',
	    'radQuit',
            'radRepeat',
	    'wndPrefs',
	    'btnDevBrowse',
	    'btnEscputilBrowse',
	    'btnPrefsCancel',
	    'dlgFileChooser',
	    'txtDevice',
	    'usbCheckButton',
	    'txtEscputil',
	    'cmbModel',
	    'btnFCOpen',
	    'btnFCCancel',
	    'radSelectModel',
	    'radAutoDetect',
	    'cbePairNum1',
	    'cbePairNum2',
	    'cbePairNum3',
	    'cbePairNum4',
        ]

        handlers = [
            'on_wndToolbox_activate_default',
	    'on_wndToolbox_delete',
            'on_quit1_activate',
            'on_cut1_activate',
            'on_copy1_activate',
            'on_paste1_activate',
            'on_delete1_activate',
            'on_preferences1_activate',
            'on_refresh1_activate',
            'on_about1_activate',
            'on_btnClean_clicked',
            'on_btnAlign_clicked',
            'on_btnPrint_clicked',
            'on_btnRefresh_clicked',
            'on_btnClose_clicked',
            'on_btnStep1Cancel_clicked',
            'on_btnStep1Forward_clicked',
            'on_btnStep2Cancel_clicked',
            'on_btnStep2Back_clicked',
            'on_btnStep2Forward_clicked',
            'on_btnStep3Cancel_clicked',
            'on_btnStep3Back_clicked',
            'on_btnStep3Forward_clicked',
            'on_btnStep4Cancel_clicked',
            'on_btnStep4Back_clicked',
            'on_btnStep4Forward_clicked',
            'on_btnStep5Cancel_clicked',
            'on_btnStep5FowardButton_clicked',
            'on_btnStep6Cancel_clicked',
            'on_btnStep6Back_clicked',
            'on_btnStep6Forward_clicked',
            'on_btnStep7Cancel_activate',
            'on_btnStep7Back_clicked',
            'on_btnStep7Forward_clicked',
            'on_btnStep8Close_clicked',
	    'on_prefsOkButton_clicked',
	    'on_PrefsWindow_closed',
	    'on_PrefsCancel_clicked',
	    'on_btnDevBrowse_clicked',
	    'on_cmbModel_changed',
	    'on_radAutoDetect_toggled',
	    'on_btnEscputilBrowse_clicked',
	    'on_btnFCOpen_clicked',
	    'on_fileChooserCancel_clicked',
	    'on_dlgFileChooser_delete_event',
            ]

        top_window = 'wndToolbox'
        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)

    #----------------------------------------------------------------------
    #  Displays the about box.
    #----------------------------------------------------------------------
    def aboutBox(self, *args):
	aboutDialog=gtk.AboutDialog()
	aboutDialog.set_name("Stylus Toolbox")
	aboutDialog.set_authors(["Rob A. Shinn <rob.shinn@gmail.com>"])
	aboutDialog.set_comments("Toolbox to control Epson inkjet printers.")
	aboutDialog.set_copyright("Copyright © 2006 Rob A. Shinn.  "+\
				"All rights reserved.")
	aboutDialog.set_license("Stylus Toolbox 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 Sofware "+\
		"Foundation; either version 2 of the License, or (at your "+\
		"option) any later version.\n\nStylus Toolbox 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.\n\nYou should have "+\
		"received a copy of the GNU General Public License along "+\
		"with Stylus Toolbox; if not, write to the Free Software "+\
		"Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA "+\
		"  02111-1307  USA")
	aboutDialog.set_version("0.2.7")
	aboutDialog.set_website("http://stylus-toolbox.sourceforge.net")
	aboutDialog.set_wrap_license(True)
	aboutDialog.show()

    #----------------------------------------------------------------------
    # Refresh main window with ink-levels and printer name from escputil
    #----------------------------------------------------------------------
    def refreshWindow(self, *args):
	print "Reading device information ... "
	sCommand = config.sEscputilProg+' -q -d -r '+config.sRawDevice
	sCommandOutput = run(sCommand)
	print 'sCommand="'+sCommand+'"'
	print sCommandOutput
	sModelName = sCommandOutput
	self.widgets['wndToolbox'].set_title(sModelName)
	if config.sModel=='Auto':
		sCommand = config.sEscputilProg+' -q -i -r '+config.sRawDevice
	else:
	
		sCommand = config.sEscputilProg+' -q -i -m '+config.sModel+' -r '+config.sRawDevice
	sCommandOutput = run(sCommand)
	y=""
	nBlackP=0
	nCyanP=0
	nMagentaP=0
	nYellowP=0
	nLtCyanP=0
	nLtMagentaP=0
	p = re.compile(r'\W+')
	fSixColor=False
	fIsLight=False
	for x in p.split(sCommandOutput):
		if y=='Black':
			nBlackP=x
			fIsLight=False
		if y=='Cyan':
			if fIsLight:
				nLtCyanP=x
			else:
				nCyanP=x
			fIsLight=False	
		if y=='Magenta':
			nMagentaP=x
			if fIsLight:
				nLtMagentaP=x
			else:
				fMagentaP=x
			fIsLight=False
		if y=='Yellow':
			nYellowP=x
			fIsLight=False
		if y=='Light': 
			fSixColor=True
			fIsLight=True
		y=x
	print 'sCommand="'+sCommand+'"'
	print sCommandOutput
	nKFraction = float(nBlackP) / 100
	nCFraction = float(nCyanP) / 100
	nMFraction = float(nMagentaP) / 100
	nYFraction = float(nYellowP) / 100
	nBFraction = float(nLtCyanP) / 100
	nRFraction = float(nLtMagentaP) / 100
	self.widgets['proBlack'].set_fraction(nKFraction)
	self.widgets['proBlack'].set_text(str(nBlackP)+"%")
	self.widgets['proCyan'].set_fraction(nCFraction)
	self.widgets['proCyan'].set_text(str(nCyanP)+"%")
	self.widgets['proMagenta'].set_fraction(nMFraction)
	self.widgets['proMagenta'].set_text(str(nMagentaP)+"%")
	self.widgets['proYellow'].set_fraction(nYFraction)
	self.widgets['proYellow'].set_text(str(nYellowP)+"%")
	if fSixColor:
		self.widgets['proLightCyan'].set_fraction(nBFraction)
		self.widgets['proLightCyan'].set_text(str(nLtCyanP)+"%")
		self.widgets['proLightMagenta'].set_fraction(nRFraction)
		self.widgets['proLightMagenta'].set_text(str(nLtMagentaP)+"%")
		self.widgets['proLightCyan'].show()
		self.widgets['proLightMagenta'].show()
		self.widgets['lblBlue'].show()
		self.widgets['lblRed'].show()
	self.show()

    #----------------------------------------------------------------------
    # Clean the print heads.  Warn the user before proceeding.
    #----------------------------------------------------------------------
    def cleanPrintHeads(self, *args):
	imgWarnIcon = gtk.Image()
	imgWarnIcon.set_from_stock(gtk.STOCK_DIALOG_WARNING,gtk.ICON_SIZE_DIALOG)
	hbox=gtk.HBox()
	msg = gtk.Label('Cleaning the print heads too much uses a lot of i'+\
		'nk.\nClean them only if the test page show breaks or streaks.')
	dlgWarn = gtk.Dialog('Warning',self.widgets['wndToolbox'],\
			gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,\
			(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, \
			 gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
	hbox.pack_start(imgWarnIcon,False,False,5)
	hbox.pack_start(msg,False,False,5)
	dlgWarn.vbox.pack_start(hbox,True,True,0)
	imgWarnIcon.show()
	msg.show()
	hbox.show()
	response = dlgWarn.run()
	if response == gtk.RESPONSE_REJECT:
		dlgWarn.destroy()
	if response == gtk.RESPONSE_ACCEPT:
		dlgWarn.destroy()
		if config.fNewUSB:
			sCommand = config.sEscputilProg+' -q -c -u -r '+\
				config.sRawDevice
		else:
			sCommand = config.sEscputilProg+' -q -c -r '+\
				config.sRawDevice
		sCommandOutput = run(sCommand)
		print sCommandOutput

    #----------------------------------------------------------------------
    # Perform a nozzle check.  Prompt the user for paper beforehand.
    #----------------------------------------------------------------------
    def printTestPage(self, *args):
	imgInfoIcon = gtk.Image()
	imgInfoIcon.set_from_stock(gtk.STOCK_DIALOG_INFO,gtk.ICON_SIZE_DIALOG)
	hbox=gtk.HBox()
	msg = gtk.Label('You are about to run a nozzle check. If you see '+\
		'breaks\n in the lines, please clean the print heads. Please '+\
		'ensure \nthat paper is in the printer.')
	msg.wrap = True;
	msg.width_chars = 20;
	dlgInfo = gtk.Dialog('Nozzle Check',self.widgets['wndToolbox'],\
			gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,\
			(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, \
			 gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
	hbox.pack_start(imgInfoIcon,False,False,5)
	hbox.pack_start(msg,False,False,5)
	dlgInfo.vbox.pack_start(hbox,True,True,0)
	imgInfoIcon.show()
	dlgInfo.show()
	msg.show()
	hbox.show()
	response = dlgInfo.run()
	if response == gtk.RESPONSE_REJECT:
		dlgInfo.destroy()
	if response == gtk.RESPONSE_ACCEPT:
		dlgInfo.destroy()
		if config.fNewUSB:
			sCommand = config.sEscputilProg+' -q -n -u -r '+\
				config.sRawDevice
		else:
			sCommand = config.sEscputilProg+' -q -n -r '+\
				config.sRawDevice
		sCommandOutput = run(sCommand)
		print 'sCommand="'+sCommand+'"'
		print sCommandOutput

    #----------------------------------------------------------------------
    # Populate Model Combo Box in the preferences dialog
    #----------------------------------------------------------------------
    def populateModels(self, *args):
	self.lstModelList=gtk.ListStore(gobject.TYPE_STRING,gobject.TYPE_STRING)
	sCommandOutput = run(config.sEscputilProg+' -M')
	print sCommandOutput
	p = re.compile(r'\n')
        n = re.compile(r'\r')
	i=0
	for x in p.split(sCommandOutput):
	    q = re.compile(r'[ ]+')
	    sLongModel=""
	    sShortModel=""
	    j=0
	    for y in q.split(x):
		if j == 0:
			sShortModel=y
		 	j += 1	
		else:
			if sLongModel == "":
				sLongModel=y
			else:
				sLongModel=sLongModel+" "+n.sub('',y)
	    i += 1
	    self.lstModelList.append([sLongModel,sShortModel])
	self.widgets['cmbModel'].set_wrap_width(3)
	self.widgets['cmbModel'].set_model(self.lstModelList)
	cell=gtk.CellRendererText()
	self.widgets['cmbModel'].pack_start(cell,True)
	self.widgets['cmbModel'].add_attribute(cell, 'text', 0)
	self.fModelsPopulated=True
	
    #----------------------------------------------------------------------
    # An assistant to walk the user through aligning the printheads. 
    #----------------------------------------------------------------------
    def alignPrintHeads(self, *args):
	self.alignPrintHeadsStep1() 
	
    def alignPrintHeadsStep1(self, *args):
	if not self.cellview1:
		bg=self.widgets['cellview1'].get_property("background-gdk")
		self.cellview1=gtk.cell_view_new_with_markup('<span '+\
			'size="large" '+\
			'foreground="white">'+
			'<b>\nAligning Print Heads 1 of 8\n</b></span>')
		self.cellview1.set_property("background-gdk",bg)
		self.widgets['vbox4'].pack_start(self.cellview1,True,True,6)
		self.widgets['vbox4'].reorder_child(self.cellview1,0)
	self.widgets['vbox4'].show()
	p=re.compile(r'\r')
	st=""
	for x in p.split(self.widgets['lblStep1Msg'].get_label()):
		line=""
		q=re.compile(r'[ ]+')
		for y in q.split(x):
			if y == '%m.':
				line=line+self.widgets['wndToolbox'].get_title()
			else:
		                line=line+y+" "
		st=st+line
	self.widgets['lblStep1Msg'].set_label(st)
	self.cellview1.show()
	self.widgets['wndStep1'].show()
	self.child = spawn(config.sEscputilProg+' -q -a -u -r '+\
		config.sRawDevice)
	fout=sys.stdout
	self.child.logfile=fout
	self.child.expect('Press enter to continue >')
	
    def alignPrintHeadsStep2(self, *args):
	if not self.cellview2:
		bg=self.widgets['cellview2'].get_property("background-gdk")
		self.cellview2=gtk.cell_view_new_with_markup('<span size="large" foreground="white"><b>\nAligning Print Heads 2 of 8\n</b></span>')
		self.cellview2.set_property("background-gdk",bg)
		self.widgets['vbox5'].pack_start(self.cellview2,True,True,6)
		self.widgets['vbox5'].reorder_child(self.cellview2,0)
	self.widgets['vbox5'].show()
	self.cellview2.show()
	self.widgets['wndStep2'].show()
    
    def alignPrintHeadsStep3(self, *args):
	self.widgets['wndStep3'].show()
	self.widgets['wndStep3'].hide()
	if not self.cellview3:
		bg=self.widgets['cellview3'].get_property("background-gdk")
		self.cellview3=gtk.cell_view_new_with_markup('<span size="large" foreground="white"><b>\nAligning Print Heads 3 of 8\n</b></span>')
		self.cellview3.set_property("background-gdk",bg)
		self.widgets['vbox8'].pack_start(self.cellview3,True,True,6)
		self.widgets['vbox8'].reorder_child(self.cellview3,0)
	self.widgets['vbox8'].show()
	self.cellview3.show()
	self.widgets['wndStep3'].show()
    
    def alignPrintHeadsStep4(self, *args):
	if not self.cellview4:
		bg=self.widgets['cellview4'].get_property("background-gdk")
		self.cellview4=gtk.cell_view_new_with_markup('<span size="large" foreground="white"><b>\nAligning Print Heads 4 of 8\n</b></span>')
		self.cellview4.set_property("background-gdk",bg)
		self.widgets['vbox10'].pack_start(self.cellview4,True,True,6)
		self.widgets['vbox10'].reorder_child(self.cellview4,0)
	self.widgets['vbox10'].show()
	self.cellview4.show()
	self.widgets['wndStep4'].show()

    def alignPrintHeadsStep5(self, *args):
	if not self.cellview5:
		bg=self.widgets['cellview5'].get_property("background-gdk")
		self.cellview5=gtk.cell_view_new_with_markup('<span size="large" foreground="white"><b>\nAligning Print Heads 5 of 8\n</b></span>')
		self.cellview5.set_property("background-gdk",bg)
		self.widgets['vbox12'].pack_start(self.cellview5,True,True,6)
		self.widgets['vbox12'].reorder_child(self.cellview5,0)
	self.widgets['vbox12'].show()
	self.cellview5.show()
	self.widgets['wndStep5'].show()

    def alignPrintHeadsStep6(self, *args):
	if not self.cellview6:
		bg=self.widgets['cellview6'].get_property("background-gdk")
		self.cellview6=gtk.cell_view_new_with_markup('<span size="large" foreground="white"><b>\nAligning Print Heads 6 of 8\n</b></span>')
		self.cellview6.set_property("background-gdk",bg)
		self.widgets['vbox14'].pack_start(self.cellview6,True,True,6)
		self.widgets['vbox14'].reorder_child(self.cellview6,0)
	self.widgets['vbox14'].show()
	self.cellview6.show()
	self.widgets['wndStep6'].show()

    def alignPrintHeadsStep7(self, *args):
	if not self.cellview7:
		bg=self.widgets['cellview7'].get_property("background-gdk")
		self.cellview7=gtk.cell_view_new_with_markup('<span size="large" foreground="white"><b>\nAligning Print Heads 7 of 8\n</b></span>')
		self.cellview7.set_property("background-gdk",bg)
		self.widgets['vbox16'].pack_start(self.cellview7,True,True,6)
		self.widgets['vbox16'].reorder_child(self.cellview7,0)
	self.widgets['vbox16'].show()
	self.cellview7.show()
	self.widgets['wndStep7'].show()

    def alignPrintHeadsStep8(self, save):
	if not self.cellview8:
		bg=self.widgets['cellview8'].get_property("background-gdk")
		self.cellview8=\
		   gtk.cell_view_new_with_markup('<span size="large" '+\
			 'foreground="white">'+\
			 '<b>\nAligning Print Heads 8 of 8'+\
			  '\n</b></span>')
		self.cellview8.set_property("background-gdk",bg)
		self.widgets['vbox19'].pack_start(self.cellview8,True,True,6)
		self.widgets['vbox19'].reorder_child(self.cellview8,0)
	if save:
		self.widgets['lblMsgStep8'].set_label("Congratulations! Your "+\
				"printer is now aligned and the alignment "+\
			        "has been saved into the printer.")
	else:
		self.widgets['lblMsgStep8'].set_label("OK, your printer is "+\
		   "aligned, but the alignment has not been saved. You may "+\
		   "want to turn the printer off and back on to restore the "+\
		   "original settings. If you wish to save the alignment, "+\
		   "you must repeat this process.")
	self.widgets['vbox19'].show()
	self.cellview8.show()
	self.widgets['wndStep8'].show()

    #----------------------------------------------------------------------
    # Read prefs from configuration file; if not, display prefs dialog
    #----------------------------------------------------------------------
    def readPrefs(self, *args):
	firstTime=False
	config.sFilename=os.path.expanduser('~/.stylus-toolbox.conf')
	try:
		os.stat(config.sFilename)
	except:
		print "Creating config file %s" % (`config.sFilename`)
		try:
			f=open(config.sFilename,'w')
			f.close()
		except (IOerror, os.error), why:
			print "Failed to create "+config.sFilename
	config.fp=open(config.sFilename)
	config.readfp(config.fp,config.sFilename)
	if not config.has_section('device'):
		firstTime=True	
		print "No [device] section"
	if not config.has_section('external programs'):
		firstTime=True	
		print "No [external programs] section"
	if not config.has_option('device','raw device'):
		firstTime=True
	else:
		config.sRawDevice=config.get('device','raw device')
	if not config.has_option('device','is newer USB printer'):
		firstTime=True
	else:
		config.fNewUSB=config.get('device','is newer USB printer')
	if not config.has_option('device','model'):
		firstTime=True
	else:
		config.sModel=config.get('device','model')
	
	if not config.has_option('external programs','escputil binary'):
		firstTime=True
	else:
		config.sEscputilProg=config.get('external programs',\
						'escputil binary')
	if firstTime:
		self.resetPrefs()
        	self.widgets['wndPrefs'].show()
		if not self.fModelsPopulated:
			self.populateModels()

    #----------------------------------------------------------------------
    # Write prefs to configuration file
    #----------------------------------------------------------------------
    def writePrefs(self, *args):
	if not config.has_section('device'):
		config.add_section('device')
	if not config.has_section('external programs'):
		config.add_section('external programs')
	config.set('device','raw device',config.sRawDevice)
	if config.fNewUSB:
		config.set('device','is newer USB printer','True')
	else:
		config.set('device','is newer USB printer','False')
	config.set('device','model',config.sModel)
	config.set('external programs','escputil binary',config.sEscputilProg)
	print 'writing preferences to '+config.sFilename
	f=open(config.sFilename,'w')
	config.write(f)
		
    #----------------------------------------------------------------------
    # Reset prefs dialog from internal configuration data 
    #----------------------------------------------------------------------
    def resetPrefs(self, *args):
	self.widgets['txtDevice'].set_text(config.sRawDevice)
	self.widgets['usbCheckButton'].set_property("active",config.fNewUSB)
	if config.sModel == 'Auto':
		self.widgets['cmbModel'].set_active(-1)
		self.widgets['radAutoDetect'].set_property("active",True)
		self.widgets['radSelectModel'].set_property("active",False)
		self.widgets['radSelectModel'].toggled()
	self.widgets['txtEscputil'].set_text(config.sEscputilProg)

    #----------------------------------------------------------------------
    # Event handling code for the main window
    #----------------------------------------------------------------------
    def on_wndToolbox_activate_default(self, *args):
#	self.refreshWindow()
        pass

    def on_wndToolbox_delete(self, *args):
  	gtk.main_quit() 

    def on_quit1_activate(self, *args):
	gtk.main_quit()


    def on_cut1_activate(self, *args):
        pass


    def on_copy1_activate(self, *args):
        pass


    def on_paste1_activate(self, *args):
        pass


    def on_delete1_activate(self, *args):
        pass


    def on_preferences1_activate(self, *args):
	self.resetPrefs()
        self.widgets['wndPrefs'].show_all()
	if not self.fModelsPopulated:
		self.populateModels()


    def on_refresh1_activate(self, *args):
	self.refreshWindow()


    def on_about1_activate(self, *args):
	self.aboutBox()

    def on_btnClean_clicked(self, *args):
      	self.cleanPrintHeads()

    def on_btnAlign_clicked(self, *args):
        self.alignPrintHeads()

    def on_btnPrint_clicked(self, *args):
        self.printTestPage()

    def on_btnRefresh_clicked(self, *args):
	self.refreshWindow()


    def on_btnClose_clicked(self, *args):
        gtk.main_quit()

    #----------------------------------------------------------------------
    # Event handling code for the alignment assistant 
    #----------------------------------------------------------------------
    def on_btnStep1Cancel_clicked(self, *args):
	self.resetPrefs()
	self.widgets['wndStep1'].hide()

    def on_btnStep1Forward_clicked(self, *args):
	self.widgets['wndStep1'].hide()
	self.child.sendline('')
	self.child.expect('Pass #1>')
	self.alignPrintHeadsStep2()

    def on_btnStep2Cancel_clicked(self, *args):
	self.widgets['wndStep2'].hide()
	self.child.kill(9)


    def on_btnStep2Back_clicked(self, *args):
	self.alignPrintHeadsStep1()
	self.widgets['wndStep2'].hide()


    def on_btnStep2Forward_clicked(self, *args):
	self.widgets['wndStep2'].hide()
	pn=self.widgets['cbePairNum1'].get_property("active")
	self.child.sendline(str(pn+1))
	self.child.expect('Pass #2>')
	self.alignPrintHeadsStep3()

    def on_btnStep3Cancel_clicked(self, *args):
	self.widgets['wndStep3'].hide()
	self.child.kill(9)

    def on_btnStep3Back_clicked(self, *args):
        pass

    def on_btnStep3Forward_clicked(self, *args):
	self.widgets['wndStep3'].hide()
	pn=self.widgets['cbePairNum1'].get_property("active")
	self.child.sendline(str(pn))
	self.child.expect('Pass #3>')
	self.alignPrintHeadsStep4()

    def on_btnStep4Cancel_clicked(self, *args):
	self.widgets['wndStep4'].hide()
	self.child.kill(9)

    def on_btnStep4Back_clicked(self, *args):
        pass

    def on_btnStep4Forward_clicked(self, *args):
	self.widgets['wndStep4'].hide()
	pn=self.widgets['cbePairNum1'].get_property("active")
	self.child.sendline(str(pn))
	self.child.expect('Pass #4>')
	self.alignPrintHeadsStep5()

    def on_btnStep5Cancel_clicked(self, *args):
	self.widgets['wndStep5'].hide()
	self.child.kill(9)

    def on_btnStep5FowardButton_clicked(self, *args):
	self.widgets['wndStep5'].hide()
	pn=self.widgets['cbePairNum1'].get_property("active")
	self.child.sendline(str(pn))
	self.child.expect('Press enter to continue >')
	self.alignPrintHeadsStep6()

    def on_btnStep6Cancel_clicked(self, *args):
	self.widgets['wndStep6'].hide()
	self.child.kill(9)

    def on_btnStep6Back_clicked(self, *args):
        pass

    def on_btnStep6Forward_clicked(self, *args):
	self.widgets['wndStep6'].hide()
	self.child.sendline('')
	self.child.expect('What do you want to do (s, q, r)?')
	self.alignPrintHeadsStep7()

    def on_btnStep7Cancel_activate(self, *args):
	self.widgets['wndStep7'].hide()

    def on_btnStep7Back_clicked(self, *args):
        pass

    def on_btnStep7Forward_clicked(self, *args):
	self.widgets['wndStep7'].hide()
	if self.widgets['radRepeat'].get_property("active"):
		self.child.sendline('r')
		self.alignPrintHeadsStep1()
	elif self.widgets['radQuit'].get_property("active"):
		self.child.sendline('q')
		self.alignPrintHeadsStep8(False)
	else:
		self.child.sendline('s')
		self.alignPrintHeadsStep8(True)

    def on_btnStep8Close_clicked(self, *args):
	self.widgets['wndStep8'].hide()

    #----------------------------------------------------------------------
    # Event handling code for the preferences dialog 
    #----------------------------------------------------------------------
    def on_btnDevBrowse_clicked(self, *args):
	self.widgets['dlgFileChooser'].set_property("title","Open Device")
	self.widgets['dlgFileChooser'].set_current_folder("/dev")
	self.widgets['dlgFileChooser'].show()

    def on_btnEscputilBrowse_clicked(self, *args):
	self.widgets['dlgFileChooser'].set_property("title","Open")
	self.widgets['dlgFileChooser'].set_current_folder("/usr/bin")
	self.widgets['dlgFileChooser'].show()

    def on_PrefsWindow_closed(self, *args):
        # avoids destruction 
	self.resetPrefs()
	self.widgets['wndPrefs'].hide()
	return True
    
    def on_PrefsCancel_clicked(self, *args):
	self.resetPrefs()
	self.widgets['wndPrefs'].hide()

    def on_prefsOkButton_clicked(self, *args):
	config.sRawDevice=self.widgets['txtDevice'].get_text()
	print 'Raw device set to "'+config.sRawDevice+'"'
	if self.widgets['usbCheckButton'].get_property("active"):
		config.fNewUSB=True
	else:
		config.fNewUSB=False
	print 'Newer model set to '+str(config.fNewUSB)
	iter=self.widgets['cmbModel'].get_active_iter()
	if not iter:
		config.sModel='Auto'
	else:
		config.sModel=self.lstModelList.get_value(iter,1)
	print 'Model set to "'+config.sModel+'"'
	config.sEscputilProg=self.widgets['txtEscputil'].get_text()
	print 'escputil location set to "'+config.sEscputilProg+'"'
	self.widgets['wndPrefs'].hide()
	print 'writing preferences'
	self.writePrefs()

    def on_radAutoDetect_toggled(self, *args):
	if self.widgets['radSelectModel'].get_property("active"):
		self.widgets['cmbModel'].set_property("sensitive",True)
	else:
		self.widgets['cmbModel'].set_property("sensitive",False)
		self.widgets['cmbModel'].set_active(-1)

    def on_dlgFileChooser_delete_event(self, *args):
        # avoids destruction 
	self.widgets['dlgFileChooser'].hide()
	return True

    def on_cmbModel_changed(self, *args):
	pass

    #----------------------------------------------------------------------
    # Event handling code for the file chooser dialog 
    #----------------------------------------------------------------------
    def on_btnFCOpen_clicked(self, *args):
	if self.widgets['dlgFileChooser'].get_property("title") == \
	    "Open Device":
		devName=self.widgets['dlgFileChooser'].get_filename()
		self.widgets['txtDevice'].set_text(devName)
	else:
		escputil=self.widgets['dlgFileChooser'].get_filename()
		self.widgets['txtEscputil'].set_text(escputil)
	self.widgets['dlgFileChooser'].hide()

    def on_fileChooserCancel_clicked(self, *args):
	self.widgets['dlgFileChooser'].hide()


#----------------------------------------------------------------------

def main(argv):
    w = stylusToolboxMain()
    w.readPrefs()
    w.refreshWindow()
    gtk.main()

#----------------------------------------------------------------------

if __name__ == '__main__':
    main(sys.argv)
