#!/usr/bin/python
# -*- coding: utf-8 -*-
### BEGIN LICENSE
# Copyright (C) 2010 Skyler Lehmkuhl
# This program is free software: you can redistribute it and/or modify it 
# under the terms of the GNU General Public License version 3, as published 
# by the Free Software Foundation.
# 
# This program is distributed in the hope that it will be useful, but 
# WITHOUT ANY WARRANTY; without even the implied warranties of 
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR 
# PURPOSE.  See the GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License along 
# with this program.  If not, see <http://www.gnu.org/licenses/>.
### END LICENSE

import sys
import os
import shutil
import tarfile
import tempfile
import numpy
import gtk
import threading
import locale
import gobject
import copy
import urllib
import time
import imp
import imghdr
from PIL import Image

# optional Launchpad integration
# this shouldn't crash if not found as it is simply used for bug reporting
try:
	import LaunchpadIntegration
	launchpad_available = True
except:
	launchpad_available = False

import gio
import gobject
import cairo
import pango
import math
import subprocess


# Check if we are working in the source tree or from the installed 
# package and mangle the python path accordingly
if os.path.dirname(sys.argv[0]) != ".":
	if sys.argv[0][0] == "/":
		fullPath = os.path.dirname(sys.argv[0])
	else:
		fullPath = os.getcwd() + "/" + os.path.dirname(sys.argv[0])
else:
	fullPath = os.getcwd()
sys.path.insert(0, os.path.dirname(fullPath))
sys.path.append("../")
from swift_swf import AboutSwiftSwfDialog, PreferencesSwiftSwfDialog, SaveDialog, OpenDialog, OpenscDialog, ImportDialog, colors, DocumentDialog, Html5dialogDialog, DataURI, images2gif, PublishDialog, mplayer
from swift_swf.swift_swfconfig import getdatapath


#define constants used in Windows vs. Unix platforms
def Is64Windows():
    return 'PROGRAMFILES(X86)' in os.environ

def GetProgramFiles32():
    if Is64Windows():
        return os.environ['PROGRAMFILES(X86)']
    else:
        return os.environ['PROGRAMFILES']
if os.sep=="\\":
	SWFC_PATH="'"+GetProgramFiles32()+"\\SWFTools\\swfc.exe'"
	GNASH_PATH="'"+GetProgramFiles32()+"\\Gnash 0.8.10dev\\sdl-gnash.exe'"
else:
	SWFC_PATH="swfc"
	GNASH_PATH="gnash"


def create_builtins(self):
        # __builtins__ is a dict for a module, but a module for__main__
        if isinstance(__builtins__, dict):
            builtins = __builtins__ #copy.copy(__builtins__)
            d = builtins
        else:
            #builtins = imp.new_module("__reinteract_builtin__")
            #builtins.__dict__.update(__builtins__.__dict__)
            builtins = __builtins__
            d = builtins.__dict__
            d['__import__'] = self.do_import

        d['help'] = _Helper()

        return builtins
def simplify_curve (curvelocs):
	global pmode
	print len(curvelocs),
	for i in range (0, len(curvelocs)/2, 2):
		del curvelocs[i]
	def angle(i,j,k):
		abx = curvelocs[j][0]-curvelocs[i][0]
		aby = curvelocs[j][1]-curvelocs[i][1]
		cbx = curvelocs[j][0]-curvelocs[k][0]
		cby = curvelocs[j][1]-curvelocs[k][1]
		# dot product  
		dot = (abx*cbx+aby*cby);
		# length square of both vectors
		abSqr = abx * abx + aby * aby+0.0;
		cbSqr = cbx * cbx + cby * cby+0.0;
		# square of cosine of the needed angle    
		cosSqr = dot * dot / abSqr / cbSqr;
		# this is a known trigonometric equality:
		# cos(alpha * 2) = [ cos(alpha) ]^2 * 2 - 1
		cos2 = 2.0 * cosSqr - 1;
		# Here's the only invocation of the heavy function.
		# It's a good idea to check explicitly if cos2 is within [-1 .. 1] range
		pi = 3.141592653589793;
		if -1<=cos2 and cos2<=1:
			alpha2 = math.acos(cos2);
		rslt = alpha2 / 2.0;
		rs = rslt * 180 / pi;
		# Now revolve the ambiguities.
		# 1. If dot product of two vectors is negative - the angle is definitely
		# above 90 degrees. Still we have no information regarding the sign of the angle.
		# NOTE: This ambiguity is the consequence of our method: calculating the cosine
		# of the double angle. This allows us to get rid of calling sqrt.
		if dot < 0:
			rs = 180 - rs;
		# 2. Determine the sign. For this we'll use the Determinant of two vectors.
		det = (abx * cby - aby * cby);
		if det < 0:
			rs = -rs;
		return rs
	bangs = []
	if pmode=="smooth" or pmode=="straight":
		for i in range(8):
			for j in range(len(curvelocs)-1, 1, -1):
				try:
					if math.sqrt((curvelocs[j][0]-curvelocs[j+1][0])*(curvelocs[j][0]-curvelocs[j+1][0])+(curvelocs[j][1]-curvelocs[j+1][1])*(curvelocs[j][1]-curvelocs[j+1][1]))<20:
						del curvelocs[j]
					elif math.fabs(180-angle(j-1,j,j+1))<40:
						del curvelocs[j]
					elif math.fabs(180-angle(j-1,j,j+1))/math.fabs(180-angle(j-1,j+1,j+3))<0.3 and math.fabs(180-angle(j+1,j+2,j+3))/math.fabs(180-angle(j-1,j+1,j+3))<0.5:
						del curvelocs[j]
						del curvelocs[j+2]
				except Exception as e:
					pass
	print "  ", len(curvelocs)
	print
	return curvelocs

def rotate_list(List, x, y, rotate):
	rotate = degrees2radians(rotate)
	for i in range(len(List)/2):
		List[i*2] = math.cos(rotate)*(List[i*2]-x)-math.sin(rotate)*(List[i*2+1]-y)+x
		List[i*2+1]=math.sin(rotate)*(List[i*2]-x)+math.cos(rotate)*(List[i*2+1]-y)+y
	return List
def button_clicked(widget, event):
	#This function tests whether the mouse was
	#double-clicked or single-clicked
	global clicked
	global middleclick
	global first
	global startmouse
	global currentframe
	global currentfile
	global currentselect
	global undostack
	global redostack
	global pixmap
	global colormap
	global doubleclick
	global selectdepth
	global level
	global coordsco
	global scale
	try:
		dumvar=coords
	except:
		coords=[sys.maxint, sys.maxint, sys.maxint, sys.maxint, sys.maxint, sys.maxint, sys.maxint, sys.maxint, sys.maxint, sys.maxint, sys.maxint, sys.maxint, sys.maxint, sys.maxint, sys.maxint, sys.maxint]
	if event.button==1:
		if currentframe[level] in objects[currentselect[level]].frames[0]:
			clicked=True
			first=True
			startmouse = widget.get_toplevel().builder.get_object("drawingarea1").get_pointer()
			undostack.append(copy.deepcopy(currentfile))
			if mode=="c":
				cc=(startmouse[0], startmouse[1])
				currentcurve.append(cc)
				expostagevent(widget.get_toplevel().builder.get_object("drawingarea1"), "exposevent")
			elif mode==" " or mode=="s":
				checktest = False
				#print mode
				scale=False
				if not currentselect[level+1]==None and mode=="s":
					for i in range(8):
						if math.fabs(startmouse[0]-coords[i*2])<5 and math.fabs(startmouse[1]-coords[i*2+1])<5:
							scale=True
							snum = i
				if not scale:
					def get_pixel_color(i_x, i_y):
						import gtk # python-gtk2
						o_gdk_pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, 1, 1)
						o_gdk_pixbuf.get_from_drawable(pixmap, colormap, i_x, i_y, 0, 0, 1, 1)
						return tuple(o_gdk_pixbuf.get_pixels_array().tolist()[0][0])
					pixcol = get_pixel_color(startmouse[0], startmouse[1])
					rgbpixcol = ("#"+str(pixcol[0]).zfill(2)+str(pixcol[1]).zfill(2)+str(pixcol[2]).zfill(2))
					print rgbpixcol
					print selectid
					currentselect[level+1] = selectors[selectid.index(rgbpixcol)]
					#print selectors, selectid.index(rgbpixcol)
					if event.type == gtk.gdk._2BUTTON_PRESS:
						if not currentselect[level+1]==None:
							if currentselect[level+1] in currentfile["objects"] and (currentfile["objects"][currentselect[level+1]].	type == "button" or currentfile["objects"][currentselect[level+1]].type == "movieclip"):
								textview = widget.get_toplevel().builder.get_object("textview2")
								ftextbuf = textview.get_buffer()
								try:
									if textview.get_editable()==True:
										objects[currentselect[level]].actions[objects[currentselect[level]].frames[0].index(currentframe[level])]= str(ftextbuf.get_text(ftextbuf.get_start_iter(), ftextbuf.get_end_iter()))
								except:
									pass
								level+=1
								if len(currentselect)-1<level:
									currentselect.append(None)
								else:
									try:
										currentselect[level+1]=None
									except:
										currentselect.append(None)
								currentframe.append(1)
								try:
									ftextbuf.set_text(objects[currentselect[level]].actions[objects[currentselect[level]].frames[0].index(currentframe[level])])
									textview.set_editable(True)
									textview.set_cursor_visible(True)
								except:
									ftextbuf.set_text("Actions cannot be applied to this frame.")
									textview.set_editable(False)
									textview.set_cursor_visible(False)
						else:
							if level>0:
								textview = widget.get_toplevel().builder.get_object("textview2")
								ftextbuf = textview.get_buffer()
								try:
									if textview.get_editable()==True:
										objects[currentselect[level]].actions[objects[currentselect[level]].frames[0].index(currentframe[level])]= str(ftextbuf.get_text(ftextbuf.get_start_iter(), ftextbuf.get_end_iter()))
								except:
									pass
								level-=1
								currentframe[level+1]=0
								try:
									ftextbuf.set_text(objects[currentselect[level]].actions[objects[currentselect[level]].frames[0].index(currentframe[level])])
									textview.set_editable(True)
									textview.set_cursor_visible(True)
								except:
									ftextbuf.set_text("Actions cannot be applied to this frame.")
									textview.set_editable(False)
									textview.set_cursor_visible(False)
				expostagevent(widget.get_toplevel().builder.get_object("drawingarea1"), "exposevent")
				widget.get_toplevel().builder.get_object("drawingarea1").grab_focus()
		if event.type == gtk.gdk._2BUTTON_PRESS:
			doubleclick = True
		else:
			doubleclick = False
	elif event.button==2:
		middleclick = True
		startmouse = widget.get_toplevel().builder.get_object("drawingarea1").get_pointer()
def mouse_scrolled(widget, event):
	global view_scale
	if event.direction == gtk.gdk.SCROLL_UP and event.state & gtk.gdk.SHIFT_MASK:
		view_scale = view_scale*2
		expostagevent(widget.get_toplevel().builder.get_object("drawingarea1"), "expose-event")
	elif event.direction == gtk.gdk.SCROLL_DOWN and event.state & gtk.gdk.SHIFT_MASK:
		view_scale = view_scale/2
		expostagevent(widget.get_toplevel().builder.get_object("drawingarea1"), "expose-event")
def alert(text, critical=False):
	#Launches an alert window with a given text.
	#If critical is True, closing the alert terminates SWIFT.
	def abutton_press_event(widget, event):
		#Close when "Ok" is pressed
		alert.destroy()
	def on_destroy(event):
		if critical==True:
			#if this is a critical alert, such as when another instrance of SWIFT is already running
			gtk.main_quit()
	alert = gtk.Window(type=gtk.WINDOW_TOPLEVEL)			# make a new window for the alert
	alert.set_position(gtk.WIN_POS_CENTER)					# put it in the center of the screen
	alert.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DIALOG)	# tell the WM that it is a dialog
	alert.set_destroy_with_parent(True)						# if someone closes SWIFT, we want the alert to close too
	alert.set_modal(True)									# alert should block input to SWIFT until acknowledged
	alert.set_title("Alert")								# call it "Alert"
	alert.set_size_request(250, 100)						# make it 250x100
	avbox = vbox = gtk.VBox(False, 0)						# create a vertical box container
	#atextview = gtk.TextView()
	#abuffer = atextview.get_buffer()
	#atextview.set_justification(gtk.JUSTIFY_CENTER)
	#atextview.set_wrap_mode(gtk.WRAP_WORD)
	#abuffer.set_text(text)
	alert.add(avbox)										# add said container to the alert
	alabel=gtk.Label(text)									# make a label to hold the text
	alabel.set_size_request(240,-1)							# make it slightly narrower than the parent window
	alabel.set_line_wrap(True)								# we want the text to word wrap
	alabel.set_justify(gtk.JUSTIFY_CENTER)					# center the text
	avbox.pack_start(alabel, False, True, 0)				# put it at the start of the vbox
	#atextview.show()
	alabel.show()											# make it visible
	abutton = gtk.Button("OK")								# new button with text "OK"
	abutton.set_use_stock(True)								# it is a stock button provided by GTK
	abutton.set_size_request(50, -1)						# we don't want it as wide as the whole alert
	abutton.set_events(gtk.gdk.ALL_EVENTS_MASK);			# capture clicks, keyboard, anything
	abutton.connect("button_press_event", abutton_press_event)	# but only listen to the clicks
	alert.connect("destroy", on_destroy)					# close alert when alert is closed
	abutton.show()											# make button visible
	ahbox = gtk.HBox(False, 10)								# make a new hbox
	ahbox.pack_start(abutton, True, False, 0)				# put the button in it, but don't make it expand
	avbox.pack_start(ahbox, True, False, 0)					# put the hbox in the vbox
	ahbox.show()											# make it visible
	avbox.show()											# make the vbox visible
	alert.show()											# make the alert itself visible

def alert_list(title, list, select=0):
	#Launches an alert window with a given text.
	global retval
	def abutton_press_event(widget, event, radlist):
		#Close when "Ok" is pressed
		global retval
		for i in radlist:
			if i.get_active():
				retval = radlist.index(i)
		alert.destroy()
	alert = gtk.Dialog()									# make a new window for the alert
	alert.set_position(gtk.WIN_POS_CENTER)					# put it in the center of the screen
	alert.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DIALOG)	# tell the WM that it is a dialog
	alert.set_destroy_with_parent(True)						# if someone closes SWIFT, we want the alert to close too
	alert.set_modal(True)									# alert should block input to SWIFT until acknowledged
	alert.set_title(title)									# call it what we want to
	#alert.set_size_request(250, 100)						# make it 250x100
	#avbox = vbox = gtk.VBox(False, 0)						# create a vertical box container
	#alert.add(avbox)										# add said container to the alert
	radio = None
	radlist = []
	for i in list:
		radiobutton = gtk.RadioButton(radio, str(i))
		radio = radiobutton
		radlist.append(radiobutton)
		alert.vbox.pack_start(radiobutton, True, False, 0)
		radiobutton.show()
	radlist[select].set_active(True)
	
	abutton = gtk.Button("OK")								# new button with text "OK"
	abutton.set_use_stock(True)								# it is a stock button provided by GTK
	abutton.set_size_request(50, -1)						# we don't want it as wide as the whole alert
	abutton.set_events(gtk.gdk.ALL_EVENTS_MASK);			# capture clicks, keyboard, anything
	abutton.connect("button_press_event", abutton_press_event, radlist)	# but only listen to the clicks
	abutton.show()											# make button visible
	ahbox = gtk.HBox(False, 10)								# make a new hbox
	ahbox.pack_start(abutton, True, False, 0)				# put the button in it, but don't make it expand
	alert.vbox.pack_start(ahbox, True, False, 0)					# put the hbox in the vbox
	ahbox.show()											# make it visible
	#avbox.show()											# make the vbox visible
	alert.show()											# make the alert itself visible
	result = alert.run()
	return retval

def vid_options(val):
	def button_press_event(widget, event):
		#Close when "Ok" is pressed
		dialog.destroy()
	opt = gtk.combo_box_new_text()
	opt.append_text("mjpeg  - Motion JPEG")
	opt.append_text("ljpeg  - lossless JPEG")
	opt.append_text("jpegls  - JPEG LS")
	opt.append_text("targa  - Targa image")
	opt.append_text("gif  - GIF image")
	opt.append_text("bmp  - BMP image")
	opt.append_text("png  - PNG image")
	opt.append_text("h261  - H.261")
	opt.append_text("h263  - H.263")
	opt.append_text("h263p  - H.263+")
	opt.append_text("mpeg4  - ISO standard MPEG-4 (DivX, Xvid compatible)")
	opt.append_text("msmpeg4  - pre-standard MPEG-4 variant by MS, v3 (AKA DivX3)")
	opt.append_text("msmpeg4v2  - pre-standard MPEG-4 by MS, v2 (used in old ASF files)")
	opt.append_text("wmv1  - Windows Media Video, version 1 (AKA WMV7)")
	opt.append_text("wmv2  - Windows Media Video, version 2 (AKA WMV8)")
	opt.append_text("rv10  - RealVideo 1.0")
	opt.append_text("rv20  - RealVideo 2.0")
	opt.append_text("mpeg1video  - MPEG-1 video")
	opt.append_text("mpeg2video  - MPEG-2 video")
	opt.append_text("huffyuv  - lossless compression")
	opt.append_text("ffvhuff  - FFmpeg modified huffyuv lossless")
	opt.append_text("asv1  - ASUS Video v1")
	opt.append_text("asv2  - ASUS Video v2")
	opt.append_text("ffv1  - FFmpeg's lossless video codec")
	opt.append_text("svq1  - Sorenson video 1")
	opt.append_text("flv  - Sorenson H.263 used in Flash Video")
	opt.append_text("flashsv  - Flash Screen Video")
	opt.append_text("dvvideo  - Sony Digital Video")
	opt.append_text("snow  - FFmpeg's experimental wavelet-based codec")
	opt.append_text("zmbv  - Zip Motion Blocks Video")
	opt.append_text("dnxhd  - AVID DNxHD")
	opt.set_active(val)
	
	dialog = gtk.Dialog()
	vbox = dialog.vbox
	label1 = gtk.Label("Select codec to use:")
	hbox1 = gtk.HBox()
	hbox1.pack_start(label1, True, True, 0)
	hbox1.pack_end(opt, True, True, 0)
	vbox.pack_start(hbox1, True, False, 0)
	label1.show()
	opt.show()
	hbox1.show()
	
	hresadjust = gtk.Adjustment(800, 48, 1024, 4)
	hspin = gtk.SpinButton(hresadjust, 0.5, 0)
	hspin.set_numeric(True)
	hspin.set_snap_to_ticks(True)
	hspin.set_update_policy(gtk.UPDATE_IF_VALID)
	label2 = gtk.Label("Horizontal resolution:")
	vresadjust = gtk.Adjustment(600, 48, 1024, 4)
	vspin = gtk.SpinButton(vresadjust, 0.5, 0)
	vspin.set_numeric(True)
	vspin.set_snap_to_ticks(True)
	vspin.set_update_policy(gtk.UPDATE_IF_VALID)
	label3 = gtk.Label("Vertical resolution:")
	hbox2 = gtk.HBox()
	hbox2.pack_start(label2, True, True, 0)
	hbox2.pack_start(hspin, True, True, 0)
	hbox2.pack_end(vspin, True, True, 0)
	hbox2.pack_end(label3, True, True, 0)
	label2.show()
	label3.show()
	hspin.show()
	vspin.show()
	hbox2.show()
	bitrateadjust = gtk.Adjustment(50, 1, 100, 1)
	bitratespin = gtk.SpinButton(bitrateadjust, 0.5, 0)
	bitratespin.set_numeric(True)
	bitratespin.set_snap_to_ticks(True)
	bitratespin.set_update_policy(gtk.UPDATE_IF_VALID)
	label4 = gtk.Label("Target bitrate multiplier:")
	hbox3 = gtk.HBox()
	hbox3.pack_start(label4, True, True, 0)
	hbox4 = gtk.HBox()
	button = gtk.Button("OK")								# new button with text "OK"
	button.set_use_stock(True)								# it is a stock button provided by GTK
	button.set_size_request(50, -1)						# we don't want it as wide as the whole alert
	button.set_events(gtk.gdk.ALL_EVENTS_MASK);			# capture clicks, keyboard, anything
	button.connect("button_press_event", button_press_event)	# but only listen to the clicks
	hbox4.pack_start(button, True, False, 0)
	hbox3.pack_end(bitratespin, True, True, 0)
	vbox.pack_end(hbox4, True, False, 0)
	vbox.pack_end(hbox2, True, False, 0)
	vbox.pack_end(hbox3, True, False, 0)
	label4.show()
	bitratespin.show()
	hbox3.show()
	button.show()
	hbox4.show()
	dialog.show()
	dialog.run()
	optimal_bitrate = bitratespin.get_value_as_int() * 25 * hspin.get_value_as_int() * vspin.get_value_as_int() / 256
	return [opt.get_active(), hspin.get_value_as_int(), vspin.get_value_as_int(), optimal_bitrate]
	


def get_pixel_colour(i_x, i_y):
	o_gdk_pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, 1, 1)
	o_gdk_pixbuf.get_from_drawable(gtk.gdk.get_default_root_window(), gtk.gdk.colormap_get_system(), i_x, i_y, 0, 0, 1, 1)
	return tuple(o_gdk_pixbuf.get_pixels_array().tolist()[0][0])

def prePend(s, i):
	#Obvious
	s.reverse()
	s.append(i)
	s.reverse()
	return
def ave(x, y, fac):
	#Weighted average. 
	#fac is the weight - 0.5 gives a standard average
	return y - fac*(y-x)
def facx(a, b, c):
	#Solves ave for fac
	return (1.0*c-1.0*a)/(1.0*b-1.0*a)
def hex2rgb(hex):
	a=hex[1]
	b=hex[2]
	c=hex[3]
	if len(hex)==7:
		d=hex[4]
		e=hex[5]
		f=hex[6]
		ab = a+b
		cd = c+d
		ef = e+f
		return (int(ab, 16)/256.0, int(cd, 16)/256.0, int(ef, 16)/256.0)
	elif len(hex)==9:
		d=hex[4]
		e=hex[5]
		f=hex[6]
		g=hex[7]
		h=hex[8]
		ab = a+b
		cd = c+d
		ef = e+f
		gh = g+h
		return (int(ab, 16)/256.0, int(cd, 16)/256.0, int(ef, 16)/256.0, int(gh, 16)/256.0)
		
	else:
		return (int(a, 16)/16.0, int(b, 16)/16.0, int(c, 16)/16.0)
def rgb2hex(r, g, b, a=1):
	r=hex(int(r*255)).split("x")[1].zfill(2)
	g=hex(int(g*255)).split("x")[1].zfill(2)
	b=hex(int(b*255)).split("x")[1].zfill(2)
	a=hex(int(a*255)).split("x")[1].zfill(2)
	return "#"+r+g+b+a
def ellipse2xml(i):
	global currentfile
	e = currentfile["objects"][i]
	strng = ""
	strng = "M "+str(e.width/2)+",0 C "+str(e.width*4/5)+",0 "+str(e.width)+","+str(e.height/5)+" "+str(e.width)+","+str(e.height/2)+" C "+str(e.width)+","+str(e.height*4/5)+" "+str(e.width*4/5)+","+str(e.height)+" "+str(e.width/2)+","+str(e.height)+" C "+str(e.width/5)+","+str(e.height)+" 0,"+str(e.height*4/5)+" 0,"+str(e.height/2)+" C 0,"+str(e.height/5)+" "+str(e.width/5)+",0 "+str(e.width/2)+",0"
	return strng
def shape2xml(i):
	global currentfile
	s = currentfile["objects"][i]
	strng = ""
	for i in s.shapedata:
		if i[0]=="M":
			strng = strng + " M "+str(i[1])+","+str(i[2])
		elif i[0]=="L":
			strng = strng + " L "+str(i[1])+","+str(i[2])
		elif i[0]=="C":
			strng = strng + " C "+str(i[1])+","+str(i[2])+" "+str(i[3])+","+str(i[4])+" "+str(i[5])+","+str(i[6])
	return strng
def curve2xml(i):
	global currentfile
	c = currentfile["objects"][i]
	strng = "M "+str(c["points"][0][0])+","+str(c["points"][0][1])
	for j in range (0, len(c["points"])/3):
		strng = strng+" C "+str(c["points"][j*3+1][0])+","+str(c["points"][j*3+1][1])+" "+str(c["points"][j*3+2][0])+","+str(c["points"][j*3+1][1])+" "+str(c["points"][j*3+3][0])+","+str(c["points"][j*3+3][1])
	return strng

def gradient(gpath):
	global currentfile
	if not type(gpath)==type(""):
		print "Error: wrong input type"
		return False;
	try:
		grad = currentfile["colors"]["gradients"][gpath]
		return grad
	except:
		print "Error: Odd exception, no idea what happened!"
		return False;
def texture(tpath, w, h):
	global currentfile
	image = currentfile["colors"]["images"][tpath]
	surface = cairo.ImageSurface.create_from_png(image)
	pattern = cairo.SurfacePattern(surface)
	matrix = cairo.Matrix(xx=surface.get_width()*1.0/w, yy=surface.get_height()*1.0/h)
	pattern.set_matrix(matrix)
	return pattern
def degrees2radians(rotate):
	return math.pi*rotate/180
#Drawing objects
#TODO:Draw outlines!
def drawLine(gc, drawable, x1, y1, x2, y2, color=None):
	drawable.draw_line(gc, x1+500, y1+500, x2+500, y2+500)

def drawBox(gc, drawable, x, y, width, height, filled=1, rotation=0, xscale=1.0, yscale=1.0):
	x0 = (0-width/2)*xscale
	y0 = (0-height/2)*yscale
	x1 = int((0+width/2)*xscale)
	y1 = int((0+height/2)*yscale)
	r = rotation
	x = 500+int(x)
	y = 500+int(y)
	xa = int(math.cos(r)*x0-math.sin(r)*y0)
	ya = int(math.cos(r)*y0+math.sin(r)*x0)
	xb = int(math.cos(r)*x1-math.sin(r)*y0)
	yb = int(math.cos(r)*y0+math.sin(r)*x1)
	xc = int(math.cos(r)*x1-math.sin(r)*y1)
	yc = int(math.cos(r)*y1+math.sin(r)*x1)
	xd = int(math.cos(r)*x0-math.sin(r)*y1)
	yd = int(math.cos(r)*y1+math.sin(r)*x0)
	drawable.draw_polygon(gc, filled, [(xa+x+x1, ya+y+y1), (xb+x+x1, yb+y+y1), (xc+x+x1, yc+y+y1), (xd+x+x1, yd+y+y1)])

