#!/usr/bin/env python

import pygtk

import gettext 
APP="SVGpage"  
DIR="./locale"
gettext.textdomain(APP)  
gettext.bindtextdomain(APP, DIR)
_ = gettext.gettext

import gobject
if gobject.pygtk_version < (2,8,1):
    print >>sys.stderr, _("pyGTK version 2.8 or greater is required for this application")
    raise SystemExit
import gtk, os
curd = os.getcwd()
os.system('export LD_LIBRARY_PATH=%s:$LD_LIBRARY_PATH' % curd)
try:
	import pango
except:
	print >> sys.stderr, _("Cannot load Pango")
	raise SystemExit

import imghdr, sys, commands, re, shutil
import cairo, pangocairo
import ConfigParser


f = commands.getoutput('type -path autotrace')
if not f:
	if not os.path.exists(os.path.join(curd, "autotrace")):
		print >>sys.stderr, _("Autotrace was not found on your system, it is required for SVG-page")
		raise SystemExit
				
font_large = pango.FontDescription()
font_large.set_weight(pango.WEIGHT_BOLD)
font_large.set_size(1024*18)

########## get any user settings #################
config = ConfigParser.ConfigParser()
samp_config = os.path.join(curd, "SVGpage.cfg")
cfile = os.path.join(os.path.expanduser("~/"), ".SVGpage")
if not os.path.exists(cfile):
	shutil.copyfile(samp_config, cfile)
#########################################################

bg_xpm = [
"1 450 52 1",
" 	c #D7D7D7",
".	c #D8D8D8",
"+	c #D9D9D9",
"@	c #DADADA",
"#	c #DBDBDB",
"$	c #DCDCDC",
"%	c #DDDDDD",
"&	c #DEDDDE",
"*	c #DEDEDE",
"=	c #DFDFDF",
"-	c #DFE0DF",
";	c #E0E0E0",
">	c #E1E1E1",
",	c #E1E1E2",
"'	c #E2E2E2",
")	c #E3E3E3",
"!	c #E4E4E4",
"~	c #E5E5E5",
"{	c #E6E5E5",
"]	c #E6E6E6",
"^	c #E7E7E7",
"/	c #E8E8E8",
"(	c #E9E9E9",
"_	c #EAEAEA",
":	c #EBEBEB",
"<	c #ECECEC",
"[	c #EDEDED",
"}	c #EEEEEE",
"|	c #EFEEEF",
"1	c #EFEFEF",
"2	c #F0F0F0",
"3	c #F1F0F0",
"4	c #F1F1F1",
"5	c #F2F2F2",
"6	c #F2F3F2",
"7	c #F3F3F3",
"8	c #F4F4F4",
"9	c #F5F4F4",
"0	c #F5F5F5",
"a	c #F6F6F6",
"b	c #F6F7F6",
"c	c #F7F7F7",
"d	c #F8F8F8",
"e	c #F9F9F9",
"f	c #F9F8F8",
"g	c #F6F6F7",
"h	c #F4F5F4",
"i	c #F3F2F2",
"j	c #E9EAE9",
"k	c #E3E3E4",
"l	c #E1E2E1",
"m	c #E0DFDF",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
".",
".",
"+",
"@",
"@",
"#",
"$",
"$",
"%",
"&",
"*",
"=",
"-",
";",
">",
",",
"'",
")",
")",
"!",
"~",
"{",
"]",
"^",
"^",
"/",
"(",
"(",
"_",
":",
":",
"<",
"[",
"[",
"}",
"|",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"0",
"a",
"b",
"c",
"d",
"d",
"e",
"f",
"d",
"c",
"g",
"a",
"0",
"h",
"8",
"7",
"i",
"5",
"4",
"3",
"2",
"1",
"1",
"}",
"[",
"[",
"<",
":",
":",
"_",
"j",
"(",
"/",
"^",
"^",
"]",
"~",
"~",
"!",
"k",
")",
"'",
"l",
">",
";",
"m",
"=",
"*",
"*",
"%",
"$",
"$",
"#",
"@",
"@",
"+",
".",
".",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" "]


ui_string = """<ui>
	<menubar name='Menubar'>
		<menu action='FileMenu'>
			<menuitem action='Open'/>
			<menuitem action='Quit'/>
		</menu>
		<menu action='ViewMenu'>\
			<menuitem action='PNG Full-Size'/>
			<menuitem action='SVG Full-Size'/>
		</menu>
		<menu action='SaveMenu'>\
			<menu action='Raster Image'>\
				<menuitem action='As PNG'/>
				<menuitem action='As JPG'/>
			</menu>
			<separator/>
			<menuitem action='Raster Half-Size'/>
			<menuitem action='Raster Double-Size'/>
			<separator/>
			<menuitem action='SVG Image'/>
		</menu>
		<menu action='HelpMenu'>
			<menuitem action='About'/>
			<menuitem action='Help Pages'/>
		</menu>
	</menubar>
</ui>"""

basePath = os.path.dirname(os.path.realpath(sys.argv[0]))
svgPath = os.path.join(basePath, "rgb.svg")
rasPath = os.path.join(basePath, "rgb.png")

