refactoring - library support is not anymore attached to configtree nodes, but handles by project controller
--- a/ConfigTreeNode.py Wed May 09 00:39:54 2012 +0200
+++ b/ConfigTreeNode.py Sat May 12 11:21:10 2012 +0200
@@ -61,7 +61,6 @@
# copy ConfNodeMethods so that it can be later customized
self.ConfNodeMethods = [dic.copy() for dic in self.ConfNodeMethods]
def ConfNodeBaseXmlFilePath(self, CTNName=None):
return os.path.join(self.CTNPath(CTNName), "baseconfnode.xml")
@@ -69,9 +68,6 @@
def ConfNodeXmlFilePath(self, CTNName=None):
return os.path.join(self.CTNPath(CTNName), "confnode.xml")
- def ConfNodeLibraryFilePath(self):
- return os.path.join(self.ConfNodePath(), "pous.xml")
return os.path.join(self.CTNParent.ConfNodePath(), self.CTNType)
@@ -252,32 +248,6 @@
return LocationCFilesAndCFLAGS, LDFLAGS, extra_files
- def ConfNodeTypesFactory(self):
- if self.LibraryControler is not None:
- return [{"name" : self.CTNType, "types": self.LibraryControler.Project}]
- def ParentsTypesFactory(self):
- return self.CTNParent.ParentsTypesFactory() + self.ConfNodeTypesFactory()
- def ConfNodesTypesFactory(self):
- list = self.ConfNodeTypesFactory()
- for CTNChild in self.IterChildren():
- list += CTNChild.ConfNodesTypesFactory()
- def STLibraryFactory(self):
- if self.LibraryControler is not None:
- program, errors, warnings = self.LibraryControler.GenerateProgram()
- def ConfNodesSTLibraryFactory(self):
- program = self.STLibraryFactory()
- for CTNChild in self.IECSortedChildren():
- program += CTNChild.ConfNodesSTLibraryFactory()
for CTNType, Children in self.Children.items():
for CTNInstance in Children:
@@ -563,15 +533,6 @@
- def LoadSTLibrary(self):
- # Get library blocks if plcopen library exist
- library_path = self.ConfNodeLibraryFilePath()
- if os.path.isfile(library_path):
- self.LibraryControler = PLCControler()
- self.LibraryControler.OpenXMLFile(library_path)
- self.LibraryControler.ClearConfNodeTypes()
- self.LibraryControler.AddConfNodeTypesList(self.ParentsTypesFactory())
def LoadXMLParams(self, CTNName = None):
methode_name = os.path.join(self.CTNPath(CTNName), "methods.py")
if os.path.isfile(methode_name):
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/POULibrary.py Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,27 @@
+from PLCControler import PLCControler + def __init__(self, TypeStack): + self.LibraryControler = PLCControler() + self.LibraryControler.OpenXMLFile(self.GetLibraryPath()) + self.LibraryControler.ClearConfNodeTypes() + self.LibraryControler.AddConfNodeTypesList(TypeStack) + self.program = self.LibraryControler.GenerateProgram()[0]+"\n" + raise Exception("Not implemented") + return {"name" : self.GetName(), "types": self.LibraryControler.Project} + def GetLibraryPath(self): + raise Exception("Not implemented") + def Generate_C(self, buildpath, varlist, IECCFLAGS): + # Pure python or IEC libs doesn't produce C code + return ((""), [], False), "" --- a/ProjectController.py Wed May 09 00:39:54 2012 +0200
+++ b/ProjectController.py Sat May 12 11:21:10 2012 +0200
@@ -1,5 +1,5 @@
-Base definitions for beremiz confnodes
+Beremiz Project Controller @@ -61,7 +61,8 @@
<xsd:attribute name="URI_location" type="xsd:string" use="optional" default=""/>
- <xsd:attribute name="Enable_ConfNodes" type="xsd:boolean" use="optional" default="true"/>
+ <xsd:attribute name="Disable_Extensions" type="xsd:boolean" use="optional" default="false"/> + """+"\n".join(['<xsd:attribute name="Enable_'+lib.rsplit('.',1)[-1]+'" type="xsd:boolean" use="optional" default="true"/>' for lib in features.libraries])+""" @@ -84,10 +85,6 @@
self.ResetIECProgramsAndVariables()
- #This method are not called here... but in NewProject and OpenProject
- #self._AddParamsMembers()
# In both new or load scenario, no need to save
self.ChangesToSave = False
@@ -104,7 +101,15 @@
self.previous_plcstate = None
# copy ConfNodeMethods so that it can be later customized
self.ConfNodeMethods = [dic.copy() for dic in self.ConfNodeMethods]
+ def LoadLibraries(self): + for clsname in features.libraries: + if getattr(self.BeremizRoot, "Enable_"+clsname.rsplit('.',1)[-1]): + Lib = GetClassImporter(clsname)()(TypeStack) + TypeStack.append(Lib.GetTypes()) + self.Libraries.append(Lib) @@ -132,9 +137,6 @@
- def ConfNodeLibraryFilePath(self):
- return os.path.join(os.path.split(__file__)[0], "pous.xml")
def CTNTestModified(self):
return self.ChangesToSave or not self.ProjectIsSaved()
@@ -311,12 +313,31 @@
self._setBuildPath(self.BuildPath)
+ def GetLibrariesTypes(self): + return [ lib.GetTypes() for lib in self.Libraries ] + def GetLibrariesSTCode(self): + return "\n".join([ lib.GetSTCode() for lib in self.Libraries ]) + def GetLibrariesCCode(self, buildpath): + self.GetIECProgramsAndVariables() + LibIECCflags = '"-I%s"'%os.path.abspath(self.GetIECLibPath()) + LocatedCCodeAndFlags=[] + for lib in self.Libraries: + res=lib.Generate_C(buildpath,self._VariablesList,LibIECCflags) + LocatedCCodeAndFlags.append(res[:2]) + return map(list,zip(*LocatedCCodeAndFlags))+[tuple(Extras)] # Update PLCOpenEditor ConfNode Block types from loaded confnodes
def RefreshConfNodesBlockLists(self):
if getattr(self, "Children", None) is not None:
self.ClearConfNodeTypes()
- self.AddConfNodeTypesList(self.ConfNodesTypesFactory())
+ self.AddConfNodeTypesList(self.GetLibrariesTypes()) if self.AppFrame is not None:
self.AppFrame.RefreshLibraryPanel()
self.AppFrame.RefreshEditor()
@@ -449,7 +470,7 @@
plc_file = open(self._getIECcodepath(), "w")
# Add ST Library from confnodes
- plc_file.write(self.ConfNodesSTLibraryFactory())
+ plc_file.write(self.GetLibrariesSTCode()) if os.path.isfile(self._getIECrawcodepath()):
plc_file.write(open(self._getIECrawcodepath(), "r").read())
@@ -708,7 +729,7 @@
[loc for loc,Cfiles,DoCalls in self.LocationCFilesAndCFLAGS if loc and DoCalls])
# Generate main, based on template
- if self.BeremizRoot.getEnable_ConfNodes():
+ if not self.BeremizRoot.getDisable_Extensions(): plc_main_code = targets.code("plc_common_main") % {
"calls_prototypes":"\n".join([(
"int __init_%(s)s(int argc,char **argv);\n"+
@@ -774,7 +795,7 @@
# Generate C code and compilation params from confnode hierarchy
- self.LocationCFilesAndCFLAGS, self.LDFLAGS, ExtraFiles = self._Generate_C(
+ CTNLocationCFilesAndCFLAGS, CTNLDFLAGS, CTNExtraFiles = self._Generate_C( self.PLCGeneratedLocatedVars)
@@ -783,6 +804,19 @@
+ # Generate C code and compilation params from liraries + LibCFilesAndCFLAGS, LibLDFLAGS, LibExtraFiles = self.GetLibrariesCCode(buildpath) + self.logger.write_error(_("Runtime extensions C code generation failed !\n")) + self.logger.write_error(traceback.format_exc()) + self.LocationCFilesAndCFLAGS = CTNLocationCFilesAndCFLAGS + LibCFilesAndCFLAGS + self.LDFLAGS = CTNLDFLAGS + LibLDFLAGS + ExtraFiles = CTNExtraFiles + LibExtraFiles # Get temporary directory path
extrafilespath = self._getExtraFilesPath()
--- a/features.py Wed May 09 00:39:54 2012 +0200
+++ b/features.py Sat May 12 11:21:10 2012 +0200
@@ -1,7 +1,10 @@
-from os import listdir, path
+libraries = ['py_ext.PythonLibrary', ('canfestival', _('CANopen support'), _('Map located variables over CANopen'), 'canfestival.canfestival.RootClass'),
- ('c_ext', _('C extention'), _('Extend project with C code accessing located variables'), 'c_ext.c_ext.RootClass'),
- ('py_ext', _('Python extention'), _('Extend project with Pyhon code executed asynchronously'), 'py_ext.py_ext.RootClass')]
+ ('c_ext', _('C extention'), _('Add C code accessing located variables synchronously'), 'c_ext.c_ext.RootClass'), + ('py_ext', _('Python file'), _('Add Python code executed asynchronously'), 'py_ext.PythonFile'), + ('wxglade_hmi', _('WxGlade GUI'), _('Add a simple WxGlade based GUI.'), 'wxglade_hmi.WxGladeHMI'), + ('svgui', _('SVGUI'), _('Experimental web based HMI'), 'svgui.SVGUI')] --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/py_ext/PythonFileCTNMixin.py Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,118 @@
+from PLCControler import UndoBuffer +from PythonEditor import PythonEditor +from xml.dom import minidom +PythonClasses = GenerateClassesFromXSD(os.path.join(os.path.dirname(__file__), "py_ext_xsd.xsd")) +class PythonFileCTNMixin: + EditorType = PythonEditor + self.ConfNodeMethods.insert(0, + {"bitmap" : opjimg("editPYTHONcode"), + "name" : _("Edit Python File"), + "tooltip" : _("Edit Python File"), + "method" : "_OpenView"}, + filepath = self.PythonFileName() + self.PythonCode = PythonClasses["Python"]() + if os.path.isfile(filepath): + xmlfile = open(filepath, 'r') + tree = minidom.parse(xmlfile) + for child in tree.childNodes: + if child.nodeType == tree.ELEMENT_NODE and child.nodeName == "Python": + self.PythonCode.loadXMLTree(child, ["xmlns", "xmlns:xsi", "xsi:schemaLocation"]) + self.CreatePythonBuffer(True) + self.CreatePythonBuffer(False) + def PythonFileName(self): + return os.path.join(self.CTNPath(), "py_ext.xml") + if self.PythonBuffer.IsCurrentSaved(): + def SetPythonCode(self, text): + self.PythonCode.settext(text) + def GetPythonCode(self): + return self.PythonCode.gettext() + def CTNTestModified(self): + return self.ChangesToSave or not self.PythonIsSaved() + filepath = self.PythonFileName() + text = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + extras = {"xmlns":"http://www.w3.org/2001/XMLSchema", + "xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance", + "xsi:schemaLocation" : "py_ext_xsd.xsd"} + text += self.PythonCode.generateXMLText("Python", 0, extras) + xmlfile = open(filepath,"w") + xmlfile.write(text.encode("utf-8")) + self.MarkPythonAsSaved() +#------------------------------------------------------------------------------- +# Current Buffering Management Functions +#------------------------------------------------------------------------------- + Return a copy of the project + return cPickle.loads(cPickle.dumps(model)) + def CreatePythonBuffer(self, saved): + self.PythonBuffer = UndoBuffer(cPickle.dumps(self.PythonCode), saved) + def BufferPython(self): + self.PythonBuffer.Buffering(cPickle.dumps(self.PythonCode)) + def StartBuffering(self): + def EndBuffering(self): + self.PythonBuffer.Buffering(cPickle.dumps(self.PythonCode)) + def MarkPythonAsSaved(self): + self.PythonBuffer.CurrentSaved() + def PythonIsSaved(self): + return self.PythonBuffer.IsCurrentSaved() and not self.Buffering + def LoadPrevious(self): + self.PythonCode = cPickle.loads(self.PythonBuffer.Previous()) + self.PythonCode = cPickle.loads(self.PythonBuffer.Next()) + def GetBufferState(self): + first = self.PythonBuffer.IsFirst() and not self.Buffering + last = self.PythonBuffer.IsLast() + return not first, not last --- a/py_ext/__init__.py Wed May 09 00:39:54 2012 +0200
+++ b/py_ext/__init__.py Sat May 12 11:21:10 2012 +0200
@@ -1,1 +1,3 @@
+from PythonEditor import PythonEditor +from PythonFileCTNMixin import PythonFileCTNMixin --- a/py_ext/modules/__init__.py Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,13 +0,0 @@
-from os import listdir, path
-_base_path = path.split(__file__)[0]
-__all__ = [name for name in listdir(_base_path) if path.isdir(path.join(_base_path, name)) and name.upper() != "CVS" or name.endswith(".py") and not name.startswith("__")]
- helpfilename = path.join(_base_path, name, "README")
- if path.isfile(helpfilename):
- helps.append(open(helpfilename).readline().strip())
--- a/py_ext/modules/svgui/README Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,1 +0,0 @@
\ No newline at end of file
--- a/py_ext/modules/svgui/__init__.py Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,1 +0,0 @@
--- a/py_ext/modules/svgui/livesvg.js Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,59 +0,0 @@
-function updateAttr(id, param, value) {
- Nevow.Athena.Widget.fromAthenaID(1).callRemote('HMIexec', 'setattr', id, param, value);
-var svguiWidgets = new Array();
-var currentObject = null;
-function setCurrentObject(obj) {
-function isCurrentObject(obj) {
- return currentObject == obj;
-function getSVGElementById(id) {
- return document.getElementById(id);
-function blockSVGElementDrag(element) {
- element.addEventListener("draggesture", function(event){event.stopPropagation()}, true);
-LiveSVGPage.LiveSVGWidget = Nevow.Athena.Widget.subclass('LiveSVGPage.LiveSVGWidget');
-LiveSVGPage.LiveSVGWidget.methods(
- function handleEvent(self, evt) {
- if (currentObject != null) {
- currentObject.handleEvent(evt);
- function receiveData(self, data){
- dataReceived = json_parse(data);
- gadget = svguiWidgets[dataReceived.id]
- gadget.updateValues(json_parse(dataReceived.kwargs));
- //console.log("OBJET : " + dataReceived.back_id + " STATE : " + newState);
- function init(self, arg1){
- //console.log("Object received : " + arg1);
- gad = json_parse(arg1[ind]);
- args = json_parse(gad.kwargs);
- gadget = new svguilib[gad.__class__](self, gad.id, args);
- svguiWidgets[gadget.id]=gadget;
- //console.log('GADGET :' + gadget);
- var elements = document.getElementsByTagName("svg");
- for (var i = 0; i < elements.length; i++) {
- elements[i].addEventListener("mouseup", self, false);
- //console.log("SVGUIWIDGETS : " + svguiWidgets);
--- a/py_ext/modules/svgui/pous.xml Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,1428 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns="http://www.plcopen.org/xml/tc6.xsd"
- xmlns:xhtml="http://www.w3.org/1999/xhtml"
- xsi:schemaLocation="http://www.plcopen.org/xml/tc6.xsd">
- <fileHeader companyName="Beremiz"
- creationDateTime="2008-12-14T16:53:26"/>
- <contentHeader name="Beremiz non-standard POUs library"
- modificationDateTime="2009-08-12T15:35:33">
- <pou name="GetBoolString" pouType="functionBlock">
- <variable name="VALUE">
- <pou name="TextCtrl" pouType="functionBlock">
- <variable name="back_id">
- <variable name="set_text">
- <variable name="SVGUI_TEXTCTRL">
- <derived name="python_eval"/>
- <variable name="setstate_Command">
- <derived name="python_eval"/>
- <block localId="1" width="193" height="160" typeName="CONCAT">
- <position x="626" y="122"/>
- <variable formalParameter="IN1">
- <relPosition x="0" y="43"/>
- <connection refLocalId="2">
- <position x="626" y="165"/>
- <position x="535" y="165"/>
- <variable formalParameter="IN2">
- <relPosition x="0" y="89"/>
- <connection refLocalId="3">
- <position x="626" y="211"/>
- <position x="535" y="211"/>
- <variable formalParameter="IN3">
- <relPosition x="0" y="135"/>
- <connection refLocalId="6">
- <position x="626" y="257"/>
- <position x="532" y="257"/>
- <variable formalParameter="OUT">
- <relPosition x="193" y="43"/>
- <inVariable localId="2" height="30" width="460">
- <position x="75" y="150"/>
- <relPosition x="460" y="15"/>
- <expression>'createSVGUIControl("textControl", back_id="'</expression>
- <inVariable localId="3" height="35" width="85">
- <position x="450" y="196"/>
- <relPosition x="85" y="15"/>
- <expression>back_id</expression>
- <inVariable localId="6" height="30" width="50">
- <position x="482" y="242"/>
- <relPosition x="50" y="15"/>
- <expression>'")'</expression>
- <block localId="7" width="125" height="115" typeName="python_eval" instanceName="SVGUI_TEXTCTRL">
- <position x="909" y="75"/>
- <variable formalParameter="TRIG">
- <relPosition x="0" y="45"/>
- <connection refLocalId="9">
- <position x="909" y="120"/>
- <position x="886" y="120"/>
- <position x="886" y="85"/>
- <position x="869" y="85"/>
- <variable formalParameter="CODE">
- <relPosition x="0" y="90"/>
- <connection refLocalId="1" formalParameter="OUT">
- <position x="909" y="165"/>
- <position x="819" y="165"/>
- <variable formalParameter="ACK">
- <relPosition x="125" y="45"/>
- <variable formalParameter="RESULT">
- <relPosition x="125" y="90"/>
- <inVariable localId="9" height="30" width="70">
- <position x="799" y="70"/>
- <relPosition x="70" y="15"/>
- <expression>BOOL#1</expression>
- <outVariable localId="10" height="30" width="30">
- <position x="1094" y="150"/>
- <relPosition x="0" y="15"/>
- <connection refLocalId="7" formalParameter="RESULT">
- <position x="1094" y="165"/>
- <position x="1034" y="165"/>
- <expression>ID</expression>
- <connector name="CREATED" localId="11" height="30" width="110">
- <position x="1096" y="105"/>
- <relPosition x="0" y="15"/>
- <connection refLocalId="7" formalParameter="ACK">
- <position x="1096" y="120"/>
- <position x="1034" y="120"/>
- <block localId="4" width="125" height="140" typeName="python_eval" instanceName="setstate_Command">
- <position x="957" y="472"/>
- <variable formalParameter="TRIG">
- <relPosition x="0" y="50"/>
- <connection refLocalId="31" formalParameter="OUT">
- <position x="957" y="522"/>
- <position x="909" y="522"/>
- <position x="909" y="444"/>
- <position x="857" y="444"/>
- <variable formalParameter="CODE">
- <relPosition x="0" y="110"/>
- <connection refLocalId="12" formalParameter="OUT">
- <position x="957" y="582"/>
- <position x="822" y="582"/>
- <variable formalParameter="ACK">
- <relPosition x="125" y="50"/>
- <variable formalParameter="RESULT">
- <relPosition x="125" y="110"/>
- <continuation name="CREATED" localId="5" height="30" width="110">
- <position x="589" y="429"/>
- <relPosition x="110" y="15"/>
- <block localId="12" width="186" height="288" typeName="CONCAT">
- <position x="636" y="536"/>
- <variable formalParameter="IN1">
- <relPosition x="0" y="46"/>
- <connection refLocalId="14">
- <position x="636" y="582"/>
- <position x="526" y="582"/>
- <variable formalParameter="IN2">
- <relPosition x="0" y="99"/>
- <connection refLocalId="8">
- <position x="636" y="635"/>
- <position x="526" y="635"/>
- <variable formalParameter="IN3">
- <relPosition x="0" y="152"/>
- <connection refLocalId="15">
- <position x="636" y="688"/>
- <position x="527" y="688"/>
- <variable formalParameter="IN4">
- <relPosition x="0" y="205"/>
- <connection refLocalId="32">
- <position x="636" y="741"/>
- <position x="528" y="741"/>
- <variable formalParameter="IN5">
- <relPosition x="0" y="258"/>
- <connection refLocalId="16">
- <position x="636" y="794"/>
- <position x="528" y="794"/>
- <variable formalParameter="OUT">
- <relPosition x="186" y="46"/>
- <inVariable localId="8" height="30" width="53">
- <position x="473" y="620"/>
- <relPosition x="53" y="15"/>
- <expression>ID</expression>
- <inVariable localId="13" height="35" width="100">
- <position x="599" y="469"/>
- <relPosition x="100" y="17"/>
- <expression>set_text</expression>
- <inVariable localId="14" height="30" width="120">
- <position x="406" y="567"/>
- <relPosition x="120" y="15"/>
- <expression>'setAttr('</expression>
- <inVariable localId="15" height="30" width="122">
- <position x="405" y="673"/>
- <relPosition x="122" y="15"/>
- <expression>',"text","'</expression>
- <inVariable localId="16" height="30" width="50">
- <position x="478" y="779"/>
- <relPosition x="50" y="15"/>
- <expression>'")'</expression>
- <block localId="31" width="75" height="105" typeName="AND">
- <position x="782" y="403"/>
- <variable formalParameter="IN1">
- <relPosition x="0" y="41"/>
- <connection refLocalId="5">
- <position x="782" y="444"/>
- <position x="699" y="444"/>
- <variable formalParameter="IN2">
- <relPosition x="0" y="83"/>
- <connection refLocalId="13">
- <position x="782" y="486"/>
- <position x="699" y="486"/>
- <variable formalParameter="OUT">
- <relPosition x="75" y="41"/>
- <inVariable localId="32" height="30" width="90">
- <position x="438" y="726"/>
- <relPosition x="90" y="15"/>
- <expression>text</expression>
- <pou name="Button" pouType="functionBlock">
- <variable name="back_id">
- <variable name="sele_id">
- <variable name="toggle">
- <variable name="set_state">
- <variable name="state_in">
- <variable name="state_out">
- <variable name="init_Command">
- <derived name="python_eval"/>
- <variable name="GetButtonState">
- <derived name="GetBoolString"/>
- <variable name="setstate_Command">
- <derived name="python_eval"/>
- <variable name="getstate_Command">
- <derived name="python_poll"/>
- <variable name="GetButtonToggle">
- <derived name="GetBoolString"/>
- <block localId="1" width="125" height="140" typeName="python_eval" instanceName="init_Command">
- <position x="838" y="32"/>
- <variable formalParameter="TRIG">
- <relPosition x="0" y="50"/>
- <connection refLocalId="10">
- <position x="838" y="82"/>
- <position x="781" y="82"/>
- <variable formalParameter="CODE">
- <relPosition x="0" y="110"/>
- <connection refLocalId="2" formalParameter="OUT">
- <position x="838" y="142"/>
- <position x="641" y="142"/>
- <variable formalParameter="ACK">
- <relPosition x="125" y="50"/>
- <variable formalParameter="RESULT">
- <relPosition x="125" y="110"/>
- <block localId="2" width="150" height="442" typeName="CONCAT">
- <position x="491" y="92"/>
- <variable formalParameter="IN1">
- <relPosition x="0" y="50"/>
- <connection refLocalId="3">
- <position x="491" y="142"/>
- <position x="433" y="142"/>
- <variable formalParameter="IN2">
- <relPosition x="0" y="110"/>
- <connection refLocalId="11">
- <position x="491" y="202"/>
- <position x="431" y="202"/>
- <variable formalParameter="IN3">
- <relPosition x="0" y="170"/>
- <connection refLocalId="5">
- <position x="491" y="262"/>
- <position x="431" y="262"/>
- <variable formalParameter="IN4">
- <relPosition x="0" y="230"/>
- <connection refLocalId="12">
- <position x="491" y="322"/>
- <position x="430" y="322"/>
- <variable formalParameter="IN5">
- <relPosition x="0" y="290"/>
- <connection refLocalId="23">
- <position x="491" y="382"/>
- <position x="463" y="382"/>
- <position x="463" y="370"/>
- <position x="430" y="370"/>
- <variable formalParameter="IN6">
- <relPosition x="0" y="350"/>
- <connection refLocalId="24" formalParameter="CODE">
- <position x="491" y="442"/>
- <position x="429" y="442"/>
- <variable formalParameter="IN7">
- <relPosition x="0" y="410"/>
- <connection refLocalId="9">
- <position x="491" y="502"/>
- <position x="430" y="502"/>
- <variable formalParameter="OUT">
- <relPosition x="150" y="50"/>
- <inVariable localId="3" height="30" width="400">
- <position x="33" y="127"/>
- <relPosition x="400" y="15"/>
- <expression>'createSVGUIControl("button",back_id="'</expression>
- <inVariable localId="5" height="30" width="140">
- <position x="291" y="247"/>
- <relPosition x="140" y="15"/>
- <expression>'",sele_id="'</expression>
- <inVariable localId="9" height="30" width="180">
- <position x="250" y="487"/>
- <relPosition x="180" y="15"/>
- <expression>',active=True)'</expression>
- <inVariable localId="10" height="30" width="70">
- <position x="711" y="67"/>
- <relPosition x="70" y="15"/>
- <expression>BOOL#1</expression>
- <inVariable localId="11" height="35" width="85">
- <position x="346" y="187"/>
- <relPosition x="85" y="15"/>
- <expression>back_id</expression>
- <inVariable localId="12" height="35" width="85">
- <position x="345" y="307"/>
- <relPosition x="85" y="15"/>
- <expression>sele_id</expression>
- <inVariable localId="13" height="35" width="100">
- <position x="452" y="639"/>
- <relPosition x="100" y="15"/>
- <expression>set_state</expression>
- <block localId="28" width="140" height="40" typeName="GetBoolString" instanceName="GetButtonState">
- <position x="239" y="897"/>
- <variable formalParameter="VALUE">
- <relPosition x="0" y="30"/>
- <connection refLocalId="32">
- <position x="239" y="927"/>
- <position x="181" y="927"/>
- <variable formalParameter="CODE">
- <relPosition x="140" y="30"/>
- <outVariable localId="29" height="30" width="53">
- <position x="1015" y="127"/>
- <relPosition x="0" y="15"/>
- <connection refLocalId="1" formalParameter="RESULT">
- <position x="1015" y="142"/>
- <position x="963" y="142"/>
- <expression>ID</expression>
- <block localId="4" width="125" height="140" typeName="python_eval" instanceName="setstate_Command">
- <position x="810" y="640"/>
- <variable formalParameter="TRIG">
- <relPosition x="0" y="50"/>
- <connection refLocalId="31" formalParameter="OUT">
- <position x="810" y="690"/>
- <position x="762" y="690"/>
- <position x="762" y="612"/>
- <position x="710" y="612"/>
- <variable formalParameter="CODE">
- <relPosition x="0" y="110"/>
- <connection refLocalId="7" formalParameter="OUT">
- <position x="810" y="750"/>
- <position x="643" y="750"/>
- <variable formalParameter="ACK">
- <relPosition x="125" y="50"/>
- <variable formalParameter="RESULT">
- <relPosition x="125" y="110"/>
- <connector name="CREATED" localId="30" height="30" width="110">
- <position x="1014" y="67"/>
- <relPosition x="0" y="15"/>
- <connection refLocalId="1" formalParameter="ACK">
- <position x="1014" y="82"/>
- <position x="963" y="82"/>
- <continuation name="CREATED" localId="6" height="30" width="110">
- <position x="442" y="597"/>
- <relPosition x="110" y="15"/>
- <block localId="31" width="75" height="105" typeName="AND">
- <position x="635" y="571"/>
- <variable formalParameter="IN1">
- <relPosition x="0" y="41"/>
- <connection refLocalId="6">
- <position x="635" y="612"/>
- <position x="552" y="612"/>
- <variable formalParameter="IN2">
- <relPosition x="0" y="83"/>
- <connection refLocalId="13">
- <position x="635" y="654"/>
- <position x="552" y="654"/>
- <variable formalParameter="OUT">
- <relPosition x="75" y="41"/>
- <inVariable localId="32" height="30" width="90">
- <position x="91" y="912"/>
- <relPosition x="90" y="15"/>
- <expression>state_in</expression>
- <outVariable localId="33" height="30" width="100">
- <position x="1334" y="1184"/>
- <relPosition x="0" y="15"/>
- <connection refLocalId="26" formalParameter="OUT">
- <position x="1334" y="1199"/>
- <position x="1286" y="1199"/>
- <expression>state_out</expression>
- <block localId="7" width="150" height="319" typeName="CONCAT">
- <position x="493" y="701"/>
- <variable formalParameter="IN1">
- <relPosition x="0" y="49"/>
- <connection refLocalId="14">
- <position x="493" y="750"/>
- <position x="379" y="750"/>
- <variable formalParameter="IN2">
- <relPosition x="0" y="108"/>
- <connection refLocalId="8">
- <position x="493" y="809"/>
- <position x="435" y="809"/>
- <position x="435" y="803"/>
- <position x="379" y="803"/>
- <variable formalParameter="IN3">
- <relPosition x="0" y="167"/>
- <connection refLocalId="15">
- <position x="493" y="868"/>
- <position x="435" y="868"/>
- <position x="435" y="855"/>
- <position x="379" y="855"/>
- <variable formalParameter="IN4">
- <relPosition x="0" y="226"/>
- <connection refLocalId="28" formalParameter="CODE">
- <position x="493" y="927"/>
- <position x="379" y="927"/>
- <variable formalParameter="IN5">
- <relPosition x="0" y="285"/>
- <connection refLocalId="16">
- <position x="493" y="986"/>
- <position x="377" y="986"/>
- <variable formalParameter="OUT">
- <relPosition x="150" y="49"/>
- <inVariable localId="8" height="30" width="53">
- <position x="326" y="788"/>
- <relPosition x="53" y="15"/>
- <expression>ID</expression>
- <inVariable localId="14" height="30" width="120">
- <position x="259" y="735"/>
- <relPosition x="120" y="15"/>
- <expression>'setAttr('</expression>
- <inVariable localId="15" height="30" width="122">
- <position x="257" y="840"/>
- <relPosition x="122" y="15"/>
- <expression>',"state",'</expression>
- <inVariable localId="16" height="30" width="41">
- <position x="336" y="971"/>
- <relPosition x="41" y="15"/>
- <expression>')'</expression>
- <block localId="17" width="125" height="140" typeName="python_poll" instanceName="getstate_Command">
- <position x="801" y="1089"/>
- <variable formalParameter="TRIG">
- <relPosition x="0" y="50"/>
- <connection refLocalId="18">
- <position x="801" y="1139"/>
- <position x="763" y="1139"/>
- <position x="763" y="1099"/>
- <position x="720" y="1099"/>
- <variable formalParameter="CODE">
- <relPosition x="0" y="110"/>
- <connection refLocalId="22" formalParameter="OUT">
- <position x="801" y="1199"/>
- <position x="643" y="1199"/>
- <variable formalParameter="ACK">
- <relPosition x="125" y="50"/>
- <variable formalParameter="RESULT">
- <relPosition x="125" y="110"/>
- <block localId="25" width="145" height="45" typeName="STRING_TO_INT">
- <position x="966" y="1169"/>
- <variable formalParameter="IN">
- <relPosition x="0" y="30"/>
- <connection refLocalId="17" formalParameter="RESULT">
- <position x="966" y="1199"/>
- <position x="926" y="1199"/>
- <variable formalParameter="OUT">
- <relPosition x="145" y="30"/>
- <block localId="26" width="125" height="45" typeName="INT_TO_BOOL">
- <position x="1161" y="1169"/>
- <variable formalParameter="IN">
- <relPosition x="0" y="30"/>
- <connection refLocalId="25" formalParameter="OUT">
- <position x="1161" y="1199"/>
- <position x="1111" y="1199"/>
- <variable formalParameter="OUT">
- <relPosition x="125" y="30"/>
- <continuation name="CREATED" localId="18" height="30" width="110">
- <position x="610" y="1084"/>
- <relPosition x="110" y="15"/>
- <inVariable localId="19" height="30" width="53">
- <position x="383" y="1238"/>
- <relPosition x="53" y="15"/>
- <expression>ID</expression>
- <inVariable localId="20" height="30" width="150">
- <position x="286" y="1184"/>
- <relPosition x="150" y="15"/>
- <expression>'int(getAttr('</expression>
- <inVariable localId="21" height="30" width="190">
- <position x="246" y="1292"/>
- <relPosition x="190" y="15"/>
- <expression>',"state",False))'</expression>
- <block localId="22" width="150" height="183" typeName="CONCAT">
- <position x="493" y="1152"/>
- <variable formalParameter="IN1">
- <relPosition x="0" y="47"/>
- <connection refLocalId="20">
- <position x="493" y="1199"/>
- <position x="436" y="1199"/>
- <variable formalParameter="IN2">
- <relPosition x="0" y="101"/>
- <connection refLocalId="19">
- <position x="493" y="1253"/>
- <position x="436" y="1253"/>
- <variable formalParameter="IN3">
- <relPosition x="0" y="155"/>
- <connection refLocalId="21">
- <position x="493" y="1307"/>
- <position x="483" y="1307"/>
- <position x="483" y="1307"/>
- <position x="436" y="1307"/>
- <variable formalParameter="OUT">
- <relPosition x="150" y="47"/>
- <inVariable localId="23" height="30" width="130">
- <position x="300" y="355"/>
- <relPosition x="130" y="15"/>
- <expression>'",toggle='</expression>
- <block localId="24" width="140" height="40" typeName="GetBoolString" instanceName="GetButtonToggle">
- <position x="289" y="412"/>
- <variable formalParameter="VALUE">
- <relPosition x="0" y="30"/>
- <connection refLocalId="27">
- <position x="289" y="442"/>
- <position x="220" y="442"/>
- <variable formalParameter="CODE">
- <relPosition x="140" y="30"/>
- <inVariable localId="27" height="30" width="90">
- <position x="130" y="427"/>
- <relPosition x="90" y="15"/>
- <expression>toggle</expression>
- <pou name="Led" pouType="functionBlock">
- <variable name="back_id">
- <variable name="sele_id">
- <variable name="state_in">
- <variable name="init_Command">
- <derived name="python_eval"/>
- <variable name="setstate_Command">
- <derived name="python_poll"/>
- <variable name="GetLedState">
- <derived name="GetBoolString"/>
- <block localId="1" width="125" height="140" typeName="python_eval" instanceName="init_Command">
- <position x="810" y="30"/>
- <variable formalParameter="TRIG">
- <relPosition x="0" y="50"/>
- <connection refLocalId="10">
- <position x="810" y="80"/>
- <position x="753" y="80"/>
- <variable formalParameter="CODE">
- <relPosition x="0" y="110"/>
- <connection refLocalId="2" formalParameter="OUT">
- <position x="810" y="140"/>
- <position x="640" y="140"/>
- <variable formalParameter="ACK">
- <relPosition x="125" y="50"/>
- <variable formalParameter="RESULT">
- <relPosition x="125" y="110"/>
- <block localId="2" width="150" height="322" typeName="CONCAT">
- <position x="490" y="90"/>
- <variable formalParameter="IN1">
- <relPosition x="0" y="50"/>
- <connection refLocalId="3">
- <position x="490" y="140"/>
- <position x="415" y="140"/>
- <variable formalParameter="IN2">
- <relPosition x="0" y="110"/>
- <connection refLocalId="11">
- <position x="490" y="200"/>
- <position x="415" y="200"/>
- <variable formalParameter="IN3">
- <relPosition x="0" y="170"/>
- <connection refLocalId="5">
- <position x="490" y="260"/>
- <position x="415" y="260"/>
- <variable formalParameter="IN4">
- <relPosition x="0" y="230"/>
- <connection refLocalId="12">
- <position x="490" y="320"/>
- <position x="414" y="320"/>
- <variable formalParameter="IN5">
- <relPosition x="0" y="290"/>
- <connection refLocalId="9">
- <position x="490" y="380"/>
- <position x="414" y="380"/>
- <variable formalParameter="OUT">
- <relPosition x="150" y="50"/>
- <inVariable localId="3" height="30" width="400">
- <position x="15" y="125"/>
- <relPosition x="400" y="15"/>
- <expression>'createSVGUIControl("button",back_id="'</expression>
- <block localId="4" width="125" height="140" typeName="python_poll" instanceName="setstate_Command">
- <position x="782" y="536"/>
- <variable formalParameter="TRIG">
- <relPosition x="0" y="50"/>
- <connection refLocalId="6">
- <position x="782" y="586"/>
- <position x="653" y="586"/>
- <position x="653" y="552"/>
- <position x="602" y="552"/>
- <variable formalParameter="CODE">
- <relPosition x="0" y="110"/>
- <connection refLocalId="7" formalParameter="OUT">
- <position x="782" y="646"/>
- <position x="615" y="646"/>
- <variable formalParameter="ACK">
- <relPosition x="125" y="50"/>
- <variable formalParameter="RESULT">
- <relPosition x="125" y="110"/>
- <inVariable localId="5" height="30" width="140">
- <position x="275" y="245"/>
- <relPosition x="140" y="15"/>
- <expression>'",sele_id="'</expression>
- <continuation name="CREATED" localId="6" height="30" width="110">
- <position x="492" y="537"/>
- <relPosition x="110" y="15"/>
- <block localId="7" width="150" height="319" typeName="CONCAT">
- <position x="465" y="597"/>
- <variable formalParameter="IN1">
- <relPosition x="0" y="49"/>
- <connection refLocalId="14">
- <position x="465" y="646"/>
- <position x="351" y="646"/>
- <variable formalParameter="IN2">
- <relPosition x="0" y="108"/>
- <connection refLocalId="8">
- <position x="465" y="705"/>
- <position x="407" y="705"/>
- <position x="407" y="699"/>
- <position x="351" y="699"/>
- <variable formalParameter="IN3">
- <relPosition x="0" y="167"/>
- <connection refLocalId="15">
- <position x="465" y="764"/>
- <position x="407" y="764"/>
- <position x="407" y="751"/>
- <position x="351" y="751"/>
- <variable formalParameter="IN4">
- <relPosition x="0" y="226"/>
- <connection refLocalId="28" formalParameter="CODE">
- <position x="465" y="823"/>
- <position x="351" y="823"/>
- <variable formalParameter="IN5">
- <relPosition x="0" y="285"/>
- <connection refLocalId="16">
- <position x="465" y="882"/>
- <position x="407" y="882"/>
- <position x="407" y="883"/>
- <position x="351" y="883"/>
- <variable formalParameter="OUT">
- <relPosition x="150" y="49"/>
- <inVariable localId="8" height="30" width="53">
- <position x="298" y="684"/>
- <relPosition x="53" y="15"/>
- <expression>ID</expression>
- <inVariable localId="9" height="30" width="300">
- <position x="124" y="365"/>
- <relPosition x="300" y="15"/>
- <expression>'",toggle=True,active=False)'</expression>
- <inVariable localId="10" height="30" width="70">
- <position x="683" y="65"/>
- <relPosition x="70" y="15"/>
- <expression>BOOL#1</expression>
- <inVariable localId="11" height="35" width="85">
- <position x="330" y="185"/>
- <relPosition x="85" y="15"/>
- <expression>back_id</expression>
- <inVariable localId="12" height="35" width="85">
- <position x="329" y="305"/>
- <relPosition x="85" y="15"/>
- <expression>sele_id</expression>
- <inVariable localId="14" height="30" width="120">
- <position x="231" y="631"/>
- <relPosition x="120" y="15"/>
- <expression>'setAttr('</expression>
- <inVariable localId="15" height="30" width="122">
- <position x="229" y="736"/>
- <relPosition x="122" y="15"/>
- <expression>',"state",'</expression>
- <inVariable localId="16" height="30" width="41">
- <position x="310" y="868"/>
- <relPosition x="41" y="15"/>
- <expression>')'</expression>
- <block localId="28" width="140" height="40" typeName="GetBoolString" instanceName="GetLedState">
- <position x="211" y="793"/>
- <variable formalParameter="VALUE">
- <relPosition x="0" y="30"/>
- <connection refLocalId="32">
- <position x="211" y="823"/>
- <position x="153" y="823"/>
- <variable formalParameter="CODE">
- <relPosition x="140" y="30"/>
- <outVariable localId="29" height="30" width="53">
- <position x="987" y="125"/>
- <relPosition x="0" y="15"/>
- <connection refLocalId="1" formalParameter="RESULT">
- <position x="987" y="140"/>
- <position x="935" y="140"/>
- <expression>ID</expression>
- <connector name="CREATED" localId="30" height="30" width="110">
- <position x="986" y="65"/>
- <relPosition x="0" y="15"/>
- <connection refLocalId="1" formalParameter="ACK">
- <position x="986" y="80"/>
- <position x="935" y="80"/>
- <inVariable localId="32" height="30" width="90">
- <position x="63" y="808"/>
- <relPosition x="90" y="15"/>
- <expression>state_in</expression>
--- a/py_ext/modules/svgui/pyjs/__init__.py Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,2 +0,0 @@
--- a/py_ext/modules/svgui/pyjs/build.py Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,724 +0,0 @@
-from os.path import join, dirname, basename, abspath, split, isfile, isdir
-from optparse import OptionParser
-from cStringIO import StringIO
- from hashlib import md5
- usage: %prog [options] <application module name or path>
-This is the command line builder for the pyjamas project, which can
-be used to build Ajax applications from Python.
-For more information, see the website at http://pyjs.org/
-# GWT1.2 Impl | GWT1.2 Output | Pyjamas 0.2 Platform | Pyjamas 0.2 Output
-# -------------+-----------------------+----------------------+----------------------
-# Opera | opera | Opera | opera
-# Safari | safari | Safari | safari
-# -- | gecko1_8 | Mozilla | mozilla
-# -- | gecko | OldMoz | oldmoz
-# Standard | all | (default code) | all
-# Mozilla | gecko1_8, gecko | -- | --
-# Old | safari, gecko, opera | -- | --
-version = "%prog pyjamas version 2006-08-19"
-# these names in lowercase need match the strings
-# returned by "provider$user.agent" in order to be selected corretly
-app_platforms = ['IE6', 'Opera', 'OldMoz', 'Safari', 'Mozilla']
-# usually defaults to e.g. /usr/share/pyjamas
-_data_dir = os.path.join(pyjs.prefix, "share/pyjamas")
-# .cache.html files produces look like this
-CACHE_HTML_PAT=re.compile('^[a-z]*.[0-9a-f]{32}\.cache\.html$')
-# ok these are the three "default" library directories, containing
-# the builtins (str, List, Dict, ord, round, len, range etc.)
-# the main pyjamas libraries (pyjamas.ui, pyjamas.Window etc.)
-# and the contributed addons
-for p in ["library/builtins",
- p = os.path.join(_data_dir, p)
-def read_boilerplate(data_dir, filename):
- return open(join(data_dir, "builder/boilerplate", filename)).read()
-def copy_boilerplate(data_dir, filename, output_dir):
- filename = join(data_dir, "builder/boilerplate", filename)
- shutil.copy(filename, output_dir)
-# taken and modified from python2.4
-def copytree_exists(src, dst, symlinks=False):
- if not os.path.exists(src):
- names = os.listdir(src)
- if name.startswith('CVS'):
- if name.startswith('.git'):
- if name.startswith('.svn'):
- srcname = os.path.join(src, name)
- dstname = os.path.join(dst, name)
- if symlinks and os.path.islink(srcname):
- linkto = os.readlink(srcname)
- os.symlink(linkto, dstname)
- copytree_exists(srcname, dstname, symlinks)
- shutil.copy2(srcname, dstname)
- except (IOError, os.error), why:
- errors.append((srcname, dstname, why))
-def check_html_file(source_file, dest_path):
- """ Checks if a base HTML-file is available in the PyJamas
- If the HTML-file isn't available, it will be created.
- If a CSS-file with the same name is available
- in the output directory, a reference to this CSS-file
- If no CSS-file is found, this function will look for a special
- CSS-file in the output directory, with the name
- "pyjamas_default.css", and if found it will be referenced
- in the generated HTML-file.
- [thank you to stef mientki for contributing this function]
- <!-- auto-generated html - you should consider editing and
- adapting this to suit your requirements
- <meta name="pygwt:module" content="%(modulename)s">
- <title>%(title)s</title>
- <script language="javascript" src="pygwt.js"></script>
- filename = os.path.split ( source_file )[1]
- mod_name = os.path.splitext ( filename )[0]
- file_name = os.path.join ( dest_path, mod_name + '.html' )
- # if html file in output directory exists, leave it alone.
- if os.path.exists ( file_name ):
- os.path.join ( dest_path, mod_name + '.css' ) ) :
- css = "<link rel='stylesheet' href='" + mod_name + ".css'>"
- os.path.join ( dest_path, 'pyjamas_default.css' ) ) :
- css = "<link rel='stylesheet' href='pyjamas_default.css'>"
- title = 'PyJamas Auto-Generated HTML file ' + mod_name
- base_html = base_html % {'modulename': mod_name, 'title': title, 'css': css}
- fh = open (file_name, 'w')
-def build(app_name, output, js_includes=(), debug=False, dynamic=0,
- data_dir=None, cache_buster=False, optimize=False):
- # make sure the output directory is always created in the current working
- # directory or at the place given if it is an absolute path.
- output = os.path.abspath(output)
- msg = "Building '%(app_name)s' to output directory '%(output)s'" % locals()
- msg += " with debugging statements"
- # check the output directory
- if os.path.exists(output) and not os.path.isdir(output):
- print >>sys.stderr, "Output destination %s exists and is not a directory" % output
- if not os.path.isdir(output):
- print "Creating output directory"
- except StandardError, e:
- print >>sys.stderr, "Exception creating output directory %s: %s" % (output, e)
- pub_dir = join(p, 'public')
- print "Copying: public directory of library %r" % p
- copytree_exists(pub_dir, output)
- ## AppName.html - can be in current or public directory
- html_input_filename = app_name + ".html"
- html_output_filename = join(output, basename(html_input_filename))
- if os.path.isfile(html_input_filename):
- if not os.path.isfile(html_output_filename) or \
- os.path.getmtime(html_input_filename) > \
- os.path.getmtime(html_output_filename):
- shutil.copy(html_input_filename, html_output_filename)
- print >>sys.stderr, "Warning: Missing module HTML file %s" % html_input_filename
- print "Copying: %(html_input_filename)s" % locals()
- if check_html_file(html_input_filename, output):
- print >>sys.stderr, "Warning: Module HTML file %s has been auto-generated" % html_input_filename
- print "Copying: pygwt.js"
- pygwt_js_template = read_boilerplate(data_dir, "pygwt.js")
- pygwt_js_output = open(join(output, "pygwt.js"), "w")
- print >>pygwt_js_output, pygwt_js_template
- pygwt_js_output.close()
- print "Copying: Images and History"
- copy_boilerplate(data_dir, "corner_dialog_topleft_black.png", output)
- copy_boilerplate(data_dir, "corner_dialog_topright_black.png", output)
- copy_boilerplate(data_dir, "corner_dialog_bottomright_black.png", output)
- copy_boilerplate(data_dir, "corner_dialog_bottomleft_black.png", output)
- copy_boilerplate(data_dir, "corner_dialog_edge_black.png", output)
- copy_boilerplate(data_dir, "corner_dialog_topleft.png", output)
- copy_boilerplate(data_dir, "corner_dialog_topright.png", output)
- copy_boilerplate(data_dir, "corner_dialog_bottomright.png", output)
- copy_boilerplate(data_dir, "corner_dialog_bottomleft.png", output)
- copy_boilerplate(data_dir, "corner_dialog_edge.png", output)
- copy_boilerplate(data_dir, "tree_closed.gif", output)
- copy_boilerplate(data_dir, "tree_open.gif", output)
- copy_boilerplate(data_dir, "tree_white.gif", output)
- copy_boilerplate(data_dir, "history.html", output)
- app_files = generateAppFiles(data_dir, js_includes, app_name, debug,
- output, dynamic, cache_buster, optimize)
- ## AppName.nocache.html
- print "Creating: %(app_name)s.nocache.html" % locals()
- home_nocache_html_template = read_boilerplate(data_dir, "home.nocache.html")
- home_nocache_html_output = open(join(output, app_name + ".nocache.html"),
- # the selector templ is added to the selectScript function
- select_tmpl = """O(["true","%s"],"%s");"""
- script_selectors = StringIO()
- for platform, file_prefix in app_files:
- print >> script_selectors, select_tmpl % (platform, file_prefix)
- print >>home_nocache_html_output, home_nocache_html_template % dict(
- script_selectors = script_selectors.getvalue(),
- home_nocache_html_output.close()
- print "Done. You can run your app by opening '%(html_output_filename)s' in a browser" % locals()
-def generateAppFiles(data_dir, js_includes, app_name, debug, output, dynamic,
- cache_buster, optimize):
- all_cache_html_template = read_boilerplate(data_dir, "all.cache.html")
- mod_cache_html_template = read_boilerplate(data_dir, "mod.cache.html")
- # clean out the old ones first
- for name in os.listdir(output):
- if CACHE_HTML_PAT.match(name):
- print "Deleting existing app file %s" % p
- tmpl = read_boilerplate(data_dir, "all.cache.html")
- parser = pyjs.PlatformParser("platform")
- scripts = ['<script type="text/javascript" src="%s"></script>'%script \
- for script in js_includes]
- app_body = '\n'.join(scripts)
- # First, generate all the code.
- # Second, (dynamic only), post-analyse the places where modules
- # Third, write everything out.
- for platform in app_platforms:
- mod_code[platform] = {}
- mod_libs[platform] = {}
- app_libs[platform] = ''
- early_app_libs[platform] = ''
- app_code[platform] = {}
- app_modnames[platform] = {}
- # Application.Platform.cache.html
- parser.setPlatform(platform)
- app_translator = pyjs.AppTranslator(
- parser=parser, dynamic=dynamic, optimize=optimize)
- early_app_libs[platform], appcode = \
- app_translator.translate(None, is_app=False,
- library_modules=['dynamicajax.js',
- pover[platform].update(app_translator.overrides.items())
- for mname, name in app_translator.overrides.items():
- pd = overrides.setdefault(mname, {})
- #mod_code[platform][app_name] = appcode
- # platform.Module.cache.js
- modules_done = ['pyjslib', 'sys', '_pyjs.js']
- #modules_to_do = [app_name] + app_translator.library_modules
- modules_to_do = [app_name] + app_translator.library_modules
- deps = map(pyjs.strip_py, modules_to_do)
- sublist = add_subdeps(dependencies, d)
- modules_to_do += sublist
- #dependencies[app_name] = deps
- modules[platform] = modules_done + modules_to_do
- #print "modules to do", modules_to_do
- mn = modules_to_do.pop()
- mod_name = pyjs.strip_py(mn)
- if mod_name in modules_done:
- modules_done.append(mod_name)
- mod_cache_name = "%s.%s.cache.js" % (platform.lower(), mod_name)
- parser.setPlatform(platform)
- mod_translator = pyjs.AppTranslator(parser=parser, optimize=optimize)
- mod_libs[platform][mod_name], mod_code[platform][mod_name] = \
- mod_translator.translate(mod_name,
- pover[platform].update(mod_translator.overrides.items())
- for mname, name in mod_translator.overrides.items():
- pd = overrides.setdefault(mname, {})
- mods = mod_translator.library_modules
- modules[platform] += mods
- deps = map(pyjs.strip_py, mods)
- while mod_name in deps:
- #print "modname preadd:", mod_name, deps
- sublist = add_subdeps(dependencies, d)
- modules_to_do += sublist
- modules_to_do += add_subdeps(dependencies, mod_name)
- #print "modname:", mod_name, deps
- #print "modname:", mod_name, deps
- dependencies[mod_name] = deps
- # work out the dependency ordering of the modules
- mod_levels[platform] = make_deps(None, dependencies, modules_done)
- # now write everything out
- for platform in app_platforms:
- early_app_libs_ = early_app_libs[platform]
- app_libs_ = app_libs[platform]
- app_code_ = app_code[platform]
- #modules_ = filter_mods(app_name, modules[platform])
- mods = flattenlist(mod_levels[platform])
- modules_ = filter_mods(None, mods)
- for mod_name in modules_:
- mod_code_ = mod_code[platform][mod_name]
- mod_name = pyjs.strip_py(mod_name)
- override_name = "%s.%s" % (platform.lower(), mod_name)
- if pover[platform].has_key(override_name):
- mod_cache_name = "%s.cache.js" % (override_name)
- mod_cache_name = "%s.cache.js" % (mod_name)
- print "Creating: " + mod_cache_name
- modlevels = make_deps(None, dependencies, dependencies[mod_name])
- mnames = map(lambda x: "'%s'" % x, md)
- mnames = "new pyjslib.List([\n\t\t\t%s])" % ',\n\t\t\t'.join(mnames)
- modnames.append(mnames)
- modnames = "new pyjslib.List([\n\t\t%s\n\t])" % ',\n\t\t'.join(modnames)
- # convert the overrides
- overnames = map(lambda x: "'%s': '%s'" % x, pover[platform].items())
- overnames = "new pyjslib.Dict({\n\t\t%s\n\t})" % ',\n\t\t'.join(overnames)
- mod_cache_html_output = open(join(output, mod_cache_name), "w")
- mod_cache_html_output = StringIO()
- print >>mod_cache_html_output, mod_cache_html_template % dict(
- mod_libs = mod_libs[platform][mod_name],
- mod_cache_html_output.close()
- mod_cache_html_output.seek(0)
- app_libs_ += mod_cache_html_output.read()
- # write out the dependency ordering of the modules
- for md in mod_levels[platform]:
- mnames = map(lambda x: "'%s'" % x, md)
- mnames = "new pyjslib.List([\n\t\t\t%s])" % ',\n\t\t\t'.join(mnames)
- app_modnames.append(mnames)
- app_modnames = "new pyjslib.List([\n\t\t%s\n\t])" % ',\n\t\t'.join(app_modnames)
- # convert the overrides
- overnames = map(lambda x: "'%s': '%s'" % x, pover[platform].items())
- overnames = "new pyjslib.Dict({\n\t\t%s\n\t})" % ',\n\t\t'.join(overnames)
- #print "platform names", platform, overnames
- # now write app.allcache including dependency-ordered list of
- file_contents = all_cache_html_template % dict(
- early_app_libs = early_app_libs_,
- platform = platform.lower(),
- app_modnames = app_modnames,
- app_headers = app_headers
- digest = md5.new(file_contents).hexdigest()
- file_name = "%s.%s.%s" % (platform.lower(), app_name, digest)
- file_name = "%s.%s" % (platform.lower(), app_name)
- file_name += ".cache.html"
- out_path = join(output, file_name)
- out_file = open(out_path, 'w')
- out_file.write(file_contents)
- app_files.append((platform.lower(), file_name))
- print "Created app file %s:%s: %s" % (
- app_name, platform, out_path)
-# creates sub-dependencies e.g. pyjamas.ui.Widget
-# creates pyjamas.ui.Widget, pyjamas.ui and pyjamas.
- for i in range(0, len(m)):
- d.append('.'.join(m[:i+1]))
-def add_subdeps(deps, mod_name):
- #print "subdeps", mod_name, sd
- for i in range(0, len(sd)-1):
- l = deps.get(child, [])
-# makes unique and preserves list order
-def filter_mods(app_name, md):
- md = filter(lambda x: not x.endswith('.js'), md)
- md = map(pyjs.strip_py, md)
-def filter_deps(app_name, deps):
- for (k, l) in deps.items():
- mods = filter_mods(k, l)
-def has_nodeps(mod, deps):
- if not deps.has_key(mod) or not deps[mod]:
-def nodeps_list(mod_list, deps):
- if has_nodeps(mod, deps):
-# this function takes a dictionary of dependent modules and
-# creates a list of lists. the first list will be modules
-# that have no dependencies; the second list will be those
-# modules that have the first list as dependencies; the
-# third will be those modules that have the first and second...
-def make_deps(app_name, deps, mod_list):
- print "Calculating Dependencies ..."
- mod_list = filter_mods(app_name, mod_list)
- deps = filter_deps(app_name, deps)
- for m, dl in deps.items():
- if m in deps.get(d, []):
- raise Exception('Circular Imports found: \n%s %s -> %s %s'
- #raise Exception('Could not calculate dependencies: \n%s' % deps)
- #print "modlist", mod_list
- nodeps = nodeps_list(mod_list, deps)
- #print "nodeps", nodeps
- mod_list = filter(lambda x: x not in nodeps, mod_list)
- depslist = filter(lambda x: x not in nodeps, depslist)
- #print "newdeps", newdeps
- ordered_deps.append(nodeps)
- ordered_deps.append(mod_list) # last dependencies - usually the app(s)
- parser = OptionParser(usage = usage, version = version)
- parser.add_option("-o", "--output", dest="output",
- help="directory to which the webapp should be written")
- parser.add_option("-j", "--include-js", dest="js_includes", action="append",
- help="javascripts to load into the same frame as the rest of the script")
- parser.add_option("-I", "--library_dir", dest="library_dirs",
- action="append", help="additional paths appended to PYJSPATH")
- parser.add_option("-D", "--data_dir", dest="data_dir",
- help="path for data directory")
- parser.add_option("-m", "--dynamic-modules", action="store_true",
- dest="dynamic", default=False,
- help="Split output into separate dynamically-loaded modules (experimental)")
- parser.add_option("-P", "--platforms", dest="platforms",
- help="platforms to build for, comma-separated")
- parser.add_option("-d", "--debug", action="store_true", dest="debug")
- parser.add_option("-O", "--optimize", action="store_true",
- dest="optimize", default=False,
- help="Optimize generated code (removes all print statements)",
- parser.add_option("-c", "--cache_buster", action="store_true",
- help="Enable browser cache-busting (MD5 hash added to output filenames)")
- parser.set_defaults(output = "output", js_includes=[], library_dirs=[],
- platforms=(','.join(app_platforms)),
- data_dir=os.path.join(sys.prefix, "share/pyjamas"),
- (options, args) = parser.parse_args()
- parser.error("incorrect number of arguments")
- data_dir = abspath(options.data_dir)
- if app_path.endswith('.py'):
- app_path = abspath(app_path)
- if not isfile(app_path):
- parser.error("Application file not found %r" % app_path)
- app_path, app_name = split(app_path)
- app_name = app_name[:-3]
- pyjs.path.append(app_path)
- elif os.path.sep in app_path:
- parser.error("Not a valid module declaration %r" % app_path)
- for d in options.library_dirs:
- pyjs.path.append(abspath(d))
- app_platforms = options.platforms.split(',')
- # this is mostly for getting boilerplate stuff
- data_dir = os.path.abspath(options.data_dir)
- build(app_name, options.output, options.js_includes,
- options.debug, options.dynamic and 1 or 0, data_dir,
- options.cache_buster, options.optimize)
-if __name__ == "__main__":
--- a/py_ext/modules/svgui/pyjs/jsonrpc/README.txt Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,12 +0,0 @@
-These classes are intended for use server-side.
-e.g. in a django view.py :
- from pyjs.jsonrpc.django import JSONService, jsonremote
- jsonservice = JSONRPCService()
- @jsonremote(jsonservice)
- def test(request, echo_param):
- return "echoing the param back: %s" % echo_param
--- a/py_ext/modules/svgui/pyjs/jsonrpc/django/jsonrpc.py Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,226 +0,0 @@
-# original code: http://trac.pyworks.org/pyjamas/wiki/DjangoWithPyJamas
-# also from: http://www.pimentech.fr/technologies/outils
-from django.utils import simplejson
-from django.http import HttpResponse
-from pyjs.jsonrpc import JSONRPCServiceBase
-# JSONRPCService and jsonremote are used in combination to drastically
-# simplify the provision of JSONRPC services. use as follows:
-# jsonservice = JSONRPCService()
-# @jsonremote(jsonservice)
-# def test(request, echo_param):
-# return "echoing the param back: %s" % echo_param
-# dump jsonservice into urlpatterns:
-# (r'^service1/$', 'djangoapp.views.jsonservice'),
-class JSONRPCService(JSONRPCServiceBase):
- def __call__(self, request, extra=None):
- return self.process(request.raw_post_data)
-def jsonremote(service):
- """Make JSONRPCService a decorator so that you can write :
- from jsonrpc import JSONRPCService
- chatservice = JSONRPCService()
- @jsonremote(chatservice)
- def login(request, user_name):
- if isinstance(service, JSONRPCService):
- service.add_method(func.__name__, func)
- emsg = 'Service "%s" not found' % str(service.__name__)
- raise NotImplementedError, emsg
-# FormProcessor provides a mechanism for turning Django Forms into JSONRPC
-# Services. If you have an existing Django app which makes prevalent
-# use of Django Forms it will save you rewriting the app.
-# use as follows. in djangoapp/views.py :
-# class SimpleForm(forms.Form):
-# testfield = forms.CharField(max_length=100)
-# class SimpleForm2(forms.Form):
-# testfield = forms.CharField(max_length=20)
-# processor = FormProcessor({'processsimpleform': SimpleForm,
-# 'processsimpleform2': SimpleForm2})
-# this will result in a JSONRPC service being created with two
-# RPC functions. dump "processor" into urlpatterns to make it
-# (r'^formsservice/$', 'djangoapp.views.processor'),
-from django import forms
- for error in form.errors.keys():
- for errorval in form.errors[error]:
- d[error].append(unicode(errorval))
-# contains the list of arguments in each field
- 'CharField': ['max_length', 'min_length'],
- 'IntegerField': ['max_value', 'min_value'],
- 'FloatField': ['max_value', 'min_value'],
- 'DecimalField': ['max_value', 'min_value', 'max_digits', 'decimal_places'],
- 'DateField': ['input_formats'],
- 'DateTimeField': ['input_formats'],
- 'TimeField': ['input_formats'],
- 'RegexField': ['max_length', 'min_length'], # sadly we can't get the expr
- 'EmailField': ['max_length', 'min_length'],
- 'URLField': ['max_length', 'min_length', 'verify_exists', 'user_agent'],
- 'ChoiceField': ['choices'],
- 'FilePathField': ['path', 'match', 'recursive', 'choices'],
- 'IPAddressField': ['max_length', 'min_length'],
-def describe_field_errors(field):
- field_type = field.__class__.__name__
- for n, m in field.error_messages.items():
- res['error_messages'] = msgs
- if field_type in ['ComboField', 'MultiValueField', 'SplitDateTimeField']:
- res['fields'] = map(describe_field, field.fields)
-def describe_fields_errors(fields, field_names):
- field_names = fields.keys()
- for name in field_names:
- res[name] = describe_field_errors(field)
-def describe_field(field):
- field_type = field.__class__.__name__
- for fname in field_names.get(field_type, []) + \
- ['help_text', 'label', 'initial', 'required']:
- res[fname] = getattr(field, fname)
- if field_type in ['ComboField', 'MultiValueField', 'SplitDateTimeField']:
- res['fields'] = map(describe_field, field.fields)
-def describe_fields(fields, field_names):
- field_names = fields.keys()
- for name in field_names:
- res[name] = describe_field(field)
-class FormProcessor(JSONRPCService):
- def __init__(self, forms, _formcls=None):
- JSONRPCService.__init__(self)
- s = FormProcessor({}, forms[k])
- self.add_method(k, s.__process)
- JSONRPCService.__init__(self, forms)
- self.formcls = _formcls
- def __process(self, request, params, command=None):
- f = self.formcls(params)
- if command is None: # just validate
- return {'success':False, 'errors': builderrors(f)}
- return {'success':True}
- elif command.has_key('describe_errors'):
- field_names = command['describe_errors']
- return describe_fields_errors(f.fields, field_names)
- elif command.has_key('describe'):
- field_names = command['describe']
- return describe_fields(f.fields, field_names)
- elif command.has_key('save'):
- return {'success':False, 'errors': builderrors(f)}
- instance = f.save() # XXX: if you want more, over-ride save.
- return {'success': True, 'instance': json_convert(instance) }
- elif command.has_key('html'):
- return {'success': True, 'html': f.as_table()}
- return "unrecognised command"
-# The following is incredibly convenient for saving vast amounts of
-# coding, avoiding doing silly things like this:
-# jsonresult = {'field1': djangoobject.field1,
-# 'field2': djangoobject.date.strftime('%Y.%M'),
-# The date/time flatten function is there because JSONRPC doesn't
-# support date/time objects or formats, so conversion to a string
-# is the most logical choice. pyjamas, being python, can easily
-# be used to parse the string result at the other end.
-# jsonservice = JSONRPCService()
-# @jsonremote(jsonservice)
-# def list_some_model(request, start=0, count=10):
-# l = SomeDjangoModelClass.objects.filter()
-# res = json_convert(l[start:end])
-# @jsonremote(jsonservice)
-# def list_another_model(request, start=0, count=10):
-# l = AnotherDjangoModelClass.objects.filter()
-# res = json_convert(l[start:end])
-# dump jsonservice into urlpatterns to make the two RPC functions,
-# list_some_model and list_another_model part of the django app:
-# (r'^service1/$', 'djangoapp.views.jsonservice'),
-from django.core.serializers import serialize
-from datetime import date
-def dict_datetimeflatten(item):
- for k, v in item.items():
- if isinstance(v, datetime.date):
- elif isinstance(v, dict):
- d[k] = dict_datetimeflatten(v)
-def json_convert(l, fields=None):
- for item in serialize('python', l, fields=fields):
- res.append(dict_datetimeflatten(item))
--- a/py_ext/modules/svgui/pyjs/jsonrpc/jsonrpc.py Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,43 +0,0 @@
-import gluon.contrib.simplejson as simplejson
-class JSONRPCServiceBase:
- def response(self, id, result):
- return simplejson.dumps({'version': '1.1', 'id':id,
- 'result':result, 'error':None})
- def error(self, id, code, message):
- return simplejson.dumps({'id': id,
- 'error': {'name': 'JSONRPCError',
- def add_method(self, name, method):
- self.methods[name] = method
- def process(self, data):
- data = simplejson.loads(data)
- id, method, params = data["id"], data["method"], data["params"]
- if method in self.methods:
- result =self.methods[method](*params)
- return self.response(id, result)
- etype, eval, etb = sys.exc_info()
- return self.error(id, 100, '%s: %s' %(etype.__name__, eval))
- etype, eval, etb = sys.exc_info()
- return self.error(id, 100, 'Exception %s: %s' %(etype, eval))
- return self.error(id, 100, 'method "%s" does not exist' % method)
- return self.methods.keys()
--- a/py_ext/modules/svgui/pyjs/jsonrpc/web2py/jsonrpc.py Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,11 +0,0 @@
-from pyjs.jsonrpc import JSONRPCServiceBase
-class JSONRPCService(JSONRPCServiceBase):
- return self.process(request.body.read())
- def __call__(self,func):
- self.methods[func.__name__]=func
--- a/py_ext/modules/svgui/pyjs/lib/_pyjs.js Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,160 +0,0 @@
-function pyjs_extend(klass, base) {
- function klass_object_inherit() {}
- klass_object_inherit.prototype = base.prototype;
- klass_object = new klass_object_inherit();
- for (var i in base.prototype.__class__) {
- v = base.prototype.__class__[i];
- if (typeof v == "function" && (v.class_method || v.static_method || v.unbound_method))
- function klass_inherit() {}
- klass_inherit.prototype = klass_object;
- klass.prototype = new klass_inherit();
- klass_object.constructor = klass;
- klass.prototype.__class__ = klass_object;
- for (var i in base.prototype) {
- if (typeof v == "function" && v.instance_method)
- klass.prototype[i] = v;
-/* creates a class, derived from bases, with methods and variables */
-function pyjs_type(clsname, bases, methods)
- var fn_cls = function() {};
- fn_cls.__name__ = clsname;
- var instance = new fn_cls();
- if(instance.__init__) instance.__init__.apply(instance, arguments);
- fn_cls.__initialize__ = function() {
- if (fn_cls.__was_initialized__) return;
- fn_cls.__was_initialized__ = true;
- fn_cls.__extend_baseclasses();
- fn_cls.prototype.__class__.__new__ = fn;
- fn_cls.prototype.__class__.__name__ = clsname;
- fn_cls.__extend_baseclasses = function() {
- for (bi in fn_cls.__baseclasses)
- var b = fn_cls.__baseclasses[bi];
- if (b.__was_initialized__)
- for (bi in fn_cls.__baseclasses)
- var b = fn_cls.__baseclasses[bi];
- pyjs_extend(fn_cls, b);
- bases = [pyjslib.__Object];
- fn_cls.__baseclasses = bases;
- fn_cls.__initialize__();
- var mtype = typeof mth;
- if (mtype == "function" ) {
- fn_cls.prototype[k] = mth;
- fn_cls.prototype.__class__[k] = function () {
- return fn_cls.prototype[k].call.apply(
- fn_cls.prototype[k], arguments);
- fn_cls.prototype.__class__[k].unbound_method = true;
- fn_cls.prototype.instance_method = true;
- fn_cls.prototype.__class__[k].__name__ = k;
- fn_cls.prototype[k].__name__ = k;
- fn_cls.prototype.__class__[k] = mth;
-function pyjs_kwargs_call(obj, func, star_args, args)
- if (!pyjslib.isIteratable(star_args))
- throw (pyjslib.TypeError(func.__name__ + "() arguments after * must be a sequence" + pyjslib.repr(star_args)));
- var __i = star_args.__iter__();
- call_args[i]=__i.next();
- if (e != pyjslib.StopIteration) {
- var n = star_args.length;
- for (var i=0; i < args.length; i++) {
- call_args[n+i]=args[i];
- return func.apply(obj, call_args);
-function pyjs_kwargs_function_call(func, star_args, args)
- return pyjs_kwargs_call(null, func, star_args, args);
-function pyjs_kwargs_method_call(obj, method_name, star_args, args)
- var method = obj[method_name];
- if (method.parse_kwargs)
- args = method.parse_kwargs.apply(null, args);
- return pyjs_kwargs_call(obj, method, star_args, args);
-//String.prototype.__getitem__ = String.prototype.charAt;
-//String.prototype.upper = String.prototype.toUpperCase;
-//String.prototype.lower = String.prototype.toLowerCase;
-//String.prototype.find=pyjslib.String_find;
-//String.prototype.join=pyjslib.String_join;
-//String.prototype.isdigit=pyjslib.String_isdigit;
-//String.prototype.__iter__=pyjslib.String___iter__;
-//String.prototype.__replace=String.prototype.replace;
-//String.prototype.replace=pyjslib.String_replace;
-//String.prototype.split=pyjslib.String_split;
-//String.prototype.strip=pyjslib.String_strip;
-//String.prototype.lstrip=pyjslib.String_lstrip;
-//String.prototype.rstrip=pyjslib.String_rstrip;
-//String.prototype.startswith=pyjslib.String_startswith;
--- a/py_ext/modules/svgui/pyjs/lib/json.js Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,293 +0,0 @@
-json_parse = (function () {
-// This is a function that can parse a JSON text, producing a JavaScript
-// data structure. It is a simple, recursive descent parser. It does not use
-// eval or regular expressions, so it can be used as a model for implementing
-// a JSON parser in other languages.
-// We are defining the function inside of another function to avoid creating
- var at, // The index of the current character
- ch, // The current character
-// Call error when something is wrong.
-// If a c parameter is provided, verify that it matches the current character.
- error("Expected '" + c + "' instead of '" + ch + "'");
-// Get the next character. When there are no more characters,
-// return the empty string.
-// Parse a number value.
- while (ch >= '0' && ch <= '9') {
- while (next() && ch >= '0' && ch <= '9') {
- if (ch === 'e' || ch === 'E') {
- if (ch === '-' || ch === '+') {
- while (ch >= '0' && ch <= '9') {
-// Parse a string value.
-// When parsing for string values, we must look for " and \ characters.
- } else if (ch === '\\') {
- for (i = 0; i < 4; i += 1) {
- hex = parseInt(next(), 16);
- uffff = uffff * 16 + hex;
- string += String.fromCharCode(uffff);
- } else if (typeof escapee[ch] === 'string') {
- while (ch && ch <= ' ') {
-// true, false, or null.
- error("Unexpected '" + ch + "'");
- value, // Place holder for the value function.
-// Parse an array value.
- return array; // empty array
-// Parse an object value.
- return object; // empty object
- if (Object.hasOwnProperty.call(object, key)) {
- error('Duplicate key "' + key + '"');
-// Parse a JSON value. It could be an object, an array, a string, a number,
- return ch >= '0' && ch <= '9' ? number() : word();
-// Return the json_parse function. It will have access to all of the above
-// functions and variables.
- return function (source, reviver) {
-// If there is a reviver function, we recursively walk the new structure,
-// passing each name/value pair to the reviver function for possible
-// transformation, starting with a temporary root object that holds the result
-// in an empty key. If there is not a reviver function, we simply return the
- return typeof reviver === 'function' ? (function walk(holder, key) {
- var k, v, value = holder[key];
- if (value && typeof value === 'object') {
- if (Object.hasOwnProperty.call(value, k)) {
- return reviver.call(holder, key, value);
- }({'': result}, '')) : result;
--- a/py_ext/modules/svgui/pyjs/lib/pyjslib.py Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,1365 +0,0 @@
-# Copyright 2006 James Tauber and contributors
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-# http://www.apache.org/licenses/LICENSE-2.0
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# iteration from Bob Ippolito's Iteration in JavaScript
-from __pyjamas__ import JS
-# must declare import _before_ importing sys
-def import_module(path, parent_module, module_name, dynamic=1, async=False):
- if (module_name == "sys" || module_name == 'pyjslib')
- /*module_load_request[module_name] = 1;*/
- var override_name = sys.platform + "." + module_name;
- if (((sys.overrides != null) &&
- (sys.overrides.has_key(override_name))))
- cache_file = sys.overrides.__getitem__(override_name) ;
- cache_file = module_name ;
- cache_file = (path + cache_file + '.cache.js' ) ;
- //alert("cache " + cache_file + " " + module_name + " " + parent_module);
- if (module_load_request[module_name])
- if (module_load_request[module_name] >= 3 && parent_module != null)
- //onload_fn = parent_module + '.' + module_name + ' = ' + module_name + ';';
- //pyjs_eval(onload_fn); /* set up the parent-module namespace */
- if (typeof (module_load_request[module_name]) == 'undefined')
- module_load_request[module_name] = 1;
- /* following a load, this first executes the script
- * "preparation" function MODULENAME_loaded_fn()
- * and then sets up the loaded module in the namespace
- onload_fn = ''; // module_name + "_loaded_fn();"
- if (parent_module != null)
- //onload_fn += parent_module + '.' + module_name + ' = ' + module_name + ';';
- /*pmod = parent_module + '.' + module_name;
- onload_fn += 'alert("' + pmod + '"+' + pmod+');';*/
- /* this one tacks the script onto the end of the DOM
- pyjs_load_script(cache_file, onload_fn, async);
- /* this one actually RUNS the script (eval) into the page.
- my feeling is that this would be better for non-async
- but i can't get it to work entirely yet.
- /*pyjs_ajax_eval(cache_file, onload_fn, async);*/
- if (module_name != "pyjslib" &&
-function import_wait(proceed_fn, parent_mod, dynamic) {
- var element = $doc.createElement("div");
- $doc.body.appendChild(element);
- function write_dom(txt) {
- element.innerHTML = txt + '<br />';
- var wait = function() {
- for (l in module_load_request)
- var m = module_load_request[l];
- if (l == "sys" || l == 'pyjslib')
- //write_dom( " import wait " + wait_count + " " + status + " parent_mod " + parent_mod);
- setTimeout(wait, timeoutperiod);
- for (l in module_load_request)
- var m = module_load_request[l];
- if (l == "sys" || l == 'pyjslib')
- module_load_request[l] = 4;
- if ((parent_mod != null) && (l == parent_mod))
- setTimeout(wait, timeoutperiod);
- /* cheat and move app on to next stage */
- module_load_request[l] = 3;
- setTimeout(wait, timeoutperiod);
- //alert("waited for module " + l + ": loaded");
- module_load_request[l] = 4;
- //alert("module wait done");
- if (proceed_fn.importDone)
- proceed_fn.importDone(proceed_fn);
- def __init__(self, path, app_modlist, app_imported_fn, dynamic,
- self.app_modlist = app_modlist
- self.app_imported_fn = app_imported_fn
- self.parent_mod = parent_mod
- for i in range(len(self.app_modlist[self.idx])):
- app = self.app_modlist[self.idx][i]
- import_module(self.path, self.parent_mod, app, self.dynamic, True);
- if self.idx >= len(self.app_modlist):
- import_wait(self.app_imported_fn, self.parent_mod, self.dynamic)
- import_wait(getattr(self, "next"), self.parent_mod, self.dynamic)
-def get_module(module_name):
- ev = "__mod = %s;" % module_name
-def preload_app_modules(path, app_modnames, app_imported_fn, dynamic,
- loader = Modload(path, app_modnames, app_imported_fn, dynamic, parent_mod)
- def __init__(self, *args):
- if len(self.args) is 0:
- elif len(self.args) is 1:
- return repr(self.args[0])
-class Exception(BaseException):
-class TypeError(BaseException):
-class StandardError(Exception):
-class LookupError(StandardError):
- return self.name + ": " + self.args[0]
-class KeyError(LookupError):
-class AttributeError(StandardError):
- name = "AttributeError"
- return "AttributeError: %s of %s" % (self.args[1], self.args[0])
-pyjslib.StopIteration = function () { };
-pyjslib.StopIteration.prototype = new Error();
-pyjslib.StopIteration.name = 'StopIteration';
-pyjslib.StopIteration.message = 'StopIteration';
-pyjslib.String_find = function(sub, start, end) {
- var pos=this.indexOf(sub, start);
- if (pyjslib.isUndefined(end)) return pos;
- if (pos + sub.length>end) return -1;
-pyjslib.String_join = function(data) {
- if (pyjslib.isArray(data)) {
- return data.join(this);
- else if (pyjslib.isIteratable(data)) {
- var iter=data.__iter__();
- if (e != pyjslib.StopIteration) throw e;
-pyjslib.String_isdigit = function() {
- return (this.match(/^\d+$/g) != null);
-pyjslib.String_replace = function(old, replace, count) {
- if (!pyjslib.isString(old)) return this.__replace(old, replace);
- if (!pyjslib.isUndefined(count)) do_max=true;
- while (start<this.length) {
- if (do_max && !count--) break;
- pos=this.indexOf(old, start);
- new_str+=this.substring(start, pos) + replace;
- if (start<this.length) new_str+=this.substring(start);
-pyjslib.String_split = function(sep, maxsplit) {
- var items=new pyjslib.List();
- if (pyjslib.isUndefined(sep) || pyjslib.isNull(sep)) {
- subject=subject.strip();
- subject=subject.replace(/\s+/g, sep);
- else if (!pyjslib.isUndefined(maxsplit)) do_max=true;
- if (subject.length == 0) {
- while (start<subject.length) {
- if (do_max && !maxsplit--) break;
- pos=subject.indexOf(sep, start);
- items.append(subject.substring(start, pos));
- if (start<=subject.length) items.append(subject.substring(start));
-pyjslib.String___iter__ = function() {
- throw pyjslib.StopIteration;
- return s.substring(i++, i, 1);
- '__iter__': function() {
-pyjslib.String_strip = function(chars) {
- return this.lstrip(chars).rstrip(chars);
-pyjslib.String_lstrip = function(chars) {
- if (pyjslib.isUndefined(chars)) return this.replace(/^\s+/, "");
- return this.replace(new RegExp("^[" + chars + "]+"), "");
-pyjslib.String_rstrip = function(chars) {
- if (pyjslib.isUndefined(chars)) return this.replace(/\s+$/, "");
- return this.replace(new RegExp("[" + chars + "]+$"), "");
-pyjslib.String_startswith = function(prefix, start) {
- if (pyjslib.isUndefined(start)) start = 0;
- if (this.substring(start, prefix.length) == prefix) return true;
- def __init__(self, name):
- if (pyjslib.hasattr(a, "__cmp__")) {
- return a.__cmp__(b) == 0;
- } else if (pyjslib.hasattr(b, "__cmp__")) {
- return b.__cmp__(a) == 0;
- if hasattr(a, "__cmp__"):
- elif hasattr(b, "__cmp__"):
- # this needs to stay in native code without any dependencies here,
- # because this is used by if and while, we need to prevent
- return v.__nonzero__();
- def __init__(self, data=None):
- def append(self, item):
- JS(""" this.l[this.l.length] = item;""")
- def extend(self, data):
- if (pyjslib.isArray(data)) {
- for (var i=0; i < data.length; i++) {
- else if (pyjslib.isIteratable(data)) {
- var iter=data.__iter__();
- if (e != pyjslib.StopIteration) throw e;
- def remove(self, value):
- var index=this.index(value);
- if (index<0) return false;
- this.l.splice(index, 1);
- def index(self, value, start=0):
- var length=this.l.length;
- for (var i=start; i<length; i++) {
- if (this.l[i]==value) {
- def insert(self, index, value):
- JS(""" var a = this.l; this.l=a.slice(0, index).concat(value, a.slice(index));""")
- def pop(self, index = -1):
- if (index<0) index = this.l.length + index;
- this.l.splice(index, 1);
- if not isinstance(l, List):
- ll = len(self) - len(l)
- for x in range(len(l)):
- ll = cmp(self.__getitem__(x), l[x])
- def slice(self, lower, upper):
- if (upper==null) return pyjslib.List(this.l.slice(lower));
- return pyjslib.List(this.l.slice(lower, upper));
- def __getitem__(self, index):
- if (index<0) index = this.l.length + index;
- def __setitem__(self, index, value):
- JS(""" this.l[index]=value;""")
- def __delitem__(self, index):
- JS(""" this.l.splice(index, 1);""")
- JS(""" return this.l.length;""")
- def __contains__(self, value):
- return self.index(value) >= 0
- throw pyjslib.StopIteration;
- '__iter__': function() {
- JS(""" this.l.reverse();""")
- def sort(self, compareFunc=None, keyFunc=None, reverse=False):
- if keyFunc and reverse:
- return -compareFunc(keyFunc(a), keyFunc(b))
- return compareFunc(keyFunc(a), keyFunc(b))
- return -compareFunc(a, b)
- self.l.sort(compareFunc)
- Access the javascript Array that is used internally by this list
- def __init__(self, data=None):
- def append(self, item):
- JS(""" this.l[this.l.length] = item;""")
- def extend(self, data):
- if (pyjslib.isArray(data)) {
- for (var i=0; i < data.length; i++) {
- else if (pyjslib.isIteratable(data)) {
- var iter=data.__iter__();
- if (e != pyjslib.StopIteration) throw e;
- def remove(self, value):
- var index=this.index(value);
- if (index<0) return false;
- this.l.splice(index, 1);
- def index(self, value, start=0):
- var length=this.l.length;
- for (var i=start; i<length; i++) {
- if (this.l[i]==value) {
- def insert(self, index, value):
- JS(""" var a = this.l; this.l=a.slice(0, index).concat(value, a.slice(index));""")
- def pop(self, index = -1):
- if (index<0) index = this.l.length + index;
- this.l.splice(index, 1);
- if not isinstance(l, Tuple):
- ll = len(self) - len(l)
- for x in range(len(l)):
- ll = cmp(self.__getitem__(x), l[x])
- def slice(self, lower, upper):
- if (upper==null) return pyjslib.Tuple(this.l.slice(lower));
- return pyjslib.Tuple(this.l.slice(lower, upper));
- def __getitem__(self, index):
- if (index<0) index = this.l.length + index;
- def __setitem__(self, index, value):
- JS(""" this.l[index]=value;""")
- def __delitem__(self, index):
- JS(""" this.l.splice(index, 1);""")
- JS(""" return this.l.length;""")
- def __contains__(self, value):
- return self.index(value) >= 0
- throw pyjslib.StopIteration;
- '__iter__': function() {
- JS(""" this.l.reverse();""")
- def sort(self, compareFunc=None, keyFunc=None, reverse=False):
- if keyFunc and reverse:
- return -compareFunc(keyFunc(a), keyFunc(b))
- return compareFunc(keyFunc(a), keyFunc(b))
- return -compareFunc(a, b)
- self.l.sort(compareFunc)
- Access the javascript Array that is used internally by this list
- def __init__(self, data=None):
- if (pyjslib.isArray(data)) {
- this.__setitem__(item[0], item[1]);
- //var sKey=pyjslib.hash(item[0]);
- //this.d[sKey]=item[1];
- else if (pyjslib.isIteratable(data)) {
- var iter=data.__iter__();
- this.__setitem__(item.__getitem__(0), item.__getitem__(1));
- if (e != pyjslib.StopIteration) throw e;
- else if (pyjslib.isObject(data)) {
- for (var key in data) {
- this.__setitem__(key, data[key]);
- def __setitem__(self, key, value):
- var sKey = pyjslib.hash(key);
- this.d[sKey]=[key, value];
- def __getitem__(self, key):
- var sKey = pyjslib.hash(key);
- var value=this.d[sKey];
- if (pyjslib.isUndefined(value)){
- throw pyjslib.KeyError(key);
- for (var i in this.d) size++;
- def has_key(self, key):
- return self.__contains__(key)
- def __delitem__(self, key):
- var sKey = pyjslib.hash(key);
- def __contains__(self, key):
- var sKey = pyjslib.hash(key);
- return (pyjslib.isUndefined(this.d[sKey])) ? false : true;
- var keys=new pyjslib.List();
- for (var key in this.d) {
- keys.append(this.d[key][0]);
- var values=new pyjslib.List();
- for (var key in this.d) values.append(this.d[key][1]);
- var items = new pyjslib.List();
- for (var key in this.d) {
- items.append(new pyjslib.List(kv))
- return self.keys().__iter__()
- return self.values().__iter__();
- return self.items().__iter__();
- def setdefault(self, key, default_value):
- if not self.has_key(key):
- self[key] = default_value
- def get(self, key, default_=None):
- if not self.has_key(key):
- for k,v in d.iteritems():
- Return the javascript Object which this class uses to store
- dictionary keys and values
- return Dict(self.items())
-# taken from mochikit: range( [start,] stop[, step] )
- if (arguments.length == 2) {
- else if (arguments.length == 3) {
- else if (arguments.length>0) stop = arguments[0];
- if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) throw pyjslib.StopIteration;
- '__iter__': function() {
-def slice(object, lower, upper):
- if (pyjslib.isString(object)) {
- lower = object.length + lower;
- upper = object.length + upper;
- if (pyjslib.isNull(upper)) upper=object.length;
- return object.substring(lower, upper);
- if (pyjslib.isObject(object) && object.slice)
- return object.slice(lower, upper);
- if (pyjslib.hasattr(text,"__str__")) {
- if(isString(x) and len(x) is 1):
- return x.charCodeAt(0);
- throw pyjslib.TypeError();
- return String.fromCharCode(x)
- return t == 'boolean' ||
-def get_pyjs_classtype(x):
- if (pyjslib.hasattr(x, "__class__"))
- if (pyjslib.hasattr(x.__class__, "__new__"))
- var src = x.__class__.__name__;
- """ Return the string representation of 'x'.
- //alert("repr typeof " + t + " : " + x);
- return "<function " + x.toString() + ">";
- if (x.indexOf("'") == -1)
- if (x.indexOf('"') == -1)
- var s = x.replace(new RegExp('"', "g"), '\\\\"');
- // If we get here, x is an object. See if it's a Pyjamas class.
- if (!pyjslib.hasattr(x, "__init__"))
- return "<" + x.toString() + ">";
- // Handle the common Pyjamas data types.
- var constructor = "UNKNOWN";
- constructor = pyjslib.get_pyjs_classtype(x);
- //alert("repr constructor: " + constructor);
- if (constructor == "Tuple") {
- var contents = x.getArray();
- for (var i=0; i < contents.length; i++) {
- s += pyjslib.repr(contents[i]);
- if (i < contents.length - 1)
- if (constructor == "List") {
- var contents = x.getArray();
- for (var i=0; i < contents.length; i++) {
- s += pyjslib.repr(contents[i]);
- if (i < contents.length - 1)
- if (constructor == "Dict") {
- var keys = new Array();
- for (var i=0; i<keys.length; i++) {
- s += pyjslib.repr(key) + ": " + pyjslib.repr(x.d[key]);
- // If we get here, the class isn't one we know -> return the class name.
- // Note that we replace underscores with dots so that the name will
- // (hopefully!) look like the original Python name.
- //var s = constructor.replace(new RegExp('_', "g"), '.');
- return "<" + constructor + " object>";
- return parseFloat(text);
- return parseInt(text, radix);
- if (object==null) return 0;
- if (pyjslib.isObject(object) && object.__len__) return object.__len__();
-def isinstance(object_, classinfo):
- if pyjslib.isUndefined(object_):
- if not pyjslib.isObject(object_):
- if _isinstance(classinfo, Tuple):
- if isinstance(object_, ci):
- return _isinstance(object_, classinfo)
-def _isinstance(object_, classinfo):
- if not pyjslib.isObject(object_):
- if (object_.__class__){
- var res = object_ instanceof classinfo.constructor;
-def getattr(obj, name, default_):
- if ((!pyjslib.isObject(obj))||(pyjslib.isUndefined(obj[name]))){
- if (pyjslib.isUndefined(default_)){
- throw pyjslib.AttributeError(obj, name);
- if (!pyjslib.isFunction(obj[name])) return obj[name];
- var fnwrap = function() {
- for (var i = 0; i < arguments.length; i++) {
- args.push(arguments[i]);
- return obj[name].apply(obj,args);
- fnwrap.__name__ = name;
-def setattr(obj, name, value):
- if (!pyjslib.isObject(obj)) return null;
- if (!pyjslib.isObject(obj)) return false;
- if (pyjslib.isUndefined(obj[name])) return false;
- var properties=new pyjslib.List();
- for (property in obj) properties.append(property);
-def filter(obj, method, sequence=None):
- # object context is LOST when a method is passed, hence object must be passed separately
- # to emulate python behaviour, should generate this code inline rather than as a function call
- if method.call(obj, item):
-def map(obj, method, sequence=None):
- items.append(method(item))
- items.append(method.call(obj, item))
-def enumerate(sequence):
- enumeration.append([nextIndex, item])
- nextIndex = nextIndex + 1
- if (obj == null) return null;
- if (obj.$H) return obj.$H;
- if (obj.__hash__) return obj.__hash__();
- if (obj.constructor == String || obj.constructor == Number || obj.constructor == Date) return obj;
- obj.$H = ++pyjslib.next_hash_id;
-# type functions from Douglas Crockford's Remedial Javascript: http://www.crockford.com/javascript/remedial.html
- return (a != null && (typeof a == 'object')) || pyjslib.isFunction(a);
- return typeof a == 'function';
- return typeof a == 'string';
- return typeof a == 'object' && !a;
- return pyjslib.isObject(a) && a.constructor == Array;
- return typeof a == 'undefined';
- return pyjslib.isString(a) || (pyjslib.isObject(a) && a.__iter__);
- return typeof a == 'number' && isFinite(a);
- Convert the pyjs pythonic List and Dict objects into javascript Object and Array
- for(var k=0; k < x.length; k++) {
- var tv = pyjslib.toJSObjects(v);
- if isinstance(x, Dict):
- result[o[i][0].toString()] = o[i][1];
- return pyjslib.toJSObjects(result)
- elif isinstance(x, List):
- return toJSObjects(x.l)
- elif hasattr(x, '__class__'):
- # we do not have a special implementation for custom
- # classes, just pass it on
- var tv = pyjslib.toJSObjects(v)
- if ($wnd.console==undefined) return;
- for(var i=0; i < objs.length; i++) {
-def type(clsname, bases=None, methods=None):
- """ creates a class, derived from bases, with methods and variables
- for k in methods.keys():
- JS(" var bss = null; ")
- JS(" return pyjs_type(clsname, bss, mths); ")
--- a/py_ext/modules/svgui/pyjs/lib/sys.py Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,59 +0,0 @@
-# the platform name (PyV8, smjs, Mozilla, IE6, Opera, Safari etc.)
-platform = '' # to be updated by app, on compile
-# a dictionary of module override names (platform-specific)
-overrides = None # to be updated by app, on compile
-# the remote path for loading modules
-def addoverride(module_name, path):
- overrides[module_name] = path
-def addstack(linedebug):
- if (pyjslib.bool((sys.stacktrace === null))) {
- sys.stacktrace = new pyjslib.List([]);
- sys.stacktrace.append(linedebug);
- var __l = sys.stacktrace.__iter__();
- if (e != pyjslib.StopIteration) {
--- a/py_ext/modules/svgui/pyjs/pyjs.py Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,1777 +0,0 @@
-# Copyright 2006 James Tauber and contributors
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-# http://www.apache.org/licenses/LICENSE-2.0
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-from types import StringType
-from compiler import ast
-# the standard location for builtins (e.g. pyjslib) can be
-# over-ridden by changing this. it defaults to sys.prefix
-# so that on a system-wide install of pyjamas the builtins
-# can be found in e.g. {sys.prefix}/share/pyjamas
-# over-rides can be done by either explicitly modifying
-# pyjs.prefix or by setting an environment variable, PYJSPREFIX.
-if os.environ.has_key('PYJSPREFIX'):
- prefix = os.environ['PYJSPREFIX']
-# pyjs.path is the list of paths, just like sys.path, from which
-# library modules will be searched for, for compile purposes.
-# obviously we don't want to use sys.path because that would result
-# in compiling standard python modules into javascript!
-path = [os.path.abspath('')]
-if os.environ.has_key('PYJSPATH'):
- for p in os.environ['PYJSPATH'].split(os.pathsep):
-# this is the python function used to wrap native javascript
-NATIVE_JS_FUNC_NAME = "JS"
-PYJSLIB_BUILTIN_FUNCTIONS=("cmp",
-PYJSLIB_BUILTIN_CLASSES=("BaseException",
-def pyjs_builtin_remap(name):
-# XXX: this is a hack: these should be dealt with another way
-# however, console is currently the only global name which is causing
-PYJS_GLOBAL_VARS=("console")
-# This is taken from the django project.
-# Escape every ASCII character with a value less than 32.
- ) + tuple([('%c' % z, '\\x%02X' % z) for z in range(32)])
- """Hex encodes characters for use in JavaScript strings."""
- for bad, good in JS_ESCAPES:
- value = value.replace(bad, good)
-def uuprefix(name, leave_alone=0):
- name = name[:leave_alone] + map(lambda x: "__%s" % x, name[leave_alone:])
- def __init__(self, name, name_):
- self.klasses[name] = self
- def set_base(self, base_name):
- self.base = self.klasses.get(base_name)
- def add_function(self, function_name):
- self.functions.add(function_name)
-class TranslationError(Exception):
- def __init__(self, message, node):
- self.message = "line %s:\n%s\n%s" % (node.lineno, message, node)
-def mod_var_name_decl(raw_module_name):
- """ function to get the last component of the module e.g.
- pyjamas.ui.DOM into the "namespace". i.e. doing
- "import pyjamas.ui.DOM" actually ends up with _two_
- variables - one pyjamas.ui.DOM, the other just "DOM".
- but "DOM" is actually local, hence the "var" prefix.
- for PyV8, this might end up causing problems - we'll have
- to see: gen_mod_import and mod_var_name_decl might have
- to end up in a library-specific module, somewhere.
- name = raw_module_name.split(".")
- return "var %s = %s;\n" % (child_name, raw_module_name)
-def gen_mod_import(parentName, importName, dynamic=1):
- #pyjs_ajax_eval("%(n)s.cache.js", null, true);
- pyjslib.import_module(sys.loadpath, '%(p)s', '%(n)s', %(d)d, false);
- """ % ({'p': parentName, 'd': dynamic, 'n': importName}) + \
- mod_var_name_decl(importName)
- def __init__(self, mn, module_name, raw_module_name, src, debug, mod, output,
- dynamic=0, optimize=False,
- self.module_prefix = module_name + "."
- self.module_prefix = ""
- self.raw_module_name = raw_module_name
- src = src.replace("\r\n", "\n")
- src = src.replace("\n\r", "\n")
- src = src.replace("\r", "\n")
- self.src = src.split("\n")
- self.imported_modules = []
- self.imported_modules_as = []
- self.imported_js = set()
- self.top_level_functions = set()
- self.top_level_classes = set()
- self.top_level_vars = set()
- self.local_arg_stack = [[]]
- self.imported_classes = {}
- self.method_imported_globals = set()
- self.method_self = None
- self.nextTupleAssignID = 1
- self.optimize = optimize
- self.findFile = findFile
- if module_name.find(".") >= 0:
- print >>self.output, UU+"%s%s = function (__mod_name__) {" % (vdec, module_name)
- print >>self.output, " if("+module_name+".__was_initialized__) return;"
- print >>self.output, " "+UU+module_name+".__was_initialized__ = true;"
- print >>self.output, UU+"if (__mod_name__ == null) __mod_name__ = '%s';" % (mn)
- print >>self.output, UU+"%s.__name__ = __mod_name__;" % (raw_module_name)
- decl = mod_var_name_decl(raw_module_name)
- print >>self.output, decl
- haltException = self.module_prefix + "HaltException"
- print >>self.output, haltException + ' = function () {'
- print >>self.output, ' this.message = "Program Halted";'
- print >>self.output, ' this.name = "' + haltException + '";'
- print >>self.output, '}'
- print >>self.output, ''
- print >>self.output, haltException + ".prototype.__str__ = function()"
- print >>self.output, '{'
- print >>self.output, 'return this.message ;'
- print >>self.output, '}'
- print >>self.output, haltException + ".prototype.toString = function()"
- print >>self.output, '{'
- print >>self.output, 'return this.name + ": \\"" + this.message + "\\"";'
- print >>self.output, '}'
- isHaltFunction = self.module_prefix + "IsHaltException"
- print >>self.output, """
- var suffix="HaltException";
- if (s.length < suffix.length) {
- //alert(s + " " + suffix);
- var ss = s.substring(s.length, (s.length - suffix.length));
- //alert(s + " " + suffix + " " + ss);
- if isinstance(child, ast.Function):
- self.top_level_functions.add(child.name)
- elif isinstance(child, ast.Class):
- self.top_level_classes.add(child.name)
- if isinstance(child, ast.Function):
- self._function(child, False)
- elif isinstance(child, ast.Class):
- elif isinstance(child, ast.Import):
- importName = child.names[0][0]
- if importName == '__pyjamas__': # special module to help make pyjamas modules loadable in the python interpreter
- elif importName.endswith('.js'):
- self.imported_js.add(importName)
- self.add_imported_module(strip_py(importName))
- elif isinstance(child, ast.From):
- if child.modname == '__pyjamas__': # special module to help make pyjamas modules loadable in the python interpreter
- self.add_imported_module(child.modname)
- elif isinstance(child, ast.Discard):
- self._discard(child, None)
- elif isinstance(child, ast.Assign):
- self._assign(child, None, True)
- elif isinstance(child, ast.AugAssign):
- self._augassign(child, None)
- elif isinstance(child, ast.If):
- elif isinstance(child, ast.For):
- elif isinstance(child, ast.While):
- self._while(child, None)
- elif isinstance(child, ast.Subscript):
- self._subscript_stmt(child, None)
- elif isinstance(child, ast.Global):
- self._global(child, None)
- elif isinstance(child, ast.Printnl):
- self._print(child, None)
- elif isinstance(child, ast.Print):
- self._print(child, None)
- elif isinstance(child, ast.TryExcept):
- self._tryExcept(child, None)
- elif isinstance(child, ast.Raise):
- self._raise(child, None)
- elif isinstance(child, ast.Stmt):
- self._stmt(child, None)
- raise TranslationError("unsupported type (in __init__)", child)
- # Initialize all classes for this module
- #print >> self.output, "__"+self.modpfx()+\
- # "classes_initialize = function() {\n"
- #for className in self.top_level_classes:
- # print >> self.output, "\t"+UU+self.modpfx()+"__"+className+"_initialize();"
- #print >> self.output, "};\n"
- print >> self.output, "return this;\n"
- print >> self.output, "}; /* end %s */ \n" % module_name
- def module_imports(self):
- return self.imported_modules + self.imported_modules_as
- def add_local_arg(self, varname):
- local_vars = self.local_arg_stack[-1]
- if varname not in local_vars:
- local_vars.append(varname)
- def add_imported_module(self, importName):
- if importName in self.imported_modules:
- self.imported_modules.append(importName)
- name = importName.split(".")
- # add the name of the module to the namespace,
- # but don't add the short name to imported_modules
- # because then the short name would be attempted to be
- # added to the dependencies, and it's half way up the
- # module import directory structure!
- self.imported_modules_as.append(child_name)
- print >> self.output, gen_mod_import(self.raw_module_name,
- def _default_args_handler(self, node, arg_names, current_klass,
- output = output or self.output
- default_pos = len(arg_names) - len(node.defaults)
- if arg_names and arg_names[0] == self.method_self:
- for default_node in node.defaults:
- if isinstance(default_node, ast.Const):
- default_value = self._const(default_node)
- elif isinstance(default_node, ast.Name):
- default_value = self._name(default_node, current_klass)
- elif isinstance(default_node, ast.UnarySub):
- default_value = self._unarysub(default_node, current_klass)
- raise TranslationError("unsupported type (in _method)", default_node)
- default_name = arg_names[default_pos]
- print >> output, " if (typeof %s == 'undefined') %s=%s;" % (default_name, default_name, default_value)
- def _varargs_handler(self, node, varargname, arg_names, current_klass):
- print >>self.output, " var", varargname, '= new pyjslib.Tuple();'
- print >>self.output, " for(var __va_arg="+str(len(arg_names))+"; __va_arg < arguments.length; __va_arg++) {"
- print >>self.output, " var __arg = arguments[__va_arg];"
- print >>self.output, " "+varargname+".append(__arg);"
- print >>self.output, " }"
- def _kwargs_parser(self, node, function_name, arg_names, current_klass):
- if len(node.defaults) or node.kwargs:
- default_pos = len(arg_names) - len(node.defaults)
- if arg_names and arg_names[0] == self.method_self:
- print >>self.output, function_name+'.parse_kwargs = function (', ", ".join(["__kwargs"]+arg_names), ") {"
- for default_node in node.defaults:
- default_value = self.expr(default_node, current_klass)
-# if isinstance(default_node, ast.Const):
-# default_value = self._const(default_node)
-# elif isinstance(default_node, ast.Name):
-# default_value = self._name(default_node)
-# elif isinstance(default_node, ast.UnarySub):
-# default_value = self._unarysub(default_node, current_klass)
-# raise TranslationError("unsupported type (in _method)", default_node)
- default_name = arg_names[default_pos]
- print >>self.output, " if (typeof %s == 'undefined')"%(default_name)
- print >>self.output, " %s=__kwargs.%s;"% (default_name, default_name)
- #self._default_args_handler(node, arg_names, current_klass)
- if node.kwargs: arg_names += ["pyjslib.Dict(__kwargs)"]
- print >>self.output, " var __r = "+"".join(["[", ", ".join(arg_names), "]"])+";"
- self._varargs_handler(node, "__args", arg_names, current_klass)
- print >>self.output, " __r.push.apply(__r, __args.getArray())"
- print >>self.output, " return __r;"
- print >>self.output, "};"
- def _function(self, node, local=False):
- function_name = node.name
- self.add_local_arg(function_name)
- function_name = UU + self.modpfx() + node.name
- arg_names = list(node.argnames)
- normal_arg_names = list(arg_names)
- if node.kwargs: kwargname = normal_arg_names.pop()
- if node.varargs: varargname = normal_arg_names.pop()
- declared_arg_names = list(normal_arg_names)
- if node.kwargs: declared_arg_names.append(kwargname)
- function_args = "(" + ", ".join(declared_arg_names) + ")"
- print >>self.output, "%s = function%s {" % (function_name, function_args)
- self._default_args_handler(node, normal_arg_names, None)
- local_arg_names = normal_arg_names + declared_arg_names
- self._varargs_handler(node, varargname, declared_arg_names, None)
- local_arg_names.append(varargname)
- # stack of local variable names for this function call
- self.local_arg_stack.append(local_arg_names)
- for child in node.code:
- self._stmt(child, None)
- # remove the top local arg names
- self.local_arg_stack.pop()
- # we need to return null always, so it is not undefined
- lastStmt = [p for p in node.code][-1]
- if not isinstance(lastStmt, ast.Return):
- if not self._isNativeFunc(lastStmt):
- print >>self.output, " return null;"
- print >>self.output, "};"
- print >>self.output, "%s.__name__ = '%s';\n" % (function_name, node.name)
- self._kwargs_parser(node, function_name, normal_arg_names, None)
- def _return(self, node, current_klass):
- expr = self.expr(node.value, current_klass)
- # in python a function call always returns None, so we do it
- print >>self.output, " return " + expr + ";"
- def _break(self, node, current_klass):
- print >>self.output, " break;"
- def _continue(self, node, current_klass):
- print >>self.output, " continue;"
- def _callfunc(self, v, current_klass):
- if isinstance(v.node, ast.Name):
- if v.node.name in self.top_level_functions:
- call_name = self.modpfx() + v.node.name
- elif v.node.name in self.top_level_classes:
- call_name = self.modpfx() + v.node.name
- elif self.imported_classes.has_key(v.node.name):
- call_name = self.imported_classes[v.node.name] + '.' + v.node.name
- elif v.node.name in PYJSLIB_BUILTIN_FUNCTIONS:
- call_name = 'pyjslib.' + v.node.name
- elif v.node.name in PYJSLIB_BUILTIN_CLASSES:
- name = pyjs_builtin_remap(v.node.name)
- call_name = 'pyjslib.' + name
- elif v.node.name == "callable":
- call_name = "pyjslib.isFunction"
- call_name = v.node.name
- elif isinstance(v.node, ast.Getattr):
- attr_name = v.node.attrname
- if isinstance(v.node.expr, ast.Name):
- call_name = self._name2(v.node.expr, current_klass, attr_name)
- elif isinstance(v.node.expr, ast.Getattr):
- call_name = self._getattr2(v.node.expr, current_klass, attr_name)
- elif isinstance(v.node.expr, ast.CallFunc):
- call_name = self._callfunc(v.node.expr, current_klass) + "." + v.node.attrname
- elif isinstance(v.node.expr, ast.Subscript):
- call_name = self._subscript(v.node.expr, current_klass) + "." + v.node.attrname
- elif isinstance(v.node.expr, ast.Const):
- call_name = self.expr(v.node.expr, current_klass) + "." + v.node.attrname
- raise TranslationError("unsupported type (in _callfunc)", v.node.expr)
- raise TranslationError("unsupported type (in _callfunc)", v.node)
- call_name = strip_py(call_name)
- star_arg_name = self.expr(v.star_args, current_klass)
- if isinstance(ch4, ast.Keyword):
- kwarg = ch4.name + ":" + self.expr(ch4.expr, current_klass)
- arg = self.expr(ch4, current_klass)
- fn_args = ", ".join(['{' + ', '.join(kwargs) + '}']+call_args)
- fn_args = ", ".join(call_args)
- if kwargs or star_arg_name:
- try: call_this, method_name = call_name.rsplit(".", 1)
- # Must be a function call ...
- return ("pyjs_kwargs_function_call("+call_name+", "
- return ("pyjs_kwargs_method_call("+call_this+", '"+method_name+"', "
- return call_name + "(" + ", ".join(call_args) + ")"
- def _print(self, node, current_klass):
- arg = self.expr(ch4, current_klass)
- print >>self.output, "pyjslib.printFunc([", ', '.join(call_args), "],", int(isinstance(node, ast.Printnl)), ");"
- def _tryExcept(self, node, current_klass):
- if len(node.handlers) != 1:
- raise TranslationError("except statements in this form are" +
- " not supported", node)
- expr = node.handlers[0][0]
- as_ = node.handlers[0][1]
- # XXX TODO: check that this should instead be added as a _separate_
- # local scope, temporary to the function. oh dearie me.
- self.add_local_arg(errName)
- print >>self.output, " try {"
- for stmt in node.body.nodes:
- self._stmt(stmt, current_klass)
- print >> self.output, " } catch(%s) {" % errName
- if isinstance(expr, ast.Tuple):
- l.append("(%(err)s.__name__ == %(expr)s.__name__)" % dict (err=errName, expr=self.expr(x, current_klass)))
- l = [ " (%(err)s.__name__ == %(expr)s.__name__) " % dict (err=errName, expr=self.expr(expr, current_klass)) ]
- print >> self.output, " if(%s) {" % '||\n\t\t'.join(l)
- for stmt in node.handlers[0][2]:
- self._stmt(stmt, current_klass)
- #print >> self.output, "} else { throw(%s); } " % errName
- print >> self.output, "}"
- print >>self.output, " } finally {"
- for stmt in node.else_:
- self._stmt(stmt, current_klass)
- print >>self.output, " }"
- # XXX: change use_getattr to True to enable "strict" compilation
- # but incurring a 100% performance penalty. oops.
- def _getattr(self, v, current_klass, use_getattr=False):
- if isinstance(v.expr, ast.Name):
- obj = self._name(v.expr, current_klass, return_none_for_module=True)
- if obj == None and v.expr.name in self.module_imports():
- # XXX TODO: distinguish between module import classes
- # and variables. right now, this is a hack to get
- # the sys module working.
- #if v.expr.name == 'sys':
- return v.expr.name+'.'+attr_name
- #return v.expr.name+'.__'+attr_name+'.prototype.__class__'
- if not use_getattr or attr_name == '__class__' or \
- attr_name == '__name__':
- return obj + "." + attr_name
- return "pyjslib.getattr(%s, '%s')" % (obj, attr_name)
- elif isinstance(v.expr, ast.Getattr):
- return self._getattr(v.expr, current_klass) + "." + attr_name
- elif isinstance(v.expr, ast.Subscript):
- return self._subscript(v.expr, self.modpfx()) + "." + attr_name
- elif isinstance(v.expr, ast.CallFunc):
- return self._callfunc(v.expr, self.modpfx()) + "." + attr_name
- raise TranslationError("unsupported type (in _getattr)", v.expr)
- return strip_py(self.module_prefix)
- def _name(self, v, current_klass, top_level=False,
- return_none_for_module=False):
- if v.name == 'ilikesillynamesfornicedebugcode':
- print top_level, current_klass, repr(v)
- print self.top_level_vars
- print self.top_level_functions
- print self.local_arg_stack
- las = len(self.local_arg_stack)
- local_var_names = self.local_arg_stack[-1]
- elif v.name == "False":
- elif v.name == '__name__' and current_klass is None:
- return self.modpfx() + v.name
- elif v.name == self.method_self:
- elif v.name in self.top_level_functions:
- return UU+self.modpfx() + v.name
- elif v.name in self.method_imported_globals:
- return UU+self.modpfx() + v.name
- elif not current_klass and las == 1 and v.name in self.top_level_vars:
- return UU+self.modpfx() + v.name
- elif v.name in local_var_names:
- elif self.imported_classes.has_key(v.name):
- return UU+self.imported_classes[v.name] + '.__' + v.name + ".prototype.__class__"
- elif v.name in self.top_level_classes:
- return UU+self.modpfx() + "__" + v.name + ".prototype.__class__"
- elif v.name in self.module_imports() and return_none_for_module:
- elif v.name in PYJSLIB_BUILTIN_CLASSES:
- return "pyjslib." + pyjs_builtin_remap( v.name )
- if v.name not in local_var_names and \
- v.name not in self.top_level_vars and \
- v.name not in PYJS_GLOBAL_VARS and \
- v.name not in self.top_level_functions:
- cls_name = current_klass
- if hasattr(cls_name, "name"):
- cls_name_ = cls_name.name_
- cls_name = cls_name.name
- cls_name_ = current_klass + "_" # XXX ???
- name = UU+cls_name_ + ".prototype.__class__." \
- if v.name == 'listener':
- name = 'listener+' + name
- def _name2(self, v, current_klass, attr_name):
- if obj in self.method_imported_globals:
- call_name = UU+self.modpfx() + obj + "." + attr_name
- elif self.imported_classes.has_key(obj):
- #if attr_name != "__init__":
- attr_str = ".prototype.__class__." + attr_name
- call_name = UU+self.imported_classes[obj] + '.__' + obj + attr_str
- elif obj in self.module_imports():
- call_name = obj + "." + attr_name
- elif obj[0] == obj[0].upper(): # XXX HACK ALERT
- call_name = UU + self.modpfx() + "__" + obj + ".prototype.__class__." + attr_name
- call_name = UU+self._name(v, current_klass) + "." + attr_name
- def _getattr2(self, v, current_klass, attr_name):
- if isinstance(v.expr, ast.Getattr):
- call_name = self._getattr2(v.expr, current_klass, v.attrname + "." + attr_name)
- elif isinstance(v.expr, ast.Name) and v.expr.name in self.module_imports():
- call_name = UU+v.expr.name + '.__' +v.attrname+".prototype.__class__."+attr_name
- obj = self.expr(v.expr, current_klass)
- call_name = obj + "." + v.attrname + "." + attr_name
- def _class(self, node):
- Handle a class definition.
- In order to translate python semantics reasonably well, the following
- A special object is created for the class, which inherits attributes
- from the superclass, or Object if there's no superclass. This is the
- class object; the object which you refer to when specifying the
- class by name. Static, class, and unbound methods are copied
- from the superclass object.
- A special constructor function is created with the same name as the
- class, which is used to create instances of that class.
- A javascript class (e.g. a function with a prototype attribute) is
- created which is the javascript class of created instances, and
- which inherits attributes from the class object. Bound methods are
- copied from the superclass into this class rather than inherited,
- because the class object contains unbound, class, and static methods
- that we don't necessarily want to inherit.
- The type of a method can now be determined by inspecting its
- static_method, unbound_method, class_method, or instance_method
- attribute; only one of these should be true.
- Much of this work is done in pyjs_extend, is pyjslib.py
- class_name = self.modpfx() + uuprefix(node.name, 1)
- class_name_ = self.modpfx() + uuprefix(node.name)
- current_klass = Klass(class_name, class_name_)
- for child in node.code:
- if isinstance(child, ast.Function):
- current_klass.add_function(child.name)
- if child.name == "__init__":
- if len(node.bases) == 0:
- base_class = "pyjslib.__Object"
- elif len(node.bases) == 1:
- if isinstance(node.bases[0], ast.Name):
- if self.imported_classes.has_key(node.bases[0].name):
- base_class_ = self.imported_classes[node.bases[0].name] + '.__' + node.bases[0].name
- base_class = self.imported_classes[node.bases[0].name] + '.' + node.bases[0].name
- base_class_ = self.modpfx() + "__" + node.bases[0].name
- base_class = self.modpfx() + node.bases[0].name
- elif isinstance(node.bases[0], ast.Getattr):
- # the bases are not in scope of the class so do not
- # pass our class to self._name
- base_class_ = self._name(node.bases[0].expr, None) + \
- ".__" + node.bases[0].attrname
- base_class = self._name(node.bases[0].expr, None) + \
- "." + node.bases[0].attrname
- raise TranslationError("unsupported type (in _class)", node.bases[0])
- current_klass.set_base(base_class)
- raise TranslationError("more than one base (in _class)", node)
- print >>self.output, UU+class_name_ + " = function () {"
- # call superconstructor
- # print >>self.output, " __" + base_class + ".call(this);"
- print >>self.output, "}"
- init_method = ast.Function([], "__init__", ["self"], [], 0, None, [])
- #self._method(init_method, current_klass, class_name)
- # Generate a function which constructs the object
- clsfunc = ast.Function([],
- init_method.argnames[1:],
- [ast.Discard(ast.CallFunc(ast.Name("JS"), [ast.Const(
-# I attempted lazy initialization, but then you can't access static class members
-# " if(!__"+base_class+".__was_initialized__)"+
-# " __" + class_name + "_initialize();\n" +
- " var instance = new " + UU + class_name_ + "();\n" +
- " if(instance.__init__) instance.__init__.apply(instance, arguments);\n" +
- self._function(clsfunc, False)
- print >>self.output, UU+class_name_ + ".__initialize__ = function () {"
- print >>self.output, " if("+UU+class_name_+".__was_initialized__) return;"
- print >>self.output, " "+UU+class_name_+".__was_initialized__ = true;"
- cls_obj = UU+class_name_ + '.prototype.__class__'
- if class_name == "pyjslib.__Object":
- print >>self.output, " "+cls_obj+" = {};"
- if base_class and base_class not in ("object", "pyjslib.__Object"):
- print >>self.output, " if(!"+UU+base_class_+".__was_initialized__)"
- print >>self.output, " "+UU+base_class_+".__initialize__();"
- print >>self.output, " pyjs_extend(" + UU+class_name_ + ", "+UU+base_class_+");"
- print >>self.output, " pyjs_extend(" + UU+class_name_ + ", "+UU+"pyjslib.__Object);"
- print >>self.output, " "+cls_obj+".__new__ = "+UU+class_name+";"
- print >>self.output, " "+cls_obj+".__name__ = '"+UU+node.name+"';"
- for child in node.code:
- if isinstance(child, ast.Pass):
- elif isinstance(child, ast.Function):
- self._method(child, current_klass, class_name, class_name_)
- elif isinstance(child, ast.Assign):
- self.classattr(child, current_klass)
- elif isinstance(child, ast.Discard) and isinstance(child.expr, ast.Const):
- # Probably a docstring, turf it
- raise TranslationError("unsupported type (in _class)", child)
- print >>self.output, "}"
- print >> self.output, class_name_+".__initialize__();"
- def classattr(self, node, current_klass):
- self._assign(node, current_klass, True)
- def _raise(self, node, current_klass):
- raise TranslationError("More than one expression unsupported",
- print >> self.output, "throw (%s);" % self.expr(
- node.expr1, current_klass)
- def _method(self, node, current_klass, class_name, class_name_):
- # reset global var scope
- self.method_imported_globals = set()
- arg_names = list(node.argnames)
- for d in node.decorators:
- if d.name == "classmethod":
- elif d.name == "staticmethod":
- staticfunc = ast.Function([], class_name_+"."+node.name, node.argnames, node.defaults, node.flags, node.doc, node.code, node.lineno)
- self._function(staticfunc, True)
- print >>self.output, " " + UU+class_name_ + ".prototype.__class__." + node.name + " = " + class_name_+"."+node.name+";";
- print >>self.output, " " + UU+class_name_ + ".prototype.__class__." + node.name + ".static_method = true;";
- if len(arg_names) == 0:
- raise TranslationError("methods must take an argument 'self' (in _method)", node)
- self.method_self = arg_names[0]
- #if not classmethod and arg_names[0] != "self":
- # raise TranslationError("first arg not 'self' (in _method)", node)
- normal_arg_names = arg_names[1:]
- if node.kwargs: kwargname = normal_arg_names.pop()
- if node.varargs: varargname = normal_arg_names.pop()
- declared_arg_names = list(normal_arg_names)
- if node.kwargs: declared_arg_names.append(kwargname)
- function_args = "(" + ", ".join(declared_arg_names) + ")"
- fexpr = UU + class_name_ + ".prototype.__class__." + node.name
- fexpr = UU + class_name_ + ".prototype." + node.name
- print >>self.output, " "+fexpr + " = function" + function_args + " {"
- self._default_args_handler(node, normal_arg_names, current_klass)
- local_arg_names = normal_arg_names + declared_arg_names
- self._varargs_handler(node, varargname, declared_arg_names, current_klass)
- local_arg_names.append(varargname)
- # stack of local variable names for this function call
- self.local_arg_stack.append(local_arg_names)
- for child in node.code:
- self._stmt(child, current_klass)
- # remove the top local arg names
- self.local_arg_stack.pop()
- print >>self.output, " };"
- self._kwargs_parser(node, fexpr, normal_arg_names, current_klass)
- # Have to create a version on the instances which automatically passes the
- altexpr = UU + class_name_ + ".prototype." + node.name
- print >>self.output, " "+altexpr + " = function() {"
- print >>self.output, " return " + fexpr + ".apply(this.__class__, arguments);"
- print >>self.output, " };"
- print >>self.output, " "+fexpr+".class_method = true;"
- print >>self.output, " "+altexpr+".instance_method = true;"
- # For instance methods, we need an unbound version in the class object
- altexpr = UU + class_name_ + ".prototype.__class__." + node.name
- print >>self.output, " "+altexpr + " = function() {"
- print >>self.output, " return " + fexpr + ".call.apply("+fexpr+", arguments);"
- print >>self.output, " };"
- print >>self.output, " "+altexpr+".unbound_method = true;"
- print >>self.output, " "+fexpr+".instance_method = true;"
- print >>self.output, " "+altexpr+".__name__ = '%s';" % node.name
- print >>self.output, UU + class_name_ + ".prototype.%s.__name__ = '%s';" % \
- if node.kwargs or len(node.defaults):
- print >>self.output, " "+altexpr + ".parse_kwargs = " + fexpr + ".parse_kwargs;"
- self.method_self = None
- self.method_imported_globals = set()
- def _isNativeFunc(self, node):
- if isinstance(node, ast.Discard):
- if isinstance(node.expr, ast.CallFunc):
- if isinstance(node.expr.node, ast.Name) and \
- node.expr.node.name == NATIVE_JS_FUNC_NAME:
- def _stmt(self, node, current_klass):
- debugStmt = self.debug and not self._isNativeFunc(node)
- print >>self.output, ' try {'
- if isinstance(node, ast.Return):
- self._return(node, current_klass)
- elif isinstance(node, ast.Break):
- self._break(node, current_klass)
- elif isinstance(node, ast.Continue):
- self._continue(node, current_klass)
- elif isinstance(node, ast.Assign):
- self._assign(node, current_klass)
- elif isinstance(node, ast.AugAssign):
- self._augassign(node, current_klass)
- elif isinstance(node, ast.Discard):
- self._discard(node, current_klass)
- elif isinstance(node, ast.If):
- self._if(node, current_klass)
- elif isinstance(node, ast.For):
- self._for(node, current_klass)
- elif isinstance(node, ast.While):
- self._while(node, current_klass)
- elif isinstance(node, ast.Subscript):
- self._subscript_stmt(node, current_klass)
- elif isinstance(node, ast.Global):
- self._global(node, current_klass)
- elif isinstance(node, ast.Pass):
- elif isinstance(node, ast.Function):
- self._function(node, True)
- elif isinstance(node, ast.Printnl):
- self._print(node, current_klass)
- elif isinstance(node, ast.Print):
- self._print(node, current_klass)
- elif isinstance(node, ast.TryExcept):
- self._tryExcept(node, current_klass)
- elif isinstance(node, ast.Raise):
- self._raise(node, current_klass)
- raise TranslationError("unsupported type (in _stmt)", node)
- lt = self.get_line_trace(node)
- haltException = self.module_prefix + "HaltException"
- isHaltFunction = self.module_prefix + "IsHaltException"
- print >>self.output, ' } catch (__err) {'
- print >>self.output, ' if (' + isHaltFunction + '(__err.name)) {'
- print >>self.output, ' throw __err;'
- print >>self.output, ' } else {'
- print >>self.output, " st = sys.printstack() + "\
- + '"%s"' % lt + "+ '\\n' ;"
- print >>self.output, ' alert("' + "Error in " \
- + '+"\\n"+__err.name+": "+__err.message'\
- + '+"\\n\\nStack trace:\\n"' \
- print >>self.output, ' debugger;'
- print >>self.output, ' throw new ' + self.module_prefix + "HaltException();"
- print >>self.output, ' }'
- print >>self.output, ' }'
- def get_line_trace(self, node):
- if hasattr(node, "lineno"):
- if node.lineno != None:
- srcLine = self.src[min(lineNum, len(self.src))-1]
- srcLine = srcLine.replace('\\', '\\\\')
- srcLine = srcLine.replace('"', '\\"')
- srcLine = srcLine.replace("'", "\\'")
- return self.raw_module_name + ".py, line " \
- def _augassign(self, node, current_klass):
- if isinstance(v, ast.Getattr):
- # XXX HACK! don't allow += on return result of getattr.
- # TODO: create a temporary variable or something.
- lhs = self._getattr(v, current_klass, False)
- lhs = self._name(node.node, current_klass)
- rhs = self.expr(node.expr, current_klass)
- print >>self.output, " " + lhs + " " + op + " " + rhs + ";"
- def _assign(self, node, current_klass, top_level = False):
- if len(node.nodes) != 1:
- tempvar = '__temp'+str(node.lineno)
- tnode = ast.Assign([ast.AssName(tempvar, "OP_ASSIGN", node.lineno)], node.expr, node.lineno)
- self._assign(tnode, current_klass, top_level)
- tnode2 = ast.Assign([v], ast.Name(tempvar, node.lineno), node.lineno)
- self._assign(tnode2, current_klass, top_level)
- if len(self.local_arg_stack) > 0:
- local_var_names = self.local_arg_stack[-1]
- def _lhsFromAttr(v, current_klass):
- if isinstance(v.expr, ast.Name):
- lhs = self._name(v.expr, current_klass) + "." + attr_name
- elif isinstance(v.expr, ast.Getattr):
- lhs = self._getattr(v, current_klass)
- elif isinstance(v.expr, ast.Subscript):
- lhs = self._subscript(v.expr, current_klass) + "." + attr_name
- raise TranslationError("unsupported type (in _assign)", v.expr)
- def _lhsFromName(v, top_level, current_klass):
- lhs = UU+current_klass.name_ + ".prototype.__class__." \
- self.top_level_vars.add(v.name)
- vname = self.modpfx() + v.name
- if not self.modpfx() and v.name not in\
- self.method_imported_globals:
- self.add_local_arg(v.name)
- if v.name in local_var_names:
- elif v.name in self.method_imported_globals:
- lhs = self.modpfx() + v.name
- self.add_local_arg(v.name)
- if isinstance(v, ast.AssAttr):
- lhs = _lhsFromAttr(v, current_klass)
- if v.flags == "OP_ASSIGN":
- raise TranslationError("unsupported flag (in _assign)", v)
- elif isinstance(v, ast.AssName):
- lhs = _lhsFromName(v, top_level, current_klass)
- if v.flags == "OP_ASSIGN":
- raise TranslationError("unsupported flag (in _assign)", v)
- elif isinstance(v, ast.Subscript):
- if v.flags == "OP_ASSIGN":
- obj = self.expr(v.expr, current_klass)
- raise TranslationError("must have one sub (in _assign)", v)
- idx = self.expr(v.subs[0], current_klass)
- value = self.expr(node.expr, current_klass)
- print >>self.output, " " + obj + ".__setitem__(" + idx + ", " + value + ");"
- raise TranslationError("unsupported flag (in _assign)", v)
- elif isinstance(v, (ast.AssList, ast.AssTuple)):
- uniqueID = self.nextTupleAssignID
- self.nextTupleAssignID += 1
- tempName = "__tupleassign" + str(uniqueID) + "__"
- print >>self.output, " var " + tempName + " = " + \
- self.expr(node.expr, current_klass) + ";"
- for index,child in enumerate(v.getChildNodes()):
- rhs = tempName + ".__getitem__(" + str(index) + ")"
- if isinstance(child, ast.AssAttr):
- lhs = _lhsFromAttr(child, current_klass)
- elif isinstance(child, ast.AssName):
- lhs = _lhsFromName(child, top_level, current_klass)
- elif isinstance(child, ast.Subscript):
- if child.flags == "OP_ASSIGN":
- obj = self.expr(child.expr, current_klass)
- if len(child.subs) != 1:
- raise TranslationError("must have one sub " +
- idx = self.expr(child.subs[0], current_klass)
- value = self.expr(node.expr, current_klass)
- print >>self.output, " " + obj + ".__setitem__(" \
- + idx + ", " + rhs + ");"
- print >>self.output, " " + lhs + " = " + rhs + ";"
- raise TranslationError("unsupported type (in _assign)", v)
- rhs = self.expr(node.expr, current_klass)
- print "b", repr(node.expr), rhs
- print >>self.output, " " + lhs + " " + op + " " + rhs + ";"
- def _discard(self, node, current_klass):
- if isinstance(node.expr, ast.CallFunc):
- debugStmt = self.debug and not self._isNativeFunc(node)
- if debugStmt and isinstance(node.expr.node, ast.Name) and \
- node.expr.node.name == 'import_wait':
- st = self.get_line_trace(node)
- print >>self.output, "sys.addstack('%s');\n" % st
- if isinstance(node.expr.node, ast.Name) and node.expr.node.name == NATIVE_JS_FUNC_NAME:
- if len(node.expr.args) != 1:
- raise TranslationError("native javascript function %s must have one arg" % NATIVE_JS_FUNC_NAME, node.expr)
- if not isinstance(node.expr.args[0], ast.Const):
- raise TranslationError("native javascript function %s must have constant arg" % NATIVE_JS_FUNC_NAME, node.expr)
- raw_js = node.expr.args[0].value
- print >>self.output, raw_js
- expr = self._callfunc(node.expr, current_klass)
- print >>self.output, " " + expr + ";"
- print >>self.output, "sys.popstack();\n"
- elif isinstance(node.expr, ast.Const):
- if node.expr.value is not None: # Empty statements generate ignore None
- print >>self.output, self._const(node.expr)
- raise TranslationError("unsupported type (in _discard)", node.expr)
- def _if(self, node, current_klass):
- for i in range(len(node.tests)):
- test, consequence = node.tests[i]
- self._if_test(keyword, test, consequence, current_klass)
- consequence = node.else_
- self._if_test(keyword, test, consequence, current_klass)
- def _if_test(self, keyword, test, consequence, current_klass):
- expr = self.expr(test, current_klass)
- print >>self.output, " " + keyword + " (pyjslib.bool(" + expr + ")) {"
- print >>self.output, " " + keyword + " {"
- if isinstance(consequence, ast.Stmt):
- for child in consequence.nodes:
- self._stmt(child, current_klass)
- raise TranslationError("unsupported type (in _if_test)", consequence)
- print >>self.output, " }"
- for name in node.names:
- # look up "hack" in AppTranslator as to how findFile gets here
- module_name = node.modname + "." + name[0]
- ff = self.findFile(module_name + ".py")
- self.add_imported_module(module_name)
- self.imported_classes[name[0]] = node.modname
- def _compare(self, node, current_klass):
- lhs = self.expr(node.expr, current_klass)
- raise TranslationError("only one ops supported (in _compare)", node)
- rhs_node = node.ops[0][1]
- rhs = self.expr(rhs_node, current_klass)
- return "pyjslib.eq(%s, %s)" % (lhs, rhs)
- return rhs + ".__contains__(" + lhs + ")"
- return "!" + rhs + ".__contains__(" + lhs + ")"
- return "(" + lhs + " " + op + " " + rhs + ")"
- def _not(self, node, current_klass):
- expr = self.expr(node.expr, current_klass)
- return "!(" + expr + ")"
- def _or(self, node, current_klass):
- expr = "("+(") || (".join([self.expr(child, current_klass) for child in node.nodes]))+')'
- def _and(self, node, current_klass):
- expr = "("+(") && (".join([self.expr(child, current_klass) for child in node.nodes]))+")"
- def _for(self, node, current_klass):
- # based on Bob Ippolito's Iteration in Javascript code
- if isinstance(node.assign, ast.AssName):
- assign_name = node.assign.name
- self.add_local_arg(assign_name)
- if node.assign.flags == "OP_ASSIGN":
- elif isinstance(node.assign, ast.AssTuple):
- for child in node.assign:
- child_name = child.name
- assign_name = "temp_" + child_name
- self.add_local_arg(child_name)
- var %(child_name)s %(op)s %(assign_name)s.__getitem__(%(i)i);
- raise TranslationError("unsupported type (in _for)", node.assign)
- if isinstance(node.list, ast.Name):
- list_expr = self._name(node.list, current_klass)
- elif isinstance(node.list, ast.Getattr):
- list_expr = self._getattr(node.list, current_klass)
- elif isinstance(node.list, ast.CallFunc):
- list_expr = self._callfunc(node.list, current_klass)
- raise TranslationError("unsupported type (in _for)", node.list)
- lhs = "var " + assign_name
- iterator_name = "__" + assign_name
- print >>self.output, """
- var %(iterator_name)s = %(list_expr)s.__iter__();
- %(lhs)s %(op)s %(iterator_name)s.next();
- for node in node.body.nodes:
- self._stmt(node, current_klass)
- print >>self.output, """
- if (e.__name__ != pyjslib.StopIteration.__name__) {
- def _while(self, node, current_klass):
- test = self.expr(node.test, current_klass)
- print >>self.output, " while (pyjslib.bool(" + test + ")) {"
- if isinstance(node.body, ast.Stmt):
- for child in node.body.nodes:
- self._stmt(child, current_klass)
- raise TranslationError("unsupported type (in _while)", node.body)
- print >>self.output, " }"
- def _const(self, node):
- if isinstance(node.value, int):
- elif isinstance(node.value, float):
- elif isinstance(node.value, basestring):
- if isinstance(node.value, unicode):
- return "String('%s')" % escapejs(v)
- elif node.value is None:
- raise TranslationError("unsupported type (in _const)", node)
- def _unaryadd(self, node, current_klass):
- return self.expr(node.expr, current_klass)
- def _unarysub(self, node, current_klass):
- return "-" + self.expr(node.expr, current_klass)
- def _add(self, node, current_klass):
- return self.expr(node.left, current_klass) + " + " + self.expr(node.right, current_klass)
- def _sub(self, node, current_klass):
- return self.expr(node.left, current_klass) + " - " + self.expr(node.right, current_klass)
- def _div(self, node, current_klass):
- return self.expr(node.left, current_klass) + " / " + self.expr(node.right, current_klass)
- def _mul(self, node, current_klass):
- return self.expr(node.left, current_klass) + " * " + self.expr(node.right, current_klass)
- def _mod(self, node, current_klass):
- if isinstance(node.left, ast.Const) and isinstance(node.left.value, StringType):
- self.imported_js.add("sprintf.js") # Include the sprintf functionality if it is used
- return "sprintf("+self.expr(node.left, current_klass) + ", " + self.expr(node.right, current_klass)+")"
- return self.expr(node.left, current_klass) + " % " + self.expr(node.right, current_klass)
- def _invert(self, node, current_klass):
- return "~" + self.expr(node.expr, current_klass)
- def _bitand(self, node, current_klass):
- return " & ".join([self.expr(child, current_klass) for child in node.nodes])
- def _bitshiftleft(self, node, current_klass):
- return self.expr(node.left, current_klass) + " << " + self.expr(node.right, current_klass)
- def _bitshiftright(self, node, current_klass):
- return self.expr(node.left, current_klass) + " >>> " + self.expr(node.right, current_klass)
- def _bitxor(self,node, current_klass):
- return " ^ ".join([self.expr(child, current_klass) for child in node.nodes])
- def _bitor(self, node, current_klass):
- return " | ".join([self.expr(child, current_klass) for child in node.nodes])
- def _subscript(self, node, current_klass):
- if node.flags == "OP_APPLY":
- if len(node.subs) == 1:
- return self.expr(node.expr, current_klass) + ".__getitem__(" + self.expr(node.subs[0], current_klass) + ")"
- raise TranslationError("must have one sub (in _subscript)", node)
- raise TranslationError("unsupported flag (in _subscript)", node)
- def _subscript_stmt(self, node, current_klass):
- if node.flags == "OP_DELETE":
- print >>self.output, " " + self.expr(node.expr, current_klass) + ".__delitem__(" + self.expr(node.subs[0], current_klass) + ");"
- raise TranslationError("unsupported flag (in _subscript)", node)
- def _list(self, node, current_klass):
- return "new pyjslib.List([" + ", ".join([self.expr(x, current_klass) for x in node.nodes]) + "])"
- def _dict(self, node, current_klass):
- key = self.expr(x[0], current_klass)
- value = self.expr(x[1], current_klass)
- items.append("[" + key + ", " + value + "]")
- return "new pyjslib.Dict([" + ", ".join(items) + "])"
- def _tuple(self, node, current_klass):
- return "new pyjslib.Tuple([" + ", ".join([self.expr(x, current_klass) for x in node.nodes]) + "])"
- def _lambda(self, node, current_klass):
- raise TranslationError("varargs are not supported in Lambdas", node)
- raise TranslationError("kwargs are not supported in Lambdas", node)
- res = cStringIO.StringIO()
- arg_names = list(node.argnames)
- function_args = ", ".join(arg_names)
- for child in node.getChildNodes():
- expr = self.expr(child, None)
- print >> res, "function (%s){" % function_args
- self._default_args_handler(node, arg_names, None,
- print >> res, 'return %s;}' % expr
- def _slice(self, node, current_klass):
- if node.flags == "OP_APPLY":
- lower = self.expr(node.lower, current_klass)
- upper = self.expr(node.upper, current_klass)
- return "pyjslib.slice(" + self.expr(node.expr, current_klass) + ", " + lower + ", " + upper + ")"
- raise TranslationError("unsupported flag (in _slice)", node)
- def _global(self, node, current_klass):
- for name in node.names:
- self.method_imported_globals.add(name)
- def expr(self, node, current_klass):
- if isinstance(node, ast.Const):
- return self._const(node)
- # @@@ not sure if the parentheses should be here or in individual operator functions - JKT
- elif isinstance(node, ast.Mul):
- return " ( " + self._mul(node, current_klass) + " ) "
- elif isinstance(node, ast.Add):
- return " ( " + self._add(node, current_klass) + " ) "
- elif isinstance(node, ast.Sub):
- return " ( " + self._sub(node, current_klass) + " ) "
- elif isinstance(node, ast.Div):
- return " ( " + self._div(node, current_klass) + " ) "
- elif isinstance(node, ast.Mod):
- return self._mod(node, current_klass)
- elif isinstance(node, ast.UnaryAdd):
- return self._unaryadd(node, current_klass)
- elif isinstance(node, ast.UnarySub):
- return self._unarysub(node, current_klass)
- elif isinstance(node, ast.Not):
- return self._not(node, current_klass)
- elif isinstance(node, ast.Or):
- return self._or(node, current_klass)
- elif isinstance(node, ast.And):
- return self._and(node, current_klass)
- elif isinstance(node, ast.Invert):
- return self._invert(node, current_klass)
- elif isinstance(node, ast.Bitand):
- return "("+self._bitand(node, current_klass)+")"
- elif isinstance(node,ast.LeftShift):
- return self._bitshiftleft(node, current_klass)
- elif isinstance(node, ast.RightShift):
- return self._bitshiftright(node, current_klass)
- elif isinstance(node, ast.Bitxor):
- return "("+self._bitxor(node, current_klass)+")"
- elif isinstance(node, ast.Bitor):
- return "("+self._bitor(node, current_klass)+")"
- elif isinstance(node, ast.Compare):
- return self._compare(node, current_klass)
- elif isinstance(node, ast.CallFunc):
- return self._callfunc(node, current_klass)
- elif isinstance(node, ast.Name):
- return self._name(node, current_klass)
- elif isinstance(node, ast.Subscript):
- return self._subscript(node, current_klass)
- elif isinstance(node, ast.Getattr):
- return self._getattr(node, current_klass)
- elif isinstance(node, ast.List):
- return self._list(node, current_klass)
- elif isinstance(node, ast.Dict):
- return self._dict(node, current_klass)
- elif isinstance(node, ast.Tuple):
- return self._tuple(node, current_klass)
- elif isinstance(node, ast.Slice):
- return self._slice(node, current_klass)
- elif isinstance(node, ast.Lambda):
- return self._lambda(node, current_klass)
- raise TranslationError("unsupported type (in expr)", node)
-def translate(file_name, module_name, debug=False):
- f = file(file_name, "r")
- output = cStringIO.StringIO()
- mod = compiler.parseFile(file_name)
- t = Translator(module_name, module_name, module_name, src, debug, mod, output)
- return output.getvalue()
- def __init__(self, platform_dir = "", verbose=True):
- self.platform_dir = platform_dir
- def setPlatform(self, platform):
- self.platform = platform
- def parseModule(self, module_name, file_name):
- if not self.parse_cache.has_key(file_name):
- mod = compiler.parseFile(file_name)
- self.parse_cache[file_name] = mod
- mod = self.parse_cache[file_name]
- platform_file_name = self.generatePlatformFilename(file_name)
- if self.platform and os.path.isfile(platform_file_name):
- mod = copy.deepcopy(mod)
- mod_override = compiler.parseFile(platform_file_name)
- self.merge(mod, mod_override)
- print "Importing %s (Platform %s)" % (module_name, self.platform)
- print "Importing %s" % (module_name)
- def generatePlatformFilename(self, file_name):
- (module_name, extension) = os.path.splitext(os.path.basename(file_name))
- platform_file_name = module_name + self.platform + extension
- return os.path.join(os.path.dirname(file_name), self.platform_dir, platform_file_name)
- def merge(self, tree1, tree2):
- for child in tree2.node:
- if isinstance(child, ast.Function):
- self.replaceFunction(tree1, child.name, child)
- elif isinstance(child, ast.Class):
- self.replaceClassMethods(tree1, child.name, child)
- def replaceFunction(self, tree, function_name, function_node):
- # find function to replace
- for child in tree.node:
- if isinstance(child, ast.Function) and child.name == function_name:
- self.copyFunction(child, function_node)
- raise TranslationError("function not found: " + function_name, function_node)
- def replaceClassMethods(self, tree, class_name, class_node):
- # find class to replace
- for child in tree.node:
- if isinstance(child, ast.Class) and child.name == class_name:
- raise TranslationError("class not found: " + class_name, class_node)
- for function_node in class_node.code:
- if isinstance(function_node, ast.Function):
- for child in old_class_node.code:
- if isinstance(child, ast.Function) and child.name == function_node.name:
- self.copyFunction(child, function_node)
- raise TranslationError("class method not found: " + class_name + "." + function_node.name, function_node)
- def copyFunction(self, target, source):
- target.code = source.code
- target.argnames = source.argnames
- target.defaults = source.defaults
- target.doc = source.doc # @@@ not sure we need to do this any more
- path, ext = os.path.splitext(fname)
- return path.replace(".", "/") + ext
- def __init__(self, library_dirs=[], parser=None, dynamic=False,
- optimize=False, verbose=True):
- self.optimize = optimize
- self.library_modules = []
- self.library_dirs = path + library_dirs
- self.parser = PlatformParser()
- self.parser.dynamic = dynamic
- def findFile(self, file_name):
- if os.path.isfile(file_name):
- for library_dir in self.library_dirs:
- file_name = dotreplace(file_name)
- full_file_name = os.path.join(
- os.path.abspath(os.path.dirname(__file__)), library_dir, file_name)
- if os.path.isfile(full_file_name):
- fnameinit, ext = os.path.splitext(file_name)
- fnameinit = fnameinit + "/__init__.py"
- full_file_name = os.path.join(
- os.path.abspath(os.path.dirname(__file__)), library_dir, fnameinit)
- if os.path.isfile(full_file_name):
- raise Exception("file not found: " + file_name)
- def _translate(self, module_name, is_app=True, debug=False,
- if module_name not in self.library_modules:
- self.library_modules.append(module_name)
- file_name = self.findFile(module_name + self.extension)
- output = cStringIO.StringIO()
- f = file(file_name, "r")
- mod, override = self.parser.parseModule(module_name, file_name)
- override_name = "%s.%s" % (self.parser.platform.lower(),
- self.overrides[override_name] = override_name
- t = Translator(mn, module_name, module_name,
- src, debug, mod, output, self.dynamic, self.optimize,
- module_str = output.getvalue()
- imported_js.update(set(t.imported_js))
- imported_modules_str = ""
- for module in t.imported_modules:
- if module not in self.library_modules:
- self.library_modules.append(module)
- #imported_js.update(set(t.imported_js))
- #imported_modules_str += self._translate(
- # module, False, debug=debug, imported_js=imported_js)
- return imported_modules_str + module_str
- def translate(self, module_name, is_app=True, debug=False,
- app_code = cStringIO.StringIO()
- lib_code = cStringIO.StringIO()
- self.library_modules = []
- for library in library_modules:
- if library.endswith(".js"):
- imported_js.add(library)
- self.library_modules.append(library)
- print 'Including LIB', library
- print >> lib_code, '\n//\n// BEGIN LIB '+library+'\n//\n'
- print >> lib_code, self._translate(
- library, False, debug=debug, imported_js=imported_js)
- print >> lib_code, "/* initialize static library */"
- print >> lib_code, "%s%s();\n" % (UU, library)
- print >> lib_code, '\n//\n// END LIB '+library+'\n//\n'
- print >> app_code, self._translate(
- module_name, is_app, debug=debug, imported_js=imported_js)
- path = self.findFile(js)
- if os.path.isfile(path):
- print 'Including JS', js
- print >> lib_code, '\n//\n// BEGIN JS '+js+'\n//\n'
- print >> lib_code, file(path).read()
- print >> lib_code, '\n//\n// END JS '+js+'\n//\n'
- print >>sys.stderr, 'Warning: Unable to find imported javascript:', js
- return lib_code.getvalue(), app_code.getvalue()
- usage: %s file_name [module_name]
- print >> sys.stderr, usage % sys.argv[0]
- file_name = os.path.abspath(sys.argv[1])
- if not os.path.isfile(file_name):
- print >> sys.stderr, "File not found %s" % file_name
- module_name = sys.argv[2]
- print translate(file_name, module_name),
-if __name__ == "__main__":
--- a/py_ext/modules/svgui/svgui.py Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,112 +0,0 @@
-from ConfigTreeNode import opjimg
-from py_ext import PythonCodeTemplate
-from pyjs import translate
- {"bitmap" : os.path.join("images","ImportSVG"),
- "name" : _("Import SVG"),
- "tooltip" : _("Import SVG"),
- "method" : "_ImportSVG"},
- {"bitmap" : os.path.join("images","ImportSVG"),
- "name" : _("Inkscape"),
- "tooltip" : _("Create HMI"),
- "method" : "_StartInkscape"},
- def ConfNodePath(self):
- return os.path.join(self.CTNParent.ConfNodePath(), "modules", self.CTNType)
- # define name for IEC raw code file
- return os.path.join(self.CTNPath(), "gui.svg")
- def _getSVGUIserverpath(self):
- return os.path.join(os.path.dirname(__file__), "svgui_server.py")
- def CTNGenerate_C(self, buildpath, locations):
- Return C code generated by iec2c compiler
- when _generate_softPLC have been called
- @param locations: ignored
- @return: [(C_file_name, CFLAGS),...] , LDFLAGS_TO_APPEND
- current_location = self.GetCurrentLocation()
- # define a unique name for the generated C file
- location_str = "_".join(map(lambda x:str(x), current_location))
- svgfile=self._getSVGpath()
- if os.path.exists(svgfile):
- res += (("gui.svg", file(svgfile,"rb")),)
- svguiserverfile = open(self._getSVGUIserverpath(), 'r')
- svguiservercode = svguiserverfile.read()
- svguiserverfile.close()
- svguilibpath = os.path.join(self._getBuildPath(), "svguilib.js")
- svguilibfile = open(svguilibpath, 'w')
- svguilibfile.write(translate(os.path.join(os.path.dirname(__file__), "pyjs", "lib", "sys.py"), "sys"))
- svguilibfile.write(open(os.path.join(os.path.dirname(__file__), "pyjs", "lib", "_pyjs.js"), 'r').read())
- svguilibfile.write(translate(os.path.join(os.path.dirname(__file__), "pyjs", "lib", "pyjslib.py"), "pyjslib"))
- svguilibfile.write(translate(os.path.join(os.path.dirname(__file__), "svguilib.py"), "svguilib"))
- svguilibfile.write("pyjslib();\nsvguilib();\n")
- svguilibfile.write(open(os.path.join(os.path.dirname(__file__), "pyjs", "lib", "json.js"), 'r').read())
- svguilibfile.write(open(os.path.join(os.path.dirname(__file__), "livesvg.js"), 'r').read())
- jsmodules = {"LiveSVGPage": "svguilib.js"}
- res += (("svguilib.js", file(svguilibpath,"rb")),)
- runtimefile_path = os.path.join(buildpath, "runtime_%s.py"%location_str)
- runtimefile = open(runtimefile_path, 'w')
- runtimefile.write(svguiservercode % {"svgfile" : "gui.svg"})
-def _runtime_%(location)s_begin():
- website.LoadHMI(%(svgui_class)s, %(jsmodules)s)
-def _runtime_%(location)s_cleanup():
-""" % {"location": location_str,
- "svgui_class": "SVGUI_HMI",
- "jsmodules" : str(jsmodules),
- res += (("runtime_%s.py"%location_str, file(runtimefile_path,"rb")),)
- dialog = wx.FileDialog(self.GetCTRoot().AppFrame, _("Choose a SVG file"), os.getcwd(), "", _("SVG files (*.svg)|*.svg|All files|*.*"), wx.OPEN)
- if dialog.ShowModal() == wx.ID_OK:
- svgpath = dialog.GetPath()
- if os.path.isfile(svgpath):
- shutil.copy(svgpath, self._getSVGpath())
- self.GetCTRoot().logger.write_error(_("No such SVG file: %s\n")%svgpath)
- def _StartInkscape(self):
- svgfile = self._getSVGpath()
- if not self.GetCTRoot().CheckProjectPathPerm():
- dialog = wx.MessageDialog(self.GetCTRoot().AppFrame,
- _("You don't have write permissions.\nOpen Inkscape anyway ?"),
- wx.YES_NO|wx.ICON_QUESTION)
- open_inkscape = dialog.ShowModal() == wx.ID_YES
- if not os.path.isfile(svgfile):
--- a/py_ext/modules/svgui/svgui_server.py Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,130 +0,0 @@
-from nevow import rend, appserver, inevow, tags, loaders, athena
-import simplejson as json
- def __init__(self, classname, id, **kwargs):
- self.classname = classname
- self.attrs = kwargs.copy()
- def setinput(self, attrname, value):
- self.inputs[attrname] = value
- def getinput(self, attrname, default=None):
- if not self.inputs.has_key(attrname):
- self.inputs[attrname] = default
- return self.inputs[attrname]
- def setoutput(self, attrname, value):
- if self.outputs.get(attrname) != value:
- self.outputs[attrname] = value
- self.RefreshInterface()
- def updateoutputs(self, **kwargs):
- for attrname, value in kwargs.iteritems():
- if self.outputs.get(attrname) != value:
- self.outputs[attrname] = value
- self.RefreshInterface()
- def RefreshInterface(self):
- interface = website.getHMI()
- if isinstance(interface, SVGUI_HMI) and self.changed and not self.inhibit:
- d = interface.sendData(self)
- d.addCallback(self.InterfaceRefreshed)
- def InterfaceRefreshed(self, result):
- self.RefreshInterface()
-def get_object_init_state(obj):
- # Convert objects to a dictionary of their representation
- attrs = obj.attrs.copy()
- attrs.update(obj.inputs)
- d = { '__class__': obj.classname,
- 'kwargs': json.dumps(attrs),
-def get_object_current_state(obj):
- # Convert objects to a dictionary of their representation
- d = { '__class__': obj.classname,
- 'kwargs': json.dumps(obj.outputs),
-class SVGUI_HMI(website.PLCHMI):
- jsClass = u"LiveSVGPage.LiveSVGWidget"
- docFactory = loaders.stan(tags.div(render=tags.directive('liveElement'))[
- tags.xml(loaders.xmlfile(os.path.join(WorkingDir, svgfile))),
- def HMIinitialisation(self):
- for gadget in svguiWidgets.values():
- gadgets.append(unicode(json.dumps(gadget, default=get_object_init_state, indent=2), 'ascii'))
- d = self.callRemote('init', gadgets)
- d.addCallback(self.HMIinitialised)
- def sendData(self,data):
- return self.callRemote('receiveData',unicode(json.dumps(data, default=get_object_current_state, indent=2), 'ascii'))
- def setattr(self, id, attrname, value):
- svguiWidgets[id].setinput(attrname, value)
-def createSVGUIControl(*args, **kwargs):
- gad = SvguiWidget(args[0], id, **kwargs)
- gadget = [unicode(json.dumps(gad, default=get_object_init_state, indent=2), 'ascii')]
- interface = website.getHMI()
- if isinstance(interface, SVGUI_HMI) and interface.initialised:
- interface.callRemote('init', gadget)
-def setAttr(id, attrname, value):
- gad = svguiWidgets.get(id, None)
- gad.setoutput(attrname, value)
-def updateAttr(id, **kwargs):
- gad = svguiWidgets.get(id, None)
- gad.updateoutput(**kwargs)
-def getAttr(id, attrname, default=None):
- gad = svguiWidgets.get(id, None)
- return gad.getinput(attrname, default)
--- a/py_ext/modules/svgui/svguilib.py Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,117 +0,0 @@
- def __init__(self, parent, id, args):
- self.back_elt = getSVGElementById(args.back_id)
- self.sele_elt = getSVGElementById(args.sele_id)
- self.toggle = args.toggle
- self.active = args.active
- if args.state != undefined:
- self.state = args.state
- self.up = not self.state
- # Add event on each element of the button
- self.back_elt.addEventListener("mouseup", self, False)
- self.back_elt.addEventListener("mousedown", self, False)
- self.back_elt.addEventListener("mouseover", self, False)
- self.back_elt.addEventListener("mouseout", self, False)
- self.sele_elt.addEventListener("mouseup", self, False)
- self.sele_elt.addEventListener("mousedown", self, False)
- self.sele_elt.addEventListener("mouseover", self, False)
- self.sele_elt.addEventListener("mouseout", self, False)
- blockSVGElementDrag(self.back_elt)
- blockSVGElementDrag(self.sele_elt)
- # method to display the current state of interface
- def updateElements(self):
- self.sele_elt.setAttribute("display", "none")
- self.back_elt.removeAttribute("display")
- self.sele_elt.removeAttribute("display")
- self.back_elt.setAttribute("display", "none")
- def updateValues(self, values):
- if values.state != self.state:
- self.state = values.state
- self.up = not self.state
- updateAttr(self.id, 'state', self.state)
- def handleEvent(self, evt):
- # Quand le bouton de la souris est presse
- if evt.type == "mousedown":
- updateAttr(self.id, 'state', self.state)
- if isCurrentObject(self) and self.dragging:
- # Quand le bouton est survole
- if evt.type == "mouseover" and self.toggle:
- # Quand le curseur quitte la zone du bouton
- elif evt.type == "mouseout" and self.toggle:
- self.up = not self.state
- # Quand le bouton de la souris est relache
- elif evt.type == "mouseup":
- if self.toggle and self.up == self.state:
- self.state = not self.state
- updateAttr(self.id, 'state', self.state)
- updateAttr(self.id, 'state', self.state)
- def __init__(self, parent, id, args):
- self.back_elt = getSVGElementById(args.back_id)
- if args.text != undefined:
- def updateValues(self, values):
- if values.text != self.value:
- self.text = values.text
- updateAttr(self.id, 'text', self.text)
- def updateElements(self):
- self.back_elt.firstChild.firstChild.textContent = self.text
- def handleEvent(self, evt):
\ No newline at end of file
--- a/py_ext/modules/wxglade_hmi/README Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,1 +0,0 @@
\ No newline at end of file
--- a/py_ext/modules/wxglade_hmi/__init__.py Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,1 +0,0 @@
-from wxglade_hmi import *
--- a/py_ext/modules/wxglade_hmi/wxglade_hmi.py Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,124 +0,0 @@
-from xml.dom import minidom
-from ConfigTreeNode import opjimg
-from py_ext import PythonCodeTemplate
-class RootClass(PythonCodeTemplate):
- {"bitmap" : opjimg("editWXGLADE"),
- "name" : _("WXGLADE GUI"),
- "tooltip" : _("Edit a WxWidgets GUI with WXGlade"),
- "method" : "_editWXGLADE"},
- def _getWXGLADEpath(self):
- # define name for IEC raw code file
- return os.path.join(self.CTNPath(), "hmi.wxg")
- def launch_wxglade(self, options, wait=False):
- from wxglade import __file__ as fileName
- path = os.path.dirname(fileName)
- glade = os.path.join(path, 'wxglade.py')
- if wx.Platform == '__WXMSW__':
- mode = {False:os.P_NOWAIT, True:os.P_WAIT}[wait]
- os.spawnv(mode, sys.executable, ["\"%s\""%sys.executable] + [glade] + options)
- def CTNGenerate_C(self, buildpath, locations):
- Return C code generated by iec2c compiler
- when _generate_softPLC have been called
- @param locations: ignored
- @return: [(C_file_name, CFLAGS),...] , LDFLAGS_TO_APPEND
- current_location = self.GetCurrentLocation()
- # define a unique name for the generated C file
- location_str = "_".join(map(lambda x:str(x), current_location))
- runtimefile_path = os.path.join(buildpath, "runtime_%s.py"%location_str)
- runtimefile = open(runtimefile_path, 'w')
- wxgfile_path=self._getWXGLADEpath()
- if os.path.exists(wxgfile_path):
- wxgfile = open(wxgfile_path, 'r')
- wxgtree = minidom.parse(wxgfile)
- for node in wxgtree.childNodes[1].childNodes:
- if node.nodeType == wxgtree.ELEMENT_NODE:
- hmi_frames[node._attrs["name"].value] = node._attrs["class"].value
- hmipyfile_path=os.path.join(self._getBuildPath(), "hmi.py")
- if wx.Platform == '__WXMSW__':
- wxgfile_path = "\"%s\""%wxgfile_path
- wxghmipyfile_path = "\"%s\""%hmipyfile_path
- wxghmipyfile_path = hmipyfile_path
- self.launch_wxglade(['-o', wxghmipyfile_path, '-g', 'python', wxgfile_path], wait=True)
- hmipyfile = open(hmipyfile_path, 'r')
- runtimefile.write(hmipyfile.read())
- runtimefile.write(self.GetPythonCode())
-def _runtime_%(location)s_begin():
- wx.MessageBox(_("Please stop PLC to close"))
-def _runtime_%(location)s_cleanup():
-""" % {"location": location_str,
- "declare": "\n".join(map(lambda x:"%s = None" % x, hmi_frames.keys())),
- "global": ",".join(hmi_frames.keys()),
- "init": "\n".join(map(lambda x: """
- %(name)s = %(class)s(None)
- %(name)s.Bind(wx.EVT_CLOSE, OnCloseFrame)
-""" % {"name": x[0], "class": x[1]},
- "cleanup": "\n ".join(map(lambda x:"%s.Destroy()" % x, hmi_frames.keys()))})
- return [], "", False, ("runtime_%s.py"%location_str, file(runtimefile_path,"rb"))
- def _editWXGLADE(self):
- wxg_filename = self._getWXGLADEpath()
- if not self.GetCTRoot().CheckProjectPathPerm():
- dialog = wx.MessageDialog(self.GetCTRoot().AppFrame,
- _("You don't have write permissions.\nOpen wxGlade anyway ?"),
- wx.YES_NO|wx.ICON_QUESTION)
- open_wxglade = dialog.ShowModal() == wx.ID_YES
- if not os.path.exists(wxg_filename):
- hmi_name = self.BaseParams.getName()
- open(wxg_filename,"w").write("""<?xml version="1.0"?>
- <application path="" name="" class="" option="0" language="python" top_window="%(name)s" encoding="UTF-8" use_gettext="0" overwrite="0" use_new_namespace="1" for_version="2.8" is_template="0">
- <object class="%(class)s" name="%(name)s" base="EditFrame">
- <style>wxDEFAULT_FRAME_STYLE</style>
- """ % {"name": hmi_name, "class": "Class_%s" % hmi_name})
- if wx.Platform == '__WXMSW__':
- wxg_filename = "\"%s\""%wxg_filename
- self.launch_wxglade([wxg_filename])
--- a/py_ext/plc_python.c Wed May 09 00:39:54 2012 +0200
+++ b/py_ext/plc_python.c Sat May 12 11:21:10 2012 +0200
@@ -43,7 +43,7 @@
-int __init_%(location)s()
@@ -55,13 +55,13 @@
-void __cleanup_%(location)s()
PythonState = PYTHON_FINISHED;
-void __retrieve_%(location)s()
+void __retrieve_py_ext() /* Check Python thread is not being
* modifying internal python_eval data */
@@ -72,7 +72,7 @@
* and python_eval will no do anything */
-void __publish_%(location)s()
if(PythonState & PYTHON_LOCKED_BY_PLC){
/* If runnig PLC did push something in the fifo*/
--- a/py_ext/py_ext.py Wed May 09 00:39:54 2012 +0200
+++ b/py_ext/py_ext.py Sat May 12 11:21:10 2012 +0200
@@ -1,185 +1,46 @@
-from ConfigTreeNode import ConfigTreeNode, opjimg
-from PLCControler import UndoBuffer
-from PythonEditor import PythonEditor
-from xml.dom import minidom
-PythonClasses = GenerateClassesFromXSD(os.path.join(os.path.dirname(__file__), "py_ext_xsd.xsd"))
-class PythonCodeTemplate:
- EditorType = PythonEditor
- self.ConfNodeMethods.insert(0,
- {"bitmap" : opjimg("editPYTHONcode"),
- "name" : _("Edit Python File"),
- "tooltip" : _("Edit Python File"),
- "method" : "_OpenView"},
- filepath = self.PythonFileName()
- self.PythonCode = PythonClasses["Python"]()
- if os.path.isfile(filepath):
- xmlfile = open(filepath, 'r')
- tree = minidom.parse(xmlfile)
- for child in tree.childNodes:
- if child.nodeType == tree.ELEMENT_NODE and child.nodeName == "Python":
- self.PythonCode.loadXMLTree(child, ["xmlns", "xmlns:xsi", "xsi:schemaLocation"])
- self.CreatePythonBuffer(True)
- self.CreatePythonBuffer(False)
- def ConfNodePath(self):
- return os.path.join(self.CTNParent.ConfNodePath(), "modules", self.CTNType)
- def PythonFileName(self):
- return os.path.join(self.CTNPath(), "py_ext.xml")
- if self.PythonBuffer.IsCurrentSaved():
- def SetPythonCode(self, text):
- self.PythonCode.settext(text)
- def GetPythonCode(self):
- return self.PythonCode.gettext()
- def CTNTestModified(self):
- return self.ChangesToSave or not self.PythonIsSaved()
- filepath = self.PythonFileName()
- text = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"
- extras = {"xmlns":"http://www.w3.org/2001/XMLSchema",
- "xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance",
- "xsi:schemaLocation" : "py_ext_xsd.xsd"}
- text += self.PythonCode.generateXMLText("Python", 0, extras)
+from POULibrary import POULibrary +from PythonFileCTNMixin import PythonFileCTNMixin - xmlfile = open(filepath,"w")
- xmlfile.write(text.encode("utf-8"))
- self.MarkPythonAsSaved()
-#-------------------------------------------------------------------------------
-# Current Buffering Management Functions
-#-------------------------------------------------------------------------------
- Return a copy of the project
- return cPickle.loads(cPickle.dumps(model))
- def CreatePythonBuffer(self, saved):
- self.PythonBuffer = UndoBuffer(cPickle.dumps(self.PythonCode), saved)
+class PythonLibrary(POULibrary): - def BufferPython(self):
- self.PythonBuffer.Buffering(cPickle.dumps(self.PythonCode))
- def StartBuffering(self):
- def EndBuffering(self):
- self.PythonBuffer.Buffering(cPickle.dumps(self.PythonCode))
- def MarkPythonAsSaved(self):
- self.PythonBuffer.CurrentSaved()
- def PythonIsSaved(self):
- return self.PythonBuffer.IsCurrentSaved() and not self.Buffering
- def LoadPrevious(self):
- self.PythonCode = cPickle.loads(self.PythonBuffer.Previous())
- self.PythonCode = cPickle.loads(self.PythonBuffer.Next())
- def GetBufferState(self):
- first = self.PythonBuffer.IsFirst() and not self.Buffering
- last = self.PythonBuffer.IsLast()
- return not first, not last
+ def GetLibraryPath(self): + return os.path.join(os.path.split(__file__)[0], "pous.xml") -def _GetClassFunction(name):
- __import__("py_ext.modules." + name)
- return getattr(modules, name).RootClass
-class RootClass(PythonCodeTemplate):
- # For root object, available Children Types are modules of the modules packages.
- CTNChildrenTypes = [(name, _GetClassFunction(name), help) for name, help in zip(modules.__all__,modules.helps)]
- def ConfNodePath(self):
- return os.path.join(self.CTNParent.ConfNodePath(), self.CTNType)
- def CTNGenerate_C(self, buildpath, locations):
- @param current_location: Tupple containing confnode IEC location : %I0.0.4.5 => (0,0,4,5)
- @param locations: List of complete variables locations \
- [{"IEC_TYPE" : the IEC type (i.e. "INT", "STRING", ...)
- "NAME" : name of the variable (generally "__IW0_1_2" style)
- "DIR" : direction "Q","I" or "M"
- "SIZE" : size "X", "B", "W", "D", "L"
- "LOC" : tuple of interger for IEC location (0,1,2,...)
- @return: [(C_file_name, CFLAGS),...] , LDFLAGS_TO_APPEND
- current_location = self.GetCurrentLocation()
- # define a unique name for the generated C file
- location_str = "_".join(map(lambda x:str(x), current_location))
- ctr.GetIECProgramsAndVariables()
+ def Generate_C(self, buildpath, varlist, IECCFLAGS): plc_python_filepath = os.path.join(os.path.split(__file__)[0], "plc_python.c")
plc_python_file = open(plc_python_filepath, 'r')
plc_python_code = plc_python_file.read()
- for v in ctr._VariablesList:
if v["vartype"] == "FB" and v["type"] in ["PYTHON_EVAL","PYTHON_POLL"]:
python_eval_fb_list.append(v)
python_eval_fb_count = max(1, len(python_eval_fb_list))
- plc_python_code = plc_python_code % {
- "python_eval_fb_count": python_eval_fb_count,
- "location": location_str}
+ plc_python_code = plc_python_code % { "python_eval_fb_count": python_eval_fb_count } - Gen_Pythonfile_path = os.path.join(buildpath, "python_%s.c"%location_str)
+ Gen_Pythonfile_path = os.path.join(buildpath, "py_ext.c") pythonfile = open(Gen_Pythonfile_path,'w')
pythonfile.write(plc_python_code)
+ return (["py_ext"], [(Gen_Pythonfile_path, IECCFLAGS)], True), "" +class PythonFile(PythonFileCTNMixin): + def CTNGenerate_C(self, buildpath, locations): + current_location = self.GetCurrentLocation() + # define a unique name for the generated C file + location_str = "_".join(map(lambda x:str(x), current_location)) runtimefile_path = os.path.join(buildpath, "runtime_%s.py"%location_str)
runtimefile = open(runtimefile_path, 'w')
runtimefile.write(self.GetPythonCode())
- matiec_flags = '"-I%s"'%os.path.abspath(self.GetCTRoot().GetIECLibPath())
- return [(Gen_Pythonfile_path, matiec_flags)], "", True, ("runtime_%s.py"%location_str, file(runtimefile_path,"rb"))
+ return [], "", False, ("runtime_%s.py"%location_str, file(runtimefile_path,"rb")) --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/svgui/README Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,1 @@
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/svgui/__init__.py Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,1 @@
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/svgui/livesvg.js Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,59 @@
+function updateAttr(id, param, value) { + Nevow.Athena.Widget.fromAthenaID(1).callRemote('HMIexec', 'setattr', id, param, value); +var svguiWidgets = new Array(); +var currentObject = null; +function setCurrentObject(obj) { +function isCurrentObject(obj) { + return currentObject == obj; +function getSVGElementById(id) { + return document.getElementById(id); +function blockSVGElementDrag(element) { + element.addEventListener("draggesture", function(event){event.stopPropagation()}, true); +LiveSVGPage.LiveSVGWidget = Nevow.Athena.Widget.subclass('LiveSVGPage.LiveSVGWidget'); +LiveSVGPage.LiveSVGWidget.methods( + function handleEvent(self, evt) { + if (currentObject != null) { + currentObject.handleEvent(evt); + function receiveData(self, data){ + dataReceived = json_parse(data); + gadget = svguiWidgets[dataReceived.id] + gadget.updateValues(json_parse(dataReceived.kwargs)); + //console.log("OBJET : " + dataReceived.back_id + " STATE : " + newState); + function init(self, arg1){ + //console.log("Object received : " + arg1); + gad = json_parse(arg1[ind]); + args = json_parse(gad.kwargs); + gadget = new svguilib[gad.__class__](self, gad.id, args); + svguiWidgets[gadget.id]=gadget; + //console.log('GADGET :' + gadget); + var elements = document.getElementsByTagName("svg"); + for (var i = 0; i < elements.length; i++) { + elements[i].addEventListener("mouseup", self, false); + //console.log("SVGUIWIDGETS : " + svguiWidgets); --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/svgui/pous.xml Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,1428 @@
+<?xml version="1.0" encoding="UTF-8"?> +<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="http://www.plcopen.org/xml/tc6.xsd" + xmlns:xhtml="http://www.w3.org/1999/xhtml" + xsi:schemaLocation="http://www.plcopen.org/xml/tc6.xsd"> + <fileHeader companyName="Beremiz" + creationDateTime="2008-12-14T16:53:26"/> + <contentHeader name="Beremiz non-standard POUs library" + modificationDateTime="2009-08-12T15:35:33"> + <pou name="GetBoolString" pouType="functionBlock"> + <variable name="VALUE"> + <pou name="TextCtrl" pouType="functionBlock"> + <variable name="back_id"> + <variable name="set_text"> + <variable name="SVGUI_TEXTCTRL"> + <derived name="python_eval"/> + <variable name="setstate_Command"> + <derived name="python_eval"/> + <block localId="1" width="193" height="160" typeName="CONCAT"> + <position x="626" y="122"/> + <variable formalParameter="IN1"> + <relPosition x="0" y="43"/> + <connection refLocalId="2"> + <position x="626" y="165"/> + <position x="535" y="165"/> + <variable formalParameter="IN2"> + <relPosition x="0" y="89"/> + <connection refLocalId="3"> + <position x="626" y="211"/> + <position x="535" y="211"/> + <variable formalParameter="IN3"> + <relPosition x="0" y="135"/> + <connection refLocalId="6"> + <position x="626" y="257"/> + <position x="532" y="257"/> + <variable formalParameter="OUT"> + <relPosition x="193" y="43"/> + <inVariable localId="2" height="30" width="460"> + <position x="75" y="150"/> + <relPosition x="460" y="15"/> + <expression>'createSVGUIControl("textControl", back_id="'</expression> + <inVariable localId="3" height="35" width="85"> + <position x="450" y="196"/> + <relPosition x="85" y="15"/> + <expression>back_id</expression> + <inVariable localId="6" height="30" width="50"> + <position x="482" y="242"/> + <relPosition x="50" y="15"/> + <expression>'")'</expression> + <block localId="7" width="125" height="115" typeName="python_eval" instanceName="SVGUI_TEXTCTRL"> + <position x="909" y="75"/> + <variable formalParameter="TRIG"> + <relPosition x="0" y="45"/> + <connection refLocalId="9"> + <position x="909" y="120"/> + <position x="886" y="120"/> + <position x="886" y="85"/> + <position x="869" y="85"/> + <variable formalParameter="CODE"> + <relPosition x="0" y="90"/> + <connection refLocalId="1" formalParameter="OUT"> + <position x="909" y="165"/> + <position x="819" y="165"/> + <variable formalParameter="ACK"> + <relPosition x="125" y="45"/> + <variable formalParameter="RESULT"> + <relPosition x="125" y="90"/> + <inVariable localId="9" height="30" width="70"> + <position x="799" y="70"/> + <relPosition x="70" y="15"/> + <expression>BOOL#1</expression> + <outVariable localId="10" height="30" width="30"> + <position x="1094" y="150"/> + <relPosition x="0" y="15"/> + <connection refLocalId="7" formalParameter="RESULT"> + <position x="1094" y="165"/> + <position x="1034" y="165"/> + <expression>ID</expression> + <connector name="CREATED" localId="11" height="30" width="110"> + <position x="1096" y="105"/> + <relPosition x="0" y="15"/> + <connection refLocalId="7" formalParameter="ACK"> + <position x="1096" y="120"/> + <position x="1034" y="120"/> + <block localId="4" width="125" height="140" typeName="python_eval" instanceName="setstate_Command"> + <position x="957" y="472"/> + <variable formalParameter="TRIG"> + <relPosition x="0" y="50"/> + <connection refLocalId="31" formalParameter="OUT"> + <position x="957" y="522"/> + <position x="909" y="522"/> + <position x="909" y="444"/> + <position x="857" y="444"/> + <variable formalParameter="CODE"> + <relPosition x="0" y="110"/> + <connection refLocalId="12" formalParameter="OUT"> + <position x="957" y="582"/> + <position x="822" y="582"/> + <variable formalParameter="ACK"> + <relPosition x="125" y="50"/> + <variable formalParameter="RESULT"> + <relPosition x="125" y="110"/> + <continuation name="CREATED" localId="5" height="30" width="110"> + <position x="589" y="429"/> + <relPosition x="110" y="15"/> + <block localId="12" width="186" height="288" typeName="CONCAT"> + <position x="636" y="536"/> + <variable formalParameter="IN1"> + <relPosition x="0" y="46"/> + <connection refLocalId="14"> + <position x="636" y="582"/> + <position x="526" y="582"/> + <variable formalParameter="IN2"> + <relPosition x="0" y="99"/> + <connection refLocalId="8"> + <position x="636" y="635"/> + <position x="526" y="635"/> + <variable formalParameter="IN3"> + <relPosition x="0" y="152"/> + <connection refLocalId="15"> + <position x="636" y="688"/> + <position x="527" y="688"/> + <variable formalParameter="IN4"> + <relPosition x="0" y="205"/> + <connection refLocalId="32"> + <position x="636" y="741"/> + <position x="528" y="741"/> + <variable formalParameter="IN5"> + <relPosition x="0" y="258"/> + <connection refLocalId="16"> + <position x="636" y="794"/> + <position x="528" y="794"/> + <variable formalParameter="OUT"> + <relPosition x="186" y="46"/> + <inVariable localId="8" height="30" width="53"> + <position x="473" y="620"/> + <relPosition x="53" y="15"/> + <expression>ID</expression> + <inVariable localId="13" height="35" width="100"> + <position x="599" y="469"/> + <relPosition x="100" y="17"/> + <expression>set_text</expression> + <inVariable localId="14" height="30" width="120"> + <position x="406" y="567"/> + <relPosition x="120" y="15"/> + <expression>'setAttr('</expression> + <inVariable localId="15" height="30" width="122"> + <position x="405" y="673"/> + <relPosition x="122" y="15"/> + <expression>',"text","'</expression> + <inVariable localId="16" height="30" width="50"> + <position x="478" y="779"/> + <relPosition x="50" y="15"/> + <expression>'")'</expression> + <block localId="31" width="75" height="105" typeName="AND"> + <position x="782" y="403"/> + <variable formalParameter="IN1"> + <relPosition x="0" y="41"/> + <connection refLocalId="5"> + <position x="782" y="444"/> + <position x="699" y="444"/> + <variable formalParameter="IN2"> + <relPosition x="0" y="83"/> + <connection refLocalId="13"> + <position x="782" y="486"/> + <position x="699" y="486"/> + <variable formalParameter="OUT"> + <relPosition x="75" y="41"/> + <inVariable localId="32" height="30" width="90"> + <position x="438" y="726"/> + <relPosition x="90" y="15"/> + <expression>text</expression> + <pou name="Button" pouType="functionBlock"> + <variable name="back_id"> + <variable name="sele_id"> + <variable name="toggle"> + <variable name="set_state"> + <variable name="state_in"> + <variable name="state_out"> + <variable name="init_Command"> + <derived name="python_eval"/> + <variable name="GetButtonState"> + <derived name="GetBoolString"/> + <variable name="setstate_Command"> + <derived name="python_eval"/> + <variable name="getstate_Command"> + <derived name="python_poll"/> + <variable name="GetButtonToggle"> + <derived name="GetBoolString"/> + <block localId="1" width="125" height="140" typeName="python_eval" instanceName="init_Command"> + <position x="838" y="32"/> + <variable formalParameter="TRIG"> + <relPosition x="0" y="50"/> + <connection refLocalId="10"> + <position x="838" y="82"/> + <position x="781" y="82"/> + <variable formalParameter="CODE"> + <relPosition x="0" y="110"/> + <connection refLocalId="2" formalParameter="OUT"> + <position x="838" y="142"/> + <position x="641" y="142"/> + <variable formalParameter="ACK"> + <relPosition x="125" y="50"/> + <variable formalParameter="RESULT"> + <relPosition x="125" y="110"/> + <block localId="2" width="150" height="442" typeName="CONCAT"> + <position x="491" y="92"/> + <variable formalParameter="IN1"> + <relPosition x="0" y="50"/> + <connection refLocalId="3"> + <position x="491" y="142"/> + <position x="433" y="142"/> + <variable formalParameter="IN2"> + <relPosition x="0" y="110"/> + <connection refLocalId="11"> + <position x="491" y="202"/> + <position x="431" y="202"/> + <variable formalParameter="IN3"> + <relPosition x="0" y="170"/> + <connection refLocalId="5"> + <position x="491" y="262"/> + <position x="431" y="262"/> + <variable formalParameter="IN4"> + <relPosition x="0" y="230"/> + <connection refLocalId="12"> + <position x="491" y="322"/> + <position x="430" y="322"/> + <variable formalParameter="IN5"> + <relPosition x="0" y="290"/> + <connection refLocalId="23"> + <position x="491" y="382"/> + <position x="463" y="382"/> + <position x="463" y="370"/> + <position x="430" y="370"/> + <variable formalParameter="IN6"> + <relPosition x="0" y="350"/> + <connection refLocalId="24" formalParameter="CODE"> + <position x="491" y="442"/> + <position x="429" y="442"/> + <variable formalParameter="IN7"> + <relPosition x="0" y="410"/> + <connection refLocalId="9"> + <position x="491" y="502"/> + <position x="430" y="502"/> + <variable formalParameter="OUT"> + <relPosition x="150" y="50"/> + <inVariable localId="3" height="30" width="400"> + <position x="33" y="127"/> + <relPosition x="400" y="15"/> + <expression>'createSVGUIControl("button",back_id="'</expression> + <inVariable localId="5" height="30" width="140"> + <position x="291" y="247"/> + <relPosition x="140" y="15"/> + <expression>'",sele_id="'</expression> + <inVariable localId="9" height="30" width="180"> + <position x="250" y="487"/> + <relPosition x="180" y="15"/> + <expression>',active=True)'</expression> + <inVariable localId="10" height="30" width="70"> + <position x="711" y="67"/> + <relPosition x="70" y="15"/> + <expression>BOOL#1</expression> + <inVariable localId="11" height="35" width="85"> + <position x="346" y="187"/> + <relPosition x="85" y="15"/> + <expression>back_id</expression> + <inVariable localId="12" height="35" width="85"> + <position x="345" y="307"/> + <relPosition x="85" y="15"/> + <expression>sele_id</expression> + <inVariable localId="13" height="35" width="100"> + <position x="452" y="639"/> + <relPosition x="100" y="15"/> + <expression>set_state</expression> + <block localId="28" width="140" height="40" typeName="GetBoolString" instanceName="GetButtonState"> + <position x="239" y="897"/> + <variable formalParameter="VALUE"> + <relPosition x="0" y="30"/> + <connection refLocalId="32"> + <position x="239" y="927"/> + <position x="181" y="927"/> + <variable formalParameter="CODE"> + <relPosition x="140" y="30"/> + <outVariable localId="29" height="30" width="53"> + <position x="1015" y="127"/> + <relPosition x="0" y="15"/> + <connection refLocalId="1" formalParameter="RESULT"> + <position x="1015" y="142"/> + <position x="963" y="142"/> + <expression>ID</expression> + <block localId="4" width="125" height="140" typeName="python_eval" instanceName="setstate_Command"> + <position x="810" y="640"/> + <variable formalParameter="TRIG"> + <relPosition x="0" y="50"/> + <connection refLocalId="31" formalParameter="OUT"> + <position x="810" y="690"/> + <position x="762" y="690"/> + <position x="762" y="612"/> + <position x="710" y="612"/> + <variable formalParameter="CODE"> + <relPosition x="0" y="110"/> + <connection refLocalId="7" formalParameter="OUT"> + <position x="810" y="750"/> + <position x="643" y="750"/> + <variable formalParameter="ACK"> + <relPosition x="125" y="50"/> + <variable formalParameter="RESULT"> + <relPosition x="125" y="110"/> + <connector name="CREATED" localId="30" height="30" width="110"> + <position x="1014" y="67"/> + <relPosition x="0" y="15"/> + <connection refLocalId="1" formalParameter="ACK"> + <position x="1014" y="82"/> + <position x="963" y="82"/> + <continuation name="CREATED" localId="6" height="30" width="110"> + <position x="442" y="597"/> + <relPosition x="110" y="15"/> + <block localId="31" width="75" height="105" typeName="AND"> + <position x="635" y="571"/> + <variable formalParameter="IN1"> + <relPosition x="0" y="41"/> + <connection refLocalId="6"> + <position x="635" y="612"/> + <position x="552" y="612"/> + <variable formalParameter="IN2"> + <relPosition x="0" y="83"/> + <connection refLocalId="13"> + <position x="635" y="654"/> + <position x="552" y="654"/> + <variable formalParameter="OUT"> + <relPosition x="75" y="41"/> + <inVariable localId="32" height="30" width="90"> + <position x="91" y="912"/> + <relPosition x="90" y="15"/> + <expression>state_in</expression> + <outVariable localId="33" height="30" width="100"> + <position x="1334" y="1184"/> + <relPosition x="0" y="15"/> + <connection refLocalId="26" formalParameter="OUT"> + <position x="1334" y="1199"/> + <position x="1286" y="1199"/> + <expression>state_out</expression> + <block localId="7" width="150" height="319" typeName="CONCAT"> + <position x="493" y="701"/> + <variable formalParameter="IN1"> + <relPosition x="0" y="49"/> + <connection refLocalId="14"> + <position x="493" y="750"/> + <position x="379" y="750"/> + <variable formalParameter="IN2"> + <relPosition x="0" y="108"/> + <connection refLocalId="8"> + <position x="493" y="809"/> + <position x="435" y="809"/> + <position x="435" y="803"/> + <position x="379" y="803"/> + <variable formalParameter="IN3"> + <relPosition x="0" y="167"/> + <connection refLocalId="15"> + <position x="493" y="868"/> + <position x="435" y="868"/> + <position x="435" y="855"/> + <position x="379" y="855"/> + <variable formalParameter="IN4"> + <relPosition x="0" y="226"/> + <connection refLocalId="28" formalParameter="CODE"> + <position x="493" y="927"/> + <position x="379" y="927"/> + <variable formalParameter="IN5"> + <relPosition x="0" y="285"/> + <connection refLocalId="16"> + <position x="493" y="986"/> + <position x="377" y="986"/> + <variable formalParameter="OUT"> + <relPosition x="150" y="49"/> + <inVariable localId="8" height="30" width="53"> + <position x="326" y="788"/> + <relPosition x="53" y="15"/> + <expression>ID</expression> + <inVariable localId="14" height="30" width="120"> + <position x="259" y="735"/> + <relPosition x="120" y="15"/> + <expression>'setAttr('</expression> + <inVariable localId="15" height="30" width="122"> + <position x="257" y="840"/> + <relPosition x="122" y="15"/> + <expression>',"state",'</expression> + <inVariable localId="16" height="30" width="41"> + <position x="336" y="971"/> + <relPosition x="41" y="15"/> + <expression>')'</expression> + <block localId="17" width="125" height="140" typeName="python_poll" instanceName="getstate_Command"> + <position x="801" y="1089"/> + <variable formalParameter="TRIG"> + <relPosition x="0" y="50"/> + <connection refLocalId="18"> + <position x="801" y="1139"/> + <position x="763" y="1139"/> + <position x="763" y="1099"/> + <position x="720" y="1099"/> + <variable formalParameter="CODE"> + <relPosition x="0" y="110"/> + <connection refLocalId="22" formalParameter="OUT"> + <position x="801" y="1199"/> + <position x="643" y="1199"/> + <variable formalParameter="ACK"> + <relPosition x="125" y="50"/> + <variable formalParameter="RESULT"> + <relPosition x="125" y="110"/> + <block localId="25" width="145" height="45" typeName="STRING_TO_INT"> + <position x="966" y="1169"/> + <variable formalParameter="IN"> + <relPosition x="0" y="30"/> + <connection refLocalId="17" formalParameter="RESULT"> + <position x="966" y="1199"/> + <position x="926" y="1199"/> + <variable formalParameter="OUT"> + <relPosition x="145" y="30"/> + <block localId="26" width="125" height="45" typeName="INT_TO_BOOL"> + <position x="1161" y="1169"/> + <variable formalParameter="IN"> + <relPosition x="0" y="30"/> + <connection refLocalId="25" formalParameter="OUT"> + <position x="1161" y="1199"/> + <position x="1111" y="1199"/> + <variable formalParameter="OUT"> + <relPosition x="125" y="30"/> + <continuation name="CREATED" localId="18" height="30" width="110"> + <position x="610" y="1084"/> + <relPosition x="110" y="15"/> + <inVariable localId="19" height="30" width="53"> + <position x="383" y="1238"/> + <relPosition x="53" y="15"/> + <expression>ID</expression> + <inVariable localId="20" height="30" width="150"> + <position x="286" y="1184"/> + <relPosition x="150" y="15"/> + <expression>'int(getAttr('</expression> + <inVariable localId="21" height="30" width="190"> + <position x="246" y="1292"/> + <relPosition x="190" y="15"/> + <expression>',"state",False))'</expression> + <block localId="22" width="150" height="183" typeName="CONCAT"> + <position x="493" y="1152"/> + <variable formalParameter="IN1"> + <relPosition x="0" y="47"/> + <connection refLocalId="20"> + <position x="493" y="1199"/> + <position x="436" y="1199"/> + <variable formalParameter="IN2"> + <relPosition x="0" y="101"/> + <connection refLocalId="19"> + <position x="493" y="1253"/> + <position x="436" y="1253"/> + <variable formalParameter="IN3"> + <relPosition x="0" y="155"/> + <connection refLocalId="21"> + <position x="493" y="1307"/> + <position x="483" y="1307"/> + <position x="483" y="1307"/> + <position x="436" y="1307"/> + <variable formalParameter="OUT"> + <relPosition x="150" y="47"/> + <inVariable localId="23" height="30" width="130"> + <position x="300" y="355"/> + <relPosition x="130" y="15"/> + <expression>'",toggle='</expression> + <block localId="24" width="140" height="40" typeName="GetBoolString" instanceName="GetButtonToggle"> + <position x="289" y="412"/> + <variable formalParameter="VALUE"> + <relPosition x="0" y="30"/> + <connection refLocalId="27"> + <position x="289" y="442"/> + <position x="220" y="442"/> + <variable formalParameter="CODE"> + <relPosition x="140" y="30"/> + <inVariable localId="27" height="30" width="90"> + <position x="130" y="427"/> + <relPosition x="90" y="15"/> + <expression>toggle</expression> + <pou name="Led" pouType="functionBlock"> + <variable name="back_id"> + <variable name="sele_id"> + <variable name="state_in"> + <variable name="init_Command"> + <derived name="python_eval"/> + <variable name="setstate_Command"> + <derived name="python_poll"/> + <variable name="GetLedState"> + <derived name="GetBoolString"/> + <block localId="1" width="125" height="140" typeName="python_eval" instanceName="init_Command"> + <position x="810" y="30"/> + <variable formalParameter="TRIG"> + <relPosition x="0" y="50"/> + <connection refLocalId="10"> + <position x="810" y="80"/> + <position x="753" y="80"/> + <variable formalParameter="CODE"> + <relPosition x="0" y="110"/> + <connection refLocalId="2" formalParameter="OUT"> + <position x="810" y="140"/> + <position x="640" y="140"/> + <variable formalParameter="ACK"> + <relPosition x="125" y="50"/> + <variable formalParameter="RESULT"> + <relPosition x="125" y="110"/> + <block localId="2" width="150" height="322" typeName="CONCAT"> + <position x="490" y="90"/> + <variable formalParameter="IN1"> + <relPosition x="0" y="50"/> + <connection refLocalId="3"> + <position x="490" y="140"/> + <position x="415" y="140"/> + <variable formalParameter="IN2"> + <relPosition x="0" y="110"/> + <connection refLocalId="11"> + <position x="490" y="200"/> + <position x="415" y="200"/> + <variable formalParameter="IN3"> + <relPosition x="0" y="170"/> + <connection refLocalId="5"> + <position x="490" y="260"/> + <position x="415" y="260"/> + <variable formalParameter="IN4"> + <relPosition x="0" y="230"/> + <connection refLocalId="12"> + <position x="490" y="320"/> + <position x="414" y="320"/> + <variable formalParameter="IN5"> + <relPosition x="0" y="290"/> + <connection refLocalId="9"> + <position x="490" y="380"/> + <position x="414" y="380"/> + <variable formalParameter="OUT"> + <relPosition x="150" y="50"/> + <inVariable localId="3" height="30" width="400"> + <position x="15" y="125"/> + <relPosition x="400" y="15"/> + <expression>'createSVGUIControl("button",back_id="'</expression> + <block localId="4" width="125" height="140" typeName="python_poll" instanceName="setstate_Command"> + <position x="782" y="536"/> + <variable formalParameter="TRIG"> + <relPosition x="0" y="50"/> + <connection refLocalId="6"> + <position x="782" y="586"/> + <position x="653" y="586"/> + <position x="653" y="552"/> + <position x="602" y="552"/> + <variable formalParameter="CODE"> + <relPosition x="0" y="110"/> + <connection refLocalId="7" formalParameter="OUT"> + <position x="782" y="646"/> + <position x="615" y="646"/> + <variable formalParameter="ACK"> + <relPosition x="125" y="50"/> + <variable formalParameter="RESULT"> + <relPosition x="125" y="110"/> + <inVariable localId="5" height="30" width="140"> + <position x="275" y="245"/> + <relPosition x="140" y="15"/> + <expression>'",sele_id="'</expression> + <continuation name="CREATED" localId="6" height="30" width="110"> + <position x="492" y="537"/> + <relPosition x="110" y="15"/> + <block localId="7" width="150" height="319" typeName="CONCAT"> + <position x="465" y="597"/> + <variable formalParameter="IN1"> + <relPosition x="0" y="49"/> + <connection refLocalId="14"> + <position x="465" y="646"/> + <position x="351" y="646"/> + <variable formalParameter="IN2"> + <relPosition x="0" y="108"/> + <connection refLocalId="8"> + <position x="465" y="705"/> + <position x="407" y="705"/> + <position x="407" y="699"/> + <position x="351" y="699"/> + <variable formalParameter="IN3"> + <relPosition x="0" y="167"/> + <connection refLocalId="15"> + <position x="465" y="764"/> + <position x="407" y="764"/> + <position x="407" y="751"/> + <position x="351" y="751"/> + <variable formalParameter="IN4"> + <relPosition x="0" y="226"/> + <connection refLocalId="28" formalParameter="CODE"> + <position x="465" y="823"/> + <position x="351" y="823"/> + <variable formalParameter="IN5"> + <relPosition x="0" y="285"/> + <connection refLocalId="16"> + <position x="465" y="882"/> + <position x="407" y="882"/> + <position x="407" y="883"/> + <position x="351" y="883"/> + <variable formalParameter="OUT"> + <relPosition x="150" y="49"/> + <inVariable localId="8" height="30" width="53"> + <position x="298" y="684"/> + <relPosition x="53" y="15"/> + <expression>ID</expression> + <inVariable localId="9" height="30" width="300"> + <position x="124" y="365"/> + <relPosition x="300" y="15"/> + <expression>'",toggle=True,active=False)'</expression> + <inVariable localId="10" height="30" width="70"> + <position x="683" y="65"/> + <relPosition x="70" y="15"/> + <expression>BOOL#1</expression> + <inVariable localId="11" height="35" width="85"> + <position x="330" y="185"/> + <relPosition x="85" y="15"/> + <expression>back_id</expression> + <inVariable localId="12" height="35" width="85"> + <position x="329" y="305"/> + <relPosition x="85" y="15"/> + <expression>sele_id</expression> + <inVariable localId="14" height="30" width="120"> + <position x="231" y="631"/> + <relPosition x="120" y="15"/> + <expression>'setAttr('</expression> + <inVariable localId="15" height="30" width="122"> + <position x="229" y="736"/> + <relPosition x="122" y="15"/> + <expression>',"state",'</expression> + <inVariable localId="16" height="30" width="41"> + <position x="310" y="868"/> + <relPosition x="41" y="15"/> + <expression>')'</expression> + <block localId="28" width="140" height="40" typeName="GetBoolString" instanceName="GetLedState"> + <position x="211" y="793"/> + <variable formalParameter="VALUE"> + <relPosition x="0" y="30"/> + <connection refLocalId="32"> + <position x="211" y="823"/> + <position x="153" y="823"/> + <variable formalParameter="CODE"> + <relPosition x="140" y="30"/> + <outVariable localId="29" height="30" width="53"> + <position x="987" y="125"/> + <relPosition x="0" y="15"/> + <connection refLocalId="1" formalParameter="RESULT"> + <position x="987" y="140"/> + <position x="935" y="140"/> + <expression>ID</expression> + <connector name="CREATED" localId="30" height="30" width="110"> + <position x="986" y="65"/> + <relPosition x="0" y="15"/> + <connection refLocalId="1" formalParameter="ACK"> + <position x="986" y="80"/> + <position x="935" y="80"/> + <inVariable localId="32" height="30" width="90"> + <position x="63" y="808"/> + <relPosition x="90" y="15"/> + <expression>state_in</expression> --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/svgui/pyjs/__init__.py Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,2 @@
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/svgui/pyjs/build.py Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,724 @@
+from os.path import join, dirname, basename, abspath, split, isfile, isdir +from optparse import OptionParser +from cStringIO import StringIO + from hashlib import md5 + usage: %prog [options] <application module name or path> +This is the command line builder for the pyjamas project, which can +be used to build Ajax applications from Python. +For more information, see the website at http://pyjs.org/ +# GWT1.2 Impl | GWT1.2 Output | Pyjamas 0.2 Platform | Pyjamas 0.2 Output +# -------------+-----------------------+----------------------+---------------------- +# Opera | opera | Opera | opera +# Safari | safari | Safari | safari +# -- | gecko1_8 | Mozilla | mozilla +# -- | gecko | OldMoz | oldmoz +# Standard | all | (default code) | all +# Mozilla | gecko1_8, gecko | -- | -- +# Old | safari, gecko, opera | -- | -- +version = "%prog pyjamas version 2006-08-19" +# these names in lowercase need match the strings +# returned by "provider$user.agent" in order to be selected corretly +app_platforms = ['IE6', 'Opera', 'OldMoz', 'Safari', 'Mozilla'] +# usually defaults to e.g. /usr/share/pyjamas +_data_dir = os.path.join(pyjs.prefix, "share/pyjamas") +# .cache.html files produces look like this +CACHE_HTML_PAT=re.compile('^[a-z]*.[0-9a-f]{32}\.cache\.html$') +# ok these are the three "default" library directories, containing +# the builtins (str, List, Dict, ord, round, len, range etc.) +# the main pyjamas libraries (pyjamas.ui, pyjamas.Window etc.) +# and the contributed addons +for p in ["library/builtins", + p = os.path.join(_data_dir, p) +def read_boilerplate(data_dir, filename): + return open(join(data_dir, "builder/boilerplate", filename)).read() +def copy_boilerplate(data_dir, filename, output_dir): + filename = join(data_dir, "builder/boilerplate", filename) + shutil.copy(filename, output_dir) +# taken and modified from python2.4 +def copytree_exists(src, dst, symlinks=False): + if not os.path.exists(src): + names = os.listdir(src) + if name.startswith('CVS'): + if name.startswith('.git'): + if name.startswith('.svn'): + srcname = os.path.join(src, name) + dstname = os.path.join(dst, name) + if symlinks and os.path.islink(srcname): + linkto = os.readlink(srcname) + os.symlink(linkto, dstname) + copytree_exists(srcname, dstname, symlinks) + shutil.copy2(srcname, dstname) + except (IOError, os.error), why: + errors.append((srcname, dstname, why)) +def check_html_file(source_file, dest_path): + """ Checks if a base HTML-file is available in the PyJamas + If the HTML-file isn't available, it will be created. + If a CSS-file with the same name is available + in the output directory, a reference to this CSS-file + If no CSS-file is found, this function will look for a special + CSS-file in the output directory, with the name + "pyjamas_default.css", and if found it will be referenced + in the generated HTML-file. + [thank you to stef mientki for contributing this function] + <!-- auto-generated html - you should consider editing and + adapting this to suit your requirements + <meta name="pygwt:module" content="%(modulename)s"> + <title>%(title)s</title> + <script language="javascript" src="pygwt.js"></script> + filename = os.path.split ( source_file )[1] + mod_name = os.path.splitext ( filename )[0] + file_name = os.path.join ( dest_path, mod_name + '.html' ) + # if html file in output directory exists, leave it alone. + if os.path.exists ( file_name ): + os.path.join ( dest_path, mod_name + '.css' ) ) : + css = "<link rel='stylesheet' href='" + mod_name + ".css'>" + os.path.join ( dest_path, 'pyjamas_default.css' ) ) : + css = "<link rel='stylesheet' href='pyjamas_default.css'>" + title = 'PyJamas Auto-Generated HTML file ' + mod_name + base_html = base_html % {'modulename': mod_name, 'title': title, 'css': css} + fh = open (file_name, 'w') +def build(app_name, output, js_includes=(), debug=False, dynamic=0, + data_dir=None, cache_buster=False, optimize=False): + # make sure the output directory is always created in the current working + # directory or at the place given if it is an absolute path. + output = os.path.abspath(output) + msg = "Building '%(app_name)s' to output directory '%(output)s'" % locals() + msg += " with debugging statements" + # check the output directory + if os.path.exists(output) and not os.path.isdir(output): + print >>sys.stderr, "Output destination %s exists and is not a directory" % output + if not os.path.isdir(output): + print "Creating output directory" + except StandardError, e: + print >>sys.stderr, "Exception creating output directory %s: %s" % (output, e) + pub_dir = join(p, 'public') + print "Copying: public directory of library %r" % p + copytree_exists(pub_dir, output) + ## AppName.html - can be in current or public directory + html_input_filename = app_name + ".html" + html_output_filename = join(output, basename(html_input_filename)) + if os.path.isfile(html_input_filename): + if not os.path.isfile(html_output_filename) or \ + os.path.getmtime(html_input_filename) > \ + os.path.getmtime(html_output_filename): + shutil.copy(html_input_filename, html_output_filename) + print >>sys.stderr, "Warning: Missing module HTML file %s" % html_input_filename + print "Copying: %(html_input_filename)s" % locals() + if check_html_file(html_input_filename, output): + print >>sys.stderr, "Warning: Module HTML file %s has been auto-generated" % html_input_filename + print "Copying: pygwt.js" + pygwt_js_template = read_boilerplate(data_dir, "pygwt.js") + pygwt_js_output = open(join(output, "pygwt.js"), "w") + print >>pygwt_js_output, pygwt_js_template + pygwt_js_output.close() + print "Copying: Images and History" + copy_boilerplate(data_dir, "corner_dialog_topleft_black.png", output) + copy_boilerplate(data_dir, "corner_dialog_topright_black.png", output) + copy_boilerplate(data_dir, "corner_dialog_bottomright_black.png", output) + copy_boilerplate(data_dir, "corner_dialog_bottomleft_black.png", output) + copy_boilerplate(data_dir, "corner_dialog_edge_black.png", output) + copy_boilerplate(data_dir, "corner_dialog_topleft.png", output) + copy_boilerplate(data_dir, "corner_dialog_topright.png", output) + copy_boilerplate(data_dir, "corner_dialog_bottomright.png", output) + copy_boilerplate(data_dir, "corner_dialog_bottomleft.png", output) + copy_boilerplate(data_dir, "corner_dialog_edge.png", output) + copy_boilerplate(data_dir, "tree_closed.gif", output) + copy_boilerplate(data_dir, "tree_open.gif", output) + copy_boilerplate(data_dir, "tree_white.gif", output) + copy_boilerplate(data_dir, "history.html", output) + app_files = generateAppFiles(data_dir, js_includes, app_name, debug, + output, dynamic, cache_buster, optimize) + ## AppName.nocache.html + print "Creating: %(app_name)s.nocache.html" % locals() + home_nocache_html_template = read_boilerplate(data_dir, "home.nocache.html") + home_nocache_html_output = open(join(output, app_name + ".nocache.html"), + # the selector templ is added to the selectScript function + select_tmpl = """O(["true","%s"],"%s");""" + script_selectors = StringIO() + for platform, file_prefix in app_files: + print >> script_selectors, select_tmpl % (platform, file_prefix) + print >>home_nocache_html_output, home_nocache_html_template % dict( + script_selectors = script_selectors.getvalue(), + home_nocache_html_output.close() + print "Done. You can run your app by opening '%(html_output_filename)s' in a browser" % locals() +def generateAppFiles(data_dir, js_includes, app_name, debug, output, dynamic, + cache_buster, optimize): + all_cache_html_template = read_boilerplate(data_dir, "all.cache.html") + mod_cache_html_template = read_boilerplate(data_dir, "mod.cache.html") + # clean out the old ones first + for name in os.listdir(output): + if CACHE_HTML_PAT.match(name): + print "Deleting existing app file %s" % p + tmpl = read_boilerplate(data_dir, "all.cache.html") + parser = pyjs.PlatformParser("platform") + scripts = ['<script type="text/javascript" src="%s"></script>'%script \ + for script in js_includes] + app_body = '\n'.join(scripts) + # First, generate all the code. + # Second, (dynamic only), post-analyse the places where modules + # Third, write everything out. + for platform in app_platforms: + mod_code[platform] = {} + mod_libs[platform] = {} + app_libs[platform] = '' + early_app_libs[platform] = '' + app_code[platform] = {} + app_modnames[platform] = {} + # Application.Platform.cache.html + parser.setPlatform(platform) + app_translator = pyjs.AppTranslator( + parser=parser, dynamic=dynamic, optimize=optimize) + early_app_libs[platform], appcode = \ + app_translator.translate(None, is_app=False, + library_modules=['dynamicajax.js', + pover[platform].update(app_translator.overrides.items()) + for mname, name in app_translator.overrides.items(): + pd = overrides.setdefault(mname, {}) + #mod_code[platform][app_name] = appcode + # platform.Module.cache.js + modules_done = ['pyjslib', 'sys', '_pyjs.js'] + #modules_to_do = [app_name] + app_translator.library_modules + modules_to_do = [app_name] + app_translator.library_modules + deps = map(pyjs.strip_py, modules_to_do) + sublist = add_subdeps(dependencies, d) + modules_to_do += sublist + #dependencies[app_name] = deps + modules[platform] = modules_done + modules_to_do + #print "modules to do", modules_to_do + mn = modules_to_do.pop() + mod_name = pyjs.strip_py(mn) + if mod_name in modules_done: + modules_done.append(mod_name) + mod_cache_name = "%s.%s.cache.js" % (platform.lower(), mod_name) + parser.setPlatform(platform) + mod_translator = pyjs.AppTranslator(parser=parser, optimize=optimize) + mod_libs[platform][mod_name], mod_code[platform][mod_name] = \ + mod_translator.translate(mod_name, + pover[platform].update(mod_translator.overrides.items()) + for mname, name in mod_translator.overrides.items(): + pd = overrides.setdefault(mname, {}) + mods = mod_translator.library_modules + modules[platform] += mods + deps = map(pyjs.strip_py, mods) + while mod_name in deps: + #print "modname preadd:", mod_name, deps + sublist = add_subdeps(dependencies, d) + modules_to_do += sublist + modules_to_do += add_subdeps(dependencies, mod_name) + #print "modname:", mod_name, deps + #print "modname:", mod_name, deps + dependencies[mod_name] = deps + # work out the dependency ordering of the modules + mod_levels[platform] = make_deps(None, dependencies, modules_done) + # now write everything out + for platform in app_platforms: + early_app_libs_ = early_app_libs[platform] + app_libs_ = app_libs[platform] + app_code_ = app_code[platform] + #modules_ = filter_mods(app_name, modules[platform]) + mods = flattenlist(mod_levels[platform]) + modules_ = filter_mods(None, mods) + for mod_name in modules_: + mod_code_ = mod_code[platform][mod_name] + mod_name = pyjs.strip_py(mod_name) + override_name = "%s.%s" % (platform.lower(), mod_name) + if pover[platform].has_key(override_name): + mod_cache_name = "%s.cache.js" % (override_name) + mod_cache_name = "%s.cache.js" % (mod_name) + print "Creating: " + mod_cache_name + modlevels = make_deps(None, dependencies, dependencies[mod_name]) + mnames = map(lambda x: "'%s'" % x, md) + mnames = "new pyjslib.List([\n\t\t\t%s])" % ',\n\t\t\t'.join(mnames) + modnames.append(mnames) + modnames = "new pyjslib.List([\n\t\t%s\n\t])" % ',\n\t\t'.join(modnames) + # convert the overrides + overnames = map(lambda x: "'%s': '%s'" % x, pover[platform].items()) + overnames = "new pyjslib.Dict({\n\t\t%s\n\t})" % ',\n\t\t'.join(overnames) + mod_cache_html_output = open(join(output, mod_cache_name), "w") + mod_cache_html_output = StringIO() + print >>mod_cache_html_output, mod_cache_html_template % dict( + mod_libs = mod_libs[platform][mod_name], + mod_cache_html_output.close() + mod_cache_html_output.seek(0) + app_libs_ += mod_cache_html_output.read() + # write out the dependency ordering of the modules + for md in mod_levels[platform]: + mnames = map(lambda x: "'%s'" % x, md) + mnames = "new pyjslib.List([\n\t\t\t%s])" % ',\n\t\t\t'.join(mnames) + app_modnames.append(mnames) + app_modnames = "new pyjslib.List([\n\t\t%s\n\t])" % ',\n\t\t'.join(app_modnames) + # convert the overrides + overnames = map(lambda x: "'%s': '%s'" % x, pover[platform].items()) + overnames = "new pyjslib.Dict({\n\t\t%s\n\t})" % ',\n\t\t'.join(overnames) + #print "platform names", platform, overnames + # now write app.allcache including dependency-ordered list of + file_contents = all_cache_html_template % dict( + early_app_libs = early_app_libs_, + platform = platform.lower(), + app_modnames = app_modnames, + app_headers = app_headers + digest = md5.new(file_contents).hexdigest() + file_name = "%s.%s.%s" % (platform.lower(), app_name, digest) + file_name = "%s.%s" % (platform.lower(), app_name) + file_name += ".cache.html" + out_path = join(output, file_name) + out_file = open(out_path, 'w') + out_file.write(file_contents) + app_files.append((platform.lower(), file_name)) + print "Created app file %s:%s: %s" % ( + app_name, platform, out_path) +# creates sub-dependencies e.g. pyjamas.ui.Widget +# creates pyjamas.ui.Widget, pyjamas.ui and pyjamas. + for i in range(0, len(m)): + d.append('.'.join(m[:i+1])) +def add_subdeps(deps, mod_name): + #print "subdeps", mod_name, sd + for i in range(0, len(sd)-1): + l = deps.get(child, []) +# makes unique and preserves list order +def filter_mods(app_name, md): + md = filter(lambda x: not x.endswith('.js'), md) + md = map(pyjs.strip_py, md) +def filter_deps(app_name, deps): + for (k, l) in deps.items(): + mods = filter_mods(k, l) +def has_nodeps(mod, deps): + if not deps.has_key(mod) or not deps[mod]: +def nodeps_list(mod_list, deps): + if has_nodeps(mod, deps): +# this function takes a dictionary of dependent modules and +# creates a list of lists. the first list will be modules +# that have no dependencies; the second list will be those +# modules that have the first list as dependencies; the +# third will be those modules that have the first and second... +def make_deps(app_name, deps, mod_list): + print "Calculating Dependencies ..." + mod_list = filter_mods(app_name, mod_list) + deps = filter_deps(app_name, deps) + for m, dl in deps.items(): + if m in deps.get(d, []): + raise Exception('Circular Imports found: \n%s %s -> %s %s' + #raise Exception('Could not calculate dependencies: \n%s' % deps) + #print "modlist", mod_list + nodeps = nodeps_list(mod_list, deps) + #print "nodeps", nodeps + mod_list = filter(lambda x: x not in nodeps, mod_list) + depslist = filter(lambda x: x not in nodeps, depslist) + #print "newdeps", newdeps + ordered_deps.append(nodeps) + ordered_deps.append(mod_list) # last dependencies - usually the app(s) + parser = OptionParser(usage = usage, version = version) + parser.add_option("-o", "--output", dest="output", + help="directory to which the webapp should be written") + parser.add_option("-j", "--include-js", dest="js_includes", action="append", + help="javascripts to load into the same frame as the rest of the script") + parser.add_option("-I", "--library_dir", dest="library_dirs", + action="append", help="additional paths appended to PYJSPATH") + parser.add_option("-D", "--data_dir", dest="data_dir", + help="path for data directory") + parser.add_option("-m", "--dynamic-modules", action="store_true", + dest="dynamic", default=False, + help="Split output into separate dynamically-loaded modules (experimental)") + parser.add_option("-P", "--platforms", dest="platforms", + help="platforms to build for, comma-separated") + parser.add_option("-d", "--debug", action="store_true", dest="debug") + parser.add_option("-O", "--optimize", action="store_true", + dest="optimize", default=False, + help="Optimize generated code (removes all print statements)", + parser.add_option("-c", "--cache_buster", action="store_true", + help="Enable browser cache-busting (MD5 hash added to output filenames)") + parser.set_defaults(output = "output", js_includes=[], library_dirs=[], + platforms=(','.join(app_platforms)), + data_dir=os.path.join(sys.prefix, "share/pyjamas"), + (options, args) = parser.parse_args() + parser.error("incorrect number of arguments") + data_dir = abspath(options.data_dir) + if app_path.endswith('.py'): + app_path = abspath(app_path) + if not isfile(app_path): + parser.error("Application file not found %r" % app_path) + app_path, app_name = split(app_path) + app_name = app_name[:-3] + pyjs.path.append(app_path) + elif os.path.sep in app_path: + parser.error("Not a valid module declaration %r" % app_path) + for d in options.library_dirs: + pyjs.path.append(abspath(d)) + app_platforms = options.platforms.split(',') + # this is mostly for getting boilerplate stuff + data_dir = os.path.abspath(options.data_dir) + build(app_name, options.output, options.js_includes, + options.debug, options.dynamic and 1 or 0, data_dir, + options.cache_buster, options.optimize) +if __name__ == "__main__": --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/svgui/pyjs/jsonrpc/README.txt Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,12 @@
+These classes are intended for use server-side. +e.g. in a django view.py : + from pyjs.jsonrpc.django import JSONService, jsonremote + jsonservice = JSONRPCService() + @jsonremote(jsonservice) + def test(request, echo_param): + return "echoing the param back: %s" % echo_param --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/svgui/pyjs/jsonrpc/django/jsonrpc.py Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,226 @@
+# original code: http://trac.pyworks.org/pyjamas/wiki/DjangoWithPyJamas +# also from: http://www.pimentech.fr/technologies/outils +from django.utils import simplejson +from django.http import HttpResponse +from pyjs.jsonrpc import JSONRPCServiceBase +# JSONRPCService and jsonremote are used in combination to drastically +# simplify the provision of JSONRPC services. use as follows: +# jsonservice = JSONRPCService() +# @jsonremote(jsonservice) +# def test(request, echo_param): +# return "echoing the param back: %s" % echo_param +# dump jsonservice into urlpatterns: +# (r'^service1/$', 'djangoapp.views.jsonservice'), +class JSONRPCService(JSONRPCServiceBase): + def __call__(self, request, extra=None): + return self.process(request.raw_post_data) +def jsonremote(service): + """Make JSONRPCService a decorator so that you can write : + from jsonrpc import JSONRPCService + chatservice = JSONRPCService() + @jsonremote(chatservice) + def login(request, user_name): + if isinstance(service, JSONRPCService): + service.add_method(func.__name__, func) + emsg = 'Service "%s" not found' % str(service.__name__) + raise NotImplementedError, emsg +# FormProcessor provides a mechanism for turning Django Forms into JSONRPC +# Services. If you have an existing Django app which makes prevalent +# use of Django Forms it will save you rewriting the app. +# use as follows. in djangoapp/views.py : +# class SimpleForm(forms.Form): +# testfield = forms.CharField(max_length=100) +# class SimpleForm2(forms.Form): +# testfield = forms.CharField(max_length=20) +# processor = FormProcessor({'processsimpleform': SimpleForm, +# 'processsimpleform2': SimpleForm2}) +# this will result in a JSONRPC service being created with two +# RPC functions. dump "processor" into urlpatterns to make it +# (r'^formsservice/$', 'djangoapp.views.processor'), +from django import forms + for error in form.errors.keys(): + for errorval in form.errors[error]: + d[error].append(unicode(errorval)) +# contains the list of arguments in each field + 'CharField': ['max_length', 'min_length'], + 'IntegerField': ['max_value', 'min_value'], + 'FloatField': ['max_value', 'min_value'], + 'DecimalField': ['max_value', 'min_value', 'max_digits', 'decimal_places'], + 'DateField': ['input_formats'], + 'DateTimeField': ['input_formats'], + 'TimeField': ['input_formats'], + 'RegexField': ['max_length', 'min_length'], # sadly we can't get the expr + 'EmailField': ['max_length', 'min_length'], + 'URLField': ['max_length', 'min_length', 'verify_exists', 'user_agent'], + 'ChoiceField': ['choices'], + 'FilePathField': ['path', 'match', 'recursive', 'choices'], + 'IPAddressField': ['max_length', 'min_length'], +def describe_field_errors(field): + field_type = field.__class__.__name__ + for n, m in field.error_messages.items(): + res['error_messages'] = msgs + if field_type in ['ComboField', 'MultiValueField', 'SplitDateTimeField']: + res['fields'] = map(describe_field, field.fields) +def describe_fields_errors(fields, field_names): + field_names = fields.keys() + for name in field_names: + res[name] = describe_field_errors(field) +def describe_field(field): + field_type = field.__class__.__name__ + for fname in field_names.get(field_type, []) + \ + ['help_text', 'label', 'initial', 'required']: + res[fname] = getattr(field, fname) + if field_type in ['ComboField', 'MultiValueField', 'SplitDateTimeField']: + res['fields'] = map(describe_field, field.fields) +def describe_fields(fields, field_names): + field_names = fields.keys() + for name in field_names: + res[name] = describe_field(field) +class FormProcessor(JSONRPCService): + def __init__(self, forms, _formcls=None): + JSONRPCService.__init__(self) + s = FormProcessor({}, forms[k]) + self.add_method(k, s.__process) + JSONRPCService.__init__(self, forms) + self.formcls = _formcls + def __process(self, request, params, command=None): + f = self.formcls(params) + if command is None: # just validate + return {'success':False, 'errors': builderrors(f)} + return {'success':True} + elif command.has_key('describe_errors'): + field_names = command['describe_errors'] + return describe_fields_errors(f.fields, field_names) + elif command.has_key('describe'): + field_names = command['describe'] + return describe_fields(f.fields, field_names) + elif command.has_key('save'): + return {'success':False, 'errors': builderrors(f)} + instance = f.save() # XXX: if you want more, over-ride save. + return {'success': True, 'instance': json_convert(instance) } + elif command.has_key('html'): + return {'success': True, 'html': f.as_table()} + return "unrecognised command" +# The following is incredibly convenient for saving vast amounts of +# coding, avoiding doing silly things like this: +# jsonresult = {'field1': djangoobject.field1, +# 'field2': djangoobject.date.strftime('%Y.%M'), +# The date/time flatten function is there because JSONRPC doesn't +# support date/time objects or formats, so conversion to a string +# is the most logical choice. pyjamas, being python, can easily +# be used to parse the string result at the other end. +# jsonservice = JSONRPCService() +# @jsonremote(jsonservice) +# def list_some_model(request, start=0, count=10): +# l = SomeDjangoModelClass.objects.filter() +# res = json_convert(l[start:end]) +# @jsonremote(jsonservice) +# def list_another_model(request, start=0, count=10): +# l = AnotherDjangoModelClass.objects.filter() +# res = json_convert(l[start:end]) +# dump jsonservice into urlpatterns to make the two RPC functions, +# list_some_model and list_another_model part of the django app: +# (r'^service1/$', 'djangoapp.views.jsonservice'), +from django.core.serializers import serialize +from datetime import date +def dict_datetimeflatten(item): + for k, v in item.items(): + if isinstance(v, datetime.date): + elif isinstance(v, dict): + d[k] = dict_datetimeflatten(v) +def json_convert(l, fields=None): + for item in serialize('python', l, fields=fields): + res.append(dict_datetimeflatten(item)) --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/svgui/pyjs/jsonrpc/jsonrpc.py Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,43 @@
+import gluon.contrib.simplejson as simplejson +class JSONRPCServiceBase: + def response(self, id, result): + return simplejson.dumps({'version': '1.1', 'id':id, + 'result':result, 'error':None}) + def error(self, id, code, message): + return simplejson.dumps({'id': id, + 'error': {'name': 'JSONRPCError', + def add_method(self, name, method): + self.methods[name] = method + def process(self, data): + data = simplejson.loads(data) + id, method, params = data["id"], data["method"], data["params"] + if method in self.methods: + result =self.methods[method](*params) + return self.response(id, result) + etype, eval, etb = sys.exc_info() + return self.error(id, 100, '%s: %s' %(etype.__name__, eval)) + etype, eval, etb = sys.exc_info() + return self.error(id, 100, 'Exception %s: %s' %(etype, eval)) + return self.error(id, 100, 'method "%s" does not exist' % method) + return self.methods.keys() --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/svgui/pyjs/jsonrpc/web2py/jsonrpc.py Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,11 @@
+from pyjs.jsonrpc import JSONRPCServiceBase +class JSONRPCService(JSONRPCServiceBase): + return self.process(request.body.read()) + def __call__(self,func): + self.methods[func.__name__]=func --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/svgui/pyjs/lib/_pyjs.js Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,160 @@
+function pyjs_extend(klass, base) { + function klass_object_inherit() {} + klass_object_inherit.prototype = base.prototype; + klass_object = new klass_object_inherit(); + for (var i in base.prototype.__class__) { + v = base.prototype.__class__[i]; + if (typeof v == "function" && (v.class_method || v.static_method || v.unbound_method)) + function klass_inherit() {} + klass_inherit.prototype = klass_object; + klass.prototype = new klass_inherit(); + klass_object.constructor = klass; + klass.prototype.__class__ = klass_object; + for (var i in base.prototype) { + if (typeof v == "function" && v.instance_method) + klass.prototype[i] = v; +/* creates a class, derived from bases, with methods and variables */ +function pyjs_type(clsname, bases, methods) + var fn_cls = function() {}; + fn_cls.__name__ = clsname; + var instance = new fn_cls(); + if(instance.__init__) instance.__init__.apply(instance, arguments); + fn_cls.__initialize__ = function() { + if (fn_cls.__was_initialized__) return; + fn_cls.__was_initialized__ = true; + fn_cls.__extend_baseclasses(); + fn_cls.prototype.__class__.__new__ = fn; + fn_cls.prototype.__class__.__name__ = clsname; + fn_cls.__extend_baseclasses = function() { + for (bi in fn_cls.__baseclasses) + var b = fn_cls.__baseclasses[bi]; + if (b.__was_initialized__) + for (bi in fn_cls.__baseclasses) + var b = fn_cls.__baseclasses[bi]; + pyjs_extend(fn_cls, b); + bases = [pyjslib.__Object]; + fn_cls.__baseclasses = bases; + fn_cls.__initialize__(); + var mtype = typeof mth; + if (mtype == "function" ) { + fn_cls.prototype[k] = mth; + fn_cls.prototype.__class__[k] = function () { + return fn_cls.prototype[k].call.apply( + fn_cls.prototype[k], arguments); + fn_cls.prototype.__class__[k].unbound_method = true; + fn_cls.prototype.instance_method = true; + fn_cls.prototype.__class__[k].__name__ = k; + fn_cls.prototype[k].__name__ = k; + fn_cls.prototype.__class__[k] = mth; +function pyjs_kwargs_call(obj, func, star_args, args) + if (!pyjslib.isIteratable(star_args)) + throw (pyjslib.TypeError(func.__name__ + "() arguments after * must be a sequence" + pyjslib.repr(star_args))); + var __i = star_args.__iter__(); + call_args[i]=__i.next(); + if (e != pyjslib.StopIteration) { + var n = star_args.length; + for (var i=0; i < args.length; i++) { + call_args[n+i]=args[i]; + return func.apply(obj, call_args); +function pyjs_kwargs_function_call(func, star_args, args) + return pyjs_kwargs_call(null, func, star_args, args); +function pyjs_kwargs_method_call(obj, method_name, star_args, args) + var method = obj[method_name]; + if (method.parse_kwargs) + args = method.parse_kwargs.apply(null, args); + return pyjs_kwargs_call(obj, method, star_args, args); +//String.prototype.__getitem__ = String.prototype.charAt; +//String.prototype.upper = String.prototype.toUpperCase; +//String.prototype.lower = String.prototype.toLowerCase; +//String.prototype.find=pyjslib.String_find; +//String.prototype.join=pyjslib.String_join; +//String.prototype.isdigit=pyjslib.String_isdigit; +//String.prototype.__iter__=pyjslib.String___iter__; +//String.prototype.__replace=String.prototype.replace; +//String.prototype.replace=pyjslib.String_replace; +//String.prototype.split=pyjslib.String_split; +//String.prototype.strip=pyjslib.String_strip; +//String.prototype.lstrip=pyjslib.String_lstrip; +//String.prototype.rstrip=pyjslib.String_rstrip; +//String.prototype.startswith=pyjslib.String_startswith; --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/svgui/pyjs/lib/json.js Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,293 @@
+json_parse = (function () { +// This is a function that can parse a JSON text, producing a JavaScript +// data structure. It is a simple, recursive descent parser. It does not use +// eval or regular expressions, so it can be used as a model for implementing +// a JSON parser in other languages. +// We are defining the function inside of another function to avoid creating + var at, // The index of the current character + ch, // The current character +// Call error when something is wrong. +// If a c parameter is provided, verify that it matches the current character. + error("Expected '" + c + "' instead of '" + ch + "'"); +// Get the next character. When there are no more characters, +// return the empty string. +// Parse a number value. + while (ch >= '0' && ch <= '9') { + while (next() && ch >= '0' && ch <= '9') { + if (ch === 'e' || ch === 'E') { + if (ch === '-' || ch === '+') { + while (ch >= '0' && ch <= '9') { +// Parse a string value. +// When parsing for string values, we must look for " and \ characters. + } else if (ch === '\\') { + for (i = 0; i < 4; i += 1) { + hex = parseInt(next(), 16); + uffff = uffff * 16 + hex; + string += String.fromCharCode(uffff); + } else if (typeof escapee[ch] === 'string') { + while (ch && ch <= ' ') { +// true, false, or null. + error("Unexpected '" + ch + "'"); + value, // Place holder for the value function. +// Parse an array value. + return array; // empty array +// Parse an object value. + return object; // empty object + if (Object.hasOwnProperty.call(object, key)) { + error('Duplicate key "' + key + '"'); +// Parse a JSON value. It could be an object, an array, a string, a number, + return ch >= '0' && ch <= '9' ? number() : word(); +// Return the json_parse function. It will have access to all of the above +// functions and variables. + return function (source, reviver) { +// If there is a reviver function, we recursively walk the new structure, +// passing each name/value pair to the reviver function for possible +// transformation, starting with a temporary root object that holds the result +// in an empty key. If there is not a reviver function, we simply return the + return typeof reviver === 'function' ? (function walk(holder, key) { + var k, v, value = holder[key]; + if (value && typeof value === 'object') { + if (Object.hasOwnProperty.call(value, k)) { + return reviver.call(holder, key, value); + }({'': result}, '')) : result; --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/svgui/pyjs/lib/pyjslib.py Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,1365 @@
+# Copyright 2006 James Tauber and contributors +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# iteration from Bob Ippolito's Iteration in JavaScript +from __pyjamas__ import JS +# must declare import _before_ importing sys +def import_module(path, parent_module, module_name, dynamic=1, async=False): + if (module_name == "sys" || module_name == 'pyjslib') + /*module_load_request[module_name] = 1;*/ + var override_name = sys.platform + "." + module_name; + if (((sys.overrides != null) && + (sys.overrides.has_key(override_name)))) + cache_file = sys.overrides.__getitem__(override_name) ; + cache_file = module_name ; + cache_file = (path + cache_file + '.cache.js' ) ; + //alert("cache " + cache_file + " " + module_name + " " + parent_module); + if (module_load_request[module_name]) + if (module_load_request[module_name] >= 3 && parent_module != null) + //onload_fn = parent_module + '.' + module_name + ' = ' + module_name + ';'; + //pyjs_eval(onload_fn); /* set up the parent-module namespace */ + if (typeof (module_load_request[module_name]) == 'undefined') + module_load_request[module_name] = 1; + /* following a load, this first executes the script + * "preparation" function MODULENAME_loaded_fn() + * and then sets up the loaded module in the namespace + onload_fn = ''; // module_name + "_loaded_fn();" + if (parent_module != null) + //onload_fn += parent_module + '.' + module_name + ' = ' + module_name + ';'; + /*pmod = parent_module + '.' + module_name; + onload_fn += 'alert("' + pmod + '"+' + pmod+');';*/ + /* this one tacks the script onto the end of the DOM + pyjs_load_script(cache_file, onload_fn, async); + /* this one actually RUNS the script (eval) into the page. + my feeling is that this would be better for non-async + but i can't get it to work entirely yet. + /*pyjs_ajax_eval(cache_file, onload_fn, async);*/ + if (module_name != "pyjslib" && +function import_wait(proceed_fn, parent_mod, dynamic) { + var element = $doc.createElement("div"); + $doc.body.appendChild(element); + function write_dom(txt) { + element.innerHTML = txt + '<br />'; + var wait = function() { + for (l in module_load_request) + var m = module_load_request[l]; + if (l == "sys" || l == 'pyjslib') + //write_dom( " import wait " + wait_count + " " + status + " parent_mod " + parent_mod); + setTimeout(wait, timeoutperiod); + for (l in module_load_request) + var m = module_load_request[l]; + if (l == "sys" || l == 'pyjslib') + module_load_request[l] = 4; + if ((parent_mod != null) && (l == parent_mod)) + setTimeout(wait, timeoutperiod); + /* cheat and move app on to next stage */ + module_load_request[l] = 3; + setTimeout(wait, timeoutperiod); + //alert("waited for module " + l + ": loaded"); + module_load_request[l] = 4; + //alert("module wait done"); + if (proceed_fn.importDone) + proceed_fn.importDone(proceed_fn); + def __init__(self, path, app_modlist, app_imported_fn, dynamic, + self.app_modlist = app_modlist + self.app_imported_fn = app_imported_fn + self.parent_mod = parent_mod + for i in range(len(self.app_modlist[self.idx])): + app = self.app_modlist[self.idx][i] + import_module(self.path, self.parent_mod, app, self.dynamic, True); + if self.idx >= len(self.app_modlist): + import_wait(self.app_imported_fn, self.parent_mod, self.dynamic) + import_wait(getattr(self, "next"), self.parent_mod, self.dynamic) +def get_module(module_name): + ev = "__mod = %s;" % module_name +def preload_app_modules(path, app_modnames, app_imported_fn, dynamic, + loader = Modload(path, app_modnames, app_imported_fn, dynamic, parent_mod) + def __init__(self, *args): + if len(self.args) is 0: + elif len(self.args) is 1: + return repr(self.args[0]) +class Exception(BaseException): +class TypeError(BaseException): +class StandardError(Exception): +class LookupError(StandardError): + return self.name + ": " + self.args[0] +class KeyError(LookupError): +class AttributeError(StandardError): + name = "AttributeError" + return "AttributeError: %s of %s" % (self.args[1], self.args[0]) +pyjslib.StopIteration = function () { }; +pyjslib.StopIteration.prototype = new Error(); +pyjslib.StopIteration.name = 'StopIteration'; +pyjslib.StopIteration.message = 'StopIteration'; +pyjslib.String_find = function(sub, start, end) { + var pos=this.indexOf(sub, start); + if (pyjslib.isUndefined(end)) return pos; + if (pos + sub.length>end) return -1; +pyjslib.String_join = function(data) { + if (pyjslib.isArray(data)) { + return data.join(this); + else if (pyjslib.isIteratable(data)) { + var iter=data.__iter__(); + if (e != pyjslib.StopIteration) throw e; +pyjslib.String_isdigit = function() { + return (this.match(/^\d+$/g) != null); +pyjslib.String_replace = function(old, replace, count) { + if (!pyjslib.isString(old)) return this.__replace(old, replace); + if (!pyjslib.isUndefined(count)) do_max=true; + while (start<this.length) { + if (do_max && !count--) break; + pos=this.indexOf(old, start); + new_str+=this.substring(start, pos) + replace; + if (start<this.length) new_str+=this.substring(start); +pyjslib.String_split = function(sep, maxsplit) { + var items=new pyjslib.List(); + if (pyjslib.isUndefined(sep) || pyjslib.isNull(sep)) { + subject=subject.strip(); + subject=subject.replace(/\s+/g, sep); + else if (!pyjslib.isUndefined(maxsplit)) do_max=true; + if (subject.length == 0) { + while (start<subject.length) { + if (do_max && !maxsplit--) break; + pos=subject.indexOf(sep, start); + items.append(subject.substring(start, pos)); + if (start<=subject.length) items.append(subject.substring(start)); +pyjslib.String___iter__ = function() { + throw pyjslib.StopIteration; + return s.substring(i++, i, 1); + '__iter__': function() { +pyjslib.String_strip = function(chars) { + return this.lstrip(chars).rstrip(chars); +pyjslib.String_lstrip = function(chars) { + if (pyjslib.isUndefined(chars)) return this.replace(/^\s+/, ""); + return this.replace(new RegExp("^[" + chars + "]+"), ""); +pyjslib.String_rstrip = function(chars) { + if (pyjslib.isUndefined(chars)) return this.replace(/\s+$/, ""); + return this.replace(new RegExp("[" + chars + "]+$"), ""); +pyjslib.String_startswith = function(prefix, start) { + if (pyjslib.isUndefined(start)) start = 0; + if (this.substring(start, prefix.length) == prefix) return true; + def __init__(self, name): + if (pyjslib.hasattr(a, "__cmp__")) { + return a.__cmp__(b) == 0; + } else if (pyjslib.hasattr(b, "__cmp__")) { + return b.__cmp__(a) == 0; + if hasattr(a, "__cmp__"): + elif hasattr(b, "__cmp__"): + # this needs to stay in native code without any dependencies here, + # because this is used by if and while, we need to prevent + return v.__nonzero__(); + def __init__(self, data=None): + def append(self, item): + JS(""" this.l[this.l.length] = item;""") + def extend(self, data): + if (pyjslib.isArray(data)) { + for (var i=0; i < data.length; i++) { + else if (pyjslib.isIteratable(data)) { + var iter=data.__iter__(); + if (e != pyjslib.StopIteration) throw e; + def remove(self, value): + var index=this.index(value); + if (index<0) return false; + this.l.splice(index, 1); + def index(self, value, start=0): + var length=this.l.length; + for (var i=start; i<length; i++) { + if (this.l[i]==value) { + def insert(self, index, value): + JS(""" var a = this.l; this.l=a.slice(0, index).concat(value, a.slice(index));""") + def pop(self, index = -1): + if (index<0) index = this.l.length + index; + this.l.splice(index, 1); + if not isinstance(l, List): + ll = len(self) - len(l) + for x in range(len(l)): + ll = cmp(self.__getitem__(x), l[x]) + def slice(self, lower, upper): + if (upper==null) return pyjslib.List(this.l.slice(lower)); + return pyjslib.List(this.l.slice(lower, upper)); + def __getitem__(self, index): + if (index<0) index = this.l.length + index; + def __setitem__(self, index, value): + JS(""" this.l[index]=value;""") + def __delitem__(self, index): + JS(""" this.l.splice(index, 1);""") + JS(""" return this.l.length;""") + def __contains__(self, value): + return self.index(value) >= 0 + throw pyjslib.StopIteration; + '__iter__': function() { + JS(""" this.l.reverse();""") + def sort(self, compareFunc=None, keyFunc=None, reverse=False): + if keyFunc and reverse: + return -compareFunc(keyFunc(a), keyFunc(b)) + return compareFunc(keyFunc(a), keyFunc(b)) + return -compareFunc(a, b) + self.l.sort(compareFunc) + Access the javascript Array that is used internally by this list + def __init__(self, data=None): + def append(self, item): + JS(""" this.l[this.l.length] = item;""") + def extend(self, data): + if (pyjslib.isArray(data)) { + for (var i=0; i < data.length; i++) { + else if (pyjslib.isIteratable(data)) { + var iter=data.__iter__(); + if (e != pyjslib.StopIteration) throw e; + def remove(self, value): + var index=this.index(value); + if (index<0) return false; + this.l.splice(index, 1); + def index(self, value, start=0): + var length=this.l.length; + for (var i=start; i<length; i++) { + if (this.l[i]==value) { + def insert(self, index, value): + JS(""" var a = this.l; this.l=a.slice(0, index).concat(value, a.slice(index));""") + def pop(self, index = -1): + if (index<0) index = this.l.length + index; + this.l.splice(index, 1); + if not isinstance(l, Tuple): + ll = len(self) - len(l) + for x in range(len(l)): + ll = cmp(self.__getitem__(x), l[x]) + def slice(self, lower, upper): + if (upper==null) return pyjslib.Tuple(this.l.slice(lower)); + return pyjslib.Tuple(this.l.slice(lower, upper)); + def __getitem__(self, index): + if (index<0) index = this.l.length + index; + def __setitem__(self, index, value): + JS(""" this.l[index]=value;""") + def __delitem__(self, index): + JS(""" this.l.splice(index, 1);""") + JS(""" return this.l.length;""") + def __contains__(self, value): + return self.index(value) >= 0 + throw pyjslib.StopIteration; + '__iter__': function() { + JS(""" this.l.reverse();""") + def sort(self, compareFunc=None, keyFunc=None, reverse=False): + if keyFunc and reverse: + return -compareFunc(keyFunc(a), keyFunc(b)) + return compareFunc(keyFunc(a), keyFunc(b)) + return -compareFunc(a, b) + self.l.sort(compareFunc) + Access the javascript Array that is used internally by this list + def __init__(self, data=None): + if (pyjslib.isArray(data)) { + this.__setitem__(item[0], item[1]); + //var sKey=pyjslib.hash(item[0]); + //this.d[sKey]=item[1]; + else if (pyjslib.isIteratable(data)) { + var iter=data.__iter__(); + this.__setitem__(item.__getitem__(0), item.__getitem__(1)); + if (e != pyjslib.StopIteration) throw e; + else if (pyjslib.isObject(data)) { + for (var key in data) { + this.__setitem__(key, data[key]); + def __setitem__(self, key, value): + var sKey = pyjslib.hash(key); + this.d[sKey]=[key, value]; + def __getitem__(self, key): + var sKey = pyjslib.hash(key); + var value=this.d[sKey]; + if (pyjslib.isUndefined(value)){ + throw pyjslib.KeyError(key); + for (var i in this.d) size++; + def has_key(self, key): + return self.__contains__(key) + def __delitem__(self, key): + var sKey = pyjslib.hash(key); + def __contains__(self, key): + var sKey = pyjslib.hash(key); + return (pyjslib.isUndefined(this.d[sKey])) ? false : true; + var keys=new pyjslib.List(); + for (var key in this.d) { + keys.append(this.d[key][0]); + var values=new pyjslib.List(); + for (var key in this.d) values.append(this.d[key][1]); + var items = new pyjslib.List(); + for (var key in this.d) { + items.append(new pyjslib.List(kv)) + return self.keys().__iter__() + return self.values().__iter__(); + return self.items().__iter__(); + def setdefault(self, key, default_value): + if not self.has_key(key): + self[key] = default_value + def get(self, key, default_=None): + if not self.has_key(key): + for k,v in d.iteritems(): + Return the javascript Object which this class uses to store + dictionary keys and values + return Dict(self.items()) +# taken from mochikit: range( [start,] stop[, step] ) + if (arguments.length == 2) { + else if (arguments.length == 3) { + else if (arguments.length>0) stop = arguments[0]; + if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) throw pyjslib.StopIteration; + '__iter__': function() { +def slice(object, lower, upper): + if (pyjslib.isString(object)) { + lower = object.length + lower; + upper = object.length + upper; + if (pyjslib.isNull(upper)) upper=object.length; + return object.substring(lower, upper); + if (pyjslib.isObject(object) && object.slice) + return object.slice(lower, upper); + if (pyjslib.hasattr(text,"__str__")) { + if(isString(x) and len(x) is 1): + return x.charCodeAt(0); + throw pyjslib.TypeError(); + return String.fromCharCode(x) + return t == 'boolean' || +def get_pyjs_classtype(x): + if (pyjslib.hasattr(x, "__class__")) + if (pyjslib.hasattr(x.__class__, "__new__")) + var src = x.__class__.__name__; + """ Return the string representation of 'x'. + //alert("repr typeof " + t + " : " + x); + return "<function " + x.toString() + ">"; + if (x.indexOf("'") == -1) + if (x.indexOf('"') == -1) + var s = x.replace(new RegExp('"', "g"), '\\\\"'); + // If we get here, x is an object. See if it's a Pyjamas class. + if (!pyjslib.hasattr(x, "__init__")) + return "<" + x.toString() + ">"; + // Handle the common Pyjamas data types. + var constructor = "UNKNOWN"; + constructor = pyjslib.get_pyjs_classtype(x); + //alert("repr constructor: " + constructor); + if (constructor == "Tuple") { + var contents = x.getArray(); + for (var i=0; i < contents.length; i++) { + s += pyjslib.repr(contents[i]); + if (i < contents.length - 1) + if (constructor == "List") { + var contents = x.getArray(); + for (var i=0; i < contents.length; i++) { + s += pyjslib.repr(contents[i]); + if (i < contents.length - 1) + if (constructor == "Dict") { + var keys = new Array(); + for (var i=0; i<keys.length; i++) { + s += pyjslib.repr(key) + ": " + pyjslib.repr(x.d[key]); + // If we get here, the class isn't one we know -> return the class name. + // Note that we replace underscores with dots so that the name will + // (hopefully!) look like the original Python name. + //var s = constructor.replace(new RegExp('_', "g"), '.'); + return "<" + constructor + " object>"; + return parseFloat(text); + return parseInt(text, radix); + if (object==null) return 0; + if (pyjslib.isObject(object) && object.__len__) return object.__len__(); +def isinstance(object_, classinfo): + if pyjslib.isUndefined(object_): + if not pyjslib.isObject(object_): + if _isinstance(classinfo, Tuple): + if isinstance(object_, ci): + return _isinstance(object_, classinfo) +def _isinstance(object_, classinfo): + if not pyjslib.isObject(object_): + if (object_.__class__){ + var res = object_ instanceof classinfo.constructor; +def getattr(obj, name, default_): + if ((!pyjslib.isObject(obj))||(pyjslib.isUndefined(obj[name]))){ + if (pyjslib.isUndefined(default_)){ + throw pyjslib.AttributeError(obj, name); + if (!pyjslib.isFunction(obj[name])) return obj[name]; + var fnwrap = function() { + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + return obj[name].apply(obj,args); + fnwrap.__name__ = name; +def setattr(obj, name, value): + if (!pyjslib.isObject(obj)) return null; + if (!pyjslib.isObject(obj)) return false; + if (pyjslib.isUndefined(obj[name])) return false; + var properties=new pyjslib.List(); + for (property in obj) properties.append(property); +def filter(obj, method, sequence=None): + # object context is LOST when a method is passed, hence object must be passed separately + # to emulate python behaviour, should generate this code inline rather than as a function call + if method.call(obj, item): +def map(obj, method, sequence=None): + items.append(method(item)) + items.append(method.call(obj, item)) +def enumerate(sequence): + enumeration.append([nextIndex, item]) + nextIndex = nextIndex + 1 + if (obj == null) return null; + if (obj.$H) return obj.$H; + if (obj.__hash__) return obj.__hash__(); + if (obj.constructor == String || obj.constructor == Number || obj.constructor == Date) return obj; + obj.$H = ++pyjslib.next_hash_id; +# type functions from Douglas Crockford's Remedial Javascript: http://www.crockford.com/javascript/remedial.html + return (a != null && (typeof a == 'object')) || pyjslib.isFunction(a); + return typeof a == 'function'; + return typeof a == 'string'; + return typeof a == 'object' && !a; + return pyjslib.isObject(a) && a.constructor == Array; + return typeof a == 'undefined'; + return pyjslib.isString(a) || (pyjslib.isObject(a) && a.__iter__); + return typeof a == 'number' && isFinite(a); + Convert the pyjs pythonic List and Dict objects into javascript Object and Array + for(var k=0; k < x.length; k++) { + var tv = pyjslib.toJSObjects(v); + if isinstance(x, Dict): + result[o[i][0].toString()] = o[i][1]; + return pyjslib.toJSObjects(result) + elif isinstance(x, List): + return toJSObjects(x.l) + elif hasattr(x, '__class__'): + # we do not have a special implementation for custom + # classes, just pass it on + var tv = pyjslib.toJSObjects(v) + if ($wnd.console==undefined) return; + for(var i=0; i < objs.length; i++) { +def type(clsname, bases=None, methods=None): + """ creates a class, derived from bases, with methods and variables + for k in methods.keys(): + JS(" var bss = null; ") + JS(" return pyjs_type(clsname, bss, mths); ") --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/svgui/pyjs/lib/sys.py Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,59 @@
+# the platform name (PyV8, smjs, Mozilla, IE6, Opera, Safari etc.) +platform = '' # to be updated by app, on compile +# a dictionary of module override names (platform-specific) +overrides = None # to be updated by app, on compile +# the remote path for loading modules +def addoverride(module_name, path): + overrides[module_name] = path +def addstack(linedebug): + if (pyjslib.bool((sys.stacktrace === null))) { + sys.stacktrace = new pyjslib.List([]); + sys.stacktrace.append(linedebug); + var __l = sys.stacktrace.__iter__(); + if (e != pyjslib.StopIteration) { --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/svgui/pyjs/pyjs.py Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,1777 @@
+# Copyright 2006 James Tauber and contributors +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from types import StringType +from compiler import ast +# the standard location for builtins (e.g. pyjslib) can be +# over-ridden by changing this. it defaults to sys.prefix +# so that on a system-wide install of pyjamas the builtins +# can be found in e.g. {sys.prefix}/share/pyjamas +# over-rides can be done by either explicitly modifying +# pyjs.prefix or by setting an environment variable, PYJSPREFIX. +if os.environ.has_key('PYJSPREFIX'): + prefix = os.environ['PYJSPREFIX'] +# pyjs.path is the list of paths, just like sys.path, from which +# library modules will be searched for, for compile purposes. +# obviously we don't want to use sys.path because that would result +# in compiling standard python modules into javascript! +path = [os.path.abspath('')] +if os.environ.has_key('PYJSPATH'): + for p in os.environ['PYJSPATH'].split(os.pathsep): +# this is the python function used to wrap native javascript +NATIVE_JS_FUNC_NAME = "JS" +PYJSLIB_BUILTIN_FUNCTIONS=("cmp", +PYJSLIB_BUILTIN_CLASSES=("BaseException", +def pyjs_builtin_remap(name): +# XXX: this is a hack: these should be dealt with another way +# however, console is currently the only global name which is causing +PYJS_GLOBAL_VARS=("console") +# This is taken from the django project. +# Escape every ASCII character with a value less than 32. + ) + tuple([('%c' % z, '\\x%02X' % z) for z in range(32)]) + """Hex encodes characters for use in JavaScript strings.""" + for bad, good in JS_ESCAPES: + value = value.replace(bad, good) +def uuprefix(name, leave_alone=0): + name = name[:leave_alone] + map(lambda x: "__%s" % x, name[leave_alone:]) + def __init__(self, name, name_): + self.klasses[name] = self + def set_base(self, base_name): + self.base = self.klasses.get(base_name) + def add_function(self, function_name): + self.functions.add(function_name) +class TranslationError(Exception): + def __init__(self, message, node): + self.message = "line %s:\n%s\n%s" % (node.lineno, message, node) +def mod_var_name_decl(raw_module_name): + """ function to get the last component of the module e.g. + pyjamas.ui.DOM into the "namespace". i.e. doing + "import pyjamas.ui.DOM" actually ends up with _two_ + variables - one pyjamas.ui.DOM, the other just "DOM". + but "DOM" is actually local, hence the "var" prefix. + for PyV8, this might end up causing problems - we'll have + to see: gen_mod_import and mod_var_name_decl might have + to end up in a library-specific module, somewhere. + name = raw_module_name.split(".") + return "var %s = %s;\n" % (child_name, raw_module_name) +def gen_mod_import(parentName, importName, dynamic=1): + #pyjs_ajax_eval("%(n)s.cache.js", null, true); + pyjslib.import_module(sys.loadpath, '%(p)s', '%(n)s', %(d)d, false); + """ % ({'p': parentName, 'd': dynamic, 'n': importName}) + \ + mod_var_name_decl(importName) + def __init__(self, mn, module_name, raw_module_name, src, debug, mod, output, + dynamic=0, optimize=False, + self.module_prefix = module_name + "." + self.module_prefix = "" + self.raw_module_name = raw_module_name + src = src.replace("\r\n", "\n") + src = src.replace("\n\r", "\n") + src = src.replace("\r", "\n") + self.src = src.split("\n") + self.imported_modules = [] + self.imported_modules_as = [] + self.imported_js = set() + self.top_level_functions = set() + self.top_level_classes = set() + self.top_level_vars = set() + self.local_arg_stack = [[]] + self.imported_classes = {} + self.method_imported_globals = set() + self.method_self = None + self.nextTupleAssignID = 1 + self.optimize = optimize + self.findFile = findFile + if module_name.find(".") >= 0: + print >>self.output, UU+"%s%s = function (__mod_name__) {" % (vdec, module_name) + print >>self.output, " if("+module_name+".__was_initialized__) return;" + print >>self.output, " "+UU+module_name+".__was_initialized__ = true;" + print >>self.output, UU+"if (__mod_name__ == null) __mod_name__ = '%s';" % (mn) + print >>self.output, UU+"%s.__name__ = __mod_name__;" % (raw_module_name) + decl = mod_var_name_decl(raw_module_name) + print >>self.output, decl + haltException = self.module_prefix + "HaltException" + print >>self.output, haltException + ' = function () {' + print >>self.output, ' this.message = "Program Halted";' + print >>self.output, ' this.name = "' + haltException + '";' + print >>self.output, '}' + print >>self.output, '' + print >>self.output, haltException + ".prototype.__str__ = function()" + print >>self.output, '{' + print >>self.output, 'return this.message ;' + print >>self.output, '}' + print >>self.output, haltException + ".prototype.toString = function()" + print >>self.output, '{' + print >>self.output, 'return this.name + ": \\"" + this.message + "\\"";' + print >>self.output, '}' + isHaltFunction = self.module_prefix + "IsHaltException" + print >>self.output, """ + var suffix="HaltException"; + if (s.length < suffix.length) { + //alert(s + " " + suffix); + var ss = s.substring(s.length, (s.length - suffix.length)); + //alert(s + " " + suffix + " " + ss); + if isinstance(child, ast.Function): + self.top_level_functions.add(child.name) + elif isinstance(child, ast.Class): + self.top_level_classes.add(child.name) + if isinstance(child, ast.Function): + self._function(child, False) + elif isinstance(child, ast.Class): + elif isinstance(child, ast.Import): + importName = child.names[0][0] + if importName == '__pyjamas__': # special module to help make pyjamas modules loadable in the python interpreter + elif importName.endswith('.js'): + self.imported_js.add(importName) + self.add_imported_module(strip_py(importName)) + elif isinstance(child, ast.From): + if child.modname == '__pyjamas__': # special module to help make pyjamas modules loadable in the python interpreter + self.add_imported_module(child.modname) + elif isinstance(child, ast.Discard): + self._discard(child, None) + elif isinstance(child, ast.Assign): + self._assign(child, None, True) + elif isinstance(child, ast.AugAssign): + self._augassign(child, None) + elif isinstance(child, ast.If): + elif isinstance(child, ast.For): + elif isinstance(child, ast.While): + self._while(child, None) + elif isinstance(child, ast.Subscript): + self._subscript_stmt(child, None) + elif isinstance(child, ast.Global): + self._global(child, None) + elif isinstance(child, ast.Printnl): + self._print(child, None) + elif isinstance(child, ast.Print): + self._print(child, None) + elif isinstance(child, ast.TryExcept): + self._tryExcept(child, None) + elif isinstance(child, ast.Raise): + self._raise(child, None) + elif isinstance(child, ast.Stmt): + self._stmt(child, None) + raise TranslationError("unsupported type (in __init__)", child) + # Initialize all classes for this module + #print >> self.output, "__"+self.modpfx()+\ + # "classes_initialize = function() {\n" + #for className in self.top_level_classes: + # print >> self.output, "\t"+UU+self.modpfx()+"__"+className+"_initialize();" + #print >> self.output, "};\n" + print >> self.output, "return this;\n" + print >> self.output, "}; /* end %s */ \n" % module_name + def module_imports(self): + return self.imported_modules + self.imported_modules_as + def add_local_arg(self, varname): + local_vars = self.local_arg_stack[-1] + if varname not in local_vars: + local_vars.append(varname) + def add_imported_module(self, importName): + if importName in self.imported_modules: + self.imported_modules.append(importName) + name = importName.split(".") + # add the name of the module to the namespace, + # but don't add the short name to imported_modules + # because then the short name would be attempted to be + # added to the dependencies, and it's half way up the + # module import directory structure! + self.imported_modules_as.append(child_name) + print >> self.output, gen_mod_import(self.raw_module_name, + def _default_args_handler(self, node, arg_names, current_klass, + output = output or self.output + default_pos = len(arg_names) - len(node.defaults) + if arg_names and arg_names[0] == self.method_self: + for default_node in node.defaults: + if isinstance(default_node, ast.Const): + default_value = self._const(default_node) + elif isinstance(default_node, ast.Name): + default_value = self._name(default_node, current_klass) + elif isinstance(default_node, ast.UnarySub): + default_value = self._unarysub(default_node, current_klass) + raise TranslationError("unsupported type (in _method)", default_node) + default_name = arg_names[default_pos] + print >> output, " if (typeof %s == 'undefined') %s=%s;" % (default_name, default_name, default_value) + def _varargs_handler(self, node, varargname, arg_names, current_klass): + print >>self.output, " var", varargname, '= new pyjslib.Tuple();' + print >>self.output, " for(var __va_arg="+str(len(arg_names))+"; __va_arg < arguments.length; __va_arg++) {" + print >>self.output, " var __arg = arguments[__va_arg];" + print >>self.output, " "+varargname+".append(__arg);" + print >>self.output, " }" + def _kwargs_parser(self, node, function_name, arg_names, current_klass): + if len(node.defaults) or node.kwargs: + default_pos = len(arg_names) - len(node.defaults) + if arg_names and arg_names[0] == self.method_self: + print >>self.output, function_name+'.parse_kwargs = function (', ", ".join(["__kwargs"]+arg_names), ") {" + for default_node in node.defaults: + default_value = self.expr(default_node, current_klass) +# if isinstance(default_node, ast.Const): +# default_value = self._const(default_node) +# elif isinstance(default_node, ast.Name): +# default_value = self._name(default_node) +# elif isinstance(default_node, ast.UnarySub): +# default_value = self._unarysub(default_node, current_klass) +# raise TranslationError("unsupported type (in _method)", default_node) + default_name = arg_names[default_pos] + print >>self.output, " if (typeof %s == 'undefined')"%(default_name) + print >>self.output, " %s=__kwargs.%s;"% (default_name, default_name) + #self._default_args_handler(node, arg_names, current_klass) + if node.kwargs: arg_names += ["pyjslib.Dict(__kwargs)"] + print >>self.output, " var __r = "+"".join(["[", ", ".join(arg_names), "]"])+";" + self._varargs_handler(node, "__args", arg_names, current_klass) + print >>self.output, " __r.push.apply(__r, __args.getArray())" + print >>self.output, " return __r;" + print >>self.output, "};" + def _function(self, node, local=False): + function_name = node.name + self.add_local_arg(function_name) + function_name = UU + self.modpfx() + node.name + arg_names = list(node.argnames) + normal_arg_names = list(arg_names) + if node.kwargs: kwargname = normal_arg_names.pop() + if node.varargs: varargname = normal_arg_names.pop() + declared_arg_names = list(normal_arg_names) + if node.kwargs: declared_arg_names.append(kwargname) + function_args = "(" + ", ".join(declared_arg_names) + ")" + print >>self.output, "%s = function%s {" % (function_name, function_args) + self._default_args_handler(node, normal_arg_names, None) + local_arg_names = normal_arg_names + declared_arg_names + self._varargs_handler(node, varargname, declared_arg_names, None) + local_arg_names.append(varargname) + # stack of local variable names for this function call + self.local_arg_stack.append(local_arg_names) + for child in node.code: + self._stmt(child, None) + # remove the top local arg names + self.local_arg_stack.pop() + # we need to return null always, so it is not undefined + lastStmt = [p for p in node.code][-1] + if not isinstance(lastStmt, ast.Return): + if not self._isNativeFunc(lastStmt): + print >>self.output, " return null;" + print >>self.output, "};" + print >>self.output, "%s.__name__ = '%s';\n" % (function_name, node.name) + self._kwargs_parser(node, function_name, normal_arg_names, None) + def _return(self, node, current_klass): + expr = self.expr(node.value, current_klass) + # in python a function call always returns None, so we do it + print >>self.output, " return " + expr + ";" + def _break(self, node, current_klass): + print >>self.output, " break;" + def _continue(self, node, current_klass): + print >>self.output, " continue;" + def _callfunc(self, v, current_klass): + if isinstance(v.node, ast.Name): + if v.node.name in self.top_level_functions: + call_name = self.modpfx() + v.node.name + elif v.node.name in self.top_level_classes: + call_name = self.modpfx() + v.node.name + elif self.imported_classes.has_key(v.node.name): + call_name = self.imported_classes[v.node.name] + '.' + v.node.name + elif v.node.name in PYJSLIB_BUILTIN_FUNCTIONS: + call_name = 'pyjslib.' + v.node.name + elif v.node.name in PYJSLIB_BUILTIN_CLASSES: + name = pyjs_builtin_remap(v.node.name) + call_name = 'pyjslib.' + name + elif v.node.name == "callable": + call_name = "pyjslib.isFunction" + call_name = v.node.name + elif isinstance(v.node, ast.Getattr): + attr_name = v.node.attrname + if isinstance(v.node.expr, ast.Name): + call_name = self._name2(v.node.expr, current_klass, attr_name) + elif isinstance(v.node.expr, ast.Getattr): + call_name = self._getattr2(v.node.expr, current_klass, attr_name) + elif isinstance(v.node.expr, ast.CallFunc): + call_name = self._callfunc(v.node.expr, current_klass) + "." + v.node.attrname + elif isinstance(v.node.expr, ast.Subscript): + call_name = self._subscript(v.node.expr, current_klass) + "." + v.node.attrname + elif isinstance(v.node.expr, ast.Const): + call_name = self.expr(v.node.expr, current_klass) + "." + v.node.attrname + raise TranslationError("unsupported type (in _callfunc)", v.node.expr) + raise TranslationError("unsupported type (in _callfunc)", v.node) + call_name = strip_py(call_name) + star_arg_name = self.expr(v.star_args, current_klass) + if isinstance(ch4, ast.Keyword): + kwarg = ch4.name + ":" + self.expr(ch4.expr, current_klass) + arg = self.expr(ch4, current_klass) + fn_args = ", ".join(['{' + ', '.join(kwargs) + '}']+call_args) + fn_args = ", ".join(call_args) + if kwargs or star_arg_name: + try: call_this, method_name = call_name.rsplit(".", 1) + # Must be a function call ... + return ("pyjs_kwargs_function_call("+call_name+", " + return ("pyjs_kwargs_method_call("+call_this+", '"+method_name+"', " + return call_name + "(" + ", ".join(call_args) + ")" + def _print(self, node, current_klass): + arg = self.expr(ch4, current_klass) + print >>self.output, "pyjslib.printFunc([", ', '.join(call_args), "],", int(isinstance(node, ast.Printnl)), ");" + def _tryExcept(self, node, current_klass): + if len(node.handlers) != 1: + raise TranslationError("except statements in this form are" + + " not supported", node) + expr = node.handlers[0][0] + as_ = node.handlers[0][1] + # XXX TODO: check that this should instead be added as a _separate_ + # local scope, temporary to the function. oh dearie me. + self.add_local_arg(errName) + print >>self.output, " try {" + for stmt in node.body.nodes: + self._stmt(stmt, current_klass) + print >> self.output, " } catch(%s) {" % errName + if isinstance(expr, ast.Tuple): + l.append("(%(err)s.__name__ == %(expr)s.__name__)" % dict (err=errName, expr=self.expr(x, current_klass))) + l = [ " (%(err)s.__name__ == %(expr)s.__name__) " % dict (err=errName, expr=self.expr(expr, current_klass)) ] + print >> self.output, " if(%s) {" % '||\n\t\t'.join(l) + for stmt in node.handlers[0][2]: + self._stmt(stmt, current_klass) + #print >> self.output, "} else { throw(%s); } " % errName + print >> self.output, "}" + print >>self.output, " } finally {" + for stmt in node.else_: + self._stmt(stmt, current_klass) + print >>self.output, " }" + # XXX: change use_getattr to True to enable "strict" compilation + # but incurring a 100% performance penalty. oops. + def _getattr(self, v, current_klass, use_getattr=False): + if isinstance(v.expr, ast.Name): + obj = self._name(v.expr, current_klass, return_none_for_module=True) + if obj == None and v.expr.name in self.module_imports(): + # XXX TODO: distinguish between module import classes + # and variables. right now, this is a hack to get + # the sys module working. + #if v.expr.name == 'sys': + return v.expr.name+'.'+attr_name + #return v.expr.name+'.__'+attr_name+'.prototype.__class__' + if not use_getattr or attr_name == '__class__' or \ + attr_name == '__name__': + return obj + "." + attr_name + return "pyjslib.getattr(%s, '%s')" % (obj, attr_name) + elif isinstance(v.expr, ast.Getattr): + return self._getattr(v.expr, current_klass) + "." + attr_name + elif isinstance(v.expr, ast.Subscript): + return self._subscript(v.expr, self.modpfx()) + "." + attr_name + elif isinstance(v.expr, ast.CallFunc): + return self._callfunc(v.expr, self.modpfx()) + "." + attr_name + raise TranslationError("unsupported type (in _getattr)", v.expr) + return strip_py(self.module_prefix) + def _name(self, v, current_klass, top_level=False, + return_none_for_module=False): + if v.name == 'ilikesillynamesfornicedebugcode': + print top_level, current_klass, repr(v) + print self.top_level_vars + print self.top_level_functions + print self.local_arg_stack + las = len(self.local_arg_stack) + local_var_names = self.local_arg_stack[-1] + elif v.name == "False": + elif v.name == '__name__' and current_klass is None: + return self.modpfx() + v.name + elif v.name == self.method_self: + elif v.name in self.top_level_functions: + return UU+self.modpfx() + v.name + elif v.name in self.method_imported_globals: + return UU+self.modpfx() + v.name + elif not current_klass and las == 1 and v.name in self.top_level_vars: + return UU+self.modpfx() + v.name + elif v.name in local_var_names: + elif self.imported_classes.has_key(v.name): + return UU+self.imported_classes[v.name] + '.__' + v.name + ".prototype.__class__" + elif v.name in self.top_level_classes: + return UU+self.modpfx() + "__" + v.name + ".prototype.__class__" + elif v.name in self.module_imports() and return_none_for_module: + elif v.name in PYJSLIB_BUILTIN_CLASSES: + return "pyjslib." + pyjs_builtin_remap( v.name ) + if v.name not in local_var_names and \ + v.name not in self.top_level_vars and \ + v.name not in PYJS_GLOBAL_VARS and \ + v.name not in self.top_level_functions: + cls_name = current_klass + if hasattr(cls_name, "name"): + cls_name_ = cls_name.name_ + cls_name = cls_name.name + cls_name_ = current_klass + "_" # XXX ??? + name = UU+cls_name_ + ".prototype.__class__." \ + if v.name == 'listener': + name = 'listener+' + name + def _name2(self, v, current_klass, attr_name): + if obj in self.method_imported_globals: + call_name = UU+self.modpfx() + obj + "." + attr_name + elif self.imported_classes.has_key(obj): + #if attr_name != "__init__": + attr_str = ".prototype.__class__." + attr_name + call_name = UU+self.imported_classes[obj] + '.__' + obj + attr_str + elif obj in self.module_imports(): + call_name = obj + "." + attr_name + elif obj[0] == obj[0].upper(): # XXX HACK ALERT + call_name = UU + self.modpfx() + "__" + obj + ".prototype.__class__." + attr_name + call_name = UU+self._name(v, current_klass) + "." + attr_name + def _getattr2(self, v, current_klass, attr_name): + if isinstance(v.expr, ast.Getattr): + call_name = self._getattr2(v.expr, current_klass, v.attrname + "." + attr_name) + elif isinstance(v.expr, ast.Name) and v.expr.name in self.module_imports(): + call_name = UU+v.expr.name + '.__' +v.attrname+".prototype.__class__."+attr_name + obj = self.expr(v.expr, current_klass) + call_name = obj + "." + v.attrname + "." + attr_name + def _class(self, node): + Handle a class definition. + In order to translate python semantics reasonably well, the following + A special object is created for the class, which inherits attributes + from the superclass, or Object if there's no superclass. This is the + class object; the object which you refer to when specifying the + class by name. Static, class, and unbound methods are copied + from the superclass object. + A special constructor function is created with the same name as the + class, which is used to create instances of that class. + A javascript class (e.g. a function with a prototype attribute) is + created which is the javascript class of created instances, and + which inherits attributes from the class object. Bound methods are + copied from the superclass into this class rather than inherited, + because the class object contains unbound, class, and static methods + that we don't necessarily want to inherit. + The type of a method can now be determined by inspecting its + static_method, unbound_method, class_method, or instance_method + attribute; only one of these should be true. + Much of this work is done in pyjs_extend, is pyjslib.py + class_name = self.modpfx() + uuprefix(node.name, 1) + class_name_ = self.modpfx() + uuprefix(node.name) + current_klass = Klass(class_name, class_name_) + for child in node.code: + if isinstance(child, ast.Function): + current_klass.add_function(child.name) + if child.name == "__init__": + if len(node.bases) == 0: + base_class = "pyjslib.__Object" + elif len(node.bases) == 1: + if isinstance(node.bases[0], ast.Name): + if self.imported_classes.has_key(node.bases[0].name): + base_class_ = self.imported_classes[node.bases[0].name] + '.__' + node.bases[0].name + base_class = self.imported_classes[node.bases[0].name] + '.' + node.bases[0].name + base_class_ = self.modpfx() + "__" + node.bases[0].name + base_class = self.modpfx() + node.bases[0].name + elif isinstance(node.bases[0], ast.Getattr): + # the bases are not in scope of the class so do not + # pass our class to self._name + base_class_ = self._name(node.bases[0].expr, None) + \ + ".__" + node.bases[0].attrname + base_class = self._name(node.bases[0].expr, None) + \ + "." + node.bases[0].attrname + raise TranslationError("unsupported type (in _class)", node.bases[0]) + current_klass.set_base(base_class) + raise TranslationError("more than one base (in _class)", node) + print >>self.output, UU+class_name_ + " = function () {" + # call superconstructor + # print >>self.output, " __" + base_class + ".call(this);" + print >>self.output, "}" + init_method = ast.Function([], "__init__", ["self"], [], 0, None, []) + #self._method(init_method, current_klass, class_name) + # Generate a function which constructs the object + clsfunc = ast.Function([], + init_method.argnames[1:], + [ast.Discard(ast.CallFunc(ast.Name("JS"), [ast.Const( +# I attempted lazy initialization, but then you can't access static class members +# " if(!__"+base_class+".__was_initialized__)"+ +# " __" + class_name + "_initialize();\n" + + " var instance = new " + UU + class_name_ + "();\n" + + " if(instance.__init__) instance.__init__.apply(instance, arguments);\n" + + self._function(clsfunc, False) + print >>self.output, UU+class_name_ + ".__initialize__ = function () {" + print >>self.output, " if("+UU+class_name_+".__was_initialized__) return;" + print >>self.output, " "+UU+class_name_+".__was_initialized__ = true;" + cls_obj = UU+class_name_ + '.prototype.__class__' + if class_name == "pyjslib.__Object": + print >>self.output, " "+cls_obj+" = {};" + if base_class and base_class not in ("object", "pyjslib.__Object"): + print >>self.output, " if(!"+UU+base_class_+".__was_initialized__)" + print >>self.output, " "+UU+base_class_+".__initialize__();" + print >>self.output, " pyjs_extend(" + UU+class_name_ + ", "+UU+base_class_+");" + print >>self.output, " pyjs_extend(" + UU+class_name_ + ", "+UU+"pyjslib.__Object);" + print >>self.output, " "+cls_obj+".__new__ = "+UU+class_name+";" + print >>self.output, " "+cls_obj+".__name__ = '"+UU+node.name+"';" + for child in node.code: + if isinstance(child, ast.Pass): + elif isinstance(child, ast.Function): + self._method(child, current_klass, class_name, class_name_) + elif isinstance(child, ast.Assign): + self.classattr(child, current_klass) + elif isinstance(child, ast.Discard) and isinstance(child.expr, ast.Const): + # Probably a docstring, turf it + raise TranslationError("unsupported type (in _class)", child) + print >>self.output, "}" + print >> self.output, class_name_+".__initialize__();" + def classattr(self, node, current_klass): + self._assign(node, current_klass, True) + def _raise(self, node, current_klass): + raise TranslationError("More than one expression unsupported", + print >> self.output, "throw (%s);" % self.expr( + node.expr1, current_klass) + def _method(self, node, current_klass, class_name, class_name_): + # reset global var scope + self.method_imported_globals = set() + arg_names = list(node.argnames) + for d in node.decorators: + if d.name == "classmethod": + elif d.name == "staticmethod": + staticfunc = ast.Function([], class_name_+"."+node.name, node.argnames, node.defaults, node.flags, node.doc, node.code, node.lineno) + self._function(staticfunc, True) + print >>self.output, " " + UU+class_name_ + ".prototype.__class__." + node.name + " = " + class_name_+"."+node.name+";"; + print >>self.output, " " + UU+class_name_ + ".prototype.__class__." + node.name + ".static_method = true;"; + if len(arg_names) == 0: + raise TranslationError("methods must take an argument 'self' (in _method)", node) + self.method_self = arg_names[0] + #if not classmethod and arg_names[0] != "self": + # raise TranslationError("first arg not 'self' (in _method)", node) + normal_arg_names = arg_names[1:] + if node.kwargs: kwargname = normal_arg_names.pop() + if node.varargs: varargname = normal_arg_names.pop() + declared_arg_names = list(normal_arg_names) + if node.kwargs: declared_arg_names.append(kwargname) + function_args = "(" + ", ".join(declared_arg_names) + ")" + fexpr = UU + class_name_ + ".prototype.__class__." + node.name + fexpr = UU + class_name_ + ".prototype." + node.name + print >>self.output, " "+fexpr + " = function" + function_args + " {" + self._default_args_handler(node, normal_arg_names, current_klass) + local_arg_names = normal_arg_names + declared_arg_names + self._varargs_handler(node, varargname, declared_arg_names, current_klass) + local_arg_names.append(varargname) + # stack of local variable names for this function call + self.local_arg_stack.append(local_arg_names) + for child in node.code: + self._stmt(child, current_klass) + # remove the top local arg names + self.local_arg_stack.pop() + print >>self.output, " };" + self._kwargs_parser(node, fexpr, normal_arg_names, current_klass) + # Have to create a version on the instances which automatically passes the + altexpr = UU + class_name_ + ".prototype." + node.name + print >>self.output, " "+altexpr + " = function() {" + print >>self.output, " return " + fexpr + ".apply(this.__class__, arguments);" + print >>self.output, " };" + print >>self.output, " "+fexpr+".class_method = true;" + print >>self.output, " "+altexpr+".instance_method = true;" + # For instance methods, we need an unbound version in the class object + altexpr = UU + class_name_ + ".prototype.__class__." + node.name + print >>self.output, " "+altexpr + " = function() {" + print >>self.output, " return " + fexpr + ".call.apply("+fexpr+", arguments);" + print >>self.output, " };" + print >>self.output, " "+altexpr+".unbound_method = true;" + print >>self.output, " "+fexpr+".instance_method = true;" + print >>self.output, " "+altexpr+".__name__ = '%s';" % node.name + print >>self.output, UU + class_name_ + ".prototype.%s.__name__ = '%s';" % \ + if node.kwargs or len(node.defaults): + print >>self.output, " "+altexpr + ".parse_kwargs = " + fexpr + ".parse_kwargs;" + self.method_self = None + self.method_imported_globals = set() + def _isNativeFunc(self, node): + if isinstance(node, ast.Discard): + if isinstance(node.expr, ast.CallFunc): + if isinstance(node.expr.node, ast.Name) and \ + node.expr.node.name == NATIVE_JS_FUNC_NAME: + def _stmt(self, node, current_klass): + debugStmt = self.debug and not self._isNativeFunc(node) + print >>self.output, ' try {' + if isinstance(node, ast.Return): + self._return(node, current_klass) + elif isinstance(node, ast.Break): + self._break(node, current_klass) + elif isinstance(node, ast.Continue): + self._continue(node, current_klass) + elif isinstance(node, ast.Assign): + self._assign(node, current_klass) + elif isinstance(node, ast.AugAssign): + self._augassign(node, current_klass) + elif isinstance(node, ast.Discard): + self._discard(node, current_klass) + elif isinstance(node, ast.If): + self._if(node, current_klass) + elif isinstance(node, ast.For): + self._for(node, current_klass) + elif isinstance(node, ast.While): + self._while(node, current_klass) + elif isinstance(node, ast.Subscript): + self._subscript_stmt(node, current_klass) + elif isinstance(node, ast.Global): + self._global(node, current_klass) + elif isinstance(node, ast.Pass): + elif isinstance(node, ast.Function): + self._function(node, True) + elif isinstance(node, ast.Printnl): + self._print(node, current_klass) + elif isinstance(node, ast.Print): + self._print(node, current_klass) + elif isinstance(node, ast.TryExcept): + self._tryExcept(node, current_klass) + elif isinstance(node, ast.Raise): + self._raise(node, current_klass) + raise TranslationError("unsupported type (in _stmt)", node) + lt = self.get_line_trace(node) + haltException = self.module_prefix + "HaltException" + isHaltFunction = self.module_prefix + "IsHaltException" + print >>self.output, ' } catch (__err) {' + print >>self.output, ' if (' + isHaltFunction + '(__err.name)) {' + print >>self.output, ' throw __err;' + print >>self.output, ' } else {' + print >>self.output, " st = sys.printstack() + "\ + + '"%s"' % lt + "+ '\\n' ;" + print >>self.output, ' alert("' + "Error in " \ + + '+"\\n"+__err.name+": "+__err.message'\ + + '+"\\n\\nStack trace:\\n"' \ + print >>self.output, ' debugger;' + print >>self.output, ' throw new ' + self.module_prefix + "HaltException();" + print >>self.output, ' }' + print >>self.output, ' }' + def get_line_trace(self, node): + if hasattr(node, "lineno"): + if node.lineno != None: + srcLine = self.src[min(lineNum, len(self.src))-1] + srcLine = srcLine.replace('\\', '\\\\') + srcLine = srcLine.replace('"', '\\"') + srcLine = srcLine.replace("'", "\\'") + return self.raw_module_name + ".py, line " \ + def _augassign(self, node, current_klass): + if isinstance(v, ast.Getattr): + # XXX HACK! don't allow += on return result of getattr. + # TODO: create a temporary variable or something. + lhs = self._getattr(v, current_klass, False) + lhs = self._name(node.node, current_klass) + rhs = self.expr(node.expr, current_klass) + print >>self.output, " " + lhs + " " + op + " " + rhs + ";" + def _assign(self, node, current_klass, top_level = False): + if len(node.nodes) != 1: + tempvar = '__temp'+str(node.lineno) + tnode = ast.Assign([ast.AssName(tempvar, "OP_ASSIGN", node.lineno)], node.expr, node.lineno) + self._assign(tnode, current_klass, top_level) + tnode2 = ast.Assign([v], ast.Name(tempvar, node.lineno), node.lineno) + self._assign(tnode2, current_klass, top_level) + if len(self.local_arg_stack) > 0: + local_var_names = self.local_arg_stack[-1] + def _lhsFromAttr(v, current_klass): + if isinstance(v.expr, ast.Name): + lhs = self._name(v.expr, current_klass) + "." + attr_name + elif isinstance(v.expr, ast.Getattr): + lhs = self._getattr(v, current_klass) + elif isinstance(v.expr, ast.Subscript): + lhs = self._subscript(v.expr, current_klass) + "." + attr_name + raise TranslationError("unsupported type (in _assign)", v.expr) + def _lhsFromName(v, top_level, current_klass): + lhs = UU+current_klass.name_ + ".prototype.__class__." \ + self.top_level_vars.add(v.name) + vname = self.modpfx() + v.name + if not self.modpfx() and v.name not in\ + self.method_imported_globals: + self.add_local_arg(v.name) + if v.name in local_var_names: + elif v.name in self.method_imported_globals: + lhs = self.modpfx() + v.name + self.add_local_arg(v.name) + if isinstance(v, ast.AssAttr): + lhs = _lhsFromAttr(v, current_klass) + if v.flags == "OP_ASSIGN": + raise TranslationError("unsupported flag (in _assign)", v) + elif isinstance(v, ast.AssName): + lhs = _lhsFromName(v, top_level, current_klass) + if v.flags == "OP_ASSIGN": + raise TranslationError("unsupported flag (in _assign)", v) + elif isinstance(v, ast.Subscript): + if v.flags == "OP_ASSIGN": + obj = self.expr(v.expr, current_klass) + raise TranslationError("must have one sub (in _assign)", v) + idx = self.expr(v.subs[0], current_klass) + value = self.expr(node.expr, current_klass) + print >>self.output, " " + obj + ".__setitem__(" + idx + ", " + value + ");" + raise TranslationError("unsupported flag (in _assign)", v) + elif isinstance(v, (ast.AssList, ast.AssTuple)): + uniqueID = self.nextTupleAssignID + self.nextTupleAssignID += 1 + tempName = "__tupleassign" + str(uniqueID) + "__" + print >>self.output, " var " + tempName + " = " + \ + self.expr(node.expr, current_klass) + ";" + for index,child in enumerate(v.getChildNodes()): + rhs = tempName + ".__getitem__(" + str(index) + ")" + if isinstance(child, ast.AssAttr): + lhs = _lhsFromAttr(child, current_klass) + elif isinstance(child, ast.AssName): + lhs = _lhsFromName(child, top_level, current_klass) + elif isinstance(child, ast.Subscript): + if child.flags == "OP_ASSIGN": + obj = self.expr(child.expr, current_klass) + if len(child.subs) != 1: + raise TranslationError("must have one sub " + + idx = self.expr(child.subs[0], current_klass) + value = self.expr(node.expr, current_klass) + print >>self.output, " " + obj + ".__setitem__(" \ + + idx + ", " + rhs + ");" + print >>self.output, " " + lhs + " = " + rhs + ";" + raise TranslationError("unsupported type (in _assign)", v) + rhs = self.expr(node.expr, current_klass) + print "b", repr(node.expr), rhs + print >>self.output, " " + lhs + " " + op + " " + rhs + ";" + def _discard(self, node, current_klass): + if isinstance(node.expr, ast.CallFunc): + debugStmt = self.debug and not self._isNativeFunc(node) + if debugStmt and isinstance(node.expr.node, ast.Name) and \ + node.expr.node.name == 'import_wait': + st = self.get_line_trace(node) + print >>self.output, "sys.addstack('%s');\n" % st + if isinstance(node.expr.node, ast.Name) and node.expr.node.name == NATIVE_JS_FUNC_NAME: + if len(node.expr.args) != 1: + raise TranslationError("native javascript function %s must have one arg" % NATIVE_JS_FUNC_NAME, node.expr) + if not isinstance(node.expr.args[0], ast.Const): + raise TranslationError("native javascript function %s must have constant arg" % NATIVE_JS_FUNC_NAME, node.expr) + raw_js = node.expr.args[0].value + print >>self.output, raw_js + expr = self._callfunc(node.expr, current_klass) + print >>self.output, " " + expr + ";" + print >>self.output, "sys.popstack();\n" + elif isinstance(node.expr, ast.Const): + if node.expr.value is not None: # Empty statements generate ignore None + print >>self.output, self._const(node.expr) + raise TranslationError("unsupported type (in _discard)", node.expr) + def _if(self, node, current_klass): + for i in range(len(node.tests)): + test, consequence = node.tests[i] + self._if_test(keyword, test, consequence, current_klass) + consequence = node.else_ + self._if_test(keyword, test, consequence, current_klass) + def _if_test(self, keyword, test, consequence, current_klass): + expr = self.expr(test, current_klass) + print >>self.output, " " + keyword + " (pyjslib.bool(" + expr + ")) {" + print >>self.output, " " + keyword + " {" + if isinstance(consequence, ast.Stmt): + for child in consequence.nodes: + self._stmt(child, current_klass) + raise TranslationError("unsupported type (in _if_test)", consequence) + print >>self.output, " }" + for name in node.names: + # look up "hack" in AppTranslator as to how findFile gets here + module_name = node.modname + "." + name[0] + ff = self.findFile(module_name + ".py") + self.add_imported_module(module_name) + self.imported_classes[name[0]] = node.modname + def _compare(self, node, current_klass): + lhs = self.expr(node.expr, current_klass) + raise TranslationError("only one ops supported (in _compare)", node) + rhs_node = node.ops[0][1] + rhs = self.expr(rhs_node, current_klass) + return "pyjslib.eq(%s, %s)" % (lhs, rhs) + return rhs + ".__contains__(" + lhs + ")" + return "!" + rhs + ".__contains__(" + lhs + ")" + return "(" + lhs + " " + op + " " + rhs + ")" + def _not(self, node, current_klass): + expr = self.expr(node.expr, current_klass) + return "!(" + expr + ")" + def _or(self, node, current_klass): + expr = "("+(") || (".join([self.expr(child, current_klass) for child in node.nodes]))+')' + def _and(self, node, current_klass): + expr = "("+(") && (".join([self.expr(child, current_klass) for child in node.nodes]))+")" + def _for(self, node, current_klass): + # based on Bob Ippolito's Iteration in Javascript code + if isinstance(node.assign, ast.AssName): + assign_name = node.assign.name + self.add_local_arg(assign_name) + if node.assign.flags == "OP_ASSIGN": + elif isinstance(node.assign, ast.AssTuple): + for child in node.assign: + child_name = child.name + assign_name = "temp_" + child_name + self.add_local_arg(child_name) + var %(child_name)s %(op)s %(assign_name)s.__getitem__(%(i)i); + raise TranslationError("unsupported type (in _for)", node.assign) + if isinstance(node.list, ast.Name): + list_expr = self._name(node.list, current_klass) + elif isinstance(node.list, ast.Getattr): + list_expr = self._getattr(node.list, current_klass) + elif isinstance(node.list, ast.CallFunc): + list_expr = self._callfunc(node.list, current_klass) + raise TranslationError("unsupported type (in _for)", node.list) + lhs = "var " + assign_name + iterator_name = "__" + assign_name + print >>self.output, """ + var %(iterator_name)s = %(list_expr)s.__iter__(); + %(lhs)s %(op)s %(iterator_name)s.next(); + for node in node.body.nodes: + self._stmt(node, current_klass) + print >>self.output, """ + if (e.__name__ != pyjslib.StopIteration.__name__) { + def _while(self, node, current_klass): + test = self.expr(node.test, current_klass) + print >>self.output, " while (pyjslib.bool(" + test + ")) {" + if isinstance(node.body, ast.Stmt): + for child in node.body.nodes: + self._stmt(child, current_klass) + raise TranslationError("unsupported type (in _while)", node.body) + print >>self.output, " }" + def _const(self, node): + if isinstance(node.value, int): + elif isinstance(node.value, float): + elif isinstance(node.value, basestring): + if isinstance(node.value, unicode): + return "String('%s')" % escapejs(v) + elif node.value is None: + raise TranslationError("unsupported type (in _const)", node) + def _unaryadd(self, node, current_klass): + return self.expr(node.expr, current_klass) + def _unarysub(self, node, current_klass): + return "-" + self.expr(node.expr, current_klass) + def _add(self, node, current_klass): + return self.expr(node.left, current_klass) + " + " + self.expr(node.right, current_klass) + def _sub(self, node, current_klass): + return self.expr(node.left, current_klass) + " - " + self.expr(node.right, current_klass) + def _div(self, node, current_klass): + return self.expr(node.left, current_klass) + " / " + self.expr(node.right, current_klass) + def _mul(self, node, current_klass): + return self.expr(node.left, current_klass) + " * " + self.expr(node.right, current_klass) + def _mod(self, node, current_klass): + if isinstance(node.left, ast.Const) and isinstance(node.left.value, StringType): + self.imported_js.add("sprintf.js") # Include the sprintf functionality if it is used + return "sprintf("+self.expr(node.left, current_klass) + ", " + self.expr(node.right, current_klass)+")" + return self.expr(node.left, current_klass) + " % " + self.expr(node.right, current_klass) + def _invert(self, node, current_klass): + return "~" + self.expr(node.expr, current_klass) + def _bitand(self, node, current_klass): + return " & ".join([self.expr(child, current_klass) for child in node.nodes]) + def _bitshiftleft(self, node, current_klass): + return self.expr(node.left, current_klass) + " << " + self.expr(node.right, current_klass) + def _bitshiftright(self, node, current_klass): + return self.expr(node.left, current_klass) + " >>> " + self.expr(node.right, current_klass) + def _bitxor(self,node, current_klass): + return " ^ ".join([self.expr(child, current_klass) for child in node.nodes]) + def _bitor(self, node, current_klass): + return " | ".join([self.expr(child, current_klass) for child in node.nodes]) + def _subscript(self, node, current_klass): + if node.flags == "OP_APPLY": + if len(node.subs) == 1: + return self.expr(node.expr, current_klass) + ".__getitem__(" + self.expr(node.subs[0], current_klass) + ")" + raise TranslationError("must have one sub (in _subscript)", node) + raise TranslationError("unsupported flag (in _subscript)", node) + def _subscript_stmt(self, node, current_klass): + if node.flags == "OP_DELETE": + print >>self.output, " " + self.expr(node.expr, current_klass) + ".__delitem__(" + self.expr(node.subs[0], current_klass) + ");" + raise TranslationError("unsupported flag (in _subscript)", node) + def _list(self, node, current_klass): + return "new pyjslib.List([" + ", ".join([self.expr(x, current_klass) for x in node.nodes]) + "])" + def _dict(self, node, current_klass): + key = self.expr(x[0], current_klass) + value = self.expr(x[1], current_klass) + items.append("[" + key + ", " + value + "]") + return "new pyjslib.Dict([" + ", ".join(items) + "])" + def _tuple(self, node, current_klass): + return "new pyjslib.Tuple([" + ", ".join([self.expr(x, current_klass) for x in node.nodes]) + "])" + def _lambda(self, node, current_klass): + raise TranslationError("varargs are not supported in Lambdas", node) + raise TranslationError("kwargs are not supported in Lambdas", node) + res = cStringIO.StringIO() + arg_names = list(node.argnames) + function_args = ", ".join(arg_names) + for child in node.getChildNodes(): + expr = self.expr(child, None) + print >> res, "function (%s){" % function_args + self._default_args_handler(node, arg_names, None, + print >> res, 'return %s;}' % expr + def _slice(self, node, current_klass): + if node.flags == "OP_APPLY": + lower = self.expr(node.lower, current_klass) + upper = self.expr(node.upper, current_klass) + return "pyjslib.slice(" + self.expr(node.expr, current_klass) + ", " + lower + ", " + upper + ")" + raise TranslationError("unsupported flag (in _slice)", node) + def _global(self, node, current_klass): + for name in node.names: + self.method_imported_globals.add(name) + def expr(self, node, current_klass): + if isinstance(node, ast.Const): + return self._const(node) + # @@@ not sure if the parentheses should be here or in individual operator functions - JKT + elif isinstance(node, ast.Mul): + return " ( " + self._mul(node, current_klass) + " ) " + elif isinstance(node, ast.Add): + return " ( " + self._add(node, current_klass) + " ) " + elif isinstance(node, ast.Sub): + return " ( " + self._sub(node, current_klass) + " ) " + elif isinstance(node, ast.Div): + return " ( " + self._div(node, current_klass) + " ) " + elif isinstance(node, ast.Mod): + return self._mod(node, current_klass) + elif isinstance(node, ast.UnaryAdd): + return self._unaryadd(node, current_klass) + elif isinstance(node, ast.UnarySub): + return self._unarysub(node, current_klass) + elif isinstance(node, ast.Not): + return self._not(node, current_klass) + elif isinstance(node, ast.Or): + return self._or(node, current_klass) + elif isinstance(node, ast.And): + return self._and(node, current_klass) + elif isinstance(node, ast.Invert): + return self._invert(node, current_klass) + elif isinstance(node, ast.Bitand): + return "("+self._bitand(node, current_klass)+")" + elif isinstance(node,ast.LeftShift): + return self._bitshiftleft(node, current_klass) + elif isinstance(node, ast.RightShift): + return self._bitshiftright(node, current_klass) + elif isinstance(node, ast.Bitxor): + return "("+self._bitxor(node, current_klass)+")" + elif isinstance(node, ast.Bitor): + return "("+self._bitor(node, current_klass)+")" + elif isinstance(node, ast.Compare): + return self._compare(node, current_klass) + elif isinstance(node, ast.CallFunc): + return self._callfunc(node, current_klass) + elif isinstance(node, ast.Name): + return self._name(node, current_klass) + elif isinstance(node, ast.Subscript): + return self._subscript(node, current_klass) + elif isinstance(node, ast.Getattr): + return self._getattr(node, current_klass) + elif isinstance(node, ast.List): + return self._list(node, current_klass) + elif isinstance(node, ast.Dict): + return self._dict(node, current_klass) + elif isinstance(node, ast.Tuple): + return self._tuple(node, current_klass) + elif isinstance(node, ast.Slice): + return self._slice(node, current_klass) + elif isinstance(node, ast.Lambda): + return self._lambda(node, current_klass) + raise TranslationError("unsupported type (in expr)", node) +def translate(file_name, module_name, debug=False): + f = file(file_name, "r") + output = cStringIO.StringIO() + mod = compiler.parseFile(file_name) + t = Translator(module_name, module_name, module_name, src, debug, mod, output) + return output.getvalue() + def __init__(self, platform_dir = "", verbose=True): + self.platform_dir = platform_dir + def setPlatform(self, platform): + self.platform = platform + def parseModule(self, module_name, file_name): + if not self.parse_cache.has_key(file_name): + mod = compiler.parseFile(file_name) + self.parse_cache[file_name] = mod + mod = self.parse_cache[file_name] + platform_file_name = self.generatePlatformFilename(file_name) + if self.platform and os.path.isfile(platform_file_name): + mod = copy.deepcopy(mod) + mod_override = compiler.parseFile(platform_file_name) + self.merge(mod, mod_override) + print "Importing %s (Platform %s)" % (module_name, self.platform) + print "Importing %s" % (module_name) + def generatePlatformFilename(self, file_name): + (module_name, extension) = os.path.splitext(os.path.basename(file_name)) + platform_file_name = module_name + self.platform + extension + return os.path.join(os.path.dirname(file_name), self.platform_dir, platform_file_name) + def merge(self, tree1, tree2): + for child in tree2.node: + if isinstance(child, ast.Function): + self.replaceFunction(tree1, child.name, child) + elif isinstance(child, ast.Class): + self.replaceClassMethods(tree1, child.name, child) + def replaceFunction(self, tree, function_name, function_node): + # find function to replace + for child in tree.node: + if isinstance(child, ast.Function) and child.name == function_name: + self.copyFunction(child, function_node) + raise TranslationError("function not found: " + function_name, function_node) + def replaceClassMethods(self, tree, class_name, class_node): + # find class to replace + for child in tree.node: + if isinstance(child, ast.Class) and child.name == class_name: + raise TranslationError("class not found: " + class_name, class_node) + for function_node in class_node.code: + if isinstance(function_node, ast.Function): + for child in old_class_node.code: + if isinstance(child, ast.Function) and child.name == function_node.name: + self.copyFunction(child, function_node) + raise TranslationError("class method not found: " + class_name + "." + function_node.name, function_node) + def copyFunction(self, target, source): + target.code = source.code + target.argnames = source.argnames + target.defaults = source.defaults + target.doc = source.doc # @@@ not sure we need to do this any more + path, ext = os.path.splitext(fname) + return path.replace(".", "/") + ext + def __init__(self, library_dirs=[], parser=None, dynamic=False, + optimize=False, verbose=True): + self.optimize = optimize + self.library_modules = [] + self.library_dirs = path + library_dirs + self.parser = PlatformParser() + self.parser.dynamic = dynamic + def findFile(self, file_name): + if os.path.isfile(file_name): + for library_dir in self.library_dirs: + file_name = dotreplace(file_name) + full_file_name = os.path.join( + os.path.abspath(os.path.dirname(__file__)), library_dir, file_name) + if os.path.isfile(full_file_name): + fnameinit, ext = os.path.splitext(file_name) + fnameinit = fnameinit + "/__init__.py" + full_file_name = os.path.join( + os.path.abspath(os.path.dirname(__file__)), library_dir, fnameinit) + if os.path.isfile(full_file_name): + raise Exception("file not found: " + file_name) + def _translate(self, module_name, is_app=True, debug=False, + if module_name not in self.library_modules: + self.library_modules.append(module_name) + file_name = self.findFile(module_name + self.extension) + output = cStringIO.StringIO() + f = file(file_name, "r") + mod, override = self.parser.parseModule(module_name, file_name) + override_name = "%s.%s" % (self.parser.platform.lower(), + self.overrides[override_name] = override_name + t = Translator(mn, module_name, module_name, + src, debug, mod, output, self.dynamic, self.optimize, + module_str = output.getvalue() + imported_js.update(set(t.imported_js)) + imported_modules_str = "" + for module in t.imported_modules: + if module not in self.library_modules: + self.library_modules.append(module) + #imported_js.update(set(t.imported_js)) + #imported_modules_str += self._translate( + # module, False, debug=debug, imported_js=imported_js) + return imported_modules_str + module_str + def translate(self, module_name, is_app=True, debug=False, + app_code = cStringIO.StringIO() + lib_code = cStringIO.StringIO() + self.library_modules = [] + for library in library_modules: + if library.endswith(".js"): + imported_js.add(library) + self.library_modules.append(library) + print 'Including LIB', library + print >> lib_code, '\n//\n// BEGIN LIB '+library+'\n//\n' + print >> lib_code, self._translate( + library, False, debug=debug, imported_js=imported_js) + print >> lib_code, "/* initialize static library */" + print >> lib_code, "%s%s();\n" % (UU, library) + print >> lib_code, '\n//\n// END LIB '+library+'\n//\n' + print >> app_code, self._translate( + module_name, is_app, debug=debug, imported_js=imported_js) + path = self.findFile(js) + if os.path.isfile(path): + print 'Including JS', js + print >> lib_code, '\n//\n// BEGIN JS '+js+'\n//\n' + print >> lib_code, file(path).read() + print >> lib_code, '\n//\n// END JS '+js+'\n//\n' + print >>sys.stderr, 'Warning: Unable to find imported javascript:', js + return lib_code.getvalue(), app_code.getvalue() + usage: %s file_name [module_name] + print >> sys.stderr, usage % sys.argv[0] + file_name = os.path.abspath(sys.argv[1]) + if not os.path.isfile(file_name): + print >> sys.stderr, "File not found %s" % file_name + module_name = sys.argv[2] + print translate(file_name, module_name), +if __name__ == "__main__": --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/svgui/svgui.py Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,116 @@
+from pyjs import translate +from POULibrary import POULibrary +class SVGUILibrary(POULibrary): + def GetLibraryPath(self): + return os.path.join(os.path.split(__file__)[0], "pous.xml") + {"bitmap" : os.path.join("images","ImportSVG"), + "name" : _("Import SVG"), + "tooltip" : _("Import SVG"), + "method" : "_ImportSVG"}, + {"bitmap" : os.path.join("images","ImportSVG"), + "name" : _("Inkscape"), + "tooltip" : _("Create HMI"), + "method" : "_StartInkscape"}, + def ConfNodePath(self): + return os.path.join(os.path.dirname(__file__)) + # define name for IEC raw code file + return os.path.join(self.CTNPath(), "gui.svg") + def _getSVGUIserverpath(self): + return os.path.join(os.path.dirname(__file__), "svgui_server.py") + def CTNGenerate_C(self, buildpath, locations): + Return C code generated by iec2c compiler + when _generate_softPLC have been called + @param locations: ignored + @return: [(C_file_name, CFLAGS),...] , LDFLAGS_TO_APPEND + current_location = self.GetCurrentLocation() + # define a unique name for the generated C file + location_str = "_".join(map(lambda x:str(x), current_location)) + svgfile=self._getSVGpath() + if os.path.exists(svgfile): + res += (("gui.svg", file(svgfile,"rb")),) + svguiserverfile = open(self._getSVGUIserverpath(), 'r') + svguiservercode = svguiserverfile.read() + svguiserverfile.close() + svguilibpath = os.path.join(self._getBuildPath(), "svguilib.js") + svguilibfile = open(svguilibpath, 'w') + svguilibfile.write(translate(os.path.join(os.path.dirname(__file__), "pyjs", "lib", "sys.py"), "sys")) + svguilibfile.write(open(os.path.join(os.path.dirname(__file__), "pyjs", "lib", "_pyjs.js"), 'r').read()) + svguilibfile.write(translate(os.path.join(os.path.dirname(__file__), "pyjs", "lib", "pyjslib.py"), "pyjslib")) + svguilibfile.write(translate(os.path.join(os.path.dirname(__file__), "svguilib.py"), "svguilib")) + svguilibfile.write("pyjslib();\nsvguilib();\n") + svguilibfile.write(open(os.path.join(os.path.dirname(__file__), "pyjs", "lib", "json.js"), 'r').read()) + svguilibfile.write(open(os.path.join(os.path.dirname(__file__), "livesvg.js"), 'r').read()) + jsmodules = {"LiveSVGPage": "svguilib.js"} + res += (("svguilib.js", file(svguilibpath,"rb")),) + runtimefile_path = os.path.join(buildpath, "runtime_%s.py"%location_str) + runtimefile = open(runtimefile_path, 'w') + runtimefile.write(svguiservercode % {"svgfile" : "gui.svg"}) +def _runtime_%(location)s_begin(): + website.LoadHMI(%(svgui_class)s, %(jsmodules)s) +def _runtime_%(location)s_cleanup(): +""" % {"location": location_str, + "svgui_class": "SVGUI_HMI", + "jsmodules" : str(jsmodules), + res += (("runtime_%s.py"%location_str, file(runtimefile_path,"rb")),) + dialog = wx.FileDialog(self.GetCTRoot().AppFrame, _("Choose a SVG file"), os.getcwd(), "", _("SVG files (*.svg)|*.svg|All files|*.*"), wx.OPEN) + if dialog.ShowModal() == wx.ID_OK: + svgpath = dialog.GetPath() + if os.path.isfile(svgpath): + shutil.copy(svgpath, self._getSVGpath()) + self.GetCTRoot().logger.write_error(_("No such SVG file: %s\n")%svgpath) + def _StartInkscape(self): + svgfile = self._getSVGpath() + if not self.GetCTRoot().CheckProjectPathPerm(): + dialog = wx.MessageDialog(self.GetCTRoot().AppFrame, + _("You don't have write permissions.\nOpen Inkscape anyway ?"), + wx.YES_NO|wx.ICON_QUESTION) + open_inkscape = dialog.ShowModal() == wx.ID_YES + if not os.path.isfile(svgfile): --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/svgui/svgui_server.py Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,130 @@
+from nevow import rend, appserver, inevow, tags, loaders, athena +import simplejson as json + def __init__(self, classname, id, **kwargs): + self.classname = classname + self.attrs = kwargs.copy() + def setinput(self, attrname, value): + self.inputs[attrname] = value + def getinput(self, attrname, default=None): + if not self.inputs.has_key(attrname): + self.inputs[attrname] = default + return self.inputs[attrname] + def setoutput(self, attrname, value): + if self.outputs.get(attrname) != value: + self.outputs[attrname] = value + self.RefreshInterface() + def updateoutputs(self, **kwargs): + for attrname, value in kwargs.iteritems(): + if self.outputs.get(attrname) != value: + self.outputs[attrname] = value + self.RefreshInterface() + def RefreshInterface(self): + interface = website.getHMI() + if isinstance(interface, SVGUI_HMI) and self.changed and not self.inhibit: + d = interface.sendData(self) + d.addCallback(self.InterfaceRefreshed) + def InterfaceRefreshed(self, result): + self.RefreshInterface() +def get_object_init_state(obj): + # Convert objects to a dictionary of their representation + attrs = obj.attrs.copy() + attrs.update(obj.inputs) + d = { '__class__': obj.classname, + 'kwargs': json.dumps(attrs), +def get_object_current_state(obj): + # Convert objects to a dictionary of their representation + d = { '__class__': obj.classname, + 'kwargs': json.dumps(obj.outputs), +class SVGUI_HMI(website.PLCHMI): + jsClass = u"LiveSVGPage.LiveSVGWidget" + docFactory = loaders.stan(tags.div(render=tags.directive('liveElement'))[ + tags.xml(loaders.xmlfile(os.path.join(WorkingDir, svgfile))), + def HMIinitialisation(self): + for gadget in svguiWidgets.values(): + gadgets.append(unicode(json.dumps(gadget, default=get_object_init_state, indent=2), 'ascii')) + d = self.callRemote('init', gadgets) + d.addCallback(self.HMIinitialised) + def sendData(self,data): + return self.callRemote('receiveData',unicode(json.dumps(data, default=get_object_current_state, indent=2), 'ascii')) + def setattr(self, id, attrname, value): + svguiWidgets[id].setinput(attrname, value) +def createSVGUIControl(*args, **kwargs): + gad = SvguiWidget(args[0], id, **kwargs) + gadget = [unicode(json.dumps(gad, default=get_object_init_state, indent=2), 'ascii')] + interface = website.getHMI() + if isinstance(interface, SVGUI_HMI) and interface.initialised: + interface.callRemote('init', gadget) +def setAttr(id, attrname, value): + gad = svguiWidgets.get(id, None) + gad.setoutput(attrname, value) +def updateAttr(id, **kwargs): + gad = svguiWidgets.get(id, None) + gad.updateoutput(**kwargs) +def getAttr(id, attrname, default=None): + gad = svguiWidgets.get(id, None) + return gad.getinput(attrname, default) --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/svgui/svguilib.py Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,117 @@
+ def __init__(self, parent, id, args): + self.back_elt = getSVGElementById(args.back_id) + self.sele_elt = getSVGElementById(args.sele_id) + self.toggle = args.toggle + self.active = args.active + if args.state != undefined: + self.state = args.state + self.up = not self.state + # Add event on each element of the button + self.back_elt.addEventListener("mouseup", self, False) + self.back_elt.addEventListener("mousedown", self, False) + self.back_elt.addEventListener("mouseover", self, False) + self.back_elt.addEventListener("mouseout", self, False) + self.sele_elt.addEventListener("mouseup", self, False) + self.sele_elt.addEventListener("mousedown", self, False) + self.sele_elt.addEventListener("mouseover", self, False) + self.sele_elt.addEventListener("mouseout", self, False) + blockSVGElementDrag(self.back_elt) + blockSVGElementDrag(self.sele_elt) + # method to display the current state of interface + def updateElements(self): + self.sele_elt.setAttribute("display", "none") + self.back_elt.removeAttribute("display") + self.sele_elt.removeAttribute("display") + self.back_elt.setAttribute("display", "none") + def updateValues(self, values): + if values.state != self.state: + self.state = values.state + self.up = not self.state + updateAttr(self.id, 'state', self.state) + def handleEvent(self, evt): + # Quand le bouton de la souris est presse + if evt.type == "mousedown": + updateAttr(self.id, 'state', self.state) + if isCurrentObject(self) and self.dragging: + # Quand le bouton est survole + if evt.type == "mouseover" and self.toggle: + # Quand le curseur quitte la zone du bouton + elif evt.type == "mouseout" and self.toggle: + self.up = not self.state + # Quand le bouton de la souris est relache + elif evt.type == "mouseup": + if self.toggle and self.up == self.state: + self.state = not self.state + updateAttr(self.id, 'state', self.state) + updateAttr(self.id, 'state', self.state) + def __init__(self, parent, id, args): + self.back_elt = getSVGElementById(args.back_id) + if args.text != undefined: + def updateValues(self, values): + if values.text != self.value: + self.text = values.text + updateAttr(self.id, 'text', self.text) + def updateElements(self): + self.back_elt.firstChild.firstChild.textContent = self.text + def handleEvent(self, evt): \ No newline at end of file
--- a/targets/toolchain_gcc.py Wed May 09 00:39:54 2012 +0200
+++ b/targets/toolchain_gcc.py Sat May 12 11:21:10 2012 +0200
@@ -100,10 +100,11 @@
for Location, CFilesAndCFLAGS, DoCalls in self.CTRInstance.LocationCFilesAndCFLAGS:
- self.CTRInstance.logger.write(_("ConfNode : ") + self.CTRInstance.GetChildByIECLocation(Location).GetCurrentName() + " " + str(Location)+"\n")
- self.CTRInstance.logger.write(_("PLC :\n"))
+ self.CTRInstance.logger.write(".".join(map(str,Location))+" :\n") + self.CTRInstance.logger.write(_("PLC :\n")) for CFile, CFLAGS in CFilesAndCFLAGS:
--- a/tests/python/beremiz.xml Wed May 09 00:39:54 2012 +0200
+++ b/tests/python/beremiz.xml Sat May 12 11:21:10 2012 +0200
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<BeremizRoot URI_location="LOCAL://">
+<?xml version="1.0" encoding="UTF-8"?> +<BeremizRoot URI_location="LOCAL://" Enable_SVGUILibrary="false"> --- a/tests/python/plc.xml Wed May 09 00:39:54 2012 +0200
+++ b/tests/python/plc.xml Sat May 12 11:21:10 2012 +0200
@@ -8,7 +8,7 @@
creationDateTime="2008-12-14T16:21:19"/>
<contentHeader name="Beremiz Python Support Tests"
- modificationDateTime="2009-12-06T12:55:54">
+ modificationDateTime="2012-05-12T10:42:17"> <pageSize x="1024" y="1024"/>
--- a/tests/python/python@py_ext/py_ext.xml Wed May 09 00:39:54 2012 +0200
+++ b/tests/python/python@py_ext/py_ext.xml Sat May 12 11:21:10 2012 +0200
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<Python xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.w3.org/2001/XMLSchema" xsi:schemaLocation="python_xsd.xsd">
+<Python xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.w3.org/2001/XMLSchema" xsi:schemaLocation="py_ext_xsd.xsd"> --- a/tests/svgui/python@py_ext/baseconfnode.xml Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,2 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<BaseParams Name="python" IEC_Channel="0"/>
--- a/tests/svgui/python@py_ext/py_ext.xml Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,8 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<Python xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.w3.org/2001/XMLSchema" xsi:schemaLocation="python_xsd.xsd">
-<![CDATA[import time,sys
--- a/tests/svgui/python@py_ext/svgui@svgui/baseconfnode.xml Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,2 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<BaseParams Name="svgui" IEC_Channel="0"/>
--- a/tests/svgui/python@py_ext/svgui@svgui/gui.svg Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,723 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<!-- Created with Inkscape (http://www.inkscape.org/) -->
- xmlns:dc="http://purl.org/dc/elements/1.1/"
- xmlns:cc="http://creativecommons.org/ns#"
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:svg="http://www.w3.org/2000/svg"
- xmlns="http://www.w3.org/2000/svg"
- xmlns:xlink="http://www.w3.org/1999/xlink"
- xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
- xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
- sodipodi:version="0.32"
- inkscape:version="0.47pre4 "
- sodipodi:docname="gui.svg"
- inkscape:output_extension="org.inkscape.output.svg.inkscape">
- inkscape:pageopacity="0.0"
- inkscape:pageshadow="2"
- inkscape:cx="200.66323"
- inkscape:cy="178.08292"
- inkscape:document-units="px"
- inkscape:current-layer="layer1"
- inkscape:window-width="1071"
- inkscape:window-height="805"
- inkscape:window-x="106"
- inkscape:window-maximized="0" />
- id="linearGradient3770">
- style="stop-color:#008000;stop-opacity:1;"
- style="stop-color:#00fb00;stop-opacity:1;"
- id="linearGradient3708">
- style="stop-color:#d40000;stop-opacity:1;"
- style="stop-color:#ff5c5c;stop-opacity:1;"
- id="linearGradient4202">
- style="stop-color:#f6edda;stop-opacity:1;" />
- style="stop-color:#e6e6e6;stop-opacity:1;" />
- id="linearGradient4192">
- style="stop-color:#faf4e9;stop-opacity:1;"
- style="stop-color:#f1f1f1;stop-opacity:1;"
- id="linearGradient3302">
- style="stop-color:#ff0000;stop-opacity:0;"
- style="stop-color:#ff0000;stop-opacity:0.49803922;" />
- style="stop-color:#ff0000;stop-opacity:1;"
- style="stop-color:#ff0000;stop-opacity:0;"
- id="linearGradient3687">
- style="stop-color:#23d5ff;stop-opacity:1;" />
- style="stop-color:#b1ffff;stop-opacity:1;" />
- id="linearGradient3679">
- style="stop-color:#00b5ff;stop-opacity:1;" />
- style="stop-color:#005bff;stop-opacity:1;" />
- id="linearGradient3659">
- style="stop-color:#ff0030;stop-opacity:1;" />
- style="stop-color:#e20000;stop-opacity:0.83211678;"
- style="stop-color:#ffffff;stop-opacity:0;" />
- id="linearGradient3639">
- style="stop-color:#ffff00;stop-opacity:1;" />
- style="stop-color:#8fff00;stop-opacity:0.49803922;"
- style="stop-color:#ffffff;stop-opacity:0;" />
- id="linearGradient3621">
- style="stop-color:#ff8080;stop-opacity:1;" />
- style="stop-color:#aa0000;stop-opacity:1;" />
- id="linearGradient3613"
- inkscape:collect="always">
- style="stop-color:#000000;stop-opacity:1;" />
- style="stop-color:#000000;stop-opacity:0;" />
- id="linearGradient3497">
- style="stop-color:#00cd00;stop-opacity:1;" />
- style="stop-color:#007900;stop-opacity:1;" />
- id="linearGradient3453">
- style="stop-color:#000000;stop-opacity:1;" />
- style="stop-color:#ffffff;stop-opacity:0;" />
- id="linearGradient3173">
- style="stop-color:#ffffff;stop-opacity:1;"
- style="stop-color:#ffffff;stop-opacity:0;" />
- style="stop-color:#ff0000;stop-opacity:0;"
- sodipodi:type="inkscape:persp3d"
- inkscape:vp_x="0 : 526.18109 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_z="744.09448 : 526.18109 : 1"
- inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
- sodipodi:type="inkscape:persp3d"
- inkscape:vp_x="0 : 526.18109 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_z="744.09448 : 526.18109 : 1"
- inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
- id="perspective2619" />
- gradientUnits="userSpaceOnUse"
- id="linearGradient3503"
- xlink:href="#linearGradient3497"
- inkscape:collect="always" />
- gradientUnits="userSpaceOnUse"
- id="linearGradient3619"
- xlink:href="#linearGradient3613"
- inkscape:collect="always" />
- gradientUnits="userSpaceOnUse"
- id="linearGradient3627"
- xlink:href="#linearGradient3621"
- inkscape:collect="always" />
- gradientTransform="translate(-18,26)"
- gradientUnits="userSpaceOnUse"
- id="linearGradient3633"
- xlink:href="#linearGradient3621"
- inkscape:collect="always" />
- gradientUnits="userSpaceOnUse"
- id="radialGradient3667"
- xlink:href="#linearGradient3639"
- inkscape:collect="always" />
- gradientUnits="userSpaceOnUse"
- id="radialGradient3675"
- xlink:href="#linearGradient3659"
- inkscape:collect="always" />
- gradientTransform="translate(-1.3119965,1.110878)"
- gradientUnits="userSpaceOnUse"
- id="linearGradient3693"
- xlink:href="#linearGradient3687"
- inkscape:collect="always" />
- gradientUnits="userSpaceOnUse"
- id="linearGradient3702"
- xlink:href="#linearGradient4202"
- inkscape:collect="always" />
- gradientTransform="translate(-1.3119965,1.110878)"
- gradientUnits="userSpaceOnUse"
- id="linearGradient3704"
- xlink:href="#linearGradient3613"
- inkscape:collect="always" />
- sodipodi:type="inkscape:persp3d"
- inkscape:vp_x="0 : 526.18109 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_z="744.09448 : 526.18109 : 1"
- inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
- id="perspective3767" />
- inkscape:collect="always"
- xlink:href="#linearGradient3302"
- id="linearGradient3308"
- gradientUnits="userSpaceOnUse"
- gradientTransform="translate(-25.178571,-3.0357143)" />
- inkscape:collect="always"
- xlink:href="#linearGradient3613"
- id="linearGradient3536"
- gradientUnits="userSpaceOnUse"
- gradientTransform="translate(5.555838,16.162441)"
- inkscape:collect="always"
- xlink:href="#linearGradient3613"
- id="linearGradient3538"
- gradientUnits="userSpaceOnUse"
- gradientTransform="translate(5.555838,16.162441)"
- inkscape:collect="always"
- xlink:href="#linearGradient3613"
- id="linearGradient3540"
- gradientUnits="userSpaceOnUse"
- gradientTransform="translate(5.555838,16.162441)"
- inkscape:collect="always"
- xlink:href="#linearGradient3613"
- id="linearGradient3542"
- gradientUnits="userSpaceOnUse"
- gradientTransform="translate(5.555838,16.162441)"
- inkscape:collect="always"
- xlink:href="#linearGradient3613"
- id="linearGradient3544"
- gradientUnits="userSpaceOnUse"
- gradientTransform="translate(5.555838,16.162441)"
- inkscape:collect="always"
- xlink:href="#linearGradient3613"
- id="linearGradient3546"
- gradientUnits="userSpaceOnUse"
- gradientTransform="translate(5.555838,16.162441)"
- inkscape:collect="always"
- xlink:href="#linearGradient3613"
- id="linearGradient3548"
- gradientUnits="userSpaceOnUse"
- gradientTransform="translate(5.555838,16.162441)"
- inkscape:collect="always"
- xlink:href="#linearGradient3613"
- id="linearGradient3550"
- gradientUnits="userSpaceOnUse"
- gradientTransform="translate(5.555838,16.162441)"
- inkscape:collect="always"
- xlink:href="#linearGradient3613"
- id="linearGradient3694"
- gradientUnits="userSpaceOnUse"
- gradientTransform="translate(-381.09403,-544.64978)"
- inkscape:collect="always"
- xlink:href="#linearGradient3613"
- id="linearGradient3696"
- gradientUnits="userSpaceOnUse"
- gradientTransform="translate(-381.09403,-544.64978)"
- inkscape:collect="always"
- xlink:href="#linearGradient3613"
- id="linearGradient3698"
- gradientUnits="userSpaceOnUse"
- gradientTransform="translate(-381.09403,-544.64978)"
- inkscape:collect="always"
- xlink:href="#linearGradient3613"
- id="linearGradient3700"
- gradientUnits="userSpaceOnUse"
- gradientTransform="translate(-381.09403,-544.64978)"
- inkscape:collect="always"
- xlink:href="#linearGradient3613"
- id="linearGradient3703"
- gradientUnits="userSpaceOnUse"
- gradientTransform="translate(-381.09403,-544.64978)"
- inkscape:collect="always"
- xlink:href="#linearGradient3613"
- id="linearGradient3705"
- gradientUnits="userSpaceOnUse"
- gradientTransform="translate(-381.09403,-544.64978)"
- inkscape:collect="always"
- xlink:href="#linearGradient3613"
- id="linearGradient3707"
- gradientUnits="userSpaceOnUse"
- gradientTransform="translate(-381.09403,-544.64978)"
- inkscape:collect="always"
- xlink:href="#linearGradient3613"
- id="linearGradient3709"
- gradientUnits="userSpaceOnUse"
- gradientTransform="translate(-381.09403,-544.64978)"
- inkscape:collect="always"
- xlink:href="#linearGradient4192"
- id="linearGradient4200"
- gradientUnits="userSpaceOnUse" />
- inkscape:persp3d-origin="0.5 : 0.33333333 : 1"
- inkscape:vp_z="1 : 0.5 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_x="0 : 0.5 : 1"
- sodipodi:type="inkscape:persp3d" />
- inkscape:collect="always"
- xlink:href="#linearGradient3708"
- id="linearGradient3714"
- gradientUnits="userSpaceOnUse" />
- inkscape:collect="always"
- xlink:href="#linearGradient3708"
- id="linearGradient3722"
- gradientUnits="userSpaceOnUse" />
- inkscape:persp3d-origin="0.5 : 0.33333333 : 1"
- inkscape:vp_z="1 : 0.5 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_x="0 : 0.5 : 1"
- sodipodi:type="inkscape:persp3d" />
- inkscape:persp3d-origin="0.5 : 0.33333333 : 1"
- inkscape:vp_z="1 : 0.5 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_x="0 : 0.5 : 1"
- sodipodi:type="inkscape:persp3d" />
- inkscape:collect="always"
- xlink:href="#linearGradient3770"
- id="linearGradient3776"
- gradientUnits="userSpaceOnUse" />
- inkscape:collect="always"
- xlink:href="#linearGradient3770"
- id="linearGradient3784"
- gradientUnits="userSpaceOnUse" />
- inkscape:collect="always"
- xlink:href="#linearGradient3621"
- id="radialGradient3792"
- gradientUnits="userSpaceOnUse" />
- inkscape:collect="always"
- xlink:href="#linearGradient3497"
- id="radialGradient3800"
- gradientUnits="userSpaceOnUse" />
- <dc:format>image/svg+xml</dc:format>
- rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
- inkscape:label="Calque 1"
- inkscape:groupmode="layer"
- style="display:inline">
- style="fill:url(#linearGradient4200);fill-opacity:1;stroke:#000000;stroke-width:1.46953177;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" />
- transform="translate(-127.27923,-40.406102)"
- style="fill:url(#linearGradient3702);fill-opacity:1;stroke:#000000;stroke-width:1;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:1, 2;stroke-dashoffset:0"
- sodipodi:linespacing="125%"
- style="font-size:36px;font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;text-indent:0;text-align:start;text-decoration:none;line-height:125%;letter-spacing:normal;word-spacing:normal;text-transform:none;direction:ltr;block-progression:tb;writing-mode:lr-tb;text-anchor:start;fill:#655fdb;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:1px;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate;font-family:DejaVu Sans;-inkscape-font-specification:DejaVu Sans Bold"
- xml:space="preserve"><tspan
- style="font-size:36px;font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;text-align:start;line-height:125%;writing-mode:lr-tb;text-anchor:start;fill:#655fdb;fill-opacity:1;stroke:none;font-family:DejaVu Sans;-inkscape-font-specification:DejaVu Sans Bold">Default</tspan></text>
- transform="translate(-33.11078,95.2077)">
- style="color:#000000;fill:url(#linearGradient3776);fill-opacity:1;fill-rule:nonzero;stroke:url(#linearGradient3784);stroke-width:3.80890393;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate"
- sodipodi:cx="103.21429"
- sodipodi:cy="127.14286"
- sodipodi:r1="91.508057"
- sodipodi:r2="45.754028"
- sodipodi:arg2="1.0471976"
- inkscape:flatsided="true"
- inkscape:randomized="0"
- d="m 194.72234,127.14286 -137.262082,79.2483 0,-158.496601 137.262082,79.248301 z"
- transform="matrix(0.78762818,0,0,0.78762818,26.492161,-44.168468)" />
- sodipodi:linespacing="100%"
- style="font-size:36px;font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;text-indent:0;text-align:end;text-decoration:none;line-height:100%;letter-spacing:normal;word-spacing:normal;text-transform:none;direction:ltr;block-progression:tb;writing-mode:lr-tb;text-anchor:end;color:#000000;fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:1px;marker:none;visibility:inherit;display:inline;overflow:visible;enable-background:accumulate;font-family:DejaVu Sans;-inkscape-font-specification:DejaVu Sans Bold"
- xml:space="preserve"><tspan
- style="font-size:36px;font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;text-indent:0;text-align:end;text-decoration:none;line-height:100%;letter-spacing:normal;word-spacing:normal;text-transform:none;direction:ltr;block-progression:tb;writing-mode:lr-tb;text-anchor:end;color:#000000;fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:1px;marker:none;visibility:inherit;display:inline;overflow:visible;enable-background:accumulate;font-family:DejaVu Sans;-inkscape-font-specification:DejaVu Sans Bold"
- sodipodi:role="line">Start</tspan></text>
- transform="translate(-18.07106,94.06456)"
- style="color:#000000;fill:url(#linearGradient3714);fill-opacity:1;fill-rule:nonzero;stroke:url(#linearGradient3722);stroke-width:3.94511151;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate"
- sodipodi:cx="83.571426"
- sodipodi:cy="224.28571"
- sodipodi:r1="94.724358"
- sodipodi:r2="87.513893"
- sodipodi:arg2="0.39269908"
- inkscape:flatsided="true"
- inkscape:randomized="0"
- d="m 178.29578,224.28571 -27.74412,66.98023 -66.980234,27.74412 -66.980235,-27.74412 -27.744122,-66.98023 27.744122,-66.98024 66.980235,-27.74412 66.980234,27.74412 27.74412,66.98024 z"
- transform="matrix(0.70255013,-0.29100577,0.29100577,0.70255013,-13.216048,-76.13621)" />
- sodipodi:linespacing="100%"
- style="font-size:36px;font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;text-indent:0;text-align:end;text-decoration:none;line-height:100%;letter-spacing:normal;word-spacing:normal;text-transform:none;direction:ltr;block-progression:tb;writing-mode:lr-tb;text-anchor:end;fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:1px;marker:none;visibility:inherit;display:inline;overflow:visible;enable-background:accumulate;font-family:DejaVu Sans;-inkscape-font-specification:DejaVu Sans Bold"
- xml:space="preserve"><tspan
- style="font-size:36px;font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;text-align:end;line-height:100%;writing-mode:lr-tb;text-anchor:end;fill:#ffffff;fill-opacity:1;stroke:none;font-family:DejaVu Sans;-inkscape-font-specification:DejaVu Sans Bold"
- sodipodi:role="line">Stop</tspan></text>
- transform="matrix(2.0899173,0,0,2.0899173,-577.84265,-204.88668)"
- transform="translate(42.282829,64.376725)"
- d="m 369.71585,101.69787 a 17.67767,17.67767 0 1 1 -35.35534,0 17.67767,17.67767 0 1 1 35.35534,0 z"
- sodipodi:cy="101.69787"
- sodipodi:cx="352.03818"
- style="fill:url(#radialGradient3800);fill-opacity:1;stroke:#000000;stroke-width:0.47848782;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- transform="matrix(2.0899173,0,0,2.0899173,-637.08625,-59.866062)"
- style="fill:url(#radialGradient3792);fill-opacity:1;stroke:#000000;stroke-width:0.47848782;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- sodipodi:cx="352.03818"
- sodipodi:cy="101.69787"
- d="m 369.71585,101.69787 a 17.67767,17.67767 0 1 1 -35.35534,0 17.67767,17.67767 0 1 1 35.35534,0 z"
- transform="translate(70.630181,-5.0138784)" />
--- a/tests/svgui/python@py_ext/svgui@svgui/py_ext.xml Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,4 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<Python xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.w3.org/2001/XMLSchema" xsi:schemaLocation="python_xsd.xsd">
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/tests/svgui/svgui@svgui/baseconfnode.xml Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8"?> +<BaseParams Name="svgui" IEC_Channel="0"/> --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/tests/svgui/svgui@svgui/gui.svg Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,723 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<!-- Created with Inkscape (http://www.inkscape.org/) --> + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:xlink="http://www.w3.org/1999/xlink" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + sodipodi:version="0.32" + inkscape:version="0.47pre4 " + sodipodi:docname="gui.svg" + inkscape:output_extension="org.inkscape.output.svg.inkscape"> + inkscape:pageopacity="0.0" + inkscape:pageshadow="2" + inkscape:cx="200.66323" + inkscape:cy="178.08292" + inkscape:document-units="px" + inkscape:current-layer="layer1" + inkscape:window-width="1071" + inkscape:window-height="805" + inkscape:window-x="106" + inkscape:window-maximized="0" /> + id="linearGradient3770"> + style="stop-color:#008000;stop-opacity:1;" + style="stop-color:#00fb00;stop-opacity:1;" + id="linearGradient3708"> + style="stop-color:#d40000;stop-opacity:1;" + style="stop-color:#ff5c5c;stop-opacity:1;" + id="linearGradient4202"> + style="stop-color:#f6edda;stop-opacity:1;" /> + style="stop-color:#e6e6e6;stop-opacity:1;" /> + id="linearGradient4192"> + style="stop-color:#faf4e9;stop-opacity:1;" + style="stop-color:#f1f1f1;stop-opacity:1;" + id="linearGradient3302"> + style="stop-color:#ff0000;stop-opacity:0;" + style="stop-color:#ff0000;stop-opacity:0.49803922;" /> + style="stop-color:#ff0000;stop-opacity:1;" + style="stop-color:#ff0000;stop-opacity:0;" + id="linearGradient3687"> + style="stop-color:#23d5ff;stop-opacity:1;" /> + style="stop-color:#b1ffff;stop-opacity:1;" /> + id="linearGradient3679"> + style="stop-color:#00b5ff;stop-opacity:1;" /> + style="stop-color:#005bff;stop-opacity:1;" /> + id="linearGradient3659"> + style="stop-color:#ff0030;stop-opacity:1;" /> + style="stop-color:#e20000;stop-opacity:0.83211678;" + style="stop-color:#ffffff;stop-opacity:0;" /> + id="linearGradient3639"> + style="stop-color:#ffff00;stop-opacity:1;" /> + style="stop-color:#8fff00;stop-opacity:0.49803922;" + style="stop-color:#ffffff;stop-opacity:0;" /> + id="linearGradient3621"> + style="stop-color:#ff8080;stop-opacity:1;" /> + style="stop-color:#aa0000;stop-opacity:1;" /> + id="linearGradient3613" + inkscape:collect="always"> + style="stop-color:#000000;stop-opacity:1;" /> + style="stop-color:#000000;stop-opacity:0;" /> + id="linearGradient3497"> + style="stop-color:#00cd00;stop-opacity:1;" /> + style="stop-color:#007900;stop-opacity:1;" /> + id="linearGradient3453"> + style="stop-color:#000000;stop-opacity:1;" /> + style="stop-color:#ffffff;stop-opacity:0;" /> + id="linearGradient3173"> + style="stop-color:#ffffff;stop-opacity:1;" + style="stop-color:#ffffff;stop-opacity:0;" /> + style="stop-color:#ff0000;stop-opacity:0;" + sodipodi:type="inkscape:persp3d" + inkscape:vp_x="0 : 526.18109 : 1" + inkscape:vp_y="0 : 1000 : 0" + inkscape:vp_z="744.09448 : 526.18109 : 1" + inkscape:persp3d-origin="372.04724 : 350.78739 : 1" + sodipodi:type="inkscape:persp3d" + inkscape:vp_x="0 : 526.18109 : 1" + inkscape:vp_y="0 : 1000 : 0" + inkscape:vp_z="744.09448 : 526.18109 : 1" + inkscape:persp3d-origin="372.04724 : 350.78739 : 1" + id="perspective2619" /> + gradientUnits="userSpaceOnUse" + id="linearGradient3503" + xlink:href="#linearGradient3497" + inkscape:collect="always" /> + gradientUnits="userSpaceOnUse" + id="linearGradient3619" + xlink:href="#linearGradient3613" + inkscape:collect="always" /> + gradientUnits="userSpaceOnUse" + id="linearGradient3627" + xlink:href="#linearGradient3621" + inkscape:collect="always" /> + gradientTransform="translate(-18,26)" + gradientUnits="userSpaceOnUse" + id="linearGradient3633" + xlink:href="#linearGradient3621" + inkscape:collect="always" /> + gradientUnits="userSpaceOnUse" + id="radialGradient3667" + xlink:href="#linearGradient3639" + inkscape:collect="always" /> + gradientUnits="userSpaceOnUse" + id="radialGradient3675" + xlink:href="#linearGradient3659" + inkscape:collect="always" /> + gradientTransform="translate(-1.3119965,1.110878)" + gradientUnits="userSpaceOnUse" + id="linearGradient3693" + xlink:href="#linearGradient3687" + inkscape:collect="always" /> + gradientUnits="userSpaceOnUse" + id="linearGradient3702" + xlink:href="#linearGradient4202" + inkscape:collect="always" /> + gradientTransform="translate(-1.3119965,1.110878)" + gradientUnits="userSpaceOnUse" + id="linearGradient3704" + xlink:href="#linearGradient3613" + inkscape:collect="always" /> + sodipodi:type="inkscape:persp3d" + inkscape:vp_x="0 : 526.18109 : 1" + inkscape:vp_y="0 : 1000 : 0" + inkscape:vp_z="744.09448 : 526.18109 : 1" + inkscape:persp3d-origin="372.04724 : 350.78739 : 1" + id="perspective3767" /> + inkscape:collect="always" + xlink:href="#linearGradient3302" + id="linearGradient3308" + gradientUnits="userSpaceOnUse" + gradientTransform="translate(-25.178571,-3.0357143)" /> + inkscape:collect="always" + xlink:href="#linearGradient3613" + id="linearGradient3536" + gradientUnits="userSpaceOnUse" + gradientTransform="translate(5.555838,16.162441)" + inkscape:collect="always" + xlink:href="#linearGradient3613" + id="linearGradient3538" + gradientUnits="userSpaceOnUse" + gradientTransform="translate(5.555838,16.162441)" + inkscape:collect="always" + xlink:href="#linearGradient3613" + id="linearGradient3540" + gradientUnits="userSpaceOnUse" + gradientTransform="translate(5.555838,16.162441)" + inkscape:collect="always" + xlink:href="#linearGradient3613" + id="linearGradient3542" + gradientUnits="userSpaceOnUse" + gradientTransform="translate(5.555838,16.162441)" + inkscape:collect="always" + xlink:href="#linearGradient3613" + id="linearGradient3544" + gradientUnits="userSpaceOnUse" + gradientTransform="translate(5.555838,16.162441)" + inkscape:collect="always" + xlink:href="#linearGradient3613" + id="linearGradient3546" + gradientUnits="userSpaceOnUse" + gradientTransform="translate(5.555838,16.162441)" + inkscape:collect="always" + xlink:href="#linearGradient3613" + id="linearGradient3548" + gradientUnits="userSpaceOnUse" + gradientTransform="translate(5.555838,16.162441)" + inkscape:collect="always" + xlink:href="#linearGradient3613" + id="linearGradient3550" + gradientUnits="userSpaceOnUse" + gradientTransform="translate(5.555838,16.162441)" + inkscape:collect="always" + xlink:href="#linearGradient3613" + id="linearGradient3694" + gradientUnits="userSpaceOnUse" + gradientTransform="translate(-381.09403,-544.64978)" + inkscape:collect="always" + xlink:href="#linearGradient3613" + id="linearGradient3696" + gradientUnits="userSpaceOnUse" + gradientTransform="translate(-381.09403,-544.64978)" + inkscape:collect="always" + xlink:href="#linearGradient3613" + id="linearGradient3698" + gradientUnits="userSpaceOnUse" + gradientTransform="translate(-381.09403,-544.64978)" + inkscape:collect="always" + xlink:href="#linearGradient3613" + id="linearGradient3700" + gradientUnits="userSpaceOnUse" + gradientTransform="translate(-381.09403,-544.64978)" + inkscape:collect="always" + xlink:href="#linearGradient3613" + id="linearGradient3703" + gradientUnits="userSpaceOnUse" + gradientTransform="translate(-381.09403,-544.64978)" + inkscape:collect="always" + xlink:href="#linearGradient3613" + id="linearGradient3705" + gradientUnits="userSpaceOnUse" + gradientTransform="translate(-381.09403,-544.64978)" + inkscape:collect="always" + xlink:href="#linearGradient3613" + id="linearGradient3707" + gradientUnits="userSpaceOnUse" + gradientTransform="translate(-381.09403,-544.64978)" + inkscape:collect="always" + xlink:href="#linearGradient3613" + id="linearGradient3709" + gradientUnits="userSpaceOnUse" + gradientTransform="translate(-381.09403,-544.64978)" + inkscape:collect="always" + xlink:href="#linearGradient4192" + id="linearGradient4200" + gradientUnits="userSpaceOnUse" /> + inkscape:persp3d-origin="0.5 : 0.33333333 : 1" + inkscape:vp_z="1 : 0.5 : 1" + inkscape:vp_y="0 : 1000 : 0" + inkscape:vp_x="0 : 0.5 : 1" + sodipodi:type="inkscape:persp3d" /> + inkscape:collect="always" + xlink:href="#linearGradient3708" + id="linearGradient3714" + gradientUnits="userSpaceOnUse" /> + inkscape:collect="always" + xlink:href="#linearGradient3708" + id="linearGradient3722" + gradientUnits="userSpaceOnUse" /> + inkscape:persp3d-origin="0.5 : 0.33333333 : 1" + inkscape:vp_z="1 : 0.5 : 1" + inkscape:vp_y="0 : 1000 : 0" + inkscape:vp_x="0 : 0.5 : 1" + sodipodi:type="inkscape:persp3d" /> + inkscape:persp3d-origin="0.5 : 0.33333333 : 1" + inkscape:vp_z="1 : 0.5 : 1" + inkscape:vp_y="0 : 1000 : 0" + inkscape:vp_x="0 : 0.5 : 1" + sodipodi:type="inkscape:persp3d" /> + inkscape:collect="always" + xlink:href="#linearGradient3770" + id="linearGradient3776" + gradientUnits="userSpaceOnUse" /> + inkscape:collect="always" + xlink:href="#linearGradient3770" + id="linearGradient3784" + gradientUnits="userSpaceOnUse" /> + inkscape:collect="always" + xlink:href="#linearGradient3621" + id="radialGradient3792" + gradientUnits="userSpaceOnUse" /> + inkscape:collect="always" + xlink:href="#linearGradient3497" + id="radialGradient3800" + gradientUnits="userSpaceOnUse" /> + <dc:format>image/svg+xml</dc:format> + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + inkscape:label="Calque 1" + inkscape:groupmode="layer" + style="display:inline"> + style="fill:url(#linearGradient4200);fill-opacity:1;stroke:#000000;stroke-width:1.46953177;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" /> + transform="translate(-127.27923,-40.406102)" + style="fill:url(#linearGradient3702);fill-opacity:1;stroke:#000000;stroke-width:1;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:1, 2;stroke-dashoffset:0" + sodipodi:linespacing="125%" + style="font-size:36px;font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;text-indent:0;text-align:start;text-decoration:none;line-height:125%;letter-spacing:normal;word-spacing:normal;text-transform:none;direction:ltr;block-progression:tb;writing-mode:lr-tb;text-anchor:start;fill:#655fdb;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:1px;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate;font-family:DejaVu Sans;-inkscape-font-specification:DejaVu Sans Bold" + xml:space="preserve"><tspan + style="font-size:36px;font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;text-align:start;line-height:125%;writing-mode:lr-tb;text-anchor:start;fill:#655fdb;fill-opacity:1;stroke:none;font-family:DejaVu Sans;-inkscape-font-specification:DejaVu Sans Bold">Default</tspan></text> + transform="translate(-33.11078,95.2077)"> + style="color:#000000;fill:url(#linearGradient3776);fill-opacity:1;fill-rule:nonzero;stroke:url(#linearGradient3784);stroke-width:3.80890393;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate" + sodipodi:cx="103.21429" + sodipodi:cy="127.14286" + sodipodi:r1="91.508057" + sodipodi:r2="45.754028" + sodipodi:arg2="1.0471976" + inkscape:flatsided="true" + inkscape:randomized="0" + d="m 194.72234,127.14286 -137.262082,79.2483 0,-158.496601 137.262082,79.248301 z" + transform="matrix(0.78762818,0,0,0.78762818,26.492161,-44.168468)" /> + sodipodi:linespacing="100%" + style="font-size:36px;font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;text-indent:0;text-align:end;text-decoration:none;line-height:100%;letter-spacing:normal;word-spacing:normal;text-transform:none;direction:ltr;block-progression:tb;writing-mode:lr-tb;text-anchor:end;color:#000000;fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:1px;marker:none;visibility:inherit;display:inline;overflow:visible;enable-background:accumulate;font-family:DejaVu Sans;-inkscape-font-specification:DejaVu Sans Bold" + xml:space="preserve"><tspan + style="font-size:36px;font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;text-indent:0;text-align:end;text-decoration:none;line-height:100%;letter-spacing:normal;word-spacing:normal;text-transform:none;direction:ltr;block-progression:tb;writing-mode:lr-tb;text-anchor:end;color:#000000;fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:1px;marker:none;visibility:inherit;display:inline;overflow:visible;enable-background:accumulate;font-family:DejaVu Sans;-inkscape-font-specification:DejaVu Sans Bold" + sodipodi:role="line">Start</tspan></text> + transform="translate(-18.07106,94.06456)" + style="color:#000000;fill:url(#linearGradient3714);fill-opacity:1;fill-rule:nonzero;stroke:url(#linearGradient3722);stroke-width:3.94511151;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate" + sodipodi:cx="83.571426" + sodipodi:cy="224.28571" + sodipodi:r1="94.724358" + sodipodi:r2="87.513893" + sodipodi:arg2="0.39269908" + inkscape:flatsided="true" + inkscape:randomized="0" + d="m 178.29578,224.28571 -27.74412,66.98023 -66.980234,27.74412 -66.980235,-27.74412 -27.744122,-66.98023 27.744122,-66.98024 66.980235,-27.74412 66.980234,27.74412 27.74412,66.98024 z" + transform="matrix(0.70255013,-0.29100577,0.29100577,0.70255013,-13.216048,-76.13621)" /> + sodipodi:linespacing="100%" + style="font-size:36px;font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;text-indent:0;text-align:end;text-decoration:none;line-height:100%;letter-spacing:normal;word-spacing:normal;text-transform:none;direction:ltr;block-progression:tb;writing-mode:lr-tb;text-anchor:end;fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:1px;marker:none;visibility:inherit;display:inline;overflow:visible;enable-background:accumulate;font-family:DejaVu Sans;-inkscape-font-specification:DejaVu Sans Bold" + xml:space="preserve"><tspan + style="font-size:36px;font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;text-align:end;line-height:100%;writing-mode:lr-tb;text-anchor:end;fill:#ffffff;fill-opacity:1;stroke:none;font-family:DejaVu Sans;-inkscape-font-specification:DejaVu Sans Bold" + sodipodi:role="line">Stop</tspan></text> + transform="matrix(2.0899173,0,0,2.0899173,-577.84265,-204.88668)" + transform="translate(42.282829,64.376725)" + d="m 369.71585,101.69787 a 17.67767,17.67767 0 1 1 -35.35534,0 17.67767,17.67767 0 1 1 35.35534,0 z" + sodipodi:cy="101.69787" + sodipodi:cx="352.03818" + style="fill:url(#radialGradient3800);fill-opacity:1;stroke:#000000;stroke-width:0.47848782;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" + transform="matrix(2.0899173,0,0,2.0899173,-637.08625,-59.866062)" + style="fill:url(#radialGradient3792);fill-opacity:1;stroke:#000000;stroke-width:0.47848782;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" + sodipodi:cx="352.03818" + sodipodi:cy="101.69787" + d="m 369.71585,101.69787 a 17.67767,17.67767 0 1 1 -35.35534,0 17.67767,17.67767 0 1 1 35.35534,0 z" + transform="translate(70.630181,-5.0138784)" /> --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/tests/svgui/svgui@svgui/py_ext.xml Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<Python xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.w3.org/2001/XMLSchema" xsi:schemaLocation="python_xsd.xsd"> --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/tests/wxGlade/HMIFrame@wxglade_hmi/baseconfnode.xml Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8"?> +<BaseParams Name="HMIFrame" IEC_Channel="0"/> --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/tests/wxGlade/HMIFrame@wxglade_hmi/hmi.wxg Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,34 @@
+<!-- generated by wxGlade 0.6.3 on Fri Aug 7 18:16:44 2009 --> +<application path="" name="" class="" option="0" language="python" top_window="HMIFrame" encoding="UTF-8" use_gettext="0" overwrite="0" use_new_namespace="1" for_version="2.8" is_template="0"> + <object class="Class_HMIFrame" name="HMIFrame" base="EditFrame"> + <style>wxDEFAULT_FRAME_STYLE</style> + <title>HMIFrame</title> + <object class="wxBoxSizer" name="sizer_1" base="EditBoxSizer"> + <orient>wxVERTICAL</orient> + <object class="sizeritem"> + <object class="wxSpinCtrl" name="spin_ctrl_1" base="EditSpinCtrl"> + <range>0, 10000</range> + <object class="sizeritem"> + <object class="wxCheckBox" name="checkbox_1" base="EditCheckBox"> + <label>checkbox_1</label> + <object class="sizeritem"> + <object class="wxStaticText" name="label_1" base="EditStaticText"> + <attribute>1</attribute> + <label>GUI modifiée !</label> --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/tests/wxGlade/HMIFrame@wxglade_hmi/py_ext.xml Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<Python xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.w3.org/2001/XMLSchema" xsi:schemaLocation="python_xsd.xsd"> --- a/tests/wxGlade/python@py_ext/HMIFrame@wxglade_hmi/baseconfnode.xml Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,2 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<BaseParams Name="HMIFrame" IEC_Channel="0"/>
--- a/tests/wxGlade/python@py_ext/HMIFrame@wxglade_hmi/hmi.wxg Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,34 +0,0 @@
-<!-- generated by wxGlade 0.6.3 on Fri Aug 7 18:16:44 2009 -->
-<application path="" name="" class="" option="0" language="python" top_window="HMIFrame" encoding="UTF-8" use_gettext="0" overwrite="0" use_new_namespace="1" for_version="2.8" is_template="0">
- <object class="Class_HMIFrame" name="HMIFrame" base="EditFrame">
- <style>wxDEFAULT_FRAME_STYLE</style>
- <title>HMIFrame</title>
- <object class="wxBoxSizer" name="sizer_1" base="EditBoxSizer">
- <orient>wxVERTICAL</orient>
- <object class="sizeritem">
- <object class="wxSpinCtrl" name="spin_ctrl_1" base="EditSpinCtrl">
- <range>0, 10000</range>
- <object class="sizeritem">
- <object class="wxCheckBox" name="checkbox_1" base="EditCheckBox">
- <label>checkbox_1</label>
- <object class="sizeritem">
- <object class="wxStaticText" name="label_1" base="EditStaticText">
- <attribute>1</attribute>
- <label>GUI modifiée !</label>
--- a/tests/wxGlade/python@py_ext/HMIFrame@wxglade_hmi/py_ext.xml Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,4 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<Python xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.w3.org/2001/XMLSchema" xsi:schemaLocation="python_xsd.xsd">
--- a/tests/wxGlade/python@py_ext/baseconfnode.xml Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,2 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<BaseParams Name="python" IEC_Channel="0"/>
--- a/tests/wxGlade/python@py_ext/py_ext.xml Wed May 09 00:39:54 2012 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,4 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<Python xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.w3.org/2001/XMLSchema" xsi:schemaLocation="python_xsd.xsd">
--- a/util/misc.py Wed May 09 00:39:54 2012 +0200
+++ b/util/misc.py Sat May 12 11:21:10 2012 +0200
@@ -25,5 +25,5 @@
return reduce(getattr, classpath.split('.')[1:], mod)
- return lambda:classpath
+ return lambda:classpath --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/wxglade_hmi/README Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,1 @@
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/wxglade_hmi/__init__.py Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,1 @@
+from wxglade_hmi import * --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/wxglade_hmi/wxglade_hmi.py Sat May 12 11:21:10 2012 +0200
@@ -0,0 +1,127 @@
+from xml.dom import minidom +from py_ext import PythonFileCTNMixin +class WxGladeHMI(PythonFileCTNMixin): + {"bitmap" : opjimg("editWXGLADE"), + "name" : _("WXGLADE GUI"), + "tooltip" : _("Edit a WxWidgets GUI with WXGlade"), + "method" : "_editWXGLADE"}, + def ConfNodePath(self): + return os.path.join(os.path.dirname(__file__)) + def _getWXGLADEpath(self): + # define name for IEC raw code file + return os.path.join(self.CTNPath(), "hmi.wxg") + def launch_wxglade(self, options, wait=False): + from wxglade import __file__ as fileName + path = os.path.dirname(fileName) + glade = os.path.join(path, 'wxglade.py') + if wx.Platform == '__WXMSW__': + mode = {False:os.P_NOWAIT, True:os.P_WAIT}[wait] + os.spawnv(mode, sys.executable, ["\"%s\""%sys.executable] + [glade] + options) + def CTNGenerate_C(self, buildpath, locations): + Return C code generated by iec2c compiler + when _generate_softPLC have been called + @param locations: ignored + @return: [(C_file_name, CFLAGS),...] , LDFLAGS_TO_APPEND + current_location = self.GetCurrentLocation() + # define a unique name for the generated C file + location_str = "_".join(map(lambda x:str(x), current_location)) + runtimefile_path = os.path.join(buildpath, "runtime_%s.py"%location_str) + runtimefile = open(runtimefile_path, 'w') + wxgfile_path=self._getWXGLADEpath() + if os.path.exists(wxgfile_path): + wxgfile = open(wxgfile_path, 'r') + wxgtree = minidom.parse(wxgfile) + for node in wxgtree.childNodes[1].childNodes: + if node.nodeType == wxgtree.ELEMENT_NODE: + hmi_frames[node._attrs["name"].value] = node._attrs["class"].value + hmipyfile_path=os.path.join(self._getBuildPath(), "hmi.py") + if wx.Platform == '__WXMSW__': + wxgfile_path = "\"%s\""%wxgfile_path + wxghmipyfile_path = "\"%s\""%hmipyfile_path + wxghmipyfile_path = hmipyfile_path + self.launch_wxglade(['-o', wxghmipyfile_path, '-g', 'python', wxgfile_path], wait=True) + hmipyfile = open(hmipyfile_path, 'r') + runtimefile.write(hmipyfile.read()) + runtimefile.write(self.GetPythonCode()) +def _runtime_%(location)s_begin(): + wx.MessageBox(_("Please stop PLC to close")) +def _runtime_%(location)s_cleanup(): +""" % {"location": location_str, + "declare": "\n".join(map(lambda x:"%s = None" % x, hmi_frames.keys())), + "global": ",".join(hmi_frames.keys()), + "init": "\n".join(map(lambda x: """ + %(name)s = %(class)s(None) + %(name)s.Bind(wx.EVT_CLOSE, OnCloseFrame) +""" % {"name": x[0], "class": x[1]}, + "cleanup": "\n ".join(map(lambda x:"%s.Destroy()" % x, hmi_frames.keys()))}) + return [], "", False, ("runtime_%s.py"%location_str, file(runtimefile_path,"rb")) + def _editWXGLADE(self): + wxg_filename = self._getWXGLADEpath() + if not self.GetCTRoot().CheckProjectPathPerm(): + dialog = wx.MessageDialog(self.GetCTRoot().AppFrame, + _("You don't have write permissions.\nOpen wxGlade anyway ?"), + wx.YES_NO|wx.ICON_QUESTION) + open_wxglade = dialog.ShowModal() == wx.ID_YES + if not os.path.exists(wxg_filename): + hmi_name = self.BaseParams.getName() + open(wxg_filename,"w").write("""<?xml version="1.0"?> + <application path="" name="" class="" option="0" language="python" top_window="%(name)s" encoding="UTF-8" use_gettext="0" overwrite="0" use_new_namespace="1" for_version="2.8" is_template="0"> + <object class="%(class)s" name="%(name)s" base="EditFrame"> + <style>wxDEFAULT_FRAME_STYLE</style> + """ % {"name": hmi_name, "class": "Class_%s" % hmi_name}) + if wx.Platform == '__WXMSW__': + wxg_filename = "\"%s\""%wxg_filename + self.launch_wxglade([wxg_filename])