def drawcrBox(cr, x, y, width, height, filled=1, fill=[0, 0, 0], rotation=0, stroke=[0, 0, 0, 0], inactive=False, xscale=1.0, yscale=1.0):
	global currentfile
	cr.save()
	cr.translate(x, y)
	cr.rotate(rotation*math.pi/180)
	cr.scale(xscale, yscale)
	cr.rectangle(0, 0, width, height)
	if type(fill)==type(()) or type(fill)==type([]):
		cr.set_source_rgb(fill[0], fill[1], fill[2])
	elif fill.startswith("#"):
		rgbfill = hex2rgb(fill)
		cr.set_source_rgb(rgbfill[0], rgbfill[1], rgbfill[2])
	else:
		fill = currentfile["colors"]["textures"][fill]
		if fill["type"]=="color":
			cr.set_source_rgb(fill["fill"][0], fill["fill"][1], fill["fill"][2])
		elif fill["type"]=="gradient":
			#make this use the gradient
			grad = gradient(fill["fill"])
			g = cairo.LinearGradient(x, y, x+width, y+height)
			for i in range(len(grad)):
				g.add_color_stop_rgba(grad[i][0], grad[i][1], grad[i][2], grad[i][3], grad[i][4])
			cr.set_source(g)
		else:
			#make it use a texture
			#tex = texture(fill["fill"], width, height)
			#cr.set_source(tex)
			#cr.fill_preserve()
			
			image = currentfile["colors"]["images"][fill["fill"]]
			surface = cairo.ImageSurface.create_from_png(image)
			pat = cairo.SurfacePattern(surface)
			#matrix = cairo.Matrix(x0=-x, y0=-y)
			#pat.set_matrix(matrix)
			cr.set_source(pat)
	if filled==1:
		cr.fill_preserve()
		if inactive:
			cr.set_source_rgba(0.5, 0.5, 0.5, 0.5)
			cr.fill_preserve()
		if len(stroke)==2: stroke[3]=1;
		cr.set_source_rgba(stroke[0], stroke[1], stroke[2], stroke[3])
	cr.stroke()
	cr.restore()
def drawEllipse(gc, drawable, x, y, width, height, filled=1, rotation=0, xscale=1.0, yscale=1.0):
	#drawable.draw_arc(gc, filled, x, y, width, height, 0, 23040)
	#TODO:Make ellipses use CUBIC Beziér Curves!!!
	x = x+500
	y = y+500
	res = 50
	points = []
	r = rotation
	#for i in range(0, res):
	#	j = math.pi*i*2/res
	#	points.append((int(math.cos(r)*math.sin(j)*width/2+x+width/2-math.sin(r)*math.cos(j)*height/2), int(math.cos(r)*math.cos(j)*height/2+y+height/2+math.sin(r)*math.sin(j)*width/2)))
	#drawable.draw_polygon(gc, filled, points)
	drawCurve(gc, drawable, [[x+width*xscale/2, y], [x+width*xscale, y], [x+width*xscale, y+height*yscale/2], [x+width*xscale, y+height*yscale], [x+width*xscale/2, y+height*yscale], [x, y+height*yscale], [x, y+height*yscale/2], [x, y], [x+width/2, y]], True, xscale, yscale) 
def drawcrEllipse(cr, x, y, w, h, fill=[0, 0, 0], rotation=0, stroke=[0,0,0,0], inactive=False, xscale=1.0, yscale=1.0):
	global currentfile
	global currentframe
	cr.save()
	cr.translate(x, y)
	cr.rotate(rotation*math.pi/180)
	cr.scale(xscale, yscale)
	if type(fill)==type(()) or type(fill)==type([]):
		cr.set_source_rgb(fill[0], fill[1], fill[2])
	elif fill.startswith("#"):
		rgbfill = hex2rgb(fill)
		cr.set_source_rgb(rgbfill[0], rgbfill[1], rgbfill[2])
	else:
		fill = currentfile["colors"]["textures"][fill]
		if fill["type"]=="color":
			cr.set_source_rgb(fill["fill"][0], fill["fill"][1], fill["fill"][2])
		elif fill["type"]=="gradient":
			#make this use the gradient
			grad = gradient(fill["fill"])
			g = cairo.LinearGradient(x, y, x+width, y+height)
			for i in range(len(grad)):
				g.add_color_stop_rgba(grad[i][0], grad[i][1], grad[i][2], grad[i][3], grad[i][4])
			cr.set_source(g)
		else:
			#make it use a texture
			#tex = texture(fill["fill"], width, height)
			#cr.set_source(tex)
			#cr.fill_preserve()
			
			image = currentfile["colors"]["images"][fill["fill"]]
			surface = cairo.ImageSurface.create_from_png(image)
			pat = cairo.SurfacePattern(surface)
			matrix = cairo.Matrix(x0=-x, y0=-y)
			pat.set_matrix(matrix)
			cr.set_source(pat)
	cr.save()
	drawcrCurve(cr, [[w/2, 0], [4*w/5, 0], [w, h/5], [w, h/2], [w, 4*h/5], [4*w/5, h], [w/2, h], [w/5, h], [0, 4*h/5], [0, h/2], [0, h/5], [w/5, 0], [w/2, 0]], True)
	cr.restore()
	if inactive:
		cr.set_source_rgba(0.5,0.5,0.5,0.5)
		cr.fill()
	else:
		cr.fill()
	cr.restore()
def drawCurve(gc, drawable, points, filled=False, xscale=1.0, yscale=1.0, precision=20):
	npoints = []
	s=[]
	r = range(len(points)-2)
	for i in r:
		if i/2==int(math.ceil(i/2.0)):
			s.append(i)					#Very opaque function to fill s with all the even numbers in r
	for i in s:
		for j in range(precision):
			k=1.0*(precision-j)
			x=int(ave(ave(points[i][0], points[i+1][0], k/precision), ave(points[i+1][0], points[i+2][0], k/precision), k/precision))
			y=int(ave(ave(points[i][1], points[i+1][1], k/precision), ave(points[i+1][1], points[i+2][1], k/precision), k/precision))
			npoints.append((x+500, y+500))
	if filled==False:
		for i in range(len(npoints)-1):
			drawLine(gc, drawable, npoints[i][0], npoints[i][1], npoints[i+1][0], npoints[i+1][1])
	else:
		drawable.draw_polygon(gc, 1, npoints)
def drawcrCurve(cr, points, filled=False, linewidth=1):
	cr.move_to(points[0][0], points[0][1])
	cr.set_line_width(linewidth)
	cr.set_line_cap(cairo.LINE_CAP_ROUND)
	for i in range(3, len(points), 3):
		cr.curve_to(points[i-2][0], points[i-2][1], points[i-1][0], points[i-1][1], points[i][0], points[i][1])
	if filled==True:
		cr.fill_preserve()
	cr.stroke_preserve()
def drawcrShape(cr, shapedata, x, y, rotate, filled=True, inactive=False, xscale=1.0, yscale=1.0):
	cr.save()
	cr.translate(x, y)
	cr.rotate(rotate*math.pi/180)
	cr.scale(xscale, yscale)
	rotate = degrees2radians(rotate)
	for i in shapedata:
		if i[0]=="M":
			cr.move_to(i[1], i[2])
		elif i[0]=="L":
			cr.line_to(i[1], i[2])
		elif i[0]=="C":
			cr.curve_to(i[1], i[2], i[3], i[4], i[5], i[6])
	if filled:
		if inactive:
			cr.fill_preserve()
			cr.set_source_rgba(0.5, 0.5, 0.5, 0.5)
			cr.fill()
		else:
			cr.fill()
	else:
		cr.stroke()
	cr.restore()
def drawShape(gc, drawable, shapedata, ix, iy, rotate, filled, xscale=1.0, yscale=1.0, precision=20):
	rotate = degrees2radians(rotate)
	npoints = []
	for i in shapedata:
		if i[0]=="C":
			for j in range(precision):
				k=1.0*(precision-j)
				x=int(ave(ave(i[1]*xscale, i[3]*xscale, k/precision), ave(i[3]*xscale, i[5]*xscale, k/precision), k/precision))
				y=int(ave(ave(i[2]*yscale, i[4]*yscale, k/precision), ave(i[4]*yscale, i[6]*yscale, k/precision), k/precision))
				npoints.append((int(math.cos(rotate)*(x)-math.sin(rotate)*(y)+ix)+500, int(math.sin(rotate)*(x)+math.cos(rotate)*(y)+iy)+500))
		elif i[0]=="L":
			npoints.append((int(math.cos(rotate)*(i[1]*xscale)-math.sin(rotate)*(i[2]*yscale)+ix)+500, int(math.sin(rotate)*(i[1]*xscale)+math.cos(rotate)*(i[2]*yscale)+iy)+500))
		elif i[0]=="M":
			if filled==False:
				for i in range(len(npoints)-1):
					drawLine(gc, drawable, npoints[i][0], npoints[i][1], npoints[i+1][0], npoints[i+1][1])
			else:
				drawable.draw_polygon(gc, 1, npoints)
			npoints = []
	if filled==False:
		for i in range(len(npoints)-1):
			drawLine(gc, drawable, npoints[i][0], npoints[i][1], npoints[i+1][0], npoints[i+1][1])
	else:
		drawable.draw_polygon(gc, 1, npoints)
def on_key_press(widget, event):
	keyname = gtk.gdk.keyval_name(event.keyval)
	if keyname=="A":
		print "A was pressed!"
	elif keyname=="B":
		print "B was pressed!"
def expostagevent(stage, event):
	global drawitems
	global clicked
	global startmouse
	global biter
	global mode
	global currentcurve
	global currentselect	
	global currentfile
	global undostack
	global redostack
	global first
	global fx
	global fy
	global selectid
	global selectors
	global level
	global objects
	global coords
	global scale
	global brushlocs
	global tnum
	global source_id
	global view_scale
	global lastinput
	tnum = tnum+1
	x,y,w,h = stage.allocation
	surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, w,h)
	cr = cairo.Context(surface)
	cra = stage.window.cairo_create()
	cr.set_source_rgb(0.5, 0.5, 0.5)
	w = stage.allocation.width
	h = stage.allocation.height
	cr.set_line_width(2)
	cr.save()
	cr.translate(500, 500)
	cr.scale(view_scale, view_scale)
	ccol = currentcolor
	biggest = 0
	if not (clicked==True and mode=="p"):
		cr.paint()
		objects["root"].draw(cr, w, h, stage.get_toplevel().builder.get_object("drawingarea2"))
	if currentframe[level] in objects[currentselect[level]].frames[0]:
		if not currentselect[level+1] == None:
			if not currentfile["objects"][currentselect[level]].type=="button":
				opts = (cr, objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["x"]+objects[objects[currentselect[level+1]].parent].x-1, objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["y"]+objects[objects[currentselect[level+1]].parent].y-1, currentfile["objects"][currentselect[level+1]].width+2, currentfile["objects"][currentselect[level+1]].height+2, 0, [0.0,0.0, 1.0], objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["rotate"]+objects[objects[currentselect[level+1]].parent].rotate, [0,0,0,0], False, objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["xscale"], objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["yscale"])
				#drawcrBox(cr, objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["x"]+objects[objects[currentselect[level+1]].parent].x-1, objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["y"]+objects[objects[currentselect[level+1]].parent].y-1, currentfile["objects"][currentselect[level+1]].width+2, currentfile["objects"][currentselect[level+1]].height+2, objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["rotate"]+objects[objects[currentselect[level+1]].parent].rotate, [0.0,0.0, 1.0])
				drawcrBox(opts[0], opts[1], opts[2], opts[3], opts[4], opts[5], opts[6], opts[7], opts[8], opts[9], opts[10], opts[11])
				corners = [0, 0, currentfile["objects"][currentselect[level+1]].width+2, currentfile["objects"][currentselect[level+1]].height+2]
			#else:
				#implement drawcrBox(cr, etc.)
				#gc = gtk.gdk.GC(pixmap, colormap.alloc_color(selectid[selectors.index(j)], True, True), colormap.alloc_color("#000000", True, True))
		cselname = stage.get_toplevel().builder.get_object("entry1").get_buffer()
		cselname.set_text(str(currentselect[level+1]), 25)
		cselx = stage.get_toplevel().builder.get_object("entry2").get_buffer()
		csely = stage.get_toplevel().builder.get_object("entry3").get_buffer()
		cselheight = stage.get_toplevel().builder.get_object("entry5").get_buffer()
		cselwidth = stage.get_toplevel().builder.get_object("entry4").get_buffer()
		cseltype = stage.get_toplevel().builder.get_object("label14")
		if not currentselect[level+1]==None:
			cselx.set_text(str(objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["x"]), 25)
			csely.set_text(str(objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["y"]), 25)
			cselwidth.set_text(str(objects[currentselect[level+1]].width), 6)
			cselheight.set_text(str(objects[currentselect[level+1]].height), 6)
			cseltype.set_text(objects[currentselect[level+1]].type)
		else:
			cselx.set_text("--", 2)
			csely.set_text("--", 2)
			cselwidth.set_text("--", 2)
			cselheight.set_text("--", 2)
			cseltype.set_text("None selected")

	'''
	else:
		for i in currentfile["frames"][biggest+1]["sort"]:
			if i in currentfile["frames"][biggest+2]["sort"]:
				f1 = currentfile["frames"][biggest+1][i]
				f2 = currentfile["frames"][biggest+2][i]
				fac = facx(currentfile["frames"][0][biggest], currentfile["frames"][0][biggest+1], currentframe[level])
				x = ave(f2["x"], f1["x"], fac)
				y = ave(f2["y"], f1["y"], fac)
				r = ave(f2["rotate"], f1["rotate"], fac)
			else:
				f1 = currentfile["frames"][biggest+1][i]
				x = f1["x"]
				y = f1["y"]
				r = f1["rotate"]
			currentfile["objects"][i].draw(x,y,r,cr,False)
	'''
	if clicked == True:
		if mode == "r":
			if startmouse[0]<stage.get_pointer()[0]:
				x = startmouse[0]
				w = stage.get_pointer()[0]-x
			else:
				x = stage.get_pointer()[0]
				w = startmouse[0]-x
			if startmouse[1]<stage.get_pointer()[1]:
				y = startmouse[1]
				h = stage.get_pointer()[1]-y
			else:
				y = stage.get_pointer()[1]
				h = startmouse[1]-y
	#		drawBox(stage.window.new_gc(ccol), stage.window, x, y, w, h)
			drawcrBox(cr, x, y, w, h, 1, ccol)
		elif mode == "e":
			if startmouse[0]<stage.get_pointer()[0]:
				x = startmouse[0]
				w = stage.get_pointer()[0]-x
			else:
				x = stage.get_pointer()[0]
				w = startmouse[0]-x
			if startmouse[1]<stage.get_pointer()[1]:
				y = startmouse[1]
				h = stage.get_pointer()[1]-y
			else:
				y = stage.get_pointer()[1]
				h = startmouse[1]-y
	#		drawEllipse(stage.window.new_gc(ccol), stage.window, x, y, w, h)
			#cr.set_source_rgb(ccol[0], ccol[1], ccol[2])
			print x, y, w, h, ccol
			drawcrEllipse(cr, x, y, w, h, ccol)
		elif mode == " ":
			if currentframe[level] in objects[currentselect[level]].frames[0]:
				if currentselect[level+1] in currentfile["objects"]:
					ref=objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]
					startmouse = stage.get_toplevel().builder.get_object("drawingarea1").get_pointer()
					if first==True:
						fx=startmouse[0]-ref["x"]
						fy=startmouse[1]-ref["y"]
						first=False
					objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["x"]=startmouse[0]-fx
					objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["y"]=startmouse[1]-fy
					global source_id
					if not source_id:
						source_id = "k"
		elif mode == "s":
			if currentframe[level] in objects[currentselect[level]].frames[0]:
				if currentselect[level+1] in currentfile["objects"]:
					ref=objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]
					startmouse = stage.get_toplevel().builder.get_object("drawingarea1").get_pointer()
					if first==True:
						fx=startmouse[0]-ref["x"]
						fy=startmouse[1]-ref["y"]
						first=False
					if not scale:
						objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["x"]=startmouse[0]-fx
						objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["y"]=startmouse[1]-fy
					else:
						xscale = (startmouse[0]-objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["x"])/(objects[currentselect[level+1]].width*1.0)
						yscale = (startmouse[1]-objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["y"])/(objects[currentselect[level+1]].height*1.0)
						if math.fabs(xscale)<0.001:
							xscale=0.001
						if math.fabs(yscale)<0.001:
							yscale=0.001
						objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["xscale"]=xscale
						objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["yscale"]=yscale
					x = objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["x"]
					y = objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["y"]
					r = objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["rotate"]
					xscale = objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["xscale"]
					yscale = objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["yscale"]
					coords = [x, y,
					x+objects[currentselect[level+1]].width*xscale/2, y,
					x+objects[currentselect[level+1]].width*xscale, y,
					x+objects[currentselect[level+1]].width*xscale, y+objects[currentselect[level+1]].height*yscale/2,
					x+objects[currentselect[level+1]].width*xscale, y+objects[currentselect[level+1]].height*yscale,
					x+objects[currentselect[level+1]].width*xscale/2, y+objects[currentselect[level+1]].height*yscale,
					x, y+objects[currentselect[level+1]].height*yscale,
					x, y+objects[currentselect[level+1]].height*yscale/2]
					coords = rotate_list(coords, x, y, r)
					for i in range(8):
						drawcrBox(cr, coords[i*2]-5, coords[i*2+1]-5, 10, 10, 1, [0, 0, 0], 0, [1, 1, 1, 1])
					if not source_id:
						source_id = "k"
		elif mode == "p":
			if time.time()-lastinput > 0.05:
				brushlocs.append((stage.get_pointer()[0]-500, stage.get_pointer()[1]-500))
				lastinput = time.time()
			try:
				cr.set_source_rgb(0,0,0)
				drawcrShape(cr, [["M", brushlocs[-2][0], brushlocs[-2][1]], ["L", brushlocs[-1][0], brushlocs[-1][1]]], 0, 0, 0, False)
			except:
				pass
	cr.restore()
	cra.set_source_surface(surface)
	cra.paint()
	
def on_drag_data_received(widget, context, x, y, selection, target_type, timestamp):
	global pid
	global sep
	x = x-500
	y = y-500
	uri = selection.data.strip('\r\n\x00')
	uri_splitted = uri.split() # we may have more than one file dropped
	for uri in uri_splitted:
		path = get_file_path_from_dnd_dropped_uri(uri)
		if os.path.isfile(path): # is it file?
			data = file(path).read()
			print path
		try:
			im = Image.open(path)
		except IOError:
			alert(path+" is not a valid image file!")
		else:
			if not imghdr.what(path)=="png":
				im.save(os.environ["TEMP"]+sep+"swift"+str(pid)+sep+path.split(sep)[-1].split(".")[0]+".png")
				path = os.environ["TEMP"]+sep+"swift"+str(pid)+sep+path.split(sep)[-1].split(".")[0]+".png"
			f=path.split("/")[-1].split(".")
			if f[0][0].isdigit():
				alert("First character of filename is a digit!! Changing to \"i\".")
				f[0] = "i"+f[0][1:]
			g=f[0]
			undostack.append(copy.deepcopy(currentfile))
			currentfile["colors"]["images"][g]=path
			currentfile["colors"]["textures"][g]={"type":"image", "fill":g}
			entry=join(f, ".")
			image = gtk.Image()
			image.set_from_file("../media/icon.png")
			image.show()
			widget.get_toplevel().AddLibItem([image,  entry, "1"])
			size = im.size
			newname = g
			if not newname in objects:
				# CHANGE THE PARENT TO BE THE APPROPRIATE OBJECT
				objects[newname+"b"] = box(newname+"b", size[0], size[1], "root", newname)
				for i in range(1, len(objects[objects[newname+"b"].parent].frames)):
					objects[objects[newname+"b"].parent].frames[i]["sort"].append(newname+"b")
					objects[objects[newname+"b"].parent].frames[i][newname+"b"] = {"x":x-size[0]/2, "y":y-size[1]/2, "rotate":0, "xscale":1.0, "yscale":1.0}
					if i==1:
						objects[objects[newname+"b"].parent].frames[i][newname+"b"]["put"] = True
				selectid.append("#01"+("%X" % (int(selectid[-1][3:7], 16)+1)).zfill(4))
				selectors.append(newname+"b")
				expostagevent(stage, "expose-event")
			else:
				alert("There is already an object called "+newname+" in the current project. I will just abandon this attempt because the alert window only has one button.")

def get_file_path_from_dnd_dropped_uri(uri):
	# get the path to file
	path = ""
	if uri.startswith('file:\\\\\\'): # windows
		path = uri[8:] # 8 is len('file:///')
	elif uri.startswith('file://'): # nautilus, rox
		path = uri[7:] # 7 is len('file://')
	elif uri.startswith('file:'): # xffm
		path = uri[5:] # 5 is len('file:')

	path = urllib.url2pathname(path) # escape special chars
	path = path.strip('\r\n\x00') # remove \r\n and NULL

	return path
	
def exposeframevent(framewin, event, instep=0):
	global step
	global currentframe
	global level
	global objects
	global MAX_FRAMES
	keyframe_active = gtk.gdk.pixbuf_new_from_file(getdatapath()+sep+"media"+sep+"keyframe_active.png")
	keyframe_inactive = gtk.gdk.pixbuf_new_from_file(getdatapath()+sep+"media"+sep+"keyframe_inactive.png")
	frame_active_tween = gtk.gdk.pixbuf_new_from_file(getdatapath()+sep+"media"+sep+"frame_active_tween.png")
	frame_inactive_tween = gtk.gdk.pixbuf_new_from_file(getdatapath()+sep+"media"+sep+"frame_inactive_tween.png")
	keyframe_active_button = gtk.gdk.pixbuf_new_from_file(getdatapath()+sep+"media"+sep+"keyframe_active_button.png")
	keyframe_inactive_button = gtk.gdk.pixbuf_new_from_file(getdatapath()+sep+"media"+sep+"keyframe_inactive_button.png")
	frame_active_blank = gtk.gdk.pixbuf_new_from_file(getdatapath()+sep+"media"+sep+"frame_active_blank.png")
	frame_inactive_blank = gtk.gdk.pixbuf_new_from_file(getdatapath()+sep+"media"+sep+"frame_inactive_blank.png")
	frame_active_blank_5 = gtk.gdk.pixbuf_new_from_file(getdatapath()+sep+"media"+sep+"frame_active_blank_5.png")
	frame_inactive_blank_5 = gtk.gdk.pixbuf_new_from_file(getdatapath()+sep+"media"+sep+"frame_inactive_blank_5.png")
	if level==0 or currentfile["objects"][currentselect[level]].type == "movieclip":
		for i in range (0, objects[currentselect[level]].frames[0][-1]+1):
			try:
				dummyvariable=objects[currentselect[level]].frames[0].index(i)
				if currentframe[level]==i:
					framewin.window.draw_pixbuf(None, keyframe_active, (instep%16)*16, 0, i*16, 0, 16, -1)
				else:
					framewin.window.draw_pixbuf(None, keyframe_inactive, 0, 0, i*16, 0, 16, -1)
			except ValueError:
				if currentframe[level]==i:
					framewin.window.draw_pixbuf(None, frame_active_tween, 0, 0, i*16, 0, 16, -1)
				else:
					framewin.window.draw_pixbuf(None, frame_inactive_tween, 0, 0, i*16, 0, 16, -1)
		for i in range (objects[currentselect[level]].frames[0][-1]+1, MAX_FRAMES):
			if currentframe[level]==i:
				if i%5==0:
					framewin.window.draw_pixbuf(None, frame_active_blank_5, 0, 0, i*16, 0, 16, -1)
				else:
					framewin.window.draw_pixbuf(None, frame_active_blank, 0, 0, i*16, 0, 16, -1)
			else:
				if i%5==0:
					framewin.window.draw_pixbuf(None, frame_inactive_blank_5, 0, 0, i*16, 0, 16, -1)
				else:
					framewin.window.draw_pixbuf(None, frame_inactive_blank, 0, 0, i*16, 0, 16, -1)
	elif currentfile["objects"][currentselect[level]].type == "button":
		framewin.window.draw_pixbuf(None, keyframe_active_button, (instep%16)*64, 0, 0, 0, 64, -1)
	step = instep
	if event=="animation-event":
		source_id = gobject.timeout_add(100, exposeframevent, framewin, "animation-event", step+1)
def exposobjevent(objwin, event):
	global step
	objpic = gtk.gdk.pixbuf_new_from_file(getdatapath()+sep+"media"+sep+"object_active.png")
	objwin.window.draw_pixbuf(None, objpic, (step%16)*128, 0, 0, 0, 128, -1)
	source_id = gobject.timeout_add(100, exposobjevent, objwin, "expose-event")