class Window(gtk.Window):
	def __init__(self):
		gtk.Window.__init__(self)
		self.set_position(gtk.WIN_POS_CENTER)
		self.set_title(_('SVGpage - 0.4'))
		self.connect('delete-event', self.delete_event_cb)
		self.set_geometry_hints(self, 640, 534, 640, 534)

		font_desc = pango.FontDescription('monospace 9')
		
		# background picture
		pixbuf = gtk.gdk.pixbuf_new_from_xpm_data(bg_xpm)
		pixmap, mask = pixbuf.render_pixmap_and_mask()
		del pixbuf
		self.set_app_paintable(True)
		self.realize()
		self.window.set_back_pixmap(pixmap, False)
		del pixmap
		
		self.rpath = rasPath
		self.spath = svgPath
		self.tmpPath = ""
		tips = gtk.Tooltips()
		vbox = gtk.VBox()
		self.add(vbox)

		self.create_ui()
		vbox.pack_start(self.ui.get_widget('/Menubar'), expand=False)
		#vbox.pack_start(self.tbar, expand=False)


		#  raster section  ####################################################
		pbox = gtk.HBox()
		rasBox = gtk.VBox()
		lframe = gtk.Frame()
		lframe.set_shadow_type(gtk.SHADOW_IN)
		lframe.set_size_request(230, 240)
		lblRaster = gtk.Label(_("Raster\nImage"))
		lblRaster.modify_font(font_large)
		lblRaster.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#3333CC"))
		rasBox.pack_start(lblRaster, False, False, 32)
		self.rfixed = gtk.Fixed()
		self.img1_img = gtk.Image()
		try:
			img1 = gtk.gdk.pixbuf_new_from_file(rasPath)
			self.img1_img.set_from_pixbuf(img1)
		except:
			print >> sys.stderr, _("Could not load the startup PNG image")
			

		self.rfixed.put(self.img1_img, 13, 32)
		rasBox.pack_start(self.rfixed, False, False, 0)	
		lframe.add(rasBox)
		pbox.pack_start(lframe, False, False, 0)


		###   SVG section  ####################################################
		svgBox = gtk.VBox()
		rframe = gtk.Frame()
		rframe.set_shadow_type(gtk.SHADOW_IN)
		rframe.set_size_request(230, 240)
		lblSVG = gtk.Label(_(" SVG\nImage"))
		lblSVG.modify_font(font_large)
		lblSVG.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#CC0033"))
		svgBox.pack_start(lblSVG, False, False, 32)
		self.sfixed = gtk.Fixed()
		self.svg_img = gtk.Image()
		try:
			img2 = gtk.gdk.pixbuf_new_from_file(svgPath)
			self.svg_img.set_from_pixbuf(img2)
		except:
			print >> sys.stderr, _("Could not load the startup SVG image")
		self.sfixed.put(self.svg_img, 13, 32)
		svgBox.pack_start(self.sfixed, False, False, 0)
		rframe.add(svgBox)
		pbox.pack_start(rframe, False, False, 0)
		#########################################################################


		# spinbutton adjustment definitions ####################################################################
		adjColor = gtk.Adjustment(256, lower=0, upper=256, step_incr=1, page_incr=0, page_size=0)
		adjColAlwThresh = gtk.Adjustment(60, lower=2, upper=180, step_incr=1, page_incr=10, page_size=0)
		adjCornSur = gtk.Adjustment(60, lower=2, upper=180, step_incr=1, page_incr=20, page_size=0)
		adjCornTh = gtk.Adjustment(100, lower=2, upper=180, step_incr=1, page_incr=10, page_size=0)
		adjDespLev = gtk.Adjustment(8, lower=0, upper=20, step_incr=1, page_incr=0, page_size=0)
		adjDespTig = gtk.Adjustment(2, lower=0, upper=8, step_incr=0.1, page_incr=1, page_size=0)
		adjErrThr = gtk.Adjustment(2, lower=.1, upper=10, step_incr=0.1, page_incr=1, page_size=0)
		adjFiltIt = gtk.Adjustment(4, lower=1, upper=16, step_incr=1, page_incr=0, page_size=0)
		adjLineRevThr = gtk.Adjustment(0.01, lower=0.01, upper=0.16, step_incr=0.01, page_incr=1, page_size=0)
		adjLineThr = gtk.Adjustment(1, lower=1, upper=20, step_incr=1, page_incr=0, page_size=0)
		adjTangSur = gtk.Adjustment(3, lower=1, upper=16, step_incr=1, page_incr=0, page_size=0)
		adjNumCol = gtk.Adjustment(0, lower=0, upper=256, step_incr=1, page_incr=20, page_size=0)
		#######################################################################################################

		cframe = gtk.Frame()

		contBox = gtk.VBox()
		cframe.set_shadow_type(gtk.SHADOW_IN)
		cframe.set_size_request(120, 240)

		self.spinDespLev = gtk.SpinButton(adjDespLev, 0, 0)
		self.spinDespLev.set_numeric(True)
		self.DespLevVal = self.spinDespLev.get_value()
		self.spinDespLev.connect("value-changed", self.cDespLev)
		tips.set_tip(self.spinDespLev, _("Most noticeable adjustment.\nLow value for text and graphics,\nhigher value for pictures."))
		lblDL = gtk.Label(_("Despeckle Level"))
		lblDL.modify_font(font_desc)
		contBox.pack_start(lblDL, True, True, 0)
		contBox.pack_start(self.spinDespLev, True, True, 0)

		self.spinColAlwThresh = gtk.SpinButton(adjColAlwThresh, 0, 0)
		self.spinColAlwThresh.set_numeric(True)
		self.ColAlwThresh = self.spinColAlwThresh.get_value()
		self.spinColAlwThresh.connect("value-changed", self.cColAlwThresh)
		lblCAT = gtk.Label(_("Color Always Threshold"))
		lblCAT.modify_font(font_desc)
		contBox.pack_start(lblCAT, True, True, 0)
		contBox.pack_start(self.spinColAlwThresh, True, True, 0)

		self.spinCornSur = gtk.SpinButton(adjCornSur, 0, 0)
		self.spinCornSur.set_numeric(True)
		self.CornSur = self.spinCornSur.get_value()
		self.spinCornSur.connect("value-changed", self.cCornSur)
		lblCS = gtk.Label(_("Corner Surround"))
		lblCS.modify_font(font_desc)
		contBox.pack_start(lblCS, True, True, 0)
		contBox.pack_start(self.spinCornSur, True, True, 0)

		self.spinCornTh = gtk.SpinButton(adjCornTh, 0, 0)
		self.spinCornTh.set_numeric(True)
		self.CornTh = self.spinCornTh.get_value()
		self.spinCornTh.connect("value-changed", self.cCornTh)
		lblCTh = gtk.Label(_("Corner Threshold"))
		lblCTh.modify_font(font_desc)
		contBox.pack_start(lblCTh, True, True, 0)
		contBox.pack_start(self.spinCornTh, True, True, 0)

		self.spinDespTig = gtk.SpinButton(adjDespTig, 0, 1)
		self.spinDespTig.set_numeric(True)
		self.DespTig = self.spinDespTig.get_value()
		self.spinDespTig.connect("value-changed", self.cDespTig)
		lblDT = gtk.Label(_("Despeckle Tightness"))
		lblDT.modify_font(font_desc)
		contBox.pack_start(lblDT, True, True, 0)
		contBox.pack_start(self.spinDespTig, True, True, 0)

		self.spinErrThr = gtk.SpinButton(adjErrThr, 0, 1)
		self.spinErrThr.set_numeric(True)
		self.ErrThr = self.spinErrThr.get_value()
		self.spinErrThr.connect("value-changed", self.cErrThr)
		lblET = gtk.Label(_("Error Threshold"))
		lblET.modify_font(font_desc)
		contBox.pack_start(lblET, True, True, 0)
		contBox.pack_start(self.spinErrThr, True, True, 0)

		self.spinFiltIt = gtk.SpinButton(adjFiltIt, 0, 0)
		self.spinFiltIt.set_numeric(True)
		self.FiltIt = self.spinFiltIt.get_value()
		self.spinFiltIt.connect("value-changed", self.cFiltIt)
		lblFI = gtk.Label(_("Filter Iterations"))
		lblFI.modify_font(font_desc)
		contBox.pack_start(lblFI, True, True, 0)
		contBox.pack_start(self.spinFiltIt, True, True, 0)	

		self.spinLineRevThr = gtk.SpinButton(adjLineRevThr, 0, 2)
		self.spinLineRevThr.set_numeric(True)
		self.LineRevThr = self.spinLineRevThr.get_value()
		self.spinLineRevThr.connect("value-changed", self.cLineRevThr)
		lblLRT = gtk.Label(_("Line Revision Threshold"))
		lblLRT.modify_font(font_desc)
		contBox.pack_start(lblLRT, True, True, 0)
		contBox.pack_start(self.spinLineRevThr, True, True, 0)

		self.spinLineThr = gtk.SpinButton(adjLineThr, 0, 0)
		self.spinLineThr.set_numeric(True)
		self.LineThr = self.spinLineThr.get_value()
		self.spinLineThr.connect("value-changed", self.cLineThr)
		lblLT = gtk.Label(_("Line Threshold"))
		lblLT.modify_font(font_desc)
		contBox.pack_start(lblLT, True, True, 0)
		contBox.pack_start(self.spinLineThr, True, True, 0)

		self.spinTangSur = gtk.SpinButton(adjTangSur, 0, 0)
		self.spinTangSur.set_numeric(True)
		self.TangSur = self.spinTangSur.get_value()
		self.spinTangSur.connect("value-changed", self.cTangSur)
		lblTS = gtk.Label(_("Tangent Surround"))
		lblTS.modify_font(font_desc)
		contBox.pack_start(lblTS, True, True, 0)
		contBox.pack_start(self.spinTangSur, True, True, 0)

		self.numColSur = gtk.SpinButton(adjNumCol, 0, 0)
		self.numColSur.set_numeric(True)
		self.ColNum = self.numColSur.get_value()
		self.numColSur.connect("value-changed", self.cColSur)
		lblNC = gtk.Label(_("Number of colors"))
		lblNC.modify_font(font_desc)
		contBox.pack_start(lblNC, True, True, 0)
		contBox.pack_start(self.numColSur, True, True, 0)
		
		cframe.add(contBox)
		pbox.pack_start(cframe, True, True, 0)

		vbox.pack_start(pbox, True, True, 0)
		######################################################

		bframe = gtk.Frame()
		bframe.set_shadow_type(gtk.SHADOW_IN)
		btnBox = gtk.HBox(True, 1)
		btn_to_svg = gtk.Button(_("Render as an SVG"))
		btn_to_svg.connect("clicked", self.renderAsSVG)
		btn_to_png = gtk.Button(_("Convert to PNG"))
		btn_to_png.connect("clicked", self.renderAsPNG)	
		btnBox.pack_start(btn_to_svg, True, True, 0)
		btnBox.pack_start(btn_to_png, True, True, 0)
		bframe.add(btnBox)
		vbox.pack_start(bframe, False, False, 0)

		#status = gtk.Statusbar()
		#vbox.pack_end(status, expand=False)
		self.show_all()

		
###########################################################################################
	
	def cDespLev(self, evt):		
		self.DespLevVal = evt.get_value()
	def cColAlwThresh(self, evt):		
		self.ColAlwThresh = evt.get_value()
	def cCornSur(self, evt):		
		self.CornSur = evt.get_value()
	def cCornTh(self, evt):		
		self.CornTh = evt.get_value()
	def cDespTig(self, evt):		
		self.DespTig = evt.get_value()
	def cErrThr(self, evt):		
		self.ErrThr = evt.get_value()
	def cFiltIt(self, evt):		
		self.FiltIt = evt.get_value()
	def cLineRevThr(self, evt):		
		self.LineRevThr = evt.get_value()
	def cLineThr(self, evt):		
		self.LineThr = evt.get_value()
	def cTangSur(self, evt):		
		self.TangSur = evt.get_value()
	def cColSur(self, evt):		
		self.ColNum = evt.get_value()
		
	def create_ui(self):
		ag = gtk.ActionGroup('WindowActions')
		actions = [
		    ('FileMenu', None, _('_File')),
		    ('Open',     gtk.STOCK_OPEN, _('_Open'), _('<control>O'), _('Open a file'), self.file_open_cb),
		    ('Quit',     gtk.STOCK_QUIT, _('_Quit'), _('<control>Q'), _('Quit application'), self.delete_event_cb),
		    ('ViewMenu', None, _('_View')),
		    ('PNG Full-Size',    None, _('Full-Size _PNG'), _('<control>P'), _('PNG Full-Size'), self.set_display),
		    ('SVG Full-Size',    None, _('Full-Size _SVG'), _('<control>S'), _('SVG Full-Size'), self.set_display),
		    ('SaveMenu', None, _('_Save')),
		    ('Raster Image', None, _('save raster')),
		    ('As PNG',    None, _('As a  PNG'), None, _('PNG Image'), self.sav_png),
		    ('As JPG',    None, _('As a  JPG'), None, _('PNG Image'), self.sav_jpg),
		    ('Raster Half-Size', None, _('Raster Half-Size'), None, _('Raster Half-Size'), self.sav_half),
		    ('Raster Double-Size', None, _('Raster Double-Size'), None, _('Raster Double-Size'), self.sav_double),
		    ('SVG Image',    None, _('SVG Image'), None, _('SVG Image'), self.sav_svg),
		    ('HelpMenu', None, _('_Help')),
		    ('About',    None, _('_About'), None, _('About application'), self.help_about_cb),
		    ('Help Pages',    None, _('Help Pages'), None, _('SVG-page help'), help_window),
		    ]
		ag.add_actions(actions)
		self.ui = gtk.UIManager()
		self.ui.insert_action_group(ag, 0)
		self.ui.add_ui_from_string(ui_string)
		self.add_accel_group(self.ui.get_accel_group())


	def file_open_cb(self, action):
		dialog = gtk.FileChooserDialog(_("Open..."), self,
                        		       gtk.FILE_CHOOSER_ACTION_OPEN,
                        		       (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                		gtk.STOCK_OPEN, gtk.RESPONSE_OK))
		dialog.set_default_response(gtk.RESPONSE_OK)
		
		config.read(cfile)
		ldir = config.get("defaults", "lastdir")
		if (ldir == "blank"):
			dialog.set_current_folder(basePath)
		else:
			if os.path.exists(ldir):
				dialog.set_current_folder(ldir)
			else:
				dialog.set_current_folder(basePath)
		
		
		preview = gtk.Image()
		dialog.set_preview_widget(preview)
		dialog.connect("update-preview", self.update_preview_cb, preview)
		
		filter = gtk.FileFilter()
		filter.set_name(_("Images"))
		filter.add_mime_type("image/png")
		filter.add_mime_type("image/jpeg")
		filter.add_mime_type("image/gif")
		filter.add_mime_type("image/svg+xml")
		filter.add_pattern("*.png")
		filter.add_pattern("*.jpg")
		filter.add_pattern("*.gif")
		filter.add_pattern("*.xpm")
		filter.add_pattern("*.svg")
		dialog.add_filter(filter)
		
		dialog.hide()
		ln = ""
		if dialog.run() == gtk.RESPONSE_OK:

			filename = dialog.get_filename()
			dialog.destroy()
			xt = os.path.splitext(filename)[1]
			if xt == ".svg" or xt == ".SVG":
				self.setImage(self.svg_img, filename)
				ln = os.path.dirname(filename)

			else:
				t = imghdr.what(filename)
				if not t: return
				if t == "png":
					self.setImage(self.img1_img, filename)
					ln = os.path.dirname(filename)
				elif t == "gif" or t == "bmp" or t == "jpeg" or t == "xpm":
					pixbuf = gtk.gdk.pixbuf_new_from_file (filename)
					pth = os.path.join(os.getenv("HOME"), "_tmp.png")
					pixbuf.save(pth, "png")
					self.setImage(self.img1_img, pth)
				else:
					print _("What the hell was that?")
		else:
			dialog.destroy()
		if len(ln):
			config.set("defaults", "lastdir", ln)
			t1 = open(cfile, "w")
			config.write(t1)
			t1.close()
			
			

	def update_preview_cb(self, file_chooser, preview):
		filename = file_chooser.get_preview_filename()
		try:
			pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(filename, 128, 128)
			preview.set_from_pixbuf(pixbuf)
			have_preview = True
		except:
			have_preview = False
		file_chooser.set_preview_widget_active(have_preview)
		return
		
    
	def setImage(self, img, pth):
		try:
			pixbuf = gtk.gdk.pixbuf_new_from_file (pth)
			(w,h)  = (pixbuf.get_width(),pixbuf.get_height())
			if w == 0:
				self.file_error()
				return False
			s = self.getWH(w,h)
			img.set_from_pixbuf(pixbuf.scale_simple(s[0],s[1],gtk.gdk.INTERP_BILINEAR))
			if s[0] < 200:
				nx = int(((200-s[0]) / 2) + 13)
			else:
				nx = 13
			if s[1] < 200:
				ny = int(((200-s[1]) / 2) + 32)
			else:
				ny = 32
			if img == self.svg_img:
				self.sfixed.move(self.svg_img, nx, ny)
				self.spath = pth
				
			else:
				self.rfixed.move(self.img1_img, nx, ny)
				self.rpath = pth
		except:
			self.file_error()
			return	False
		return True
		
		
	def renderAsSVG(self, evt=None):

		#saves a png as an svg
		if not len(self.rpath): return
		self.tmpPath = os.path.join(os.getenv("HOME"), "_tmp.svg")

		AT_CMD = ""
		f = commands.getoutput('type -path autotrace')
		if f:
			AT_CMD = 'autotrace --output-format svg --output-file %s --despeckle-level %f --corner-always-threshold %f --corner-surround %f --tangent-surround %f --color-count %f --corner-threshold %f --despeckle-tightness %f --error-threshold %f --filter-iterations %f --line-reversion-threshold %f --line-threshold %f %s' % (self.tmpPath, self.DespLevVal, self.ColAlwThresh, self.CornSur, self.TangSur, self.ColNum, self.CornTh, self.DespTig, self.ErrThr, self.FiltIt, self.LineRevThr, self.LineThr, self.rpath)
		else:
			AT_CMD = 'cd %s && ./autotrace --output-format svg --output-file %s --despeckle-level %f --corner-always-threshold %f --corner-surround %f --tangent-surround %f --color-count %f --corner-threshold %f --despeckle-tightness %f --error-threshold %f --filter-iterations %f --line-reversion-threshold %f --line-threshold %f %s' % (basePath, self.tmpPath, self.DespLevVal, self.ColAlwThresh, self.CornSur, self.TangSur, self.ColNum, self.CornTh, self.DespTig, self.ErrThr, self.FiltIt, self.LineRevThr, self.LineThr, self.rpath)
		
		self.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
		while gtk.events_pending():
			gtk.main_iteration()
		try:
			s = commands.getoutput(AT_CMD)
			self.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.LEFT_PTR))
		except:
			self.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.LEFT_PTR))
			self.file_create_err(None, s)
			return	
		x = re.search("permission", s)
		if x:
			self.file_create_err(None, s)
			return
		self.setImage(self.svg_img, self.tmpPath)

		
	def renderAsPNG(self, evt=None):
		if not len(self.spath): return
		self.tmpPath = os.path.join(os.getenv("HOME"), "_tmp.png")

		pixbuf = gtk.gdk.pixbuf_new_from_file(self.spath)
		pixbuf.save(self.tmpPath, "png")
		self.setImage(self.img1_img, self.tmpPath)

  
 	def getWH(self, imW, imH):
		if imW > 200 or imH > 200:
			if imW > imH:
				scale = 200 / float(imW)
			else:
				scale = 200 / float(imH)
			m = int(imW * scale), int(imH * scale), scale
		else:
			if imW > imH:
				scale = 200 / float(imW)
			else:
				scale = 200 / float(imH)
 			m = imW, imH, scale
		return m
 	
	
	def sav_png(self, evt):	
		self.do_save("png")
	def sav_jpg(self, evt):	
		self.do_save("jpg")
	def sav_bmp(self, evt):	
		self.do_save("bmp")
	def sav_gif(self, evt):	
		self.do_save("gif")	
	def sav_xpm(self, evt):	
		self.do_save("xpm")

	def sav_half(self, evt):	
		try:
			pixbuf = gtk.gdk.pixbuf_new_from_file (self.rpath)
			(w,h)  = (pixbuf.get_width(),pixbuf.get_height())
			if w == 0:
				self.file_error()
				return
			w = int(w * 0.5)
			h = int(h * 0.5)
			self.tmpPath = os.path.join(os.getenv("HOME"), "_tmp.png")
			scaled_pix = pixbuf.scale_simple(w, h, gtk.gdk.INTERP_BILINEAR)
			scaled_pix.save(self.tmpPath, "png")
			self.rpath = self.tmpPath
			self.setImage(self.img1_img, self.tmpPath)
			dialog = gtk.MessageDialog(self,
                        		   gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                        		   gtk.MESSAGE_INFO, gtk.BUTTONS_OK,
                        		   _('Image saved in tmp file, HALF-sized: \n\nYou can now use the updated raster image to\nrender an SVG, or save it permanently\nto a file via the Save Menu.'))
			dialog.run()
			dialog.destroy()
		except:
			self.file_error()
			return
			
			
	def sav_double(self, evt):	
		try:
			pixbuf = gtk.gdk.pixbuf_new_from_file (self.rpath)
			(w,h)  = (pixbuf.get_width(),pixbuf.get_height())
			if w == 0:
				self.file_error()
				return
			w = int(w * 2)
			h = int(h * 2)
			self.tmpPath = os.path.join(os.getenv("HOME"), "_tmp.png")
			scaled_pix = pixbuf.scale_simple(w, h, gtk.gdk.INTERP_BILINEAR)
			scaled_pix.save(self.tmpPath, "png")
			self.rpath = self.tmpPath
			self.setImage(self.img1_img, self.tmpPath)
			dialog = gtk.MessageDialog(self,
                        		   gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                        		   gtk.MESSAGE_INFO, gtk.BUTTONS_OK,
                        		   _('Image saved in tmp file, DOUBLE-sized: \n\nYou can now use the updated raster image to\nrender an SVG, or save it permanently\nto a file via the Save Menu.'))
			dialog.run()
			dialog.destroy()
		except:
			self.file_error()
			return
	
	def sav_svg(self, evt):	
		fn = self.save_svg_dialog()
		if self.SVGdlg: self.SVGdlg.destroy()
		if not fn: return
		try:
			shutil.copyfile(self.spath, fn)
		except:
			self.file_save_err
			return
		self.file_saved(None, fn)
			
			
	def save_svg_dialog(self):
		self.SVGdlg = gtk.FileChooserDialog(_("Save the SVG image"), self, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK))
		self.SVGdlg.set_default_response(gtk.RESPONSE_OK)
		
		config.read(cfile)
		ldir = config.get("defaults", "lastsaved_svg")
		if (ldir == "blank"):
			self.SVGdlg.set_current_folder(os.getenv("HOME"))
		else:
			if os.path.exists(ldir):
				self.SVGdlg.set_current_folder(ldir)
			else:
				self.SVGdlg.set_current_folder(os.getenv("HOME"))
		
		self.SVGdlg.set_current_name("new.svg")
		self.SVGdlg.set_do_overwrite_confirmation(True)
		filter = gtk.FileFilter()
		filter.set_name(_("SVG"))
		filter.add_mime_type("image/svg+xml")
		filter.add_pattern("*.svg")
		self.SVGdlg.add_filter(filter)
		response = self.SVGdlg.run()
		if response == gtk.RESPONSE_OK:
			filename = self.SVGdlg.get_filename()
			ext = ".svg"
			if os.path.splitext(filename)[1] != ext: filename += ext
			
			config.set("defaults", "lastsaved_svg", os.path.dirname(filename))
			t1 = open(cfile, "w")
			config.write(t1)
			t1.close()			
			
			return filename
			
		else: 
			self.SVGdlg.destroy()
			return None				
		
	def do_save(self, ft):
		fn = self.save_ras_dialog(ft)
		if self.savedlg: self.savedlg.destroy()
		if not fn: return
		try:	
			if ft == "jpg":
				ft = "jpeg"
			if ft == "jpeg" or ft == "png":
				pixbuf = gtk.gdk.pixbuf_new_from_file (self.rpath)
				pixbuf.save(fn, ft)		
			else:
				self.file_save_err
				return
			self.file_saved(None, fn)
				
		except:
			self.file_save_err
	    
	
 	def save_ras_dialog(self, ftype):
		sStr = _('Save as %s') % ftype
		newName = _('new.%s') % ftype
		self.savedlg = gtk.FileChooserDialog(sStr, self, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK))
		self.savedlg.set_default_response(gtk.RESPONSE_OK)
		config.read(cfile)
		ldir = config.get("defaults", "lastsaved_png")
		if (ldir == "blank"):
			self.savedlg.set_current_folder(os.getenv("HOME"))
		else:
			if os.path.exists(ldir):
				self.savedlg.set_current_folder(ldir)
			else:
				self.savedlg.set_current_folder(os.getenv("HOME"))
				
		self.savedlg.set_current_name(newName)
		self.savedlg.set_do_overwrite_confirmation(True)
		filter = gtk.FileFilter()
		filter.set_name(ftype)
		if ftype == "png":
			filter.add_mime_type("image/png")
		elif ftype == "jpg":
			filter.add_mime_type("image/jpeg")
		
		self.savedlg.add_filter(filter)
		response = self.savedlg.run()
		if response == gtk.RESPONSE_OK:
			filename = self.savedlg.get_filename()
			ext = "." + ftype
			if os.path.splitext(filename)[1] != ext: filename += ext
			config.set("defaults", "lastsaved_png", os.path.dirname(filename))
			t1 = open(cfile, "w")
			config.write(t1)
			t1.close()			
			
			return filename
			
		else: 
			self.savedlg.destroy()
			return None		

 
 
	def help_about_cb(self, action):
		dialog = gtk.MessageDialog(self,
                        		   gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                        		   gtk.MESSAGE_INFO, gtk.BUTTONS_OK,
                        		   _("SVGpage\n\nSVG viewer and converter\nc2005 by Paul Sherman\nLicensed under GNU GPL"))
		dialog.run()
		dialog.destroy()
		
		
	def file_error(self, action=None):
		dialog = gtk.MessageDialog(self,
                        		   gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                        		   gtk.MESSAGE_ERROR, gtk.BUTTONS_OK,
                        		   _("\nCould not open the requested image"))
		dialog.run()
		dialog.destroy()
		
	def file_save_err(self, action=None):
		dialog = gtk.MessageDialog(self,
                        		   gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                        		   gtk.MESSAGE_ERROR, gtk.BUTTONS_OK,
                        		   _("\nCould not save the file"))
		dialog.run()
		dialog.destroy()		
		
	def file_saved(self, action=None, data=""):
		dialog = gtk.MessageDialog(self,
                        		   gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                        		   gtk.MESSAGE_INFO, gtk.BUTTONS_OK,
                        		   _('Success!\n\nThe new file was saved as: \n%s') % data)
		dialog.run()
		dialog.destroy()

	def file_create_err(self, action=None, data=""):
		dialog = gtk.MessageDialog(self,
                        		   gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                        		   gtk.MESSAGE_INFO, gtk.BUTTONS_OK,
                        		   _('\nProblem creating the file: \n%s') % data)
		dialog.run()
		dialog.destroy()


	def delete_event_cb(self, window=None, event=None):
		pth = os.getenv("HOME")
		try:
			os.remove(os.path.join(pth, "_tmp.svg"))
		except os.error:
			pass
		try:
			os.remove(os.path.join(pth, "_tmp.png"))
		except os.error:
			pass

        	gtk.main_quit()
	
	
	def set_display(self, evt):
		if evt.get_name() == _("PNG Full-Size"):
			DISPLAY(self, self.img1_img, self.rpath)
		else:
			DISPLAY(self, self.svg_img, self.spath)
				
		
		