def exposegradevent(gradwin, event):
	gb0=gradwin.get_toplevel().builder.get_object("drawingarea4")
	
	gb1=gradwin.get_toplevel().builder.get_object("drawingarea5")
	gb2=gradwin.get_toplevel().builder.get_object("drawingarea6")
	cr = gb0.window.cairo_create()
	cr1 = gb1.window.cairo_create()
	cr2 = gb2.window.cairo_create()
	w = gb0.allocation.width
	w1 = gb1.allocation.width
	w2 = gb2.allocation.width
	
	h = gb0.allocation.height
	h1 = gb1.allocation.height
	h2 = gb2.allocation.height
	grad = [[0.0, 0, 0, 0, 1], [0.5, 1, 1, 0, 1], [1.0, 0, 0, 0, 1]]
	grad = getdatapath()+sep+"media"+sep+"icon.png"
	#cr.set_line_width(2)
	surface = cairo.ImageSurface.create_from_png(getdatapath()+sep+"media"+sep+"background_transparent.png")
	pattern = cairo.SurfacePattern(surface)
	pattern.set_extend(cairo.EXTEND_REPEAT)
	cr.set_source(pattern)
	cr.paint()
	cr1.set_source(pattern)
	cr1.paint()
	cr2.set_source(pattern)
	cr2.paint()
	typ = "bitmap"
	if typ == "solid":
		cr.set_source_rgb(1, 0, 0)
		cr.rectangle(0, 0, w, 15)
		cr.fill()
		cr.rectangle(0, 25, w, h)
		cr.fill()
		cr1.set_source_rgb(1, 0, 0)
		cr1.paint()
		cr2.set_source_rgb(1, 0, 0)
		cr2.paint()
	elif typ == "linear":
		g = cairo.LinearGradient(0, 0, w, 0)
		for i in range(len(grad)):
			g.add_color_stop_rgba(grad[i][0], grad[i][1], grad[i][2], grad[i][3], grad[i][4])
		cr.set_source(g)
		cr.rectangle(0, 0, w, 15)
		cr.fill()
		cr.rectangle(0, 25, w, h)
		cr.fill()
		g1 = cairo.LinearGradient(0.0, 0.0, w1, 0.0)
		for i in range(len(grad)):
			g1.add_color_stop_rgba(grad[i][0], grad[i][1], grad[i][2], grad[i][3], grad[i][4])
		cr1.set_source(g1)
		cr1.paint()
		g2 = cairo.LinearGradient(0.0, 0.0, w2, 0.0)
		for i in range(len(grad)):
			g2.add_color_stop_rgba(grad[i][0], grad[i][1], grad[i][2], grad[i][3], grad[i][4])
		cr2.set_source(g2)
		cr2.paint()
	elif typ == "radial":
		g = cairo.RadialGradient(w/2, (25+h)/2, 0.0, w/2, (25+h)/2, w/2)
		gl = cairo.LinearGradient(0, 0, w, 0)
		for i in range(len(grad)):
			g.add_color_stop_rgba(grad[i][0], grad[i][1], grad[i][2], grad[i][3], grad[i][4])
			gl.add_color_stop_rgba(grad[i][0], grad[i][1], grad[i][2], grad[i][3], grad[i][4])
		cr.set_source(gl)
		cr.rectangle(0, 0, w, 15)
		cr.fill()
		cr.set_source(g)
		cr.rectangle(0, 25, w, h)
		cr.fill()
		g1 = cairo.RadialGradient(w1/2, h1/2, 0.0, w1/2, h1/2, w1/2)
		for i in range(len(grad)):
			g1.add_color_stop_rgba(grad[i][0], grad[i][1], grad[i][2], grad[i][3], grad[i][4])
		cr1.set_source(g1)
		cr1.paint()
		g2 = cairo.RadialGradient(w2/2, h2/2, 0.0, w2/2, h2/2, w2/2)
		for i in range(len(grad)):
			g2.add_color_stop_rgba(grad[i][0], grad[i][1], grad[i][2], grad[i][3], grad[i][4])
		cr2.set_source(g2)
		cr2.paint()
	elif typ == "bitmap":
		surface = cairo.ImageSurface.create_from_png(grad)
		pattern = cairo.SurfacePattern(surface)
		cr.set_source(pattern)
		cr.rectangle(0, 0, w, h)
		cr.fill()
		matrix = cairo.Matrix(xx=surface.get_width()*1.0/w1, yy=surface.get_height()*1.0/h1)
		pattern.set_matrix(matrix)
		cr1.set_source(pattern)
		cr1.paint()
		cr2.set_source(pattern)
		cr2.paint()
	
	if event=="init-event":
		source_id = gobject.timeout_add(1000, exposegradevent, gradwin, "expose-event")
def exposecolorevent(cwin, event):
	global currentcolor
	gb1=gradwin.get_toplevel().builder.get_object("fillcolor")
	gb2=gradwin.get_toplevel().builder.get_object("linecolor")
	cr1 = gb1.window.cairo_create()
	cr2 = gb2.window.cairo_create()
	w1 = gb1.allocation.width
	w2 = gb2.allocation.width
	
	h1 = gb1.allocation.height
	h2 = gb2.allocation.height
	grad = [[0.0, 0, 0, 0, 1], [0.5, 1, 1, 0, 1], [1.0, 0, 0, 0, 1]]
	grad = getdatapath()+sep+"media"+sep+"icon.png"
	surface = cairo.ImageSurface.create_from_png(getdatapath()+sep+"media"+sep+"background_transparent.png")
	pattern = cairo.SurfacePattern(surface)
	pattern.set_extend(cairo.EXTEND_REPEAT)
	cr1.set_source(pattern)
	cr1.paint()
	cr2.set_source(pattern)
	cr2.paint()
	if type(currentcolor)==type([]):
		typ="solid"
	else:
		typ = "bitmap"
	if typ == "solid":
		cr1.set_source_rgb(currentcolor[0], currentcolor[1], currentcolor[2])
		cr1.paint()
		cr2.set_source_rgb(currentcolor[0], currentcolor[1], currentcolor[2])
		cr2.paint()
	elif typ == "linear":
		g1 = cairo.LinearGradient(0.0, 0.0, w1, 0.0)
		for i in range(len(grad)):
			g1.add_color_stop_rgba(grad[i][0], grad[i][1], grad[i][2], grad[i][3], grad[i][4])
		cr1.set_source(g1)
		cr1.paint()
		g2 = cairo.LinearGradient(0.0, 0.0, w2, 0.0)
		for i in range(len(grad)):
			g2.add_color_stop_rgba(grad[i][0], grad[i][1], grad[i][2], grad[i][3], grad[i][4])
		cr2.set_source(g2)
		cr2.paint()
	elif typ == "radial":
		g1 = cairo.RadialGradient(w1/2, h1/2, 0.0, w1/2, h1/2, w1/2)
		for i in range(len(grad)):
			g1.add_color_stop_rgba(grad[i][0], grad[i][1], grad[i][2], grad[i][3], grad[i][4])
		cr1.set_source(g1)
		cr1.paint()
		g2 = cairo.RadialGradient(w2/2, h2/2, 0.0, w2/2, h2/2, w2/2)
		for i in range(len(grad)):
			g2.add_color_stop_rgba(grad[i][0], grad[i][1], grad[i][2], grad[i][3], grad[i][4])
		cr2.set_source(g2)
		cr2.paint()
	elif typ == "bitmap":
		surface = cairo.ImageSurface.create_from_png(grad)
		pattern = cairo.SurfacePattern(surface)
		#cr1.set_source(pattern)
		#cr1.rectangle(0, 0, w, h)
	   # cr1.fill()
		matrix = cairo.Matrix(xx=surface.get_width()*1.0/w1, yy=surface.get_height()*1.0/h1)
		pattern.set_matrix(matrix)
		cr1.set_source(pattern)
		cr1.paint()
		cr2.set_source(pattern)
		cr2.paint()
	
	if event=="init-event":
		source_id = gobject.timeout_add(1000, exposegradevent, gradwin, "expose-event")
def join(List, char=""):
	#Simple implementation of join
	#If it isn't obvious, it shouldn't be changed
	ret = ""
	for i in range(len(List)):
		if not i==len(List)-1:
			ret = ret + str(List[i]) + char
		else:
			ret = ret + str(List[i])
	return str(ret)

def check(script):
	errors = []
	line = 1
	paren = 0
	curly = 0
	brack = 0
	quote = False
	for i in range(len(script)):
		if script[i] == "\n":
			if script[i-1]==";" or script[i-1]=="{":
				print "Good"
			else:
				errors.append("Line "+str(line)+": Semicolon missing")
			line+=1
			if paren>0:
				errors.append("Line "+str(line)+": Missing \")\"")
				break;
			if quote==True:
				errors.append("Line "+str(line)+": Missing \"")
				break;
		elif i==len(script)-1:
			if script[i]==";":
				print "Good"
			else:
				errors.append("Line "+str(line)+": Semicolon missing")
			if paren>0:
				errors.append("Line "+str(line)+": Extra \"(\" - missing a \")\"")
			if curly>0:
				errors.append("Line "+str(line)+": Extra \"{\" - missing a \"}\"")
			if brack>0:
				errors.append("Line "+str(line)+": Extra \"[\" - missing a \"]\"") 
			if quote==True:
				errors.append("Line "+str(line)+": Missing \"")
				break;
				
		elif script[i] == "(":
			paren+=1;
		elif script[i] == ")":
			paren-=1;
			if paren<0:
				errors.append("Line "+str(line)+": Encountered \")\" without matching \"(\"")
				break;
		elif script[i] == "{":
			curly+=1;
		elif script[i] == "}":
			curly-=1;
			if curly<0:
				errors.append("Line "+str(line)+": Encountered \"}\" without matching \"{\"")
				break;
		elif script[i] == "[":
			curly+=1;
		elif script[i] == "]":
			curly-=1;
			if curly<0:
				errors.append("Line "+str(line)+": Encountered \"]\" without matching \"[\"")
				break;
		elif script[i] == "\"":
			quote = not quote
		elif script[i] == "\'":
			errors.append("Line "+str(line)+": Please use double quotes instead of single quotes.")
			break;
	if not errors==[]:
		x = "The following errors were encountered. Please correct them and try again.\n"+join(errors, "\n")
	else:
		x = True
	return x;

	
def keyvent(stage, event=None, window=None, data=None):
	keyname = str(gtk.gdk.keyval_name(event.keyval))
	if keyname=="space":
		window.select_any(stage, data)
	elif keyname=="r":
		window.draw_rect(stage, data)
	elif keyname=="e":
		window.draw_ellipse(stage, data)
	elif keyname=="s":
		window.resize_any(stage, data)
	elif keyname=="t":
		window.draw_text(stage, data)
	elif keyname=="b":
		window.paint_bucket(stage, data)
	elif keyname=="p":
		window.paint_brush(stage, data)
	elif keyname=="Return":
		window.play_frames(stage, data)
	elif keyname=="Delete":
		window.delete_item(stage, data)
	else:
		print keyname

class box:
	# Basic class for box. Will be deprecated as soon as replacement "shape" class is created.
	def __init__(self, name, width=100, height=100, parent="root", fill="none"):
		global objects
		self.name = name
		self.width = width
		self.height = height
		self.parent = parent
		self.fill = fill
		self.level = objects[parent].level+1
		self.type = "box"
	def draw(self, cr, gc=None, pixmap=None, stage=None):
		global currentfile
		global currentframe
		global level
		global objects
		# x, y, rotate, keyframe=False, 
		parent = objects[self.parent]
		if parent.type=="button":
			if not currentframe[self.level-1] in parent.frames[0]:
				currentframe[self.level-1]="idle"
		if currentframe[self.level-1] in parent.frames[0]:
			if self.name in parent.frames[parent.frames[0].index(currentframe[self.level-1])+1]:
				x = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["x"]
				y = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["y"]
				xscale = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["xscale"]
				yscale = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["yscale"]
				rotate = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["rotate"]
				keyframe = True
			else:
				return
		else:
			keyframe = False
			biggest=0
			for i in range (0, currentframe[self.level-1]+1):
				if i in parent.frames[0]:
					biggest = parent.frames[0].index(i)
			if self.name in parent.frames[biggest+1]:
				if len(parent.frames)>biggest+2 and self.name in parent.frames[biggest+2]["sort"]:
					f1 = parent.frames[biggest+1][self.name]
					f2 = parent.frames[biggest+2][self.name]
					fac = facx(parent.frames[0][biggest], parent.frames[0][biggest+1], currentframe[self.level-1])
					x = ave(f2["x"], f1["x"], fac)
					y = ave(f2["y"], f1["y"], fac)
					xscale = ave(f2["xscale"], f1["xscale"], fac)
					yscale = ave(f2["yscale"], f1["yscale"], fac)
					rotate = ave(f2["rotate"], f1["rotate"], fac)
				else:
					f1 = parent.frames[biggest+1][self.name]
					x = f1["x"]
					y = f1["y"]
					xscale = f1["xscale"]
					yscale = f1["yscale"]
					rotate = f1["rotate"]
			else:
				return
		x = x*parent.xscale+parent.x
		y = y*parent.yscale+parent.y
		xscale = xscale*parent.xscale
		yscale = yscale*parent.yscale
		rotate = rotate+parent.rotate
		fill = self.fill
		if type(fill)==type([]):
			fill = hex2rgb(fill)
		if self.level<=level and not self.parent == currentselect[level]:
			inactive = True
		else:
			inactive = False
		drawcrBox(cr, x, y, self.width, self.height, 1, self.fill, rotate, [0, 0, 0, 0], inactive, xscale, yscale)
		if keyframe and not inactive:
			try:
				drawBox(gc, pixmap, x, y, self.width, self.height, 1, rotate, xscale, yscale)
			except:
				print "Drawing to offscreen buffer failed. Not a problem if you were exporting an image."

class ellipse:
	# Basic class for ellipse. Will be deprecated as soon as replacement "shape" class is created.
	def __init__(self, name, width=100, height=100, parent="root", fill="none"):
		global objects
		self.name = name
		self.width = width
		self.height = height
		self.parent = parent
		self.fill = copy.deepcopy(fill)
		self.level = objects[parent].level+1
		self.type = "ellipse"
	def draw(self, cr, gc=None, pixmap=None, stage=None):
		global currentfile
		global currentframe
		global level
		global objects
		# x, y, rotate, keyframe=False,
		parent = objects[self.parent]
		if parent.type=="button":
			if not currentframe[self.level-1] in parent.frames[0]:
				currentframe[self.level-1]="idle"
		if currentframe[self.level-1] in parent.frames[0]:
			if self.name in parent.frames[parent.frames[0].index(currentframe[self.level-1])+1]:
				x = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["x"]
				y = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["y"]
				xscale = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["xscale"]
				yscale = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["yscale"]
				rotate = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["rotate"]
				keyframe = True
			else:
				return
		else:
			keyframe = False
			biggest=0
			for i in range (0, currentframe[self.level-1]+1):
				if i in parent.frames[0]:
					biggest = parent.frames[0].index(i)
			if self.name in parent.frames[biggest+1]:
				if len(parent.frames)>biggest+2 and self.name in parent.frames[biggest+2]["sort"]:
					f1 = parent.frames[biggest+1][self.name]
					f2 = parent.frames[biggest+2][self.name]
					fac = facx(parent.frames[0][biggest], parent.frames[0][biggest+1], currentframe[self.level-1])
					x = ave(f2["x"], f1["x"], fac)
					y = ave(f2["y"], f1["y"], fac)
					xscale = ave(f2["xscale"], f1["xscale"], fac)
					yscale = ave(f2["yscale"], f1["yscale"], fac)
					rotate = ave(f2["rotate"], f1["rotate"], fac)
				else:
					f1 = parent.frames[biggest+1][self.name]
					x = f1["x"]
					y = f1["y"]
					xscale = f1["xscale"]
					yscale = f1["yscale"]
					rotate = f1["rotate"]
			else:
				return
		x = x*parent.xscale+parent.x
		y = y*parent.yscale+parent.y
		xscale = xscale*parent.xscale
		yscale = yscale*parent.yscale
		rotate = rotate+parent.rotate
		fill = copy.deepcopy(self.fill)
		if type(fill)==type([]):
			fill = hex2rgb(fill)
		if self.level<=level and not self.parent == currentselect[level]:
			inactive = True
		else:
			inactive = False
		drawcrEllipse(cr, x, y, self.width, self.height, self.fill, rotate, [0, 0, 0, 0], inactive, xscale, yscale)
		if keyframe and not inactive:
			try:
				drawEllipse(gc, pixmap, x, y, self.width, self.height, 1, rotate, xscale, yscale)
			except:
				print "Drawing to offscreen buffer failed. Not a problem if you were exporting an image."
class shape:
	def __init__(self, name, width=0, height=0, parent="root", fill="none", shapedata=[], filled=True):
		global objects
		self.name = name
		self.width = width
		self.height = height
		self.parent = parent
		self.fill = copy.deepcopy(fill)
		self.level = objects[parent].level+1
		self.shapedata = shapedata
		self.type = "shape"
		self.filled=filled
	def draw(self, cr, gc=None, pixmap=None, stage=None):
		#implement shape.draw()
		global currentfile
		global currentframe
		global level
		global objects
		# x, y, rotate, keyframe=False,
		parent = objects[self.parent]
		if parent.type=="button":
			if not currentframe[self.level-1] in parent.frames[0]:
				currentframe[self.level-1]="idle"
		if currentframe[self.level-1] in parent.frames[0]:
			if self.name in parent.frames[parent.frames[0].index(currentframe[self.level-1])+1]:
				x = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["x"]
				y = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["y"]
				xscale = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["xscale"]
				yscale = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["yscale"]
				rotate = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["rotate"]
				keyframe = True
			else:
				return
		else:
			keyframe = False
			biggest=0
			for i in range (0, currentframe[self.level-1]+1):
				if i in parent.frames[0]:
					biggest = parent.frames[0].index(i)
			if self.name in parent.frames[biggest+1]:
				if len(parent.frames)>biggest+2 and self.name in parent.frames[biggest+2]["sort"]:
					f1 = parent.frames[biggest+1][self.name]
					f2 = parent.frames[biggest+2][self.name]
					fac = facx(parent.frames[0][biggest], parent.frames[0][biggest+1], currentframe[self.level-1])
					x = ave(f2["x"], f1["x"], fac)
					y = ave(f2["y"], f1["y"], fac)
					xscale = ave(f2["xscale"], f1["xscale"], fac)
					yscale = ave(f2["yscale"], f1["yscale"], fac)
					rotate = ave(f2["rotate"], f1["rotate"], fac)
				else:
					f1 = parent.frames[biggest+1][self.name]
					x = f1["x"]
					y = f1["y"]
					xscale = f1["xscale"]
					yscale = f1["yscale"]
					rotate = f1["rotate"]
			else:
				return
		x = x*parent.xscale+parent.x
		y = y*parent.yscale+parent.y
		xscale = xscale*parent.xscale
		yscale = yscale*parent.yscale
		rotate = rotate+parent.rotate
		fill = copy.deepcopy(self.fill)
		if type(fill)==type([]):
			fill = hex2rgb(fill)
		if self.level<=level and not self.parent == currentselect[level]:
			inactive = True
		else:
			inactive = False
		if type(fill)==type(()) or type(fill)==type([]):
			cr.set_source_rgb(fill[0], fill[1], fill[2])
		elif fill.startswith("#"):
			rgbfill = hex2rgb(fill)
			cr.set_source_rgb(rgbfill[0], rgbfill[1], rgbfill[2])
		else:
			fill = currentfile["colors"]["textures"][fill]
			if fill["type"]=="color":
				cr.set_source_rgb(fill["fill"][0], fill["fill"][1], fill["fill"][2])
			elif fill["type"]=="gradient":
				#make this use the gradient
				grad = gradient(fill["fill"])
				g = cairo.LinearGradient(x, y, x+width, y+height)
				for i in range(len(grad)):
					g.add_color_stop_rgba(grad[i][0], grad[i][1], grad[i][2], grad[i][3], grad[i][4])
				cr.set_source(g)
			else:
				#use a texture			
				image = currentfile["colors"]["images"][fill["fill"]]
				surface = cairo.ImageSurface.create_from_png(image)
				pat = cairo.SurfacePattern(surface)
				matrix = cairo.Matrix(x0=-x, y0=-y)
				pat.set_matrix(matrix)
				cr.set_source(pat)
		drawcrShape(cr, self.shapedata, x, y, rotate, self.filled, inactive, xscale, yscale)
		if keyframe and not inactive:
			try:
				gc.set_line_attributes(5, gtk.gdk.LINE_SOLID, gtk.gdk.CAP_ROUND, gtk.gdk.JOIN_ROUND)
				drawShape(gc, pixmap, self.shapedata, x, y, rotate, self.filled, xscale, yscale)
				#drawEllipse(gc, pixmap, 20, 20, 300, 200, 1)
			except:
				print "Drawing to offscreen buffer failed. Not a problem if you were exporting an image."
		test=False
		if test:
			stage.window.draw_drawable(gc, pixmap, 0, 0, 0, self.filled, 500, 500)
class button:
	# Basic class for buttons.
	def __init__(self, name, width=100, height=100, parent="root", frames=[["idle"],{"sort":[]}]):
		self.width = width
		self.height = height
		self.name = name
		self.type = "button"
		self.parent = parent
		self.level = objects[parent].level+1
		self.frames = copy.deepcopy(frames)
	def draw(self, cr, gc=None, pixmap=None, stage=None):
		global currentfile
		global currentframe
		global level
		global objects
		parent = objects[self.parent]
		if currentframe[self.level-1] in parent.frames[0]:
			x = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["x"]
			y = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["y"]
			xscale = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["xscale"]
			yscale = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["yscale"]
			rotate = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["rotate"]
			keyframe = True
		else:
			keyframe = False
			print currentframe[self.level]
			for i in range (0, currentframe[self.level]+1):
				if i in parent.frames[0]:
					biggest = i
			if self.name in parent.frames[biggest+2]["sort"]:
				f1 = parent.frames[biggest+1][self.name]
				f2 = parent.frames[biggest+2][self.name]
				fac = facx(parent.frames[0][biggest], parent.frames[0][biggest+1], currentframe[self.level-1])
				x = ave(f2["x"], f1["x"], fac)
				y = ave(f2["y"], f1["y"], fac)
				xscale = ave(f2["xscale"], f1["xscale"], fac)
				yscale = ave(f2["yscale"], f1["yscale"], fac)
				rotate = ave(f2["rotate"], f1["rotate"], fac)
			else:
				f1 = parent.frames[biggest+1][self.name]
				x = f1["x"]
				y = f1["y"]
				xscale = f1["xscale"]
				yscale = f1["yscale"]
				rotate = f1["rotate"]
		if level<self.level:
			frame = "idle"
		else:
			frame = currentframe[self.level]
		self.x = x*parent.xscale+parent.x
		self.y = y*parent.yscale+parent.y
		self.xscale = xscale*parent.xscale
		self.yscale = yscale*parent.yscale
		self.rotate = rotate+parent.rotate
		for i in self.frames[self.frames[0].index(frame)+1]["sort"]:
			self.frames[self.frames[0].index(frame)+1][i][i].draw(cr, gc, pixmap)
			
	def toString(self):
		return "{width = "+str(self.width)+", height = "+str(self.height)+", name = '"+str(self.name)+"', parent = '"+str(self.parent)+"', level = "+str(self.level)+", frames = "+str(self.frames)+"}"

class MovieClip:
	def __init__(self, name, width=100, height=100, parent="root", frames=[[0],{"sort":[]}]):
		self.name = name
		self.width = width
		self.height = height
		self.type = "movieclip"
		self.parent = parent
		self.level = objects[parent].level+1
		self.frames = copy.deepcopy(frames)
		self.actions = [""]
	def draw(self, cr, gc=None, pixmap=None, stage=None):
		global currentfile
		global currentframe
		global level
		global objects
		parent = objects[self.parent]
		if currentframe[self.level-1] in parent.frames[0]:
			x = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["x"]
			y = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["y"]
			xscale = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["xscale"]
			yscale = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["yscale"]
			rotate = parent.frames[parent.frames[0].index(currentframe[self.level-1])+1][self.name]["rotate"]
			keyframe = True
		else:
			keyframe = False
			for i in range (0, currentframe[self.level]+1):
				if i in parent.frames[0]:
					biggest = i
			if self.name in parent.frames[biggest+2]["sort"]:
				f1 = parent.frames[biggest+1][self.name]
				f2 = parent.frames[biggest+2][self.name]
				fac = facx(parent.frames[0][biggest], parent.frames[0][biggest+1], currentframe[self.level-1])
				x = ave(f2["x"], f1["x"], fac)
				y = ave(f2["y"], f1["y"], fac)
				xscale = ave(f2["xscale"], f1["xscale"], fac)
				yscale = ave(f2["yscale"], f1["yscale"], fac)
				rotate = ave(f2["rotate"], f1["rotate"], fac)
			else:
				f1 = parent.frames[biggest+1][self.name]
				x = f1["x"]
				y = f1["y"]
				xscale = f1["xscale"]
				yscale = f1["yscale"]
				rotate = f1["rotate"]
		if level<self.level:
			frame = 0
		else:
			frame = currentframe[self.level]
		self.x = x*parent.xscale+parent.x
		self.y = y*parent.yscale+parent.y
		self.xscale = xscale*parent.xscale
		self.yscale = yscale*parent.yscale
		self.rotate = rotate+parent.rotate
		if len(currentframe)<self.level or currentframe[self.level] in self.frames[0]:
			for i in self.frames[self.frames[0].index(frame)+1]["sort"]:
				if level<self.level:
					self.frames[self.frames[0].index(frame)+1][i][i].draw(cr, gc, pixmap)
				else:
					gc = gtk.gdk.GC(pixmap, colormap.alloc_color(selectid[selectors.index(i)], True, True), colormap.alloc_color("#000000", True, True))
					self.frames[self.frames[0].index(frame)+1][i][i].draw(cr, gc, pixmap)
		else:
			for i in range (0, currentframe[self.level]+1):
				if i in self.frames[0]:
					biggest = i
			for i in self.frames[self.frames[0].index(biggest)+1]["sort"]:
				self.frames[self.frames[0].index(biggest)+1][i][i].draw(cr, gc, pixmap)
class root:
	# Class for root. Only ever one instance I think.
	def __init__(self):
		self.level = 0
		self.type = "root"
		self.x=0
		self.y=0
		self.rotate=0
		self.xscale=1.0
		self.yscale=1.0
	def draw(self, cr, w, h, stage):
		global currentframe
		drawcrBox(cr, 0, 0, currentfile["fileinfo"]["bbox"][0], currentfile["fileinfo"]["bbox"][1], True, [1, 1, 1])
		if currentframe[0] in self.frames[0]:
			global pixmap
			global colormap
			pixmap=gtk.gdk.Pixmap(None, w, h, 24)
			colormap=pixmap.get_colormap()
			for i in self.frames[self.frames[0].index(currentframe[0])+1]["sort"]:
				gc = gtk.gdk.GC(pixmap, colormap.alloc_color(selectid[selectors.index(i)], True, True), colormap.alloc_color("#000000", True, True))
				currentfile["objects"][i].draw(cr, gc, pixmap, stage)
		else:
			for i in range (0, currentframe[0]+1):
				if i in self.frames[0]:
					biggest = i
			for i in self.frames[self.frames[0].index(biggest)+1]["sort"]:
				currentfile["objects"][i].draw(cr, None, None)
	def toString(self):
		return "{x = "+str(self.x)+", y = "+str(self.y)+"', rotate = '"+str(self.rotate)+"', level = "+str(self.level)+", frames = "+str(self.frames)+"}"
class point:
	def __init__(self, xy):
		self.x = xy[0]
		self.y = xy[1]
class SwiftSwfWindow(gtk.Window):
	__gtype_name__ = "SwiftSwfWindow"
	

	def AddLibItem(self, item):
		self.liblist.append(item)
	def __init__(self):
		"""__init__ - This function is typically not called directly.
		Creation a SwiftSwfWindow requires redeading the associated ui
		file and parsing the ui definition extrenally,
		and then calling SwiftSwfWindow.finish_initializing().

		Use the convenience function NewSwiftSwfWindow to create
		SwiftSwfWindow object.

		"""
		pass

	def finish_initializing(self, builder):
		"""finish_initalizing should be called after parsing the ui definition
		and creating a SwiftSwfWindow object with it in order to finish
		initializing the start of the new SwiftSwfWindow instance.

		"""
		#get a reference to the builder and set up the signals
		self.builder = builder
		self.builder.connect_signals(self)
		global currentfile
		global launchpad_available
		if launchpad_available:
			# see https://wiki.ubuntu.com/UbuntuDevelopment/Internationalisation/Coding for more information
			# about LaunchpadIntegration
			helpmenu = self.builder.get_object('menu3')
			if helpmenu:
				LaunchpadIntegration.set_sourcepackagename('swift-swf')
				LaunchpadIntegration.add_items(helpmenu, 0, False, True)
			else:
				launchpad_available = False	
				
		#uncomment the following code to read in preferences at start up
		#dlg = PreferencesSwiftDialog.NewPreferencesSwiftDialog()
		#self.preferences = dlg.get_preferences()

		#code for other initialization actions should be added here
		
		self.builder.get_object("textview1").set_wrap_mode(gtk.WRAP_CHAR)
		buff = self.builder.get_object("textview1").get_buffer()
		buff.set_text(str(currentfile))
		self.set_title("Swift - Untitled.swift")
		libview = self.builder.get_object("libview")
		combobox = self.builder.get_object("combobox1")
		cell = gtk.CellRendererText()
		combobox.pack_start(cell, True)
		combobox.add_attribute(cell, 'text', 0)
		def AddLibColumnI(title, columnId):
			"""This function adds a column to the list view.
			First it create the gtk.TreeViewColumn and then set
			some needed properties"""
			
			column = gtk.TreeViewColumn(title, gtk.CellRendererPixbuf())
			column.set_resizable(True)
			column.set_sort_column_id(columnId)
			self.builder.get_object("libview").append_column(column)
		def AddLibColumnT(title, columnId):
			"""This function adds a column to the list view.
			First it create the gtk.TreeViewColumn and then set
			some needed properties"""
			
			column = gtk.TreeViewColumn(title, gtk.CellRendererText(), text=columnId)
			column.set_resizable(True)
			column.set_sort_column_id(columnId)
			self.builder.get_object("libview").append_column(column)
		AddLibColumnI("Icon", 0)
		AddLibColumnT("Title", 1)
		AddLibColumnT("Instances", 2)
		#Create the listStore Model to use with the wineView
		self.liblist = gtk.ListStore(gtk.Image, str, str)
		#Attatch the model to the treeView
		libview.set_model(self.liblist)
		if len(sys.argv)==2:
			print "looks good..."
		for arg in sys.argv:
			if not arg=="swift-swf" or arg=="./swift-swf":
				print arg
		
	def about(self, widget, data=None):
		"""about - display the about box for swift """
		about = AboutSwiftSwfDialog.NewAboutSwiftSwfDialog()
		response = about.run()
		about.destroy()

	def preferences(self, widget, data=None):
		#TODO:Set up preferences
		"""preferences - display the preferences window for swift """
		prefs = PreferencesSwiftSwfDialog.NewPreferencesSwiftSwfDialog()
		response = prefs.run()
		if response == gtk.RESPONSE_OK:
			#make any updates based on changed preferences here
			pass
		prefs.destroy()

	def quit(self, widget, data=None):
		"""quit - signal handler for closing the SwiftSwfWindow"""
		self.destroy()

	def on_destroy(self, widget, data=None):
		"""on_destroy - called when the SwiftSwfWindow is closed. """
		#clean up code for saving application state should be added here
		#Delete any temp files so swift won't give an error on next boot
		global pid
		try:
			os.remove(os.environ["TEMP"]+sep+"swift"+str(pid)+sep+"currentfile")
		except:
			print "no saved file"
		gtk.main_quit()
	def save_dialog(self, widget, data=None):
		global path
		global title
		global currentfile
		#get the title from the user
		saver = SaveDialog.NewSaveDialog(["swift"])
		result = saver.run()
		#Filename includes path
		filename = saver.get_filename()
		patharray = filename.split(sep)
		title = patharray.pop()
		titlearray = title.split(".")
		title = titlearray[0] #no extension
		path = ""
		for i in patharray:
			path = path+i+sep
		
		
		saver.destroy()
		'''
		if 1==1:
			savestring=str(currentfile)
		else:
			#get the text to save
			#buff = self.builder.get_object("textview1").get_buffer()
			#start_iter = buff.get_start_iter()
			#end_iter = buff.get_end_iter()
			#text = buff.get_text(start_iter,end_iter)
			act = self.builder.get_object("textview2").get_buffer()
			actions = act.get_text(act.get_start_iter(), act.get_end_iter()).split("\n")
			frame_actions = [".frame "+"1"+"\n", "\t.action:\n"]
			for i in actions:
				frame_actions.append("\t\t"+i)
			frame_actions.append("\t.end")
			buff = self.builder.get_object("textview1").get_buffer()
			start_iter = buff.get_start_iter()
			end_iter = buff.get_end_iter()
			currentfile = buff.get_text(start_iter,end_iter).split("\n")
			currentfile[0] = ".flash filename=\""+title+".swf\""
			savestring = ""
			index = 0
			for i in currentfile:
				currentfile[index]=i.strip()
				savestring = savestring+str(i)+"\n"
				index = index + 1
		#get all the records
		#record_type = "http://wiki.ubuntu.com/Quickly/JottyDoc"
		#results = self.database.get_records(record_type = record_type, 
		#									create_view = True)
		fc = open(path+title+".swift", "w")
		fc.write(savestring)
		fc.flush()
		fc.close()
		self.set_title("Swift - "+title+".swift")
		'''
		self.save_file(widget, True)
		if result != gtk.RESPONSE_OK:
			return

	def save_file_as(self, widget, data=None):
		self.save_dialog(widget, data)

	def save_file(self, widget, data=None):
 		global path
		global title
		global currentfile
		a = open(path+"currentfile", "a+")
		b = ""
		for i in a:
			b = b + i
		if data==True:
			
			tar = tarfile.open(path+title+".swift", "w:gz")
			for i in currentfile["colors"]["images"]:
				tar.add(currentfile["colors"]["images"][i], currentfile["colors"]["images"][i].split("/")[-1], False)
			currentfilo = copy.deepcopy(currentfile)
			for i in currentfilo["colors"]["images"]:
				currentfilo["colors"]["images"][i] = currentfilo["colors"]["images"][i].split("/")[-1]
			currentfilo["objects"] = {}
			a.write(str(currentfilo))
			for i in currentfile["objects"]:
				j = currentfile["objects"][i]
				if j.type=="box" or j.type=="ellipse":
					a.write("\n"+j.type+"(\""+j.name+"\","+str(j.width)+","+str(j.height)+",\""+str(j.parent)+"\",\""+str(j.fill)+"\")")
				elif j.type=="shape":
					a.write("\n"+j.type+"(\""+j.name+"\","+str(j.width)+","+str(j.height)+",\""+str(j.parent)+"\",\""+str(j.fill)+"\","+str(j.shapedata)+")")
				elif j.type=="button":
					a.write("\n"+j.type+"(\""+j.name+"\","+str(j.width)+","+str(j.height)+",\""+str(j.parent)+"\","+str(j.frames)+")")
			a.close()
			tar.add(path+"currentfile", "currentfile", False)
			tar.close()
			os.remove(path+"currentfile")
			
		elif b == "":
			self.save_dialog(widget)
		elif title == "Untitled":
			a.close()
			self.save_file_as(widget, data)
		else:
			tar = tarfile.open(path+title+".swift", "w:gz")
			for i in currentfile["colors"]["images"]:
				tar.add(currentfile["colors"]["images"][i], currentfile["colors"]["images"][i].split("/")[-1], False)
			currentfilo = copy.deepcopy(currentfile)
			for i in currentfilo["colors"]["images"]:
				currentfilo["colors"]["images"][i] = "\""+currentfilo["colors"]["images"][i].split("/")[-1]+"\""
			currentfilo["objects"] = {}
			#for i in currentfilo["colors"]["textures"]
			a.write(str(currentfilo))
			for i in currentfile["objects"]:
				j = currentfile["objects"][i]
				if j.type=="box" or j.type=="ellipse":
					a.write("\n"+j.type+"(\""+j.name+"\","+str(j.width)+","+str(j.height)+",\""+str(j.parent)+"\",\""+str(j.fill)+"\")")
				elif j.type=="shape":
					a.write("\n"+j.type+"(\""+j.name+"\","+str(j.width)+","+str(j.height)+",\""+str(j.parent)+"\",\""+str(j.fill)+"\","+str(j.shapedata)+")")
				elif j.type=="button":
					a.write("\n"+j.type+"(\""+j.name+"\","+str(j.width)+","+str(j.height)+",\""+str(j.parent)+"\","+str(j.frames)+")")
			a.close()
			tar.add(path+"currentfile", "currentfile", False)
			tar.close()
			os.remove(path+"currentfile")
			#self.save_dialog(widget, data)

	def open_file(self, widget, data=None):
		global library
		global title
		global path
		global currentfile
		global currentselect
		global selectors
		global selectid
		global objects
		global level
		#run the open dialog
		opener = OpenDialog.NewOpenDialog()
		result = opener.run()
		filename = opener.get_filename()
		patharray = filename.split("/")
		title = patharray.pop()
		titlearray = title.split(".")
		title = titlearray[0]
		path = ""
		for i in patharray:
			path = path+i+"/"
		try:
			ren = os.environ["TEMP"]+sep+title+".tar.gz"
			shutil.copyfile(filename, ren)
			tar = tarfile.open(ren, 'r:gz')
			for item in tar:
				tar.extract(item, os.environ["TEMP"]+sep+"swift"+str(pid)+sep)
			os.remove(ren)
		except:
			print "Error opening file."
			alert("Error opening file!")
			opener.destroy()
			return 415
		fc = open(os.environ["TEMP"]+sep+"swift"+str(pid)+sep+"currentfile", "r")
		currentfilebase = []
		for i in fc:
			currentfilebase.append(i)
		currentfile = eval (currentfilebase[0])
		objects = currentfile["objects"]
		objects["root"] = root()
		objects["root"].frames = currentfile["frames"]
		objects["root"].actions = currentfile["actions"]
		for i in range(1, len(currentfilebase)):
			obtemp = eval (currentfilebase[i])
			currentfile["objects"][obtemp.name] = obtemp
		currentselect = ["root", None]
		for i in currentfile["colors"]["images"]:
			currentfile["colors"]["images"][i] = os.environ["TEMP"]+sep+"swift"+str(pid)+sep+currentfile["colors"]["images"][i]
		level = 0
		fc.close()
		self.set_title("Swift - "+title+".swift")
		selectid=["#000000"]
		selectors=[None]
		for i in currentfile["objects"]:
			self.AddLibItem([None, i, 1])
			if currentfile["objects"][i].type=="box":
				#Ugly expression meaning add 1 to highest hex value
				selectid.append("#01"+("%X" % (int(selectid[-1][3:7], 16)+1)).zfill(4))
				selectors.append(i)
			elif currentfile["objects"][i].type=="ellipse":
				selectid.append("#02"+("%X" % (int(selectid[-1][3:7], 16)+1)).zfill(4))
				selectors.append(i)
			elif currentfile["objects"][i].type=="curve":
				selectid.append("#03"+("%X" % (int(selectid[-1][3:7], 16)+1)).zfill(4))
				selectors.append(i)
			elif currentfile["objects"][i].type=="shape":
				selectid.append("#03"+("%X" % (int(selectid[-1][3:7], 16)+1)).zfill(4))
				selectors.append(i)
				
		print selectid, selectors
		stage = self.builder.get_object("drawingarea1")
		expostagevent(stage, "expose-event")
		buff = self.builder.get_object("textview1").get_buffer()
		buff.set_text(str(currentfile))
		self.builder.get_object("textview1").set_wrap_mode(gtk.WRAP_CHAR)
		#for i in currentfile["objects"]:
		#	entry=i
		#	image = gtk.Image()
		#	image.set_from_file("../media/icon.png")
		#	image.show()
		#	self.AddLibItem([image,  entry, "1"])
		#close the dialog, and check whether to proceed
		opener.destroy()
		if result != gtk.RESPONSE_OK:
			return


	def new_file(self, widget=None, data=None):
		global currentfile
		global currentframe
		global path
		global title
		global mode
		global clicked
		global drawitems
		global biter
		global eiter
		global citer
		global fiter
		global step
		global currentcurve
		global currentselect
		global currentcolor
		global selectid
		global selectors
		global undostack
		global redostack
		global doubleclick
		global level
		global objects
		global sep
		sep = os.sep
		level = 0
		title = "Untitled"
		currentfile = {"fileinfo":{"filename":"Untitled.swf", "bbox":[500, 500, 0, 0], "fps":50}, "colors":{"gradients":{}, "textures":{}, "images":{}}, "objects":{}, "sprites":{}, "buttons":{}, "actions":[""], "sounds":{}, "frames":[[0], {"sort":[], "sounds":[]}]}
		objects = currentfile["objects"]
		theoneroot = root()
		objects["root"]=theoneroot
		objects["root"].frames = currentfile["frames"]
		buff = self.builder.get_object("textview1").get_buffer()
		buff.set_text(str(currentfile))
		libbuff = self.builder.get_object("libview")
		self.set_title("Swift - "+title+".swift")
		currentcolor = [1, 0, 0]
		biter = 0
		eiter = 0
		fiter = 0
		citer = 0
		step = 0
		path = os.environ["HOME"]+sep+"Desktop"+sep
		clicked = False
		doubleclick = False
		selectid=["#000000"]
		selectors=[None]
		undostack=[]
		redostack=[]
		currentselect = ["root", None]

		stage = self.builder.get_object("drawingarea1")
		framewin = self.builder.get_object("drawingarea2")
		stage.show()
		stage.set_size_request(1500, 1500)
		colormap = stage.get_colormap()
		red = colormap.alloc_color('#FF0000', True, True)
		stagedraw = stage.window
		gc = stagedraw.new_gc(red)
		drawitems[1] = "drawBox(gc, stagedraw, 23, 42, 256, 365)"
		stage.connect("expose-event", expostagevent)
		expostagevent(stage, "expose-event")
		exposeframevent(framewin, "expose-event")
		self.liblist.clear()
		

	def run_file(self, widget, data=None):
		global currentfile
		global path
		global title
		global outputwin
		global err
		global win
		global outbox
		global outbuffer
		global level
		output = ""
		err = ""
		
		ftextbuf = self.builder.get_object("textview2").get_buffer()
		currentfile["actions"][currentfile["frames"][0].index(currentframe[level])]= str(ftextbuf.get_text(ftextbuf.get_start_iter(), ftextbuf.get_end_iter()))
		'''
		text = ".flash filename=\""+title+".swf\"\n.end"
		currentfile[0] = ".flash filename=\""+title+".swf\""
		savestring = ""
		for i in currentfile:
			savestring = savestring+str(i)+"\n"
		savefile = gio.File(path+title+".sct")
		gio.File.create(savefile)
		fc = open(path+title+".sct", "w")
		fc.write(savestring)
		fc.flush()
		fc.close()
		os.chdir(path)
		os.system("swfc "+title+".sct")
		os.system("rm "+path+title+".sct")
		os.system("swfdec-player "+path+title+".swf")
		'''
		output = output+".flash filename=\""+title+".swf\" fps="+str(currentfile["fileinfo"]["fps"])+" bbox="+str(currentfile["fileinfo"]["bbox"][0])+"x"+str(currentfile["fileinfo"]["bbox"][1])+"x"+str(currentfile["fileinfo"]["bbox"][2])+"x"+str(currentfile["fileinfo"]["bbox"][1])+"\n"
		for i in currentfile["colors"]["images"]:
			ex = currentfile["colors"]["images"][i].split(".")
			if ex[-1]=="png":
				output = output+".png "+i+" \""+currentfile["colors"]["images"][i]+"\"\n"
			else:
				output = output+".jpg "+i+" \""+currentfile["colors"]["images"][i]+"\"\n"
		for i in currentfile["sounds"]:
			output = output+".sound "+i.replace(" ", "")+" \""+currentfile["sounds"][i]+"\"\n"
		for i in currentfile["colors"]["gradients"]:
			output = output+".gradient "+i+":\n"
			for q in currentfile["colors"]["gradients"][i]:
				output = output+str(int(q[0]*100))+"% "+rgb2hex(q[1], q[2], q[3], q[4])+"\n"
			output = output+".end\n"
		for i in currentfile["colors"]["textures"]:
			if type(currentfile["colors"]["textures"][i]["fill"])==type([]):
				output = output+".texture "+i+"="+rgb2hex(currentfile["colors"]["textures"][i]["fill"][0],currentfile["colors"]["textures"][i]["fill"][1],currentfile["colors"]["textures"][i]["fill"][2])+"\n"
			else:
				output = output+".texture "+i+"="+currentfile["colors"]["textures"][i]["fill"]+"\n"
		for i in currentfile["objects"]:
			ob = currentfile["objects"][i]
			if ob.type=="box":
				if type(currentfile["colors"]["textures"][ob.fill]["fill"])==type([]):
					fill = rgb2hex(currentfile["colors"]["textures"][ob.fill]["fill"][0],currentfile["colors"]["textures"][ob.fill]["fill"][1],currentfile["colors"]["textures"][ob.fill]["fill"][2])
				else:
					fill = str(ob.fill)
				output = output+".box "+i+" width="+str(ob.width)+" height="+str(ob.height)+" fill="+str(fill)+" color=#00000000"+"\n"
			elif ob.type=="ellipse":
				output = output+".outline "+i+"_outline:\n"
				output = output+ellipse2xml(i)+"\n"
				output = output+".end\n"
				if type(currentfile["colors"]["textures"][ob.fill]["fill"])==type([]):
					fill = rgb2hex(currentfile["colors"]["textures"][ob.fill]["fill"][0],currentfile["colors"]["textures"][ob.fill]["fill"][1],currentfile["colors"]["textures"][ob.fill]["fill"][2])
				else:
					fill = str(ob.fill)
				output = output+".filled "+i+" outline="+i+"_outline fill="+fill+"\n"
			elif ob.type=="shape":
				output = output+".outline "+i+"_outline:\n"
				output = output+shape2xml(i)+"\n"
				output = output+".end\n"
				if type(currentfile["colors"]["textures"][ob.fill]["fill"])==type([]):
					fill = rgb2hex(currentfile["colors"]["textures"][ob.fill]["fill"][0],currentfile["colors"]["textures"][ob.fill]["fill"][1],currentfile["colors"]["textures"][ob.fill]["fill"][2])
				else:
					fill = str(ob.fill)
				output = output+".filled "+i+" outline="+i+"_outline fill="+fill+"\n"
			elif ob.type=="button":
				pass
				
			elif ob.type=="movieclip":
				pass
				
		for i in currentfile["objects"]:
			ob = currentfile["objects"][i]	
			if ob.type=="button":
				idlefile = open(os.environ["TEMP"]+sep+"idlefile"+i+".png", "w")
				hoverfile = open(os.environ["TEMP"]+sep+"hoverfile"+i+".png", "w")
				pressedfile = open(os.environ["TEMP"]+sep+"pressedfile"+i+".png", "w")
				hitfile = open(os.environ["TEMP"]+sep+"hitfile"+i+".png", "w")
				idlesurf = cairo.ImageSurface(cairo.FORMAT_ARGB32, ob.width, ob.height)
				hoversurf = cairo.ImageSurface(cairo.FORMAT_ARGB32, ob.width, ob.height)
				pressedsurf = cairo.ImageSurface(cairo.FORMAT_ARGB32, ob.width, ob.height)
				hitsurf = cairo.ImageSurface(cairo.FORMAT_ARGB32, ob.width, ob.height)
				idlecr = cairo.Context(idlesurf)
				hovercr = cairo.Context(hoversurf)
				pressedcr = cairo.Context(pressedsurf)
				hitcr = cairo.Context(hitsurf)
				idlecr.translate(-ob.x, -ob.y)
				hovercr.translate(-ob.x, -ob.y)
				pressedcr.translate(-ob.x, -ob.y)
				hitcr.translate(-ob.x, -ob.y)
				idle = ob.frames[ob.frames[0].index("idle")+1]
				if not "hover" in ob.frames[0]:
					hover = ob.frames[ob.frames[0].index("idle")+1]
				else:
					hover = ob.frames[ob.frames[0].index("hover")+1]
				if not "pressed" in ob.frames[0]:
					pressed = ob.frames[ob.frames[0].index("idle")+1]
				else:
					pressed = ob.frames[ob.frames[0].index("pressed")+1]
				if not "hit" in ob.frames[0]:
					hit = ob.frames[ob.frames[0].index("idle")+1]
				else:
					hit = ob.frames[ob.frames[0].index("hit")+1]
				for j in idle:
					idle[j][j].draw(idlecr, None, None)
				for j in hover:
					hover[j][j].draw(hovercr, None, None)
				for j in pressed:
					pressed[j][j].draw(pressedcr, None, None)
				for j in hit:
					hit[j][j].draw(hitcr, None, None)
				
				idlesurf.write_to_png(idlefile)
				hoversurf.write_to_png(hoverfile)
				pressedsurf.write_to_png(pressedfile)
				hitsurf.write_to_png(hitfile)
				idlefile.flush()
				hoverfile.flush()
				pressedfile.flush()
				hitfile.flush()
				idlefile.close()
				hoverfile.close()
				pressedfile.close()
				hitfile.close()
				output = output+".png idle"+i+" \""+os.environ["TEMP"]+sep+"idlefile"+i+".png\"\n"
				output = output+".png hover"+i+" \""+os.environ["TEMP"]+sep+"hoverfile"+i+".png\"\n"
				output = output+".png pressed"+i+" \""+os.environ["TEMP"]+sep+"pressedfile"+i+".png\"\n"
				output = output+".png hit"+i+" \""+os.environ["TEMP"]+sep+"hitfile"+i+".png\"\n"
				output = output+".button "+i+"\n.show idle"+i+" as=idle\n"+"\n.show hover"+i+" as=hover\n"+"\n.show pressed"+i+" as=pressed\n.show hit"+i+" as=area\n"+".end\n"

			elif ob.type=="movieclip":
				output = output+".sprite "+ob.name+"\n"
				for i in ob.frames[0]:
					output = output+".frame "+str(i+1)+"\n"
					for j in ob.frames[ob.frames[0].index(i)+1]["sort"]:
						f = ob.frames[ob.frames[0].index(i)+1][j]
						if f["put"]==True:
							output = output+".put "+j+" x="+str(f["x"])+" y="+str(f["y"])+" scalex="+str(f["xscale"]*100)+"% scaley="+str(f["yscale"]*100)+"% rotate="+str(f["rotate"])+"\n"
						else:
							output = output+".change "+j+" x="+str(f["x"])+" y="+str(f["y"])+" scalex="+str(f["xscale"]*100)+"% scaley="+str(f["yscale"]*100)+"% rotate="+str(f["rotate"])+"\n"
					if not ob.actions[ob.frames[0].index(i)]=="":
						output = output+".action:\n"+ob.actions[ob.frames[0].index(i)]+"\n.end\n"
						c = check(ob.actions[currentfile["frames"][0].index(i)])
						if not c==True:
							err = err+c
				output = output+".end\n"

			elif ob.type=="curve":
				output = output+".outline "+i+"_outline:\n"
				output = output+curve2xml(i)+"\n"
				output = output+".end\n"
				output = output+".filled "+i+" outline="+i+"_outline fill="+str(ob.fill)+"\n"
		for i in currentfile["frames"][0]:
			output = output+".frame "+str(i+1)+"\n"
			for j in currentfile["frames"][currentfile["frames"][0].index(i)+1]["sounds"]:
				output = output+".play "+j.replace(" ","")+"\n"
			for j in currentfile["frames"][currentfile["frames"][0].index(i)+1]["sort"]:
				f = currentfile["frames"][currentfile["frames"][0].index(i)+1][j]
				if f["put"]==True:
					output = output+".put "+j+" x="+str(f["x"])+" y="+str(f["y"])+" scalex="+str(f["xscale"]*100)+"% scaley="+str(f["yscale"]*100)+"% rotate="+str(f["rotate"])+"\n"
				else:
					output = output+".change "+j+" x="+str(f["x"])+" y="+str(f["y"])+" scalex="+str(f["xscale"]*100)+"% scaley="+str(f["yscale"]*100)+"% rotate="+str(f["rotate"])+"\n"
					
			if not currentfile["actions"][currentfile["frames"][0].index(i)]=="":
				output = output+".action:\n"+currentfile["actions"][currentfile["frames"][0].index(i)]+"\n.end\n"
				c = check(currentfile["actions"][currentfile["frames"][0].index(i)])
				if not c==True:
					err = err+c
		output = output+".end"
		savefile = gio.File(path+title+".sct")
		gio.File.create(savefile)
		fc = open(path+title+".sct", "w")
		fc.write(output)
		fc.flush()
		fc.close()
		#os.system("swfc -o"+path+title+".swf "+path+title+".sct")
		compile = subprocess.Popen(SWFC_PATH+" -o "+path+title+".swf "+path+title+".sct", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=(os.sep=="/"))
		stdino, stdouterro = (compile.stdin, compile.stdout)
		print stdouterro.read()
		os.remove(path+title+".sct")
		#q = os.system("gnash -v "+path+title+".swf &")
				
		gobject.threads_init()
		gtk.gdk.threads_init()

		encoding = locale.getpreferredencoding()
		utf8conv = lambda x : unicode(x, encoding).encode('utf8')
		
		def on_output_close(dummy, dummy1):
			global outputwin
			outputwin = False
		def read_output(view, buffer, command):
			global err
			print "err: "+ err
			#stdin, stdouterr = os.popen4(command)
			p = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=(os.sep=="/"))
			(stdin, stdouterr) = (p.stdin, p.stdout)
			tracing = False
			while 1:
				line = stdouterr.readline()
				if not line:
					break
				if line[18:19] == "S" or line[18:19] == "U":
					line = ""
				else:
					line = line+"%"
					line = line[0:-1]
					if "TRACE: " in line:
						line = line[line.index("TRACE: ")+7:-1]+"\n"
						if tracing==False:
							line = "\n\n\n ----- BEGIN TRACE ----- \n\n\n"+line
							tracing=True
					elif "SECURITY: " in line:
						line = line[line.index("SECURITY: ")+10:-1]+"\n\n"
					elif "UNIMPLEMENTED: " in line:
						line = line[line.index("UNIMPLEMENTED: "):-1]
				if not err == "":
					line = err+"\n"+line
					err = ""
				gtk.gdk.threads_enter()
				iter = buffer.get_end_iter()
				buffer.place_cursor(iter)
				buffer.insert(iter, utf8conv(line))
				view.scroll_to_mark(buffer.get_insert(), 0.1)
				gtk.gdk.threads_leave()
		
		if outputwin==False:
			sw = gtk.ScrolledWindow()
			sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
			outbox = gtk.TextView()
			outbox.set_editable(False)
			outbox.set_cursor_visible(False)
			outbox.set_wrap_mode(gtk.WRAP_WORD_CHAR)
			outbuffer = outbox.get_buffer()
			sw.add(outbox)
			win = gtk.Window()
			win.resize(300,500)
			win.set_title("Output")
			win.connect('delete-event', on_output_close)
			#command = "gnash -v "+path+title+".swf"
			vbox = gtk.VBox()
			vbox.pack_start(sw)
			win.add(vbox)
			win.show_all()
			outputwin=True
		else:
			win.present()
		thr = threading.Thread(target= read_output, args=(outbox, outbuffer, GNASH_PATH+" -v "+path+title+".swf"))
		thr.start()

	def open_sc_file(self, widget, data=None):
		alert("Not implemented yet.")

	def import_file(self, widget, data=None):
		global title
		global path
		global currentfile
		global objects
		#run the open dialog
		importer = ImportDialog.NewImportDialog()
		result = importer.run()
		filename = importer.get_filename()
		f=filename.split("/")[-1].split(".")
		tdict = {"image":["png", "jpg", "jpeg", "gif", "pbm", "pgm", "ppm", "tiff", "tga", "rast", "xbm", "bmp"], "sound":["wav", "mp3"]}
		if f[-1] in tdict["image"]:
			filetype="image"
		elif f[-1] in tdict["sound"]:
			filetype="sound"
		else:
			filetype="unknown"
		if filetype=="image":
			if not imghdr.what(filename)=="png":
				Image.open(filename).save(os.environ["TEMP"]+sep+"swift"+str(pid)+sep+f[0]+".png")
				filename = os.environ["TEMP"]+sep+"swift"+str(pid)+os.sep+filename.split(os.sep)[-1].split(".")[0]+".png"
		elif filetype=="sound":
			mplayer_exe_name = 'mplayer' if os.sep == '/' else 'mplayer.exe'
			os.system(mplayer_exe_name+" -nolirc \""+filename+"\" -ao pcm:file='"+os.environ["TEMP"]+os.sep+"swift"+str(pid)+os.sep+f[0]+".wav' -vc dummy -aid 1 -vo null")
			filename = os.environ["TEMP"]+sep+"swift"+str(pid)+os.sep+f[0]+".wav"
			
			
			
		f=filename.split("/")[-1].split(".")
		if f[0][0].isdigit():
				alert("First character of filename is a digit!! Changing to \"i\".")
				f[0] = "i"+f[0][1:]
		g=f[0]
		if filetype=="image":
			currentfile["colors"]["images"][g]=filename
			currentfile["colors"]["textures"][g]={"type":"image", "fill":g}
		elif filetype=="sound":
			currentfile["sounds"][g]=filename
		entry=join(f, ".")
		image = gtk.Image()
		image.set_from_file("../media/icon.png")
		image.show()
		self.AddLibItem([image,  entry, "1"])
		importer.destroy()
		return (filename, filetype)
	def import_file_to_stage(self, widget, data=None):
		stage = self.builder.get_object("drawingarea1")
		(filename, filetype) = self.import_file(widget, data)
		newname = filename.split("/")[-1].split(".")[0]
		print filename, filetype
		if filetype=="image":
			try:
				im = Image.open(filename)
			except IOError:
				alert(filename+" is not a valid image file!")
			else:
				size = im.size
				if newname[0].isdigit():
					newname = "i"+newname[1:]
				if not newname+"b" in objects:
					# CHANGE THE PARENT TO BE THE APPROPRIATE OBJECT
					objects[newname+"b"] = box(newname+"b", size[0], size[1], "root", newname)
					for i in range(1, len(objects[objects[newname+"b"].parent].frames)):
						objects[objects[newname+"b"].parent].frames[i]["sort"].append(newname+"b")
						objects[objects[newname+"b"].parent].frames[i][newname+"b"] = {"x":0, "y":0, "rotate":0, "xscale":1.0, "yscale":1.0}
						if i==1:
							objects[objects[newname+"b"].parent].frames[i][newname+"b"]["put"] = True
					selectid.append("#01"+("%X" % (int(selectid[-1][3:7], 16)+1)).zfill(4))
					selectors.append(newname+"b")
					expostagevent(stage, "expose-event")
				else:
					alert("There is already an object called "+newname+" in the current project. I will just abandon this attempt because the alert window only has one button.")
		elif filetype=="sound":
			print "Hey!"
			if newname[0].isdigit():
				newname = "i"+newname[1:]
			objects["root"].frames[1]["sounds"].append(newname)
			pass

	def draw_rect(self, widget, data=None):
		global mode
		global currentframe
		global currentfile
		if currentframe[level] in currentfile["frames"][0]:
			mode = "r"
			stage = self.builder.get_object("drawingarea1")
			cursor = gtk.gdk.Cursor(gtk.gdk.CROSSHAIR)
			stage.window.set_cursor(cursor)
	def draw_ellipse(self, widget, data=None):
		global mode
		global currentframe
		global currentfile
		if currentframe[level] in currentfile["frames"][0]:
			mode = "e"
			stage = self.builder.get_object("drawingarea1")
			cursor = gtk.gdk.Cursor(gtk.gdk.CROSSHAIR)
			stage.window.set_cursor(cursor)
	def draw_text(self, widget, data=None):
		global mode
		global currentframe
		global currentfile
		if currentframe[level] in currentfile["frames"][0]:
			mode = "t"
			stage = self.builder.get_object("drawingarea1")
			cursor = gtk.gdk.Cursor(gtk.gdk.XTERM)
			stage.window.set_cursor(cursor)
		
	def stage_action(self, widget, data=None):
		global clicked
		global middleclick
		global mode
		global startmouse
		if clicked == True or mode=="c":
			stage = self.builder.get_object("drawingarea1")
			expostagevent(stage, "expose-event")
		elif middleclick == True:
			stage = self.builder.get_object("drawingarea1")
			hresadjust = self.builder.get_object("scrolledwindow1").get_hadjustment()
			hresadjust.set_value(startmouse[0]-self.builder.get_object("scrolledwindow1").get_pointer()[0])
			self.builder.get_object("scrolledwindow1").set_hadjustment(hresadjust)
			vresadjust = self.builder.get_object("scrolledwindow1").get_vadjustment()
			vresadjust.set_value(startmouse[1]-self.builder.get_object("scrolledwindow1").get_pointer()[1])
			self.builder.get_object("scrolledwindow1").set_vadjustment(vresadjust)
			expostagevent(stage, "expose-event")

	def stage_click(self, widget, data=None):
		pass
	'''def stage_click(self, widget, data=None):
		global clicked
		global first
		global startmouse
		global currentframe
		global currentfile
		global currentselect
		global undostack
		global redostack
		global pixmap
		global colormap
		global doubleclick
		global selectdepth
		global level
		if currentframe[level] in currentfile["frames"][0]:
			clicked=True
			first=True
			startmouse = self.builder.get_object("drawingarea1").get_pointer()
			undostack.append(copy.deepcopy(currentfile))
			if mode=="c":
				cc=(startmouse[0], startmouse[1])
				currentcurve.append(cc)
				expostagevent(self.builder.get_object("drawingarea1"), "exposevent")
			elif mode==" ":
				checktest = False
				\'''for i in currentfile["frames"][currentfile["frames"][0].index(currentframe)+1]["sort"]:
					if currentfile["objects"][i]["type"]=="box" or currentfile["objects"][i]["type"]=="ellipse":
						ref=currentfile["frames"][currentfile["frames"][0].index(currentframe)+1][i]
						if startmouse[0]>ref["x"] and startmouse[0]<ref["x"]+currentfile["objects"][i]["width"] and startmouse[1]>ref["y"] and startmouse[1]<ref["y"]+currentfile["objects"][i]["height"]:
							currentselect = i
							checktest=True
				\'''
				def get_pixel_color(i_x, i_y):
					import gtk # python-gtk2
					o_gdk_pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, 1, 1)
					o_gdk_pixbuf.get_from_drawable(pixmap, colormap, i_x, i_y, 0, 0, 1, 1)
					return tuple(o_gdk_pixbuf.get_pixels_array().tolist()[0][0])
				pixcol = get_pixel_color(startmouse[0], startmouse[1])
				rgbpixcol = ("#"+str(pixcol[0]).zfill(2)+str(pixcol[1]).zfill(2)+str(pixcol[2]).zfill(2))
				print rgbpixcol
				currentselect[level+1] = selectors[selectid.index(rgbpixcol)]
				if doubleclick==True:
					if not currentselect[level+1]==None:
						if currentselect[level+1] in currentfile["objects"] and (currentfile["objects"][currentselect[level+1]].type == "button" or currentfile["objects"][currentselect[level+1]].type == "movieclip"):
							level+=1
							print level
							if len(currentselect)-1<level:
								currentselect.append(None)
							else:
								currentselect[level+1]=None
							currentframe.append(1)
				expostagevent(self.builder.get_object("drawingarea1"), "exposevent")
				self.builder.get_object("drawingarea1").grab_focus()'''
			
	def stage_unclick(self, widget, data=None):
		global clicked
		global middleclick
		global mode
		global currentframe
		global currentfile
		global biter
		global eiter
		global siter
		global selectid
		global selectors
		global undostack
		global currentselect
		global level
		global brushlocs
		global pmode
		if currentframe[level] in objects[currentselect[level]].frames[0]:
			clicked=False
			middleclick=False	
			if mode == "r":
				if startmouse[0]<stage.get_pointer()[0]:
					x = startmouse[0]+objects[currentselect[level]].x
					w = stage.get_pointer()[0]-x+objects[currentselect[level]].x
				else:
					x = stage.get_pointer()[0]+objects[currentselect[level]].x
					w = startmouse[0]-x+objects[currentselect[level]].x
				if startmouse[1]<stage.get_pointer()[1]:
					y = startmouse[1]+objects[currentselect[level]].y
					h = stage.get_pointer()[1]-y+objects[currentselect[level]].y
				else:
					y = stage.get_pointer()[1]+objects[currentselect[level]].y
					h = startmouse[1]-y+objects[currentselect[level]].y
				if type(currentcolor)==type([]):
					newcolor = "rgb"+rgb2hex(currentcolor[0], currentcolor[1], currentcolor[2])[1:]
					currentfile["colors"]["textures"][newcolor]={"type":"color", "fill":[currentcolor[0], currentcolor[1], currentcolor[2]]}
					currentfile["objects"]["b"+str(biter)]=box("b"+str(biter), w, h, currentselect[level], newcolor)
				else:
					currentfile["objects"]["b"+str(biter)]=box("b"+str(biter), w, h, currentselect[level], currentcolor)
				selectid.append("#01"+("%X" % (int(selectid[-1][3:7], 16)+1)).zfill(4))
				selectors.append("b"+str(biter))
				for i in range(objects[currentselect[level]].frames[0].index(currentframe[level]), len(objects[currentselect[level]].frames[0])):
					objects[currentselect[level]].frames[i+1]["b"+str(biter)]={"put":True, "x":x, "y":y, "rotate":0, "xscale":1.0, "yscale":1.0, "b"+str(biter):objects["b"+str(biter)]}
					objects[currentselect[level]].frames[i+1]["sort"].append("b"+str(biter))
				biter += 1
			elif mode == "e":
				if startmouse[0]<stage.get_pointer()[0]:
					x = startmouse[0]+objects[currentselect[level]].x
					w = stage.get_pointer()[0]-x+objects[currentselect[level]].x
				else:
					x = stage.get_pointer()[0]+objects[currentselect[level]].x
					w = startmouse[0]-x+objects[currentselect[level]].x
				if startmouse[1]<stage.get_pointer()[1]:
					y = startmouse[1]+objects[currentselect[level]].y
					h = stage.get_pointer()[1]-y+objects[currentselect[level]].y
				else:
					y = stage.get_pointer()[1]+objects[currentselect[level]].y
					h = startmouse[1]-y+objects[currentselect[level]].y
				if type(currentcolor)==type([]):
					currentfile["objects"]["e"+str(eiter)]=ellipse("e"+str(eiter), w, h, currentselect[level], rgb2hex(currentcolor[0], currentcolor[1], currentcolor[2]))
				else:
					currentfile["objects"]["e"+str(eiter)]=ellipse("e"+str(eiter), w, h, currentselect[level], currentcolor)
				
				selectid.append("#02"+("%X" % (int(selectid[-1][3:7], 16)+1)).zfill(4))
				selectors.append("e"+str(eiter))
				for i in range(objects[currentselect[level]].frames[0].index(currentframe[level]), len(objects[currentselect[level]].frames[0])):
					objects[currentselect[level]].frames[i+1]["e"+str(eiter)]={"put":True, "x":x, "y":y, "rotate":0, "xscale":1.0, "yscale":1.0, "e"+str(eiter):objects["e"+str(eiter)]}
					objects[currentselect[level]].frames[i+1]["sort"].append("e"+str(eiter))
				eiter += 1
			elif mode=="p":
				curvedata = brushlocs
				curvedata = simplify_curve(curvedata)
				shapedata=[["M", curvedata[0][0], curvedata[0][1]]]
				if pmode=="straight" or pmode=="ink":
					for i in range(1, len(curvedata)):
						shapedata.append(["L", curvedata[i][0], curvedata[i][1]])
				else:
					#curvedata = [[0,0], [100,0], [100,100], [0, 100]]
					shapedata=[["M", curvedata[0][0], curvedata[0][1]]]
					for i in range(1, len(curvedata), 1):
						#
						#
						#
						#
						#		CONFUSING MATH NEEDED - see http://www.efg2.com/Lab/Graphics/Jean-YvesQueinecBezierCurves.htm
						#
						#
						#
						#
						#
						if i>1:
							a = point(curvedata[i-2])
						else:
							a = point(curvedata[i])
						if i>0:
							b = point(curvedata[i-1])
						else:
							b = point(curvedata[i])
						c = point(curvedata[i])
						if i<(len(curvedata)-1):
							d = point(curvedata[i+1])
						else:
							d = point(curvedata[i])
						e = point((b.x-a.x+c.x, b.y-a.y+c.y))
						f = point((c.x-d.x+b.x, c.y-d.y+b.y))
						g = point((ave(e.x, b.x, 0.5), ave(e.y, b.y, 0.2)))
						h = point((ave(f.x, c.x, 0.5), ave(f.y, c.y, 0.2)))
						shapedata.append(["C", g.x, g.y, h.x, h.y, c.x, c.y])
						
				if type(currentcolor)==type([]):
					newcolor = "rgb"+rgb2hex(currentcolor[0], currentcolor[1], currentcolor[2])[1:]
					currentfile["colors"]["textures"][newcolor]={"type":"color", "fill":[currentcolor[0], currentcolor[1], currentcolor[2]]}
					currentfile["objects"]["s"+str(siter)]=shape("s"+str(siter), 0, 0, currentselect[level], newcolor, shapedata, False)
				else:
					currentfile["objects"]["s"+str(siter)]=shape("s"+str(siter), 0, 0, currentselect[level], currentcolor, shapedata, False)
				selectid.append("#03"+("%X" % (int(selectid[-1][3:7], 16)+1)).zfill(4))
				selectors.append("s"+str(siter))
				for i in range(objects[currentselect[level]].frames[0].index(currentframe[level]), len(objects[currentselect[level]].frames[0])):
					objects[currentselect[level]].frames[i+1]["s"+str(siter)]={"put":True, "x":0, "y":0, "rotate":0, "xscale":1.0, "yscale":1.0, "s"+str(siter):objects["s"+str(siter)]}
					objects[currentselect[level]].frames[i+1]["sort"].append("s"+str(siter))
				siter+=1
				brushlocs=[]
				expostagevent(self.builder.get_object("drawingarea1"), "expose-event")
				print currentfile["objects"]
			
	def click_frame(self, widget, data=None):
		global currentframe
		global objects
		global level
		global currentselect
		textview = self.builder.get_object("textview2")
		ftextbuf = textview.get_buffer()
		try:
			if textview.get_editable()==True:
				objects[currentselect[level]].actions[objects[currentselect[level]].frames[0].index(currentframe[level])]= str(ftextbuf.get_text(ftextbuf.get_start_iter(), ftextbuf.get_end_iter()))
		except:
			d = "d"
		px = self.builder.get_object("drawingarea2").get_pointer()[0]
		currentframe[level] = int(px/16)
		try:
			ftextbuf.set_text(objects[currentselect[level]].actions[objects[currentselect[level]].frames[0].index(currentframe[level])])
			textview.set_editable(True)
			textview.set_cursor_visible(True)
		except:
			ftextbuf.set_text("Actions cannot be applied to this frame.")
			textview.set_editable(False)
			textview.set_cursor_visible(False)
		finally:
			expostagevent(self.builder.get_object("drawingarea1"), "expose-event")
	def play_frames(self, widget, data=None):
		global currentframe
		global currentfile
		global currentcurve
		global mode
		global citer
		global objects
		global level
		global playing
		global sounds
		if data==None:
			playing=True
		if mode=="c":
			for i in range(len(objects[currentselect[level]].frames[0])):
				objects[currentselect[level]].frames[i+1]["sort"].append("c"+str(citer))
				objects[currentselect[level]].frames[i+1]["c"+str(citer)]={"put":True, "x":0, "y":0, "rotate":0}				
			currentfile["objects"]["c"+str(citer)]={"type":"curve", "points":currentcurve, "outline":str(self.builder.get_object("colorbutton1").get_color())}
			currentcurve=[]
			citer+=1
		else:
			stage=self.builder.get_object("drawingarea1")
			expostagevent(stage, "expose-event")
			fwin = self.builder.get_object("scrolledwindow2")
			hadj = fwin.get_hadjustment()
			hadj.set_value(currentframe[level]*16-hadj.page_size/2)
			exposeframevent(self.builder.get_object("drawingarea2"), "expose-event")
			if currentframe[level] in objects[currentselect[level]].frames[0]:
				for i in objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1]["sounds"]:
					if not i in sounds:
						sounds[i] = mplayer.MPlayer()
						sounds[i].command("loadfile", currentfile["sounds"][i])
			if (playing==True or data==None) and currentframe[level]<objects[currentselect[level]].frames[0][-1]:
				source_id = gobject.timeout_add(1000/currentfile["fileinfo"]["fps"], self.play_frames, widget, True)
				currentframe[level]+=1
			elif data==None and currentframe[level]==objects[currentselect[level]].frames[0][-1]:
				source_id = gobject.timeout_add(1000/currentfile["fileinfo"]["fps"], self.play_frames, widget, True)
				currentframe[level]=0
			else:
				playing=False
				for i in sounds:
					sounds[i].command("quit")
					del sounds[i]
	def next_frame(self, widget, data=None):
		global currentframe
		global currentfile
		global objects
		global level
		if currentframe[level]<objects[currentselect[level]].frames[0][-1]:
			currentframe[level] += 1
			stage=self.builder.get_object("drawingarea1")
			expostagevent(stage, "expose-event")
	def last_frame(self, widget, data=None):
		global currentframe
		if currentframe[level]>0:
			currentframe[level] -= 1
			stage=self.builder.get_object("drawingarea1")
			expostagevent(stage, "expose-event")
	def paint_bucket(self, widget, data=None):
		global mode
		global currentframe
		if currentframe[level] in currentfile["frames"][0]:
			mode = "b"
			pixbuf = gtk.gdk.pixbuf_new_from_file(getdatapath()+sep+"media"+sep+"cursor_paintbucket.png")
			display = gtk.gdk.display_get_default()
			cursor = gtk.gdk.Cursor(display, pixbuf, 0, 0)
			stage = self.builder.get_object("drawingarea1")
			stage.window.set_cursor(cursor)
	def paint_brush(self, widget, data=None):
		global mode
		global currentframe
		print "KSJUFG"
		if currentframe[level] in currentfile["frames"][0]:
			mode = "p"
			pixbuf = gtk.gdk.pixbuf_new_from_file(getdatapath()+sep+"media"+sep+"cursor_paintbrush.png")
			display = gtk.gdk.display_get_default()
			cursor = gtk.gdk.Cursor(display, pixbuf, 0, 0)
			stage = self.builder.get_object("drawingarea1")
			stage.window.set_cursor(cursor)
	def draw_curve(self, widget, data=None):
		global mode
		global currentframe
		if currentframe[level] in currentfile["frames"][0]:
			mode = "c"
			pixbuf = gtk.gdk.pixbuf_new_from_file(getdatapath()+sep+"media"+sep+"cursor_curve.png")
			display = gtk.gdk.display_get_default()
			cursor = gtk.gdk.Cursor(display, pixbuf, 0, 0)
			stage = self.builder.get_object("drawingarea1")
			stage.window.set_cursor(cursor)
	def resize_any(self, widget, data=None):
		global mode
		if currentframe[level] in currentfile["frames"][0]:
			mode = "s"
			pixbuf = gtk.gdk.pixbuf_new_from_file(getdatapath()+sep+"media"+sep+"cursor_resize.png")
			display = gtk.gdk.display_get_default()
			cursor = gtk.gdk.Cursor(display, pixbuf, 0, 0)
			stage = self.builder.get_object("drawingarea1")
			stage.window.set_cursor(cursor)
		print "Enter resize mode"
	def select_any(self, widget, data=None):
		global mode
		global playing
		playing = False
		mode = " "
		arrow = gtk.gdk.Cursor(gtk.gdk.ARROW)
		stage = self.builder.get_object("drawingarea1")
		stage.window.set_cursor(arrow)
		print "Enter select mode"
	def delete_item(self, widget, data=None):
		global currentfile
		global currentframe
		global currentselect
		global level
		if currentframe[level+1] in currentfile["frames"][0]:
			if currentselect[level+1] in currentfile["frames"][currentfile["frames"][0].index(currentframe[level])+1]:
				del currentfile["frames"][currentfile["frames"][0].index(currentframe[level])+1][currentselect[level+1]]
				del currentfile["frames"][currentfile["frames"][0].index(currentframe[level])+1]["sort"][currentfile["frames"][currentfile["frames"][0].index(currentframe[level+1])+1]["sort"].index(currentselect[level+1])]
				currentselect[level+1]=None
				expostagevent(self.builder.get_object("drawingarea1"), "expose-event")
	def send_to_back(self, widget, data=None):
		global currentselect
		global currentfile
		global level
		if not currentselect[level]==None:
			for j in range (len(currentfile["frames"])-1):
				s = currentfile["frames"][j+1]["sort"]
				i = currentselect[level+1]
				del s[s.index(i)]
				prePend(s, i)
			expostagevent(self.builder.get_object("drawingarea1"), "expose-event")
		return
	def send_backwards(self, widget, data=None):
		global currentselect
		global currentfile
		global level
		if not currentselect[level]==None:
			for j in range (len(currentfile["frames"])-1):
				s = currentfile["frames"][j+1]["sort"]
				i = currentselect[level+1]
				k = s.index(i)
				del s[k]
				if k<1:
					k=1
				s.insert(k-1, i)
			expostagevent(self.builder.get_object("drawingarea1"), "expose-event")
		return
				
	def bring_forwards(self, widget, data=None):
		global currentselect
		global currentfile
		if not currentselect[level]==None:
			for j in range (len(currentfile["frames"])-1):
				s = currentfile["frames"][j+1]["sort"]
				i = currentselect[level+1]
				k = s.index(i)
				del s[k]
				if k>len(s):
					k=len(s)
				s.insert(k+1, i)
			expostagevent(self.builder.get_object("drawingarea1"), "expose-event")
		return	
	def bring_to_front(self, widget, data=None):
		global currentselect
		global currentfile
		if not currentselect[level]==None:
			for j in range (len(currentfile["frames"])-1):
				s = currentfile["frames"][j+1]["sort"]
				i = currentselect[level+1]
				del s[s.index(i)]
				s.append(i)
			expostagevent(self.builder.get_object("drawingarea1"), "expose-event")
		return
	def fillColor(self, widget, data=None):
		global cwindow
		global currentcolor
		cwindow = gtk.Window(type=gtk.WINDOW_TOPLEVEL)
		def focus_out_event(widget, event):
			cwindow.destroy()
			return True
		def expose_event(widget, event):
			cr = widget.window.cairo_create()
			cr.set_source_rgb(0,0,0)
			cr.paint()
			carray = colors.colorArray()
			for i in range(len(carray)):
				for j in range(len(carray[i])):
					drawcrBox(cr, i*15, j*15, 14, 14, 1, carray[i][j], 0, [1, 1, 1, 0])
			q=0
			for i in currentfile["colors"]["textures"]:
				if currentfile["colors"]["textures"][i]["type"]=="image":
					cr.save()
					surface = cairo.ImageSurface.create_from_png(currentfile["colors"]["images"][currentfile["colors"]["textures"][i]["fill"]])
					cr.translate(q*15, 180)
					cr.scale(15.0/surface.get_width(), 15.0/surface.get_height())
					q=q+1
					pattern = cairo.SurfacePattern(surface)
					cr.set_source(pattern)
					cr.paint()
					cr.restore()
		def button_release_event(widget, event):
			global currentcolor
			mouse = drawing_area.get_pointer()
			carray = colors.colorArray()
			if int(mouse[1]/15)<12:
				currentcolor = carray[int(mouse[0]/15)][int(mouse[1]/15)]
			else:
				q = mouse[0]/15
				z = 0
				for i in currentfile["colors"]["textures"]:
					if currentfile["colors"]["textures"][i]["type"]=="image":
						if z==q:
							currentcolor = i
							break;
						else:
							z+=1
			color=self.builder.get_object("fillcolor")
			exposecolorevent(color, "expose-event")
			cwindow.destroy()
			return True
		cwindow.set_events(gtk.gdk.ALL_EVENTS_MASK);
		cwindow.connect("focus_out_event", focus_out_event)
		cwindow.connect("button_release_event", button_release_event)
		cwindow.set_decorated(False)
		cwindow.grab_focus()
		cwindow.set_position(gtk.WIN_POS_MOUSE)
		cwindow.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_MENU)
		cwindow.set_resizable(False)
		cwindow.set_deletable(False)
		cwindow.set_modal(True)
		cwindow.set_property('skip-taskbar-hint',True)
		cwindow.set_default_size(315, 230)
		cwindow.set_size_request(315, 230)
		cwindow.show()
		cwindow.resize(315, 230)
		vbox = gtk.VBox(False, 0)
		cwindow.add(vbox)
		vbox.show()
		hbox = gtk.HBox(False, 0)
		vbox.pack_start(hbox, False, True, 0)
		hbox.show()
		preview_area = gtk.DrawingArea()
		preview_area.set_size_request(20, 30)
		hbox.pack_start(preview_area, False, False)
		preview_area.show()
		drawing_area = gtk.DrawingArea()
		drawing_area.set_size_request(315, 150)
		vbox.pack_start(drawing_area, True, True, 0)
		drawing_area.show()
		drawing_area.grab_focus()
		drawing_area.connect("expose_event", expose_event)
		drawing_area.set_events(gtk.gdk.EXPOSURE_MASK
							| gtk.gdk.LEAVE_NOTIFY_MASK
							| gtk.gdk.BUTTON_PRESS_MASK
							| gtk.gdk.POINTER_MOTION_MASK
							| gtk.gdk.POINTER_MOTION_HINT_MASK)
	def add_keyframe(self, widget, data=None):
		global currentfile
		global currentframe
		global undostack
		global objects
		global MAX_FRAMES
		textview = self.builder.get_object("textview2")
		ftextbuf = textview.get_buffer()
		undostack.append(copy.deepcopy(currentfile))
		if not (currentframe[level] in objects[currentselect[level]].frames[0]):
			framenum=0
			for i in objects[currentselect[level]].frames[0]:
				if i<currentframe[level]:
					framenum+=1
			objects[currentselect[level]].frames[0].insert(framenum, currentframe[level])
			objects[currentselect[level]].frames.insert(framenum+1, {})
			objects[currentselect[level]].actions.insert(framenum, "")
			for i in objects[currentselect[level]].frames[framenum]:
				q=copy.deepcopy(objects[currentselect[level]].frames[framenum][i])
				objects[currentselect[level]].frames[framenum+1][i]=q
				q=False
			for i in objects[currentselect[level]].frames[framenum+1]["sort"]:
				objects[currentselect[level]].frames[framenum+1][i]["put"]=False
			objects[currentselect[level]].frames[framenum+1]["sounds"]=[]
			print objects[currentselect[level]].frames[framenum+1]
		ftextbuf.set_text(objects[currentselect[level]].actions[objects[currentselect[level]].frames[0].index(currentframe[level])])
		textview.set_editable(True)
		textview.set_cursor_visible(True)
		stage=self.builder.get_object("drawingarea1")
		expostagevent(stage, "expose-event")
		print MAX_FRAMES, currentframe[level]
		if currentframe[level]>MAX_FRAMES*0.75:
			MAX_FRAMES = MAX_FRAMES*2
			print MAX_FRAMES
			frameframe = self.get_toplevel().builder.get_object("drawingarea2")
			frameframe.set_size_request(16*MAX_FRAMES, 32)
		print objects[currentselect[level]].frames
	def convert_to_symbol(self, widget, data=None):
		global currentfile
		global currentframe
		global undostack
		global currentselect
		global selectid
		global selectors
		global level
		global objects
		undostack.append(copy.deepcopy(currentfile))
		if not currentselect[level]==None:
			def okbutton_press_event(widget, event):
				global currentselect
				name = tarea.get_text()
				global retval
				for i in radlist:
					if i.get_active():
						retval = radlist.index(i)
				if not name in objects:
					x = objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["x"]
					y = objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["y"]
					xscale = objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["xscale"]
					yscale = objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["yscale"]
					rotate = objects[currentselect[level]].frames[objects[currentselect[level]].frames[0].index(currentframe[level])+1][currentselect[level+1]]["rotate"]
					if retval == 0:
						currentfile["objects"][name]=MovieClip(name)
						objects[name].frames[1] = {"sort":[currentselect[level+1]], currentselect[level+1]:{currentselect[level+1]:currentfile["objects"][currentselect[level+1]], "x":0, "y":0, "rotate":0, "xscale":1.0, "yscale":1.0, "put":True}}
						objects[currentselect[level+1]].level=objects[currentselect[level+1]].level+1
						objects[currentselect[level+1]].parent=name
						objects[name].width = objects[currentselect[level+1]].width
						objects[name].height = objects[currentselect[level+1]].height
						objects[name].x = x
						objects[name].y = y
						objects[name].rotate = rotate
						objects[name].xscale = xscale
						objects[name].yscale = yscale
					elif retval == 1:
						currentfile["objects"][name]=button(name)
						objects[name].frames[objects[name].frames[0].index("idle")+1] = {"sort":[currentselect[level+1]], currentselect[level+1]:{currentselect[level+1]:currentfile["objects"][currentselect[level+1]], "x":0, "y":0, "xscale":1.0, "yscale":1.0, "rotate":0}}
						objects[currentselect[level+1]].level=objects[currentselect[level+1]].level+1
						objects[currentselect[level+1]].parent=name
						objects[name].width = objects[currentselect[level+1]].width
						objects[name].height = objects[currentselect[level+1]].height
						objects[name].x = x
						objects[name].y = y
						objects[name].rotate = rotate
					for i in range(len(currentfile["frames"][0])):
						if currentselect[level+1] in currentfile["frames"][i+1]:
							del currentfile["frames"][i+1][currentselect[level+1]]
							del currentfile["frames"][i+1]["sort"][currentfile["frames"][i+1]["sort"].index(currentselect[level+1])]
							currentfile["frames"][i+1][name]={"put":True, "x":x, "y":y, "xscale":1.0, "yscale":1.0, "rotate":0} 
							currentfile["frames"][i+1]["sort"].append(name)
					selectid.append("#05"+("%X" % (int(selectid[-1][3:7], 16)+1)).zfill(4))
					selectors.append(name)
					dialog.destroy()
					currentselect[level+1]=name
					expostagevent(self.builder.get_object("drawingarea1"), "expose-event")
					image = gtk.Image()
					image.set_from_file("../media/icon.png")
					image.show()
					libarea = self.builder.get_object("libarea")
					expostagevent(libarea, "expose-event")
					self.AddLibItem([image, name, "1"])
				else:
					alert("The name "+name+" is already taken. Please use a different name.")
			def cancelbutton_press_event(widget, event):
				dialog.destroy()
			dialog = gtk.Window(type=gtk.WINDOW_TOPLEVEL)
			dialog.set_position(gtk.WIN_POS_CENTER)
			dialog.set_transient_for(self.get_toplevel())
			dialog.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DIALOG)
			dialog.set_destroy_with_parent(True)
			dialog.set_modal(True)
			dialog.set_title("Convert to Symbol")
			dialog.set_default_size(220, 150)
			vbox = gtk.VBox(False, 0)
			dialog.add(vbox)
			tarea=gtk.Entry(20)
			tarea.set_text("Symbol")
			vbox.pack_start(tarea, False, True, 0)
			tarea.show()
			mov = gtk.RadioButton(None, "Movie Clip")
			but = gtk.RadioButton(mov, "Button")
			gra = gtk.RadioButton(mov, "Graphic")
			radlist = [mov, but, gra]
			mov.show()
			but.show()
			gra.show()
			vbox.pack_start(mov, False, True, 0)
			vbox.pack_start(but, False, True, 0)
			vbox.pack_start(gra, False, True, 0)
			hbox = gtk.HBox(False, 0)
			okbutton = gtk.Button("OK")
			okbutton.set_use_stock(True)
			okbutton.set_events(gtk.gdk.ALL_EVENTS_MASK);
			okbutton.connect("button_press_event", okbutton_press_event)
			okbutton.show()
			cancelbutton = gtk.Button("Cancel")
			cancelbutton.set_use_stock(True)
			cancelbutton.set_events(gtk.gdk.ALL_EVENTS_MASK);
			cancelbutton.connect("button_press_event", cancelbutton_press_event)
			cancelbutton.show()
			hbox.pack_start(cancelbutton, False, True, 0)
			hbox.pack_end(okbutton, False, True, 0)
			vbox.pack_start(hbox, False, True, 0)
			hbox.show()
			vbox.show()
			dialog.show()
		else:
			alert("Nothing selected!")
	def undo(self, widget, data=None):
		global currentfile
		global currentframe
		global undostack
		global redostack
		global objects
		print "Undo - "
		for i in undostack:
			print i["objects"]
		try:
			redostack.append(copy.deepcopy(currentfile))
			currentfile=undostack.pop()
			objects = currentfile["objects"]
			if not currentframe[level] in currentfile["frames"][0]:
				currentframe[level]=currentfile["frames"][0][-1]
			expostagevent(self.builder.get_object("drawingarea1"), "expose-event")
		except:
			alert("Nothing to undo!")
	def redo(self, widget, data=None):
		global currentfile
		global undostack
		global redostack
		global objects
		try:
			undostack.append(copy.deepcopy(currentfile))
			currentfile=redostack.pop()
			objects = currentfile["objects"]
			expostagevent(self.builder.get_object("drawingarea1"), "expose-event")
		except:
			alert("Nothing to redo!")
	def export_swf(self, widget, data=None):
		global currentfile
		#global path
		#global title
		global outputwin
		global err
		global win
		global outbox
		global outbuffer
		global level
		output = ""
		err = ""
		
		#get the title from the user
		saver = SaveDialog.NewSaveDialog()
		result = saver.run()
		#Filename includes path
		filename = saver.get_filename()
		patharray = filename.split("/")
		title = patharray.pop()
		titlearray = title.split(".")
		title = titlearray[0] #no extension
		path = ""
		for i in patharray:
			path = path+i+"/"
		saver.destroy()
		ftextbuf = self.builder.get_object("textview2").get_buffer()
		currentfile["actions"][currentfile["frames"][0].index(currentframe[level])]= str(ftextbuf.get_text(ftextbuf.get_start_iter(), ftextbuf.get_end_iter()))
		output = output+".flash filename=\""+title+".swf\" fps="+str(currentfile["fileinfo"]["fps"])+" bbox="+str(currentfile["fileinfo"]["bbox"][0])+"x"+str(currentfile["fileinfo"]["bbox"][1])+"x"+str(currentfile["fileinfo"]["bbox"][2])+"x"+str(currentfile["fileinfo"]["bbox"][1])+"\n"
		for i in currentfile["colors"]["images"]:
			ex = currentfile["colors"]["images"][i].split(".")
			if ex[-1]=="png":
				output = output+".png "+i+" \""+currentfile["colors"]["images"][i]+"\"\n"
			else:
				output = output+".jpg "+i+" \""+currentfile["colors"]["images"][i]+"\"\n"
		for i in currentfile["colors"]["gradients"]:
			output = output+".gradient "+i+":\n"
			for q in currentfile["colors"]["gradients"][i]:
				output = output+str(int(q[0]*100))+"% "+rgb2hex(q[1], q[2], q[3], q[4])+"\n"
			output = output+".end\n"
		for i in currentfile["colors"]["textures"]:
			if type(currentfile["colors"]["textures"][i]["fill"])==type([]):
				output = output+".texture "+i+"="+rgb2hex(currentfile["colors"]["textures"][i]["fill"][0],currentfile["colors"]["textures"][i]["fill"][1],currentfile["colors"]["textures"][i]["fill"][2])+"\n"
			else:
				output = output+".texture "+i+"="+currentfile["colors"]["textures"][i]["fill"]+"\n"
		for i in currentfile["objects"]:
			ob = currentfile["objects"][i]
			if ob.type=="box":
				if type(currentfile["colors"]["textures"][ob.fill]["fill"])==type([]):
					fill = rgb2hex(currentfile["colors"]["textures"][ob.fill]["fill"][0],currentfile["colors"]["textures"][ob.fill]["fill"][1],currentfile["colors"]["textures"][ob.fill]["fill"][2])
				else:
					fill = str(ob.fill)
				output = output+".box "+i+" width="+str(ob.width)+" height="+str(ob.height)+" fill="+str(fill)+" color=#00000000"+"\n"
			elif ob.type=="ellipse":
				output = output+".outline "+i+"_outline:\n"
				output = output+ellipse2xml(i)+"\n"
				output = output+".end\n"
				if type(currentfile["colors"]["textures"][ob.fill]["fill"])==type([]):
					fill = rgb2hex(currentfile["colors"]["textures"][ob.fill]["fill"][0],currentfile["colors"]["textures"][ob.fill]["fill"][1],currentfile["colors"]["textures"][ob.fill]["fill"][2])
				else:
					fill = str(ob.fill)
				output = output+".filled "+i+" outline="+i+"_outline fill="+fill+"\n"
			elif ob.type=="shape":
				output = output+".outline "+i+"_outline:\n"
				output = output+shape2xml(i)+"\n"
				output = output+".end\n"
				if type(currentfile["colors"]["textures"][ob.fill]["fill"])==type([]):
					fill = rgb2hex(currentfile["colors"]["textures"][ob.fill]["fill"][0],currentfile["colors"]["textures"][ob.fill]["fill"][1],currentfile["colors"]["textures"][ob.fill]["fill"][2])
				else:
					fill = str(ob.fill)
				output = output+".filled "+i+" outline="+i+"_outline fill="+fill+"\n"
			elif ob.type=="button":
				pass
				
			elif ob.type=="movieclip":
				pass
				
		for i in currentfile["objects"]:
			ob = currentfile["objects"][i]	
			if ob.type=="button":
				idlefile = open(os.environ["TEMP"]+sep+"idlefile"+i+".png", "w")
				hoverfile = open(os.environ["TEMP"]+sep+"hoverfile"+i+".png", "w")
				pressedfile = open(os.environ["TEMP"]+sep+"pressedfile"+i+".png", "w")
				hitfile = open(os.environ["TEMP"]+sep+"hitfile"+i+".png", "w")
				idlesurf = cairo.ImageSurface(cairo.FORMAT_ARGB32, ob.width, ob.height)
				hoversurf = cairo.ImageSurface(cairo.FORMAT_ARGB32, ob.width, ob.height)
				pressedsurf = cairo.ImageSurface(cairo.FORMAT_ARGB32, ob.width, ob.height)
				hitsurf = cairo.ImageSurface(cairo.FORMAT_ARGB32, ob.width, ob.height)
				idlecr = cairo.Context(idlesurf)
				hovercr = cairo.Context(hoversurf)
				pressedcr = cairo.Context(pressedsurf)
				hitcr = cairo.Context(hitsurf)
				idlecr.translate(-ob.x, -ob.y)
				hovercr.translate(-ob.x, -ob.y)
				pressedcr.translate(-ob.x, -ob.y)
				hitcr.translate(-ob.x, -ob.y)
				idle = ob.frames[ob.frames[0].index("idle")+1]
				if not "hover" in ob.frames[0]:
					hover = ob.frames[ob.frames[0].index("idle")+1]
				else:
					hover = ob.frames[ob.frames[0].index("hover")+1]
				if not "pressed" in ob.frames[0]:
					pressed = ob.frames[ob.frames[0].index("idle")+1]
				else:
					pressed = ob.frames[ob.frames[0].index("pressed")+1]
				if not "hit" in ob.frames[0]:
					hit = ob.frames[ob.frames[0].index("idle")+1]
				else:
					hit = ob.frames[ob.frames[0].index("hit")+1]
				for j in idle:
					idle[j][j].draw(idlecr, None, None)
				for j in hover:
					hover[j][j].draw(hovercr, None, None)
				for j in pressed:
					pressed[j][j].draw(pressedcr, None, None)
				for j in hit:
					hit[j][j].draw(hitcr, None, None)
				
				idlesurf.write_to_png(idlefile)
				hoversurf.write_to_png(hoverfile)
				pressedsurf.write_to_png(pressedfile)
				hitsurf.write_to_png(hitfile)
				idlefile.flush()
				hoverfile.flush()
				pressedfile.flush()
				hitfile.flush()
				idlefile.close()
				hoverfile.close()
				pressedfile.close()
				hitfile.close()
				output = output+".png idle"+i+" \""+os.environ["TEMP"]+sep+"idlefile"+i+".png\"\n"
				output = output+".png hover"+i+" \""+os.environ["TEMP"]+sep+"hoverfile"+i+".png\"\n"
				output = output+".png pressed"+i+" \""+os.environ["TEMP"]+sep+"pressedfile"+i+".png\"\n"
				output = output+".png hit"+i+" \""+os.environ["TEMP"]+sep+"hitfile"+i+".png\"\n"
				output = output+".button "+i+"\n.show idle"+i+" as=idle\n"+"\n.show hover"+i+" as=hover\n"+"\n.show pressed"+i+" as=pressed\n.show hit"+i+" as=area\n"+".end\n"

			elif ob.type=="movieclip":
				output = output+".sprite "+ob.name+"\n"
				for i in ob.frames[0]:
					output = output+".frame "+str(i+1)+"\n"
					for j in ob.frames[ob.frames[0].index(i)+1]["sort"]:
						f = ob.frames[ob.frames[0].index(i)+1][j]
						if f["put"]==True:
							output = output+".put "+j+" x="+str(f["x"])+" y="+str(f["y"])+" scalex="+str(f["xscale"]*100)+"% scaley="+str(f["yscale"]*100)+"% rotate="+str(f["rotate"])+"\n"
						else:
							output = output+".change "+j+" x="+str(f["x"])+" y="+str(f["y"])+" scalex="+str(f["xscale"]*100)+"% scaley="+str(f["yscale"]*100)+"% rotate="+str(f["rotate"])+"\n"
					if not ob.actions[ob.frames[0].index(i)]=="":
						output = output+".action:\n"+ob.actions[ob.frames[0].index(i)]+"\n.end\n"
						c = check(ob.actions[currentfile["frames"][0].index(i)])
						if not c==True:
							err = err+c
				output = output+".end\n"

			elif ob.type=="curve":
				output = output+".outline "+i+"_outline:\n"
				output = output+curve2xml(i)+"\n"
				output = output+".end\n"
				output = output+".filled "+i+" outline="+i+"_outline fill="+str(ob.fill)+"\n"
		for i in currentfile["frames"][0]:
			output = output+".frame "+str(i+1)+"\n"
			for j in currentfile["frames"][currentfile["frames"][0].index(i)+1]["sort"]:
				f = currentfile["frames"][currentfile["frames"][0].index(i)+1][j]
				if f["put"]==True:
					output = output+".put "+j+" x="+str(f["x"])+" y="+str(f["y"])+" scalex="+str(f["xscale"]*100)+"% scaley="+str(f["yscale"]*100)+"% rotate="+str(f["rotate"])+"\n"
				else:
					output = output+".change "+j+" x="+str(f["x"])+" y="+str(f["y"])+" scalex="+str(f["xscale"]*100)+"% scaley="+str(f["yscale"]*100)+"% rotate="+str(f["rotate"])+"\n"
					
			if not currentfile["actions"][currentfile["frames"][0].index(i)]=="":
				output = output+".action:\n"+currentfile["actions"][currentfile["frames"][0].index(i)]+"\n.end\n"
				c = check(currentfile["actions"][currentfile["frames"][0].index(i)])
				if not c==True:
					err = err+c
		output = output+".end"
		savefile = gio.File(path+title+".sct")
		gio.File.create(savefile)
		fc = open(path+title+".sct", "w")
		fc.write(output)
		fc.flush()
		fc.close()
		#os.system("swfc -o"+path+title+".swf "+path+title+".sct")
		compile = subprocess.Popen(SWFC_PATH+" -o "+path+title+".swf "+path+title+".sct", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=(os.sep=="/"))
		stdino, stdouterro = (compile.stdin, compile.stdout)
		print stdouterro.read()
		os.remove(path+title+".sct")
		print stout
		if os.access(path+title+".swf", os.F_OK)==True:
			alert(path+title+".swf exported succesfully!")
	def export_html5(self, widget, data=None):
		global currentfile
		alert("HTML5 export is in progress. Expect many bugs!")
		exporter, button = Html5dialogDialog.Html5dialogDialog()
		result = exporter.run()
		if button.get_active():
			pack=True;
		else:
			pack=False;
		filename = exporter.get_filename()
		patharray = filename.split("/")
		title = patharray.pop()
		titlearray = title.split(".")
		title = titlearray[0] #no extension
		path = ""
		for i in patharray:
			path = path+i+"/"
		exporter.destroy()
		html5="<html>\n<head>\n<title>"+title+"</title>\n<script type=\"text/javascript\">\n"
		html5=html5+"""var currentframe=(-1);\n
			function drawEllipse(ctx, x, y, w, h){\n
				ctx.beginPath();\n
				ctx.moveTo(x+w/2, y);\n
				ctx.bezierCurveTo(x+4*w/5, y, x+w, y+h/5, x+w, y+h/2);\n
				ctx.bezierCurveTo(x+w, y+4*h/5, x+4*w/5, y+h, x+w/2, y+h);\n
				ctx.bezierCurveTo(x+w/5, y+h, x, y+4*h/5, x, y+h/2);\n
				ctx.bezierCurveTo(x, y+h/5, x+w/5, y, x+w/2, y);\n
				ctx.fill();\n
			}\n
			function play(ctx, frames, _root){\n
				ctx.clearRect(0,0,500,500);\n
				currentframe+=1;\n
				if (currentframe>"""+str(currentfile["frames"][0][-1])+"""){\n
					currentframe=0;\n
				}\n
				if (currentframe in frames[0]){\n
					for (var j in frames[frames[0].indexOf(currentframe)+1]['sort']){\n
						i=frames[frames[0].indexOf(currentframe)+1]['sort'][j];\n
						_root[i]._x=frames[frames[0].indexOf(currentframe)+1][i][\"x\"];\n
						_root[i]._y=frames[frames[0].indexOf(currentframe)+1][i][\"y\"];\n
						ctx.fillStyle = _root[i]._color;\n
						if (_root[i]._type==\"ellipse\"){\n
							ctx.save();\n
							ctx.translate(_root[i]._x, _root[i]._y);\n
							drawEllipse(ctx,0,0,_root[i]._width,_root[i]._height);\n
							ctx.restore();\n
						}else if(_root[i]._type==\"box\"){\n
							ctx.save();\n
							ctx.translate(_root[i]._x, _root[i]._y);\n
							ctx.fillRect(0, 0, _root[i]._width,_root[i]._height);\n
							ctx.restore();\n
						}\n
					}\n
					for (var k in frames[frames[0].indexOf(currentframe)+1]['sounds']){\n
						frames[frames[0].indexOf(currentframe)+1]['sounds'][k].play();\n
					}\n
				}else{\n
					biggest = 0;\n
					for (var i=1;i<currentframe;i++){\n
						if (i in frames[0]){\n
							biggest = i;\n
						}\n
					}\n
					fac = (frames[frames[0].indexOf(biggest)+1]-biggest)/(currentframe-biggest)\n
					for (var j in frames[frames[0].indexOf(biggest)+1]['sort']){\n
						i=frames[frames[0].indexOf(biggest)+1]['sort'][j];\n
						_root[i]._x=ave(frames[frames[0].indexOf(biggest)+1][i][\"x\"],frames[frames[0].indexOf(biggest)+1][i][\"x\"], fac);\n
						_root[i]._y=ave(frames[frames[0].indexOf(biggest)+1][i][\"y\"],frames[frames[0].indexOf(biggest)+1][i][\"x\"], fac);\n
						ctx.fillStyle = _root[i]._color;\n
						if (_root[i]._type==\"ellipse\"){\n
							ctx.save();\n
							ctx.translate(_root[i]._x, _root[i]._y);\n
							drawEllipse(ctx,0,0,_root[i]._width,_root[i]._height);\n
							ctx.restore();\n
						}else if(_root[i]._type==\"box\"){\n
							ctx.save();\n
							ctx.translate(_root[i]._x, _root[i]._y);\n
							ctx.fillRect(0, 0, _root[i]._width,_root[i]._height);\n
							ctx.restore();\n
						}\n
					}\n
				}\n
			}\n"""
		html5=html5+"function draw(){\nvar canvas=document.getElementById('"+title+"');\nif (canvas.getContext){\nvar ctx = canvas.getContext('2d');\n"
		for i in currentfile["sounds"]:
			html5=html5+"var "+i.replace(" ","").replace("-","")+" = new Audio(\""+currentfile["sounds"][i]+"\")\n"
		for i in currentfile["colors"]["textures"]:
			if currentfile["colors"]["textures"][i]["type"]=="color":
				html5=html5+"var "+i+" = "
				html5=html5+"\"rgb("+str(int(currentfile["colors"]["textures"][i]["fill"][0]*255))+","+str(int(currentfile["colors"]["textures"][i]["fill"][1]*255))+","+str(int(currentfile["colors"]["textures"][i]["fill"][2]*255))+")\";\n"
			elif currentfile["colors"]["textures"][i]["type"]=="image":
				if pack:
					print "Packing"
					#html5=html5+"var "+i+"_img = new Image();\n "+i+"_img.src = "+currentfile["colors"]["images"][currentfile["colors"]["textures"][i]["fill"]].split("/")[-1].split(".")[0]+";\n
					html5=html5+"var "+i+" = "
				else:
					html5=html5+"var "+i+"_img = new Image();\n"+i+"_img.src = '"+currentfile["colors"]["images"][currentfile["colors"]["textures"][i]["fill"]].split("/")[-1]+"';\nvar "+i+" = "
				html5=html5+"ctx.createPattern("+i+"_img, 'repeat');\n"
			else:
				html5=html5+"var "+i+" = \"rgb(0,0,0)\";\n"
		html5=html5+"var _root = {_x:0,_y:0,_rotation:0,play:true"
		for i in currentfile["objects"]:
			if not (currentfile["objects"][i].type=="root" or currentfile["objects"][i].type=="button" or currentfile["objects"][i].type=="movieclip"):
				try:
					html5=html5+","+i+":{_x:"+str(currentfile["frames"][1][i]["x"])+",_y:"+str(currentfile["frames"][1][i]["y"])+",_rotation:0,_xscale:1,_yscale:1,_scale:1,_alpha:100,_visible:true,_height:"+str(currentfile["objects"][i].height)+",_width:"+str(currentfile["objects"][i].width)+",_type:\""+str(currentfile["objects"][i].type)+"\", _color:"+str(currentfile["objects"][i].fill)+"}"
				except KeyError:
					html5=html5+","+i+":{_x:0,_y:0,_rotation:0,_xscale:1,_yscale:1,_scale:1,_alpha:100,_visible:true,_height:"+str(currentfile["objects"][i].height)+",_width:"+str(currentfile["objects"][i].width)+",_type:\""+str(currentfile["objects"][i].type)+"\", _color:"+str(currentfile["objects"][i].fill)+"}"
		frs = copy.deepcopy(currentfile["frames"])
		nfrs = [[]]
		for i in range(frs[0][-1]):
			if i in frs[0]:
				nfrs.append(frs[frs[0].index(i)+1])
			else:
				biggest = 0
				for j in frs[0]:
					if j<i:
						biggest=j
				q = {}
				q["sort"]=frs[frs[0].index(biggest)+1]['sort']
				for j in frs[frs[0].index(biggest)+1]['sort']:
					f1 = frs[frs[0].index(biggest)+1][j]
					f2 = frs[frs[0].index(biggest)+2][j]
					fac = facx(frs[0][frs[0].index(biggest)], frs[0][frs[0].index(biggest)+1], i)
					x = ave(f2["x"], f1["x"], fac)
					y = ave(f2["y"], f1["y"], fac)
					xscale = ave(f2["xscale"], f1["xscale"], fac)
					yscale = ave(f2["yscale"], f1["yscale"], fac)
					rotate = ave(f2["rotate"], f1["rotate"], fac)
					q[j]={"x":x,"y":y,"xscale":xscale,"yscale":yscale,"rotate":rotate}
				nfrs.append(q)
		nfrs[0]=range(frs[0][-1])
		html5=html5+"};\nvar frames = "+str(nfrs)+";\n"
		html5=html5+"play(ctx, frames, _root);\n"
		#	if currentfile["objects"][i]["type"]=="box":
		#		html5=html5+"ctx.fillStyle = \"rgb(200,0,0)\";\nctx.fillRect ("+str(currentfile["frames"][1][i]["x"])+", "+str(currentfile["frames"][1][i]["y"])+", "+str(currentfile["objects"][i]["width"])+", "+str(currentfile["objects"][i]["height"])+");\n"
		#	elif currentfile["objects"][i]["type"]=="ellipse":
		#		html5=html5+"ctx.fillStyle = \"rgb(200,0,0)\";\nctx.fillRect ("+str(currentfile["frames"][1][i]["x"])+", "+str(currentfile["frames"][1][i]["y"])+", "+str(currentfile["objects"][i]["width"])+", "+str(currentfile["objects"][i]["height"])+");\n"
		if pack:
			html5=html5+"}\n}\n"
			imcount=0
			progress = gtk.Window(type=gtk.WINDOW_TOPLEVEL)
			progress.set_position(gtk.WIN_POS_CENTER)
			progress.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DIALOG)
			progress.set_destroy_with_parent(True)
			progress.set_modal(True)
			progress.present()
			label = gtk.Label("Packing images...")
			pvbox = vbox = gtk.VBox(False, 0)
			progress.add(pvbox)
			pvbox.pack_start(label, False, True, 0)
			bar = gtk.ProgressBar()
			pvbox.pack_start(bar, True, False, 0)
			bar.set_text("Packing images...")
			label.show()
			bar.show()
			pvbox.show()
			progress.show()
			bar.set_fraction(imcount)
			#html5=html5+"\nvar ip = null;\nfunction onPreload(aImages, nImages)\n{\nif ( nImages != aImg.length )\n{\nalert(\'Images did not load properly\');\nreturn;\n}\ndraw();\n}\n"
			#html5=html5+"function ImagePreloader(images, call_back)\n{\n\nthis.call_back = call_back;\nthis.nLoaded = 0;\nthis.nProcessed = 0;\nthis.aImages = [];\nthis.nImages = images.length;\nfor ( var i = 0; i < images.length; i++ ){\nthis.preload(images[i]);\n}\n}\n"
			#html5=html5+"ImagePreloader.prototype.preload = function(image)\n{\n\nvar oImage = new Image();\nthis.aImages.push(oImage);\noImage.onload = ImagePreloader.prototype.onload;\noImage.onerror = ImagePreloader.prototype.onerror;\noImage.onabort = ImagePreloader.prototype.onabort;\noImage.oImagePreloader = this;\noImage.bLoaded = false;\noImage.src = image;\n};\n"
			#html5=html5+"ImagePreloader.prototype.onComplete = function()\n{\nthis.nProcessed++;\nif ( this.nProcessed == this.nImages )\n{\nthis.call_back(this.aImages, this.nLoaded);\n}\n};\nImagePreloader.prototype.onload = function()\n{\nthis.bLoaded = true;\nthis.oImagePreloader.nLoaded++;\nthis.oImagePreloader.onComplete();\n};\nImagePreloader.prototype.onerror = function()\n{\nthis.bError = true;\nthis.oImagePreloader.onComplete();\n};\nImagePreloader.prototype.onabort = function()\n{\nthis.bAbort = true;\nthis.oImagePreloader.onComplete();\n};\n"
			#html5=html5+"var aImg = ["
			#for i in currentfile["colors"]["textures"]:
			#	if currentfile["colors"]["textures"][i]["type"]=="image":
			#		html5=html5+i+"_img,"
			#html5=html5[:-1]+"]\n"
			for i in currentfile["colors"]["textures"]:
				if currentfile["colors"]["textures"][i]["type"]=="image":
					bar.set_text("Packing "+currentfile["colors"]["images"][currentfile["colors"]["textures"][i]["fill"]])
					imgtype = currentfile["colors"]["images"][currentfile["colors"]["textures"][i]["fill"]][-3:]
					html5=html5+"var "+i+"_img = new Image();\n"+i+"_img.src=\""+DataURI.img2data(currentfile["colors"]["images"][currentfile["colors"]["textures"][i]["fill"]], imgtype)+"\"\n"
					#html5=html5+currentfile["colors"]["images"][currentfile["colors"]["textures"][i]["fill"]].split("/")[-1]+" = "+i+"_src;\nvar "+i+" = ctx.createPattern("+i+"_img, 'repeat');\n"
					imcount=imcount+1
					bar.set_fraction(imcount*1.0/len(currentfile["colors"]["images"]))
			
			progress.destroy()
			html5=html5+"</script>\n<style type=\"text/css\">\ncanvas { border: 1px solid black; }\n</style>\n</head>\n<body onload=\"setInterval(draw, 100);\">\n<canvas id=\""+title+"\" width=\""+str(currentfile["fileinfo"]["bbox"][0])+"\" height=\""+str(currentfile["fileinfo"]["bbox"][1])+"\"></canvas>\n</body>\n</html>"
		else:
			html5=html5+"}\n}\n"
			html5=html5+"var aImg = ["
			for i in currentfile["colors"]["images"]:
				html5=html5+"\""+currentfile["colors"]["images"][i].split("/")[-1]+"\","
				shutil.copyfile(currentfile["colors"]["images"][i], path+currentfile["colors"]["images"][i].split("/")[-1])
			html5=html5[:-1]+"""];\n
			var ip = null;\n
			function onPreload(aImages, nImages)\n
			{\n
				if ( nImages != aImg.length )\n
				{\n
					alert(\'Images did not load properly\');\n
					return;\n
				}\n
				setInterval(draw, 100);\n
			}\n
			function ImagePreloader(images, call_back)\n
			{\n
				\n
				this.call_back = call_back;\n
				this.nLoaded = 0;\n
				this.nProcessed = 0;\n
				this.aImages = [];\n
				this.nImages = images.length;\n
				for ( var i = 0; i < images.length; i++ ){\n
					this.preload(images[i]);\n
				}\n
			}\n
			ImagePreloader.prototype.preload = function(image)\n
			{\n
				\n
				var oImage = new Image();\n
				this.aImages.push(oImage);\n
				oImage.onload = ImagePreloader.prototype.onload;\n
				oImage.onerror = ImagePreloader.prototype.onerror;\n
				oImage.onabort = ImagePreloader.prototype.onabort;\n
				oImage.oImagePreloader = this;\n
				oImage.bLoaded = false;\n
				oImage.src = image;\n
			};\n
			ImagePreloader.prototype.onComplete = function()\n
			{\n
				this.nProcessed++;\n
				if ( this.nProcessed == this.nImages )\n
				{\n
					this.call_back(this.aImages, this.nLoaded);\n
				}\n
			};\n
			ImagePreloader.prototype.onload = function()\n
			{\n
				this.bLoaded = true;\n
				this.oImagePreloader.nLoaded++;\n
				this.oImagePreloader.onComplete();\n
			};\n
			ImagePreloader.prototype.onerror = function()\n
			{\n
				this.bError = true;\n
				this.oImagePreloader.onComplete();\n
			};\n
			ImagePreloader.prototype.onabort = function()\n
			{\n
				this.bAbort = true;\n
				this.oImagePreloader.onComplete();\n
			};\n"""
			html5=html5+"</script>\n<style type=\"text/css\">\ncanvas { border: 1px solid black; }\n</style>\n</head>\n<body onload=\"ip = new ImagePreloader(aImg, onPreload);\">\n<canvas id=\""+title+"\" width=\""+str(currentfile["fileinfo"]["bbox"][0])+"\" height=\""+str(currentfile["fileinfo"]["bbox"][1])+"\"></canvas>\n</body>\n</html>"
		html5=html5.replace("True", "true")
		html5=html5.replace("False", "false")
		try:
			savefile = gio.File(path+title+".html")
			gio.File.create(savefile)
		except:
			alert("File exists. Overwiting without asking you for permission, mwahahaha.")
		fc = open(path+title+".html", "w")
		fc.write(html5)
		fc.flush()
		fc.close()
	def export_image(self, widget, data=None):
		global currentframe
		global currentfile
		global level
		savedial = SaveDialog.NewSaveDialog(["images"])
		result = savedial.run()
		filename = savedial.get_filename()
		savedial.destroy()
		whatodo = alert_list("What do you want to do?", ["Export current frame as PNG", "Pi!", "Export all frames as one PNG", "Export all frames as PNG sequence"])
		lastcf = copy.deepcopy(currentframe)
		lastlevel = level
		level = 0
		if filename.split(".")[-1]=="png":
			if whatodo==0:
				png = open(filename, "w")
				surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 512, 512)
				cr = cairo.Context(surf)
				currentfile["objects"]["root"].draw(cr, 512, 512, None)
				surf.write_to_png(png)
				print filename
				png.flush()
				png.close()
			elif whatodo==2:
				png = open(filename, "w")
				surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 512, 512)
				cr = cairo.Context(surf)
				for i in range(currentfile["objects"]["root"].frames[0][-1]):
					currentframe[0] = i
					currentfile["objects"]["root"].draw(cr, 512, 512, None)
				surf.write_to_png(png)
				png.flush()
				png.close()
			elif whatodo == 3:
				for i in range(currentfile["objects"]["root"].frames[0][-1]):
					filename1 = filename.split(".")
					filename1 = filename1[0]+str(i).zfill(3)+"."+filename1[1]
					png = open(filename1, "w")
					surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 512, 512)
					cr = cairo.Context(surf)
					currentframe[0] = i
					currentfile["objects"]["root"].draw(cr, 512, 512, None)
					surf.write_to_png(png)
					png.flush()
					png.close()
		level = lastlevel
		currentframe = lastcf
	def export_video(self, widget, data=None):
		global currentframe
		global currentfile
		global level
		savedial = SaveDialog.NewSaveDialog(["videos"])
		result = savedial.run()
		filename = savedial.get_filename()
		savedial.destroy()
		splitname = filename.split(".")
		if len(splitname)>1:
			ext = splitname.pop()
		else:
			ext = ""
		path = join(splitname, ".")
		print path
		exts = ["flv", "avi", "mpg", "mp4", "mov", "dv", "mkv"]
		if not ext in exts:
			ext = "flv"
		whatformat = alert_list("What video format do you want to use?", [".FLV (Flash video)", ".AVI (Microsoft video)", ".MPG (Compatibility)", ".MP4 (Mobile Device)", ".MOV (Quicktime)", ".DV (Camcorder)", ".MKV (DVD)"], exts.index(ext))
		vext = exts[whatformat]
		extc = {"flv":25, "avi":10, "mpg":18, "mp4":10, "mov":9, "dv":27, "mkv":10}
		opts = vid_options(extc[vext])
		width = opts[1]
		height = opts[2]
		bitrate = opts[3]
		whatcodec = opts[0]
		#whatcodec = alert_list("Specify the codec.", ["mjpeg  - Motion JPEG", "ljpeg  - lossless JPEG", "jpegls  - JPEG LS", "targa  - Targa image", "gif  - GIF image", "bmp  - BMP image", "png  - PNG image", "h261  - H.261", "h263  - H.263", "h263p  - H.263+", "mpeg4  - ISO standard MPEG-4 (DivX, Xvid compatible)", "msmpeg4  - pre-standard MPEG-4 variant by MS, v3 (AKA DivX3)", "msmpeg4v2  - pre-standard MPEG-4 by MS, v2 (used in old ASF files)", "wmv1  - Windows Media Video, version 1 (AKA WMV7)", "wmv2  - Windows Media Video, version 2 (AKA WMV8)", "rv10  - RealVideo 1.0", "rv20  - RealVideo 2.0", "mpeg1video  - MPEG-1 video", "mpeg2video  - MPEG-2 video", "huffyuv  - lossless compression", "ffvhuff  - FFmpeg modified huffyuv lossless", "asv1  - ASUS Video v1", "asv2  - ASUS Video v2", "ffv1  - FFmpeg's lossless video codec", "svq1  - Sorenson video 1", "flv  - Sorenson H.263 used in Flash Video", "flashsv  - Flash Screen Video", "dvvideo  - Sony Digital Video", "snow  - FFmpeg's experimental wavelet-based codec", "zmbv  - Zip Motion Blocks Video", "dnxhd  - AVID DNxHD"], extc[vext])
		codecs = ["mjpeg", "ljpeg", "jpegls",  "targa", "gif", "bmp", "png", "h261", "h263", "h263p", "mpeg4", "msmpeg4", "msmpeg4v2", "wmv1", "wmv2", "rv10", "rv20", "mpeg1video", "mpeg2video", "huffyuv", "ffvhuff", "asv1", "asv2", "ffv1", "svq1", "flv", "flashsv", "dvvideo", "snow", "zmbv", "dnxhd"]
		codec = codecs[whatcodec]
		lastcf = copy.deepcopy(currentframe)
		lastlevel = level
		level = 0
		tempdir = tempfile.mkdtemp()
		
		progressbar = gtk.ProgressBar()
		dialog = gtk.Dialog()
		dialog.vbox.pack_start(progressbar)
		progressbar.show()
		dialog.show()
		progressbar.set_pulse_step(0.05)
		def videxport(progressbar, tempdir, currentframe, currentfile):
			for i in range(currentfile["objects"]["root"].frames[0][-1]):
					filename1 = tempdir+"/"+str(i).zfill(3)+".png"
					try:
						png = open(filename1, "w")
					except IOError:
						create_builtins(self)
					surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 512, 512)
					cr = cairo.Context(surf)
					currentframe[0] = i+1
					currentfile["objects"]["root"].draw(cr, 512, 512, None)
					surf.write_to_png(png)
					png.flush()
					png.close()
					if i > currentfile["objects"]["root"].frames[0][-1]-2:
						progressbar.set_fraction(1.0)
						progressbar.set_text("Encoding video...")
					else:
						progressbar.set_fraction(i/(currentfile["objects"]["root"].frames[0][-1]*1.0))
						progressbar.set_text("Rendering frame "+str(i))
					yield True
			print path+"."+vext
			for i in currentfile["frames"][1]["sounds"]:
				audiofile = currentfile["sounds"][i]
			try:
				os.system("mencoder mf://"+tempdir+"/*.png -mf w="+str(width)+":h="+str(height)+":fps="+str(currentfile["fileinfo"]["fps"])+":type=png -ovc lavc -lavcopts vcodec="+codec+":vbitrate="+str(bitrate)+":mbd=2:trell -audiofile '"+audiofile+"' -oac copy -o "+path+"."+vext)
			except:
				os.system("mencoder mf://"+tempdir+"/*.png -mf w="+str(width)+":h="+str(height)+":fps="+str(currentfile["fileinfo"]["fps"])+":type=png -ovc lavc -lavcopts vcodec="+codec+":vbitrate="+str(bitrate)+":mbd=2:trell -oac copy -o "+path+"."+vext)
			dialog.destroy()
			yield False
		
		vex = videxport(progressbar, tempdir, currentframe, currentfile)
		gobject.idle_add(vex.next)

	def export_pdf(self, widget, data=None):
		alert("PDF export is in progress. Beta may work better.")
		global currentfile
		global selectid
		global selectors
		for i in currentfile["frames"][0]:
			surface = cairo.PDFSurface("/home/skyler/Desktop/drawings"+str(i)+".pdf",432, 543)
			cr = cairo.Context(surface)
			cr.set_source_rgb(0.5, 0.5, 0.5)
			w = 500
			h = 500
			cr.paint()
			cr.set_line_width(2)
			for j in currentfile["frames"][currentfile["frames"][0].index(i)+1]["sort"]:
				if j in currentfile["objects"]:
					if currentfile["objects"][j]["type"]=="box":
						fill = currentfile["objects"][j]["fill"]
						if type(fill)==type([]):
							fill = hex2rgb(fill)
						drawcrBox(cr, currentfile["frames"][currentfile["frames"][0].index(i)+1][j]["x"], currentfile["frames"][currentfile["frames"][0].index(i)+1][j]["y"], currentfile["objects"][j]["width"], currentfile["objects"][j]["height"], 1, fill, currentfile["frames"][currentfile["frames"][0].index(i)+1][j]["rotate"])
					elif currentfile["objects"][j]["type"]=="ellipse":
						fill = currentfile["objects"][j]["fill"]
						if type(fill)==type([]):
							fill = hex2rgb(fill)
						x = currentfile["frames"][currentfile["frames"][0].index(i)+1][j]["x"]
						y = currentfile["frames"][currentfile["frames"][0].index(i)+1][j]["y"]
						w = currentfile["objects"][j]["width"]
						h = currentfile["objects"][j]["height"]
						drawcrEllipse(cr, x, y, w, h, fill)
					elif currentfile["objects"][j]["type"]=="curve": 
						rgb = hex2rgb(currentfile["objects"][j]["outline"])
						cr.set_source_rgb(rgb[0], rgb[1], rgb[2])
						drawcrCurve(cr, currentfile["objects"][j]["points"])
				elif j in currentfile["buttons"]:
					q = currentfile["buttons"][j]["idle"]
					if currentfile["objects"][q]["type"]=="box":
						fill = currentfile["objects"][q]["fill"]
						if type(fill)==type([]):
							fill = hex2rgb(fill)
						drawcrBox(cr, currentfile["frames"][currentfile["frames"][0].index(i)+1][j]["x"], currentfile["frames"][currentfile["frames"][0].index(i)+1][j]["y"], currentfile["objects"][q]["width"], currentfile["objects"][q]["height"], 1, fill, 0)
					elif currentfile["objects"][q]["type"]=="ellipse":
						fill = currentfile["objects"][q]["fill"]
						if type(fill)==type(""):
							fill = hex2rgb(fill)
						x = currentfile["frames"][currentfile["frames"][0].index(i)+1][j][q]["x"]
						y = currentfile["frames"][currentfile["frames"][0].index(i)+1][j][q]["y"]
						w = currentfile["objects"][j][q]["width"]
						h = currentfile["objects"][j][q]["height"]
						drawcrEllipse(cr, x, y, w, h, fill)
					elif currentfile["objects"][j]["type"]=="curve":	
						rgb = hex2rgb(currentfile["objects"][q]["outline"])
						cr.set_source_rgb(rgb[0], rgb[1], rgb[2])
						drawcrCurve(cr, currentfile["objects"][q]["points"])

	def export_gif(self, widget, data=None):
		global currentframe
		global currentfile
		global level
		savedial = SaveDialog.NewSaveDialog(["gif"])
		result = savedial.run()
		filename = savedial.get_filename()
		savedial.destroy()
		splitname = filename.split(".")
		if len(splitname)>1:
			splitname.pop()
		filname = join(splitname, ".")+".gif"
		tempdir = tempfile.mkdtemp()
		giframes = []
		progressbar = gtk.ProgressBar()
		dialog = gtk.Dialog()
		dialog.vbox.pack_start(progressbar)
		progressbar.show()
		dialog.show()
		progressbar.set_pulse_step(0.05)
		def gifexport(progressbar, tempdir, currentframe, currentfile):
			for i in range(currentfile["objects"]["root"].frames[0][-1]):
				filename1 = tempdir+"/"+str(i).zfill(3)+".png"
				png = open(filename1, "w")
				surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 512, 512)
				cr = cairo.Context(surf)
				currentframe[0] = i+1
				currentfile["objects"]["root"].draw(cr, 512, 512, None)
				surf.write_to_png(png)
				png.flush()
				png.close()
				giframes.append(Image.open(tempdir+"/"+str(i).zfill(3)+".png"))
				if i > currentfile["objects"]["root"].frames[0][-1]-2:
					progressbar.set_fraction(1.0)
					progressbar.set_text("Building gif...")
				else:
					progressbar.set_fraction(i/(currentfile["objects"]["root"].frames[0][-1]*1.0))
					progressbar.set_text("Rendering frame "+str(i))
				yield True
			images2gif.writeGif(filename, giframes, 1.0/currentfile["fileinfo"]["fps"])
			dialog.destroy()
			yield False
		gex = gifexport(progressbar, tempdir, currentframe, currentfile)
		gobject.idle_add(gex.next)
	def export_sc(self, widget, data=None):
		global currentfile
		#global path
		#global title
		global outputwin
		global err
		global win
		global outbox
		global outbuffer
		global level
		output = ""
		err = ""
		
		#get the title from the user
		saver = SaveDialog.NewSaveDialog()
		result = saver.run()
		#Filename includes path
		filename = saver.get_filename()
		patharray = filename.split("/")
		title = patharray.pop()
		titlearray = title.split(".")
		title = titlearray[0] #no extension
		path = ""
		for i in patharray:
			path = path+i+"/"
		saver.destroy()
		ftextbuf = self.builder.get_object("textview2").get_buffer()
		currentfile["actions"][currentfile["frames"][0].index(currentframe[level])]= str(ftextbuf.get_text(ftextbuf.get_start_iter(), ftextbuf.get_end_iter()))
		output = output+".flash filename=\""+title+".swf\" fps="+str(currentfile["fileinfo"]["fps"])+" bbox="+str(currentfile["fileinfo"]["bbox"][0])+"x"+str(currentfile["fileinfo"]["bbox"][1])+"x"+str(currentfile["fileinfo"]["bbox"][2])+"x"+str(currentfile["fileinfo"]["bbox"][1])+"\n"
		for i in currentfile["colors"]["images"]:
			ex = currentfile["colors"]["images"][i].split(".")
			if ex[-1]=="png":
				output = output+".png "+i+" \""+currentfile["colors"]["images"][i]+"\"\n"
			else:
				output = output+".jpg "+i+" \""+currentfile["colors"]["images"][i]+"\"\n"
		for i in currentfile["colors"]["gradients"]:
			output = output+".gradient "+i+":\n"
			for q in currentfile["colors"]["gradients"][i]:
				output = output+str(int(q[0]*100))+"% "+rgb2hex(q[1], q[2], q[3], q[4])+"\n"
			output = output+".end\n"
		for i in currentfile["colors"]["textures"]:
			if type(currentfile["colors"]["textures"][i]["fill"])==type([]):
				output = output+".texture "+i+"="+rgb2hex(currentfile["colors"]["textures"][i]["fill"][0],currentfile["colors"]["textures"][i]["fill"][1],currentfile["colors"]["textures"][i]["fill"][2])+"\n"
			else:
				output = output+".texture "+i+"="+currentfile["colors"]["textures"][i]["fill"]+"\n"
		for i in currentfile["objects"]:
			ob = currentfile["objects"][i]
			if ob.type=="box":
				if type(currentfile["colors"]["textures"][ob.fill]["fill"])==type([]):
					fill = rgb2hex(currentfile["colors"]["textures"][ob.fill]["fill"][0],currentfile["colors"]["textures"][ob.fill]["fill"][1],currentfile["colors"]["textures"][ob.fill]["fill"][2])
				else:
					fill = str(ob.fill)
				output = output+".box "+i+" width="+str(ob.width)+" height="+str(ob.height)+" fill="+str(fill)+" color=#00000000"+"\n"
			elif ob.type=="ellipse":
				output = output+".outline "+i+"_outline:\n"
				output = output+ellipse2xml(i)+"\n"
				output = output+".end\n"
				if type(currentfile["colors"]["textures"][ob.fill]["fill"])==type([]):
					fill = rgb2hex(currentfile["colors"]["textures"][ob.fill]["fill"][0],currentfile["colors"]["textures"][ob.fill]["fill"][1],currentfile["colors"]["textures"][ob.fill]["fill"][2])
				else:
					fill = str(ob.fill)
				output = output+".filled "+i+" outline="+i+"_outline fill="+fill+"\n"
			elif ob.type=="shape":
				output = output+".outline "+i+"_outline:\n"
				output = output+shape2xml(i)+"\n"
				output = output+".end\n"
				if type(currentfile["colors"]["textures"][ob.fill]["fill"])==type([]):
					fill = rgb2hex(currentfile["colors"]["textures"][ob.fill]["fill"][0],currentfile["colors"]["textures"][ob.fill]["fill"][1],currentfile["colors"]["textures"][ob.fill]["fill"][2])
				else:
					fill = str(ob.fill)
				output = output+".filled "+i+" outline="+i+"_outline fill="+fill+"\n"
			elif ob.type=="button":
				pass
				
			elif ob.type=="movieclip":
				pass
				
		for i in currentfile["objects"]:
			ob = currentfile["objects"][i]	
			if ob.type=="button":
				idlefile = open(os.environ["TEMP"]+sep+"idlefile"+i+".png", "w")
				hoverfile = open(os.environ["TEMP"]+sep+"hoverfile"+i+".png", "w")
				pressedfile = open(os.environ["TEMP"]+sep+"pressedfile"+i+".png", "w")
				hitfile = open(os.environ["TEMP"]+sep+"hitfile"+i+".png", "w")
				idlesurf = cairo.ImageSurface(cairo.FORMAT_ARGB32, ob.width, ob.height)
				hoversurf = cairo.ImageSurface(cairo.FORMAT_ARGB32, ob.width, ob.height)
				pressedsurf = cairo.ImageSurface(cairo.FORMAT_ARGB32, ob.width, ob.height)
				hitsurf = cairo.ImageSurface(cairo.FORMAT_ARGB32, ob.width, ob.height)
				idlecr = cairo.Context(idlesurf)
				hovercr = cairo.Context(hoversurf)
				pressedcr = cairo.Context(pressedsurf)
				hitcr = cairo.Context(hitsurf)
				idlecr.translate(-ob.x, -ob.y)
				hovercr.translate(-ob.x, -ob.y)
				pressedcr.translate(-ob.x, -ob.y)
				hitcr.translate(-ob.x, -ob.y)
				idle = ob.frames[ob.frames[0].index("idle")+1]
				if not "hover" in ob.frames[0]:
					hover = ob.frames[ob.frames[0].index("idle")+1]
				else:
					hover = ob.frames[ob.frames[0].index("hover")+1]
				if not "pressed" in ob.frames[0]:
					pressed = ob.frames[ob.frames[0].index("idle")+1]
				else:
					pressed = ob.frames[ob.frames[0].index("pressed")+1]
				if not "hit" in ob.frames[0]:
					hit = ob.frames[ob.frames[0].index("idle")+1]
				else:
					hit = ob.frames[ob.frames[0].index("hit")+1]
				for j in idle:
					idle[j][j].draw(idlecr, None, None)
				for j in hover:
					hover[j][j].draw(hovercr, None, None)
				for j in pressed:
					pressed[j][j].draw(pressedcr, None, None)
				for j in hit:
					hit[j][j].draw(hitcr, None, None)
				
				idlesurf.write_to_png(idlefile)
				hoversurf.write_to_png(hoverfile)
				pressedsurf.write_to_png(pressedfile)
				hitsurf.write_to_png(hitfile)
				idlefile.flush()
				hoverfile.flush()
				pressedfile.flush()
				hitfile.flush()
				idlefile.close()
				hoverfile.close()
				pressedfile.close()
				hitfile.close()
				output = output+".png idle"+i+" \""+os.environ["TEMP"]+sep+"idlefile"+i+".png\"\n"
				output = output+".png hover"+i+" \""+os.environ["TEMP"]+sep+"hoverfile"+i+".png\"\n"
				output = output+".png pressed"+i+" \""+os.environ["TEMP"]+sep+"pressedfile"+i+".png\"\n"
				output = output+".png hit"+i+" \""+os.environ["TEMP"]+sep+"hitfile"+i+".png\"\n"
				output = output+".button "+i+"\n.show idle"+i+" as=idle\n"+"\n.show hover"+i+" as=hover\n"+"\n.show pressed"+i+" as=pressed\n.show hit"+i+" as=area\n"+".end\n"

			elif ob.type=="movieclip":
				output = output+".sprite "+ob.name+"\n"
				for i in ob.frames[0]:
					output = output+".frame "+str(i+1)+"\n"
					for j in ob.frames[ob.frames[0].index(i)+1]["sort"]:
						f = ob.frames[ob.frames[0].index(i)+1][j]
						if f["put"]==True:
							output = output+".put "+j+" x="+str(f["x"])+" y="+str(f["y"])+" scalex="+str(f["xscale"]*100)+"% scaley="+str(f["yscale"]*100)+"% rotate="+str(f["rotate"])+"\n"
						else:
							output = output+".change "+j+" x="+str(f["x"])+" y="+str(f["y"])+" scalex="+str(f["xscale"]*100)+"% scaley="+str(f["yscale"]*100)+"% rotate="+str(f["rotate"])+"\n"
					if not ob.actions[ob.frames[0].index(i)]=="":
						output = output+".action:\n"+ob.actions[ob.frames[0].index(i)]+"\n.end\n"
						c = check(ob.actions[currentfile["frames"][0].index(i)])
						if not c==True:
							err = err+c
				output = output+".end\n"

			elif ob.type=="curve":
				output = output+".outline "+i+"_outline:\n"
				output = output+curve2xml(i)+"\n"
				output = output+".end\n"
				output = output+".filled "+i+" outline="+i+"_outline fill="+str(ob.fill)+"\n"
		for i in currentfile["frames"][0]:
			output = output+".frame "+str(i+1)+"\n"
			for j in currentfile["frames"][currentfile["frames"][0].index(i)+1]["sort"]:
				f = currentfile["frames"][currentfile["frames"][0].index(i)+1][j]
				if f["put"]==True:
					output = output+".put "+j+" x="+str(f["x"])+" y="+str(f["y"])+" scalex="+str(f["xscale"]*100)+"% scaley="+str(f["yscale"]*100)+"% rotate="+str(f["rotate"])+"\n"
				else:
					output = output+".change "+j+" x="+str(f["x"])+" y="+str(f["y"])+" scalex="+str(f["xscale"]*100)+"% scaley="+str(f["yscale"]*100)+"% rotate="+str(f["rotate"])+"\n"
					
			if not currentfile["actions"][currentfile["frames"][0].index(i)]=="":
				output = output+".action:\n"+currentfile["actions"][currentfile["frames"][0].index(i)]+"\n.end\n"
				c = check(currentfile["actions"][currentfile["frames"][0].index(i)])
				if not c==True:
					err = err+c
		output = output+".end"
		savefile = gio.File(path+title+".sc")
		gio.File.create(savefile)
		fc = open(path+title+".sc", "w")
		fc.write(output)
		fc.flush()
		fc.close()
	def publish_file(self, widget, data=None):
		publisher = PublishDialog.NewPublishDialog()
		result = publisher.run()
		alert("File publishing is not implemented yet. Wait for the beta!")
	def launch_shortcut(self, widget, data=None):
		alert("Launching shortcut!")
	def modify_document(self, widget, data=None):
		alert("Not complete")
		dialog = DocumentDialog.NewDocumentDialog()
		result = dialog.run()
	def console(self, widget, data="None"):
		Credits = "Everything © 2011 Skyler Lehmkuhl."
		global SWIFT_ROOT
		global consoledir
		for i in consoledir:
			locals()[i] = consoledir[i]
		def load(b):
			a = b.split("/")[-1].split(".")[0]
			if a==b:
				globals()[a] = __import__(b)
			else:
				globals()[a] = imp.load_source(a, b)
			return "Imported "+a
		class sw:
			def __init__(self):
				global currentfile
				global selectid
				global currentcolor
				global currentselect
				self.__cf = currentfile
				self.__id = selectid
				self.__cc = currentcolor
				self.__cs = currentselect
			def addBox(self, x, y, w, h):
				global currentframe
				global biter
				global selectors
				if type(currentcolor)==type([]):
					newcolor = "rgb"+rgb2hex(self.__cc[0], self.__cc[1], self.__cc[2])[1:]
					self.__cf["colors"]["textures"][newcolor]={"type":"color", "fill":[self.__cc[0], self.__cc[1], self.__cc[2]]}
					self.__cf["objects"]["b"+str(biter)]=box("b"+str(biter), w, h, self.__cs[level], newcolor)
				else:
					self.__cf["objects"]["b"+str(biter)]=box("b"+str(biter), w, h, self.__cs[level], self.__cc)
				self.__id.append("#01"+("%X" % (int(self.__id[-1][3:7], 16)+1)).zfill(4))
				selectors.append("b"+str(biter))
				for i in range(self.__cf["frames"][0].index(currentframe[level]), len(self.__cf["frames"][0])):
					self.__cf["frames"][i+1]["b"+str(biter)]={"put":True, "x":x, "y":y, "xscale":1.0, "yscale":1.0, "rotate":0}
					self.__cf["frames"][i+1]["sort"].append("b"+str(biter))
				biter += 1
				return "Added new box."
			def addEllipse(self, x, y, w, h):
				global currentframe
				global eiter
				global selectors
				if type(currentcolor)==type([]):
					newcolor = "rgb"+rgb2hex(self.__cc[0], self.__cc[1], self.__cc[2])[1:]
					self.__cf["colors"]["textures"][newcolor]={"type":"color", "fill":[self.__cc[0], self.__cc[1], self.__cc[2]]}
					self.__cf["objects"]["e"+str(eiter)]=ellipse("e"+str(eiter), w, h, self.__cs[level], newcolor)
				else:
					self.__cf["objects"]["e"+str(eiter)]=ellipse("e"+str(eiter), w, h, self.__cs[level], self.__cc)
				self.__id.append("#01"+("%X" % (int(self.__id[-1][3:7], 16)+1)).zfill(4))
				selectors.append("e"+str(eiter))
				for i in range(self.__cf["frames"][0].index(currentframe[level]), len(self.__cf["frames"][0])):
					self.__cf["frames"][i+1]["e"+str(eiter)]={"put":True, "x":x, "y":y, "rotate":0}
					self.__cf["frames"][i+1]["sort"].append("e"+str(eiter))
				eiter += 1
				return "Added new ellipse."
			def redraw(self):
				expostagevent(window.builder.get_object("drawingarea1"), "expose-event")
				return "Redrawing stage."
		if SWIFT_ROOT:
			global currentfile
			global currentframe
			global path
			global title
			global mode
			global clicked
			global drawitems
			global biter
			global eiter
			global citer
			global fiter
			global step
			global currentcurve
			global currentselect
			global currentcolor
			global selectid
			global source_id
			global selectors
			global undostack
			global redostack
			global doubleclick
			global outputwin
			global level
			global outbox
			global outbuffer
			global objects
			global tnum
			global SWIFT_VERSION
			global SWIFT_COMPAT
			
			locals()["currentfile"] = currentfile
			locals()["currentframe"] = currentframe
			locals()["path"] = path
			locals()["title"] = title
			locals()["mode"] = mode
			locals()["clicked"] = clicked
			locals()["drawitems"] = drawitems
			locals()["biter"] = biter
			locals()["eiter"] = eiter
			locals()["citer"] = citer
			locals()["fiter"] = fiter
			locals()["step"] = step
			locals()["currentcurve"] = currentcurve
			locals()["currentselect"] = currentselect
			locals()["currentcolor"] = currentcolor
			locals()["selectid"] = selectid
			locals()["source_id"] = source_id
			locals()["selectors"] = selectors
			locals()["undostack"] = undostack
			locals()["redostack"] = redostack
			locals()["doubleclick"] = doubleclick
			locals()["outputwin"] = outputwin
			locals()["level"] = level
			locals()["outbox"] = outbox
			locals()["outbuffer"] = outbuffer
			locals()["objects"] = objects
			locals()["tnum"] = tnum
			locals()["SWIFT_VERSION"] = SWIFT_VERSION
			locals()["SWIFT_COMPAT"] = SWIFT_COMPAT
			window.builder.get_object("checkbutton1").set_visible(True)
			print "ROOTROOTROOTROOT"
			class STDOUTWRITER:
					def __init__(self, window):
						self.terminal = sys.stdout
						self.buffer = window.builder.get_object("textview3").get_buffer()
						self.type = "writer"
					def write(self, message):
						self.terminal.write(message)
						self.buffer.set_text(self.buffer.get_text(self.buffer.get_start_iter(), self.buffer.get_end_iter())+message)
		def help(func=None):
			if func==None:
				return "Current commands are: \"help()\", \"Credits\", \"set()\", \"load()\" and if you know what you are doing, \"swiftroot()\"\nOr type help(\"function\") to get information about that function."
			elif func=="Credits" or func==Credits:
				return "Credits is not a function. Just type Credits (no parentheses)."
			elif func=="set" or func=="set()":
				return "set() sets a variable to a value. Use it instead of an equals sign.\nYou should enclose the variable name in quotes, i.e. set(\"foo\", 5)."
			elif func=="sw" or func=="sw()":
				return "sw is the class used to access Swift. Its usage is:\n\tsw().function(arguments)\n\nHere is a list of functions:\n\taddBox(x, y, width, height)\n\taddEllipse(x, y, width, height)\n\tredraw()"
			elif func=="load" or func=="load()":
				return "load() is the function used to load custom modules. This allows you to write scripts to do useful things in SWIFT, or just cool things like fractals.\nUseage:\n\tload(\"/path/to/module.py\")"
			elif func=="function":
				return "No, I meant you type a quote, then the name of the function, then another quote. Like this:\n\thelp(\"set\")"
		def set(arg1, arg2):
			if not arg1:
				return "You must put quotes around the first argument!"
			else:
				if SWIFT_ROOT:
					arg1 = arg2
				else:
					consoledir[arg1] = arg2
				return arg2
		def swiftroot():
			global SWIFT_ROOT
			SWIFT_ROOT = True
			return "Be warned, this will give you complete access to all internal variables in SWIFT. DO NOT do this unless you have read the source code (or seriously don't care about the current file!)!!!\nIf you didn't want to become root, type set(SWIFT_ROOT, False)"
		print widget, data
		if window.builder.get_object("checkbutton1").get_active():
			try:
				stype = sys.stdout.type
			except:
				sys.stdout = STDOUTWRITER(window)
			try:
				stype = sys.stderr.type
			except:
				sys.stderr = STDOUTWRITER(window)
			exec widget.get_text() in globals(), locals()
		else:
			try:
				window.builder.get_object("textview3").get_buffer().set_text(window.builder.get_object("textview3").get_buffer().get_text(window.builder.get_object("textview3").get_buffer().get_start_iter(), window.builder.get_object("textview3").get_buffer().get_end_iter())+"\n"+str(eval(widget.get_text())))
			except NameError as n:
				for i in n:
					consoledir[i[6:-16]]=None
				try:
					window.builder.get_object("textview3").get_buffer().set_text(window.builder.get_object("textview3").get_buffer().get_text(window.builder.get_object("textview3").get_buffer().get_start_iter(), window.builder.get_object("textview3").get_buffer().get_end_iter())+"\n"+str(eval(widget.get_text())))
				except Exception as e:
					window.builder.get_object("textview3").get_buffer().set_text(window.builder.get_object("textview3").get_buffer().get_text(window.builder.get_object("textview3").get_buffer().get_start_iter(), window.builder.get_object("textview3").get_buffer().get_end_iter())+"\n"+str(e))
		window.builder.get_object("textview3").set_wrap_mode(gtk.WRAP_CHAR)
		window.builder.get_object("textview3").scroll_mark_onscreen(window.builder.get_object("textview3").get_buffer().get_insert())
		widget.set_text("")
		
	