class DISPLAY:
	def __init__(self,mother, img, pth):
		imName = os.path.basename(pth)
		try:
			pixbuf = gtk.gdk.pixbuf_new_from_file (pth)
		except:
			return
		(w,h)  = (pixbuf.get_width(),pixbuf.get_height())
		if w == 0:
			self.file_error()
			return
		maxW = gtk.gdk.screen_width() - 80
		maxH = gtk.gdk.screen_height() - 80
		if maxW > w: maxW = w + 40
		if maxH > h: maxH = h + 40
        	self.window = gtk.Dialog()
        	self.window.set_title(imName)
        	self.window.set_border_width(0)
        	self.window.set_size_request(maxW, maxH)
		self.window.set_transient_for(mother)
		self.window.set_resizable(False)

        	scrolled_window = gtk.ScrolledWindow()
		scrolled_window.connect("button-press-event", self.close_me)
        	scrolled_window.set_border_width(10)
        	scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        	self.window.vbox.pack_start(scrolled_window, True, True, 0)
        	scrolled_window.show()
	
		dImg = gtk.Image()
		dImg.set_from_pixbuf(pixbuf)
		dImg.show()	
        	scrolled_window.add_with_viewport(dImg)
        	self.window.show()		
		
	def close_me(self, evt=None, data=None):
		self.window.destroy()
		
		