def NewSwiftSwfWindow():
	"""NewSwiftSwfWindow - returns a fully instantiated
	SwiftSwfWindow object. Use this function rather than
	creating a SwiftSwfWindow directly.
	"""

	#look for the ui file that describes the ui
	ui_filename = os.path.join(getdatapath(), 'ui', 'SwiftSwfWindow.ui')  
	if not os.path.exists(ui_filename):
		print "Couldn't locate window data!"
		sys.exit(1)
		ui_filename = "C:\\trunk\\data\ui\\SwiftSwfWindow.ui"

	global scale
	global currentfile
	global currentframe
	global path
	global title
	global mode
	global clicked
	global middleclick
	global drawitems
	global biter
	global eiter
	global siter
	global fiter
	global step
	global currentcurve
	global currentselect
	global currentcolor
	global selectid
	global source_id
	global selectors
	global undostack
	global redostack
	global doubleclick
	global outputwin
	global level
	global outbox
	global outbuffer
	global objects
	global tnum
	global consoledir
	global coords
	global brushlocs
	global SWIFT_VERSION
	global SWIFT_COMPAT
	global SWIFT_ROOT
	global view_scale
	global pmode
	global lastinput
	global playing
	global sounds
	global sep
	global MAX_FRAMES
	#specify the current version and what version files it can still open
	SWIFT_VERSION = "1.0-alpha4"
	SWIFT_COMPAT = ["1.0-alpha4"]
	#setting this to True gives you "root" access in the console
	SWIFT_ROOT = False
	#the list of variables in the console
	consoledir = {}
	tnum = 0
	scale=False
	brushlocs = []
	source_id = None
	#level: Depth of editing stack (0 is working at toplevel, i.e. main timeline)
	level = 0
	currentcurve = []
	currentframe = [0, 0]
	currentcolor = [1, 0, 0]
	biter = 1
	eiter = 1
	fiter = 0
	siter = 1
	step = 0
	lastinput = time.time()
	playing = False
	sounds = {}
	drawitems = ["", "x=1"]
	mode = " "
	pmode = "straight"
	theoneroot = root()
	objects = {"root":theoneroot}
	b0 = box("b0", 256, 256, "root", "t2")
	e0 = ellipse("e0", 300, 100, "root", "turquoise")
	s0 = shape("s0", 300, 300, "root", "turquoise")
	s0.shapedata = [["M", 0, 0], ["L", 300, 0], ["L", 300, 300], ["C", 0, 300, 300, 0, 0, 0]]
	currentfile = {"fileinfo":{"fps":25, "bbox":[500, 500, 0, 0]}, "colors":{"gradients":{"gr1":[[0.0, 0.0, 0.0, 1.0, 1], [0.5, 0.0, 1.0, 0.0, 1], [1.0, 1.0, 0.0, 0.0, 1]]}, "textures":{"t1":{"type":"gradient", "fill":"gr1"}, "t2":{"type":"image", "fill":"i1"}, "turquoise":{"type":"color", "fill":[0.0, 1.0, 1.0]}}, "images":{"i1":getdatapath()+sep+"media"+sep+"icon.png"}}, "objects":{"b0":b0, "e0":e0, "s0":s0}, "sprites":{}, "buttons":{}, "sounds":{}, "actions":[""], "frames":[[0], {"sort":["s0", "b0", "e0"], "s0":{"put":True, "x":20, "y":20, "rotate":10, "xscale":1.0, "yscale":1.0}, "b0":{"put":True, "x":100, "y":100, "rotate":0, "xscale":1.0, "yscale":1.0}, "e0":{"put":True, "x":200, "y":300, "rotate":-0.5, "xscale":1.0, "yscale":1.0}, "sounds":[]}]}
	MAX_FRAMES = currentfile["frames"][0][-1]+500
	objects = currentfile["objects"]
	objects["root"] = theoneroot
	objects["root"].frames = currentfile["frames"]
	objects["root"].actions = currentfile["actions"]
	currentselect = ["root", None]
	try:
		path = os.environ["HOME"]+sep+"Desktop"+sep
	except KeyError:
		path = os.environ["HOMEPATH"]+sep+"Desktop"+sep
	title = "Untitled"
	clicked = False
	middleclick = False
	doubleclick = False
	selectid=["#000000", "#010101", "#020102", "#030103"]
	selectors=[None, "b0", "e0", "s0"]
	undostack=[]
	redostack=[]
	outputwin=False
	outbox = None
	outbuffer = None
	view_scale = 1.0
	
	
	builder = gtk.Builder()
	builder.add_from_file(ui_filename)
	window = builder.get_object("swift_swf_window")
	window.finish_initializing(builder)
	return window

if __name__ == "__main__":
	if not "TEMP" in os.environ:
		os.environ["TEMP"]="/tmp"
	global pid
	global sep
	pid = os.getpid()
	sep = os.sep
	TARGET_TYPE_URI_LIST = 80
	dnd_list = [ ( 'text/uri-list', 0, TARGET_TYPE_URI_LIST ) ]
	#support for command line options
	import logging, optparse
	parser = optparse.OptionParser(version="%prog %ver")
	parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="Show debug messages")
	(options, args) = parser.parse_args()
	
	print "args ", args
	#set the logging level to show debug messages
	if options.verbose:
		logging.basicConfig(level=logging.DEBUG)
		logging.debug('logging enabled')	

	#run the application
	if not "currentfile" in os.listdir(os.environ["TEMP"]):
		window = NewSwiftSwfWindow()
		window.show()
	
		global step
	
		buff = window.builder.get_object("textview1").get_buffer()
		#buff.set_text(currenttext)
		libbuff = window.builder.get_object("libview")
		window.set_title("Swift - "+title+".swift")
		window.maximize()
		fg = gtk.gdk.Color(0.0, 1.0, 1.0)
		bg = gtk.gdk.Color(1.0, 0.0, 0.0)
		image4 = window.builder.get_object("image4")
		stage = window.builder.get_object("drawingarea1")
		stage.show()
		stage.set_size_request(1500, 1500)
		stage.connect('drag_data_received', on_drag_data_received)
		stage.drag_dest_set( gtk.DEST_DEFAULT_MOTION | gtk.DEST_DEFAULT_HIGHLIGHT | gtk.DEST_DEFAULT_DROP, dnd_list, gtk.gdk.ACTION_COPY)
		
		stage.set_can_focus(True)
		stage.add_events(gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.KEY_PRESS_MASK)
		stage.connect('key_press_event', keyvent, window)
		stage.grab_focus()
		
		window.set_size_request(1024, 520)
		frameframe = window.builder.get_object("drawingarea2")
		objwin = window.builder.get_object("drawingarea3")
		gradwin = window.builder.get_object("drawingarea4")
		grad1win = window.builder.get_object("drawingarea5")
		grad2win = window.builder.get_object("drawingarea6")
		cwin = window.builder.get_object("fillcolor")
		c2win = window.builder.get_object("linecolor")
		frameframe.set_size_request(8000, 32)
		objwin.set_size_request(128, 32)
		drawitems[1]="drawBox(gc, stagedraw, 23, 42, 256, 365)"
		stage.connect("expose-event", expostagevent)
		stage.connect("button-press-event", button_clicked)
		stage.connect("scroll-event", mouse_scrolled)
		window.connect('key_press_event', on_key_press)
		frameframe.connect("expose-event", exposeframevent)
		objwin.connect("expose-event", exposobjevent)
		gradwin.connect("expose-event", exposegradevent)
		grad1win.connect("expose-event", exposegradevent)
		grad2win.connect("expose-event", exposegradevent)
		cwin.connect("expose-event", exposecolorevent)
		c2win.connect("expose-event", exposecolorevent)
		#Get keyframe animation going
		exposeframevent(frameframe, "animation-event")
		exposegradevent(gradwin, "init-event")
		exposecolorevent(cwin, "init-event")
		console = window.builder.get_object("textview3")
		# create a font description object
		fontdesc = pango.FontDescription("Courier 10")
		# and pass it on as parameter to the method:
		console.modify_font(fontdesc)
		consolebuffer = console.get_buffer()
		consolebuffer.set_text("SWIFT Internal Python Console, v1.0.0\nType \"help()\" for instructions,\nor \"Credits\" to see all the people who have worked on SWIFT.")
		consolentry = window.builder.get_object("entry6")
		consolentry.connect("activate", window.console, gtk.RESPONSE_OK)
		sw = window.builder.get_object("scrolledwindow1")
		hadj = sw.get_hadjustment()
		hadj.set_upper(1000)
		hadj.set_value(500)
		vadj = sw.get_vadjustment()
		vadj.set_upper(1000)
		vadj.set_value(500)
		os.mkdir(os.environ["TEMP"]+sep+"swift"+str(pid))
		if len(args)>0:
			patharray = args[0].split("/")
			title = patharray.pop()
			titlearray = title.split(".")
			title = titlearray[0]
			path = ""
			for i in patharray:
				path = path+i+"/"
			try:
				ren = os.environ["TEMP"]+sep+""+title+".tar.gz"
				shutil.copyfile(args[0], ren)
				tar = tarfile.open(ren, 'r:gz')
				for item in tar:
					tar.extract(item, os.environ["TEMP"]+sep+"swift"+str(pid))
				os.remove (ren)
			except:
				print "Error opening file."
				alert("Error opening file!", True)
			fc = open(os.environ["TEMP"]+sep+"swift"+str(pid)+"/currentfile", "r")
			currentfilebase = []
			for i in fc:
				currentfilebase.append(i)
			currentfile = eval (currentfilebase[0])
			objects = currentfile["objects"]
			objects["root"] = root()
			objects["root"].frames = currentfile["frames"]
			for i in range(1, len(currentfilebase)):
				obtemp = eval (currentfilebase[i])
				currentfile["objects"][obtemp.name] = obtemp
			currentselect = ["root", None]
			for i in currentfile["colors"]["images"]:
				currentfile["colors"]["images"][i] = os.environ["TEMP"]+sep+"swift"+str(pid)+"/"+currentfile["colors"]["images"][i]
			level = 0
			fc.close()
			window.set_title("Swift - "+title+".swift")
			selectid=["#000000"]
			selectors=[None]
			for i in currentfile["objects"]:
				window.AddLibItem([None, i, 1])
				if currentfile["objects"][i].type=="box":
					#Ugly expression meaning add 1 to highest hex value
					selectid.append("#01"+("%X" % (int(selectid[-1][3:7], 16)+1)).zfill(4))
					selectors.append(i)
				elif currentfile["objects"][i].type=="ellipse":
					selectid.append("#02"+("%X" % (int(selectid[-1][3:7], 16)+1)).zfill(4))
					selectors.append(i)
				elif currentfile["objects"][i].type=="curve":
					selectid.append("#03"+("%X" % (int(selectid[-1][3:7], 16)+1)).zfill(4))
					selectors.append(i)
				elif currentfile["objects"][i].type=="shape":
					selectid.append("#03"+("%X" % (int(selectid[-1][3:7], 16)+1)).zfill(4))
					selectors.append(i)
				
			print selectid, selectors
			expostagevent(stage, "expose-event")
			buff = window.builder.get_object("textview1").get_buffer()
			buff.set_text(str(currentfile))
			window.builder.get_object("textview1").set_wrap_mode(gtk.WRAP_CHAR)
			#for i in currentfile["objects"]:
			#	entry=i
			#	image = gtk.Image()
			#	image.set_from_file("../media/icon.png")
			#	image.show()
			#	window.AddLibItem([image,  entry, "1"])
			#close the dialog, and check whether to proceed

		
	else:
		alert("Swift is already running!", True)
		print "Swift is already running!"
		
	gtk.main()