class help_window(gtk.Window):


	def delete_event(self, e=None):
		self.destroy()


	def __init__(self, evt=None):
		gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)

		self.connect("destroy", self.delete_event)

        	self.set_title(_('SVG-page Help'))
		self.set_border_width(0)
		self.set_size_request(670, 450)
		self.set_position(gtk.WIN_POS_CENTER)
		
		me_img = gtk.Image()
		try:
			me = gtk.gdk.pixbuf_new_from_file (os.path.join(pth, "beer.svg"))
			me_img.set_from_pixbuf(me)
		except:
			pass

		box1 = gtk.VBox()
		self.add(box1)
		box1.show()

		box2 = gtk.VBox(spacing=4)
		box2.set_border_width(4)
		box1.pack_start(box2)
		box2.show()

		notebook = gtk.Notebook()
		notebook.set_tab_pos(gtk.POS_TOP)
		box2.pack_start(notebook)
		notebook.show()

		names = [_('About'), _('Autotrace'), _('General Use'), _('Viewing'), _('Rendering'), _('License'), _('When Finished...') ]
		msg = self.mlist()

		for i in range(len(names)):
			buffer = names[i]
			sw=gtk.ScrolledWindow()
			sw.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC)
			sw.set_shadow_type(gtk.SHADOW_NONE)
			sw.show()
			############################################################################
			# add widgets to each frame here
			if i == 0:
				label = gtk.Label(msg[i])
				sw.add_with_viewport(label)
			if i == 1:
				label = gtk.Label(msg[i])
				sw.add_with_viewport(label)
			if i == 2:
				label = gtk.Label(msg[i])
				sw.add_with_viewport(label)
			if i == 3:
				label = gtk.Label(msg[i])
				sw.add_with_viewport(label)
			if i == 4:
				label = gtk.Label(msg[i])
				sw.add_with_viewport(label)
			if i == 5:
				label = gtk.Label(msg[i])
				sw.add_with_viewport(label)
			if i == 6:
				#label = gtk.Label(msg[i])
				box_me = gtk.VBox()
				box_me.pack_start(me_img)
				#box_me.pack_start(label)
				me_img.show()
				box_me.show()
				sw.add_with_viewport(box_me)

			###########################################################################
			label.show()
			lbl = gtk.Label(buffer)
			lbl.set_padding(2, 2)
			notebook.append_page(sw, lbl)

		self.show()

	def mlist(self):
		msglist = [""]
		msg1 = _("""
SVG-page (c)2005-2006 by Paul Sherman
Distributed under the GNU GPL version 2\n
Source and binary packages are available, the binary compiled with cx-freeze into what 
I call a Python And Gtk Executable (PAGE). Dependency information is in the "INSTALL" 
file. If you are reading this you likely already know.

SVGpage is a pyGTK application to view and convert to and from vector (SVG) graphics. 
In addition to SVG files the application is able to open PNG, GIF, JPG (including Exif), 
BMP and XPM. It can save as SVG, PNG or JPG.

If you are looking for an SVG editor capable of creating fine, crisp curves and gradients, 
you've got the wrong program. For simple graphics SVGpage can convert to SVG and render 
something very close. For involved images, like pictures, you wind up with a PAINTERLY EFFECT. 
This effect can be very distinctive and attractive and is sought after by many. Sort of a good, 
single-click "GIMPressionist." So if that's what you're looking for, you've found it.

SVGpage can also take your SVG images and convert them to a PNG or a JPG. Even resize them. 
It uses Bilinear Interpolation and does an excellent job.

My webite should have the latest version of this software as well as several other programs 
I have made and distribute as Open Source. My personal website is located at:
http://www.pcbypaul.com

This program and updates will be posted with other graphics-related software at:
http://www.gimphelp.org
""")


		msg2 = _("""
First, for my fellow geeks...I compiled autotrace with the following flags: 
--disable-shared --without-pstoedit --without-magick

  HEADS UP: if you are looking for an SVG editor capable of creating fine, 
crisp curves and gradients, you've got the wrong program. SVGs are just XML 
files with a whole bunch of math in them. In an editor's environment the points 
and curves are known and plotted with precice equations. 
  IN CONTRAST to this, 
a utility like SVG-page/autotrace is taking an existing image and grabbing points 
and making controlled "best guess" estimates. What you end up with is, for simple 
graphics, something very close. For involved images, like pictures, you wind up 
with a PAINTERLY EFFECT. So if that's what you'd like, enjoy.

As explanations for some of the possible parameter tweaks, below is the MAN 
page for autotrace. One tip -- by far the most influential parameter is the 
DESPECKLE-LEVEL. Use a low number for something simple or text, a higher number 
for pictures and such... SVG-page makes playing with these values simple.

--------------------------------------------------------------------------------------

NAME

       autotrace - convert bit map image data to vector graphics



SYNOPSIS

       autotrace  [-background    hexvalue]  [-centerline] [-color-count  int]
       [-corner-always-threshold  angle]  [-corner-surround    int]  [-corner-
       threshold   angle] [-despeckle-level  int] [-despeckle-tightness  real]
       [-error-threshold  real] [-filter-iterations  int] [-help] [-input-for-
       mat   format] [-line-reversion-threshold  real] [-line-threshold  real]
       [-list-input-formats]  [-list-output-formats]  [-log]  [-output-file
       file]  [-output-format    format]  [-remove-adjacent-corners] [-report-
       progress] [-tangent-surround  int] [-version] inputfile


DESCRIPTION

       The autotrace program accepts bitmap graphics from the  file  inputfile
       specified  on  the command line, and as output produces a collection of
       splines approximating the original image, the converting the image from
       bitmap to vector format.  It behaves in a manner similar to the commer-
       cial software known as StreamLine  (from  Adobe  Systems,  Inc.).   The
       result  is  sent  to  standard output unless the -output-file option is
       active.



OPTIONS

       Options can begin with either -- or -.   Any  unambiguous  abbreviation
       can  be used for the option name.  Option names and values can be sepa-
       rated with either a space or equal sign (=).

       -background-color hexvalue
              Employ the color specified by the hexadecimal  code  hexcode  as
              the  background  that  should  be  ignored,  for  example FFFFFF
              (default: no background color).

       -centerline
              Trace an object's centerline (default: employ its outline).

       -color-count int
              Reduce the bitmap to using the number of colors specified by the
              unsigned  integer  int  (range:  1-256).  The default value of 0
              indicates that no color reduction is to be done.  Does not  work
              with grayscale images.

       -corner-always-threshold angle
              Consider  any  angle  at a pixel which falls below the specified
              angle (in degrees) as a corner, even if it is bordered by  other
              corner pixels (default: 60).

       -corner-surround int
              Consider  the  specified  number  of  pixels on either side of a
              point when determining if that point is a corner (default: 4).

       -corner-threshold angle
              Consider any pixel which forms an angle with its  predecessor(s)
              and  successor(s)  that  is smaller than the specified angle (in
              degrees) as a corner (default: 100).

              Subdivide fitted curves that are offset by a  number  of  pixels
              exceeding the specified real number (default: 2.0).

       -filter-iterations int
              Smooth  the curve the specified number of times prior to fitting
              (default: 4).

       -help  Print a help message and exit.

       -input-format format
              Employ the specified input format, where format is one of:

              BMP (Windows bitmap format)

              PBM (Portable BitMap format)

              PGM (Portable Graymap format)

              PNM (Portable Anymap format)

              PPM (Portable Pixmap format)

              TGA (Targa format)

              The supported input formats are determined when the  application
              is built and depend upon the availability of other software (the
              -list-input-formats command can be used to determine  which  are
              supported locally).

       -line-reversion-threshold real
              When  a  spline  is closer to a straight line than the specified
              real number weighted by the square of the curve length (default:
              .01),  maintain it as a straight line, even if it is a list with
              curves.

       -line-threshold real
              If a spline does not deviate from the straight line  defined  by
              its  endpoints by more than the specified number of pixels, then
              treat it as a straight line (default: 1).

       -list-input-formats
              Send a list of the supported input formats to stderr.

       -list-output-formats
              Send a list of the supported output formats to stderr.

       -log   Send a detailed progress report to the file inputfile.log.

       -output-file file
              Send the output to the specified file.

       -output-format format
              Employ the specified output format, where format is one of:

              ai(Adobe Illustrator)

              cgm(Computer Graphics Metafile)
              eps(Encapsulated )

              er(Elastic Reality Shape format)

              fig(xfig (1) 3.2)

              mif(FrameMaker MIF format)

              pdf(Portable Data Format)

              p2e(pstoedit (1) frontend)

              sk(Sketch)

              svg(Scalable Vector Graphics)

              swf(Shockwave Flash 3)

              The supported output formats are determined when the application
              is built and depend upon the availability of other software (the
              -list-output-formats command can be used to determine which  are
              supported locally).

       -remove-adjacent-corners
              Remove adjacent corners.

       -report-progress
              Report tracing status in real time.

       -tangent-surround int
              Consider  the  specified  number  of  points to either side of a
              point when computing the tangent at that point (default: 3).

       -version
              Print the version number of the program and exit.
""")

		msg3 = _("""
You can use SVG-page as a simple image viewer that can render SVGs, but 
most will be using it to convert back and forth from raster(png, jpeg, etc) to SVG.

It makes very nice quality rasters from SVGs. And as mentioned on the autotrace tab -- 
does OK with simple graphics to SVG, and makes what many find a desireable painterly 
effect from photos.
 
Some examples are included in the distribution folder along with SVG-page. Check out 
what is there and play with thew settings to get a feel. A couple things to note:

Starting with larger rasters will yield smoother curves and gradients when rendered 
as SVGs. Although this can vary with individual images, as well as the desired effect. 
To save time openning an external graphics editor all the time, there are "Save Half-Size" 
and "Save Double-Size" menu items which will alter the size of the displayed raster image 
(saved in a temporary file) -- so subsequent calls to "Render as SVG" will have a larger 
or smaller image to start with.

If you are NOT interested in making SVGs with a painterly effect, then the 
suggestions for alternate editor programs include:

Inkscape
http://www.inkscape.org/

Sodipodi
http://www.sodipodi.com/

Skencil
http://www.nongnu.org/skencil/

""")

		msg4 = _("""
SVG-page will open JPG (including exif), PNG, BMP, GIF, XPM and SVG images.
All but the SVG are viwed in the "raster Image" panel, while SVGs are 
displayed in -- you guessed it -- the "SVG Image" panel.

New images are loaded with the File -> Open menu.

Images are scaled into the appropriate viewing panel at a size no larger than 
200x200 pixels. If you wish to see the "real"image, that is, full-scale, then 
simple use the:

View -> Full-Size PNG or View -> Full-Size SVG

Any raster type will be opened in a separate window with the "Full-Size PNG" menu. 
If it is too big for the screen the opened window will have scrollbars to make things 
more convenient. Same goes for SVGs.

You can double or half the size of Raster images with:

Save -> Raster Half-Size or Save -> Raster Double-Size

The resized image is saved into a temporary file. Always as a PNG. This eases some 
possible later rendering actions, so the menu was titled PNG to reflect this fact, 
but you may also save it as a JPG. The listing is under:

Save -> save Raster -> Save As...

""")
		msg5 = _("""
Rendering is accomplished via autotrace. Simply click the:

"Render As SVG" button

And the currently displayed raster image will be converted to an SVG. There is a 
whole column of parameters you can play with to influence the output of the 
rendering. The most common general setings are already the defaults.

The most dramatic setting is on the top of the parameter list at the far right 
of the main window -- DESPECKLE LEVEL.

The Full-Size of the original raster image can affect the quality and "smoothness" 
of the resulting SVG. This is most noticeable with gradients and curves. For an example, 
try rendering "circles200.png" and also try "circles." Circles is a much larger image, 
and the resulting SVGs are quite different. The smaller image rendered looks very 
"broken up", while the larger image rendered looks very close to the original.

If tweaking the render parametersw is giving you an image that is too choppy -- 
try saving double-size and then render. Or save double-size a couple times.

Want to save the results of rendering as a PNG or a JPG?
Then "Convert to PNG", then "Save->save Raster->As a... whatever.
""")


		msg6 = _("""
		    GNU GENERAL PUBLIC LICENSE
		       Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

			    Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.)  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must show them these terms so they know their
rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

  The precise terms and conditions for copying, distribution and
modification follow.

		    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

			    NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

		     END OF TERMS AND CONDITIONS

	    How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    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


Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:

    Gnomovision version 69, Copyright (C) year name of author
    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  `Gnomovision' (which makes passes at compilers) written by James Hacker.

  <signature of Ty Coon>, 1 April 1989
  Ty Coon, President of Vice

This General Public License does not permit incorporating your program into
proprietary programs.  If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library.  If this is what you want to do, use the GNU Library General
Public License instead of this License.

		
""")	
		msg7 = _("""
			
""")		

		msglist.insert(0,msg1)
		msglist.remove("")
		msglist.insert(1,msg2)
		msglist.insert(2,msg3)
		msglist.insert(3,msg4)
		msglist.insert(4,msg5)
		msglist.insert(5,msg6)
		msglist.insert(6,msg7)
		return msglist




if __name__ == '__main__':
    w = Window()
    w.show_all()
    gtk.main()
