Laurent@814: #!/usr/bin/env python
Laurent@814: # -*- coding: utf-8 -*-
Laurent@814: 
Laurent@814: #This file is part of PLCOpenEditor, a library implementing an IEC 61131-3 editor
Laurent@814: #based on the plcopen standard. 
Laurent@814: #
Laurent@814: #Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD
Laurent@814: #
Laurent@814: #See COPYING file for copyrights details.
Laurent@814: #
Laurent@814: #This library is free software; you can redistribute it and/or
Laurent@814: #modify it under the terms of the GNU General Public
Laurent@814: #License as published by the Free Software Foundation; either
Laurent@814: #version 2.1 of the License, or (at your option) any later version.
Laurent@814: #
Laurent@814: #This library is distributed in the hope that it will be useful,
Laurent@814: #but WITHOUT ANY WARRANTY; without even the implied warranty of
Laurent@814: #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Laurent@814: #General Public License for more details.
Laurent@814: #
Laurent@814: #You should have received a copy of the GNU General Public
Laurent@814: #License along with this library; if not, write to the Free Software
Laurent@814: #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
Laurent@814: 
Laurent@814: from xmlclass import *
Laurent@814: from structures import *
Laurent@814: from types import *
Laurent@814: import os, re
Laurent@814: 
Laurent@814: """
Laurent@814: Dictionary that makes the relation between var names in plcopen and displayed values
Laurent@814: """
Laurent@814: VarTypes = {"Local" : "localVars", "Temp" : "tempVars", "Input" : "inputVars",
Laurent@814:             "Output" : "outputVars", "InOut" : "inOutVars", "External" : "externalVars",
Laurent@814:             "Global" : "globalVars", "Access" : "accessVars"}
Laurent@814: 
Laurent@814: searchResultVarTypes = {
Laurent@814:     "inputVars": "var_input",
Laurent@814:     "outputVars": "var_output",
Laurent@814:     "inOutVars": "var_inout"
Laurent@814: }
Laurent@814: 
Laurent@814: """
Laurent@814: Define in which order var types must be displayed
Laurent@814: """
Laurent@814: VarOrder = ["Local","Temp","Input","Output","InOut","External","Global","Access"]
Laurent@814: 
Laurent@814: """
Laurent@814: Define which action qualifier must be associated with a duration 
Laurent@814: """
Laurent@814: QualifierList = {"N" : False, "R" : False, "S" : False, "L" : True, "D" : True, 
Laurent@814:     "P" : False, "P0" : False, "P1" : False, "SD" : True, "DS" : True, "SL" : True}
Laurent@814: 
Laurent@814: 
Laurent@814: FILTER_ADDRESS_MODEL = "(%%[IQM](?:[XBWDL])?)(%s)((?:\.[0-9]+)*)" 
Laurent@814: 
Laurent@814: def update_address(address, address_model, new_leading):
Laurent@814:     result = address_model.match(address)
Laurent@814:     if result is None:
Laurent@814:         return address
Laurent@814:     groups = result.groups()
Laurent@814:     return groups[0] + new_leading + groups[2]
Laurent@814: 
Laurent@814: def _init_and_compare(function, v1, v2):
Laurent@814:     if v1 is None:
Laurent@814:         return v2
Laurent@814:     if v2 is not None:
Laurent@814:         return function(v1, v2)
Laurent@814:     return v1
Laurent@814: 
Laurent@814: """
Laurent@814: Helper class for bounding_box calculation 
Laurent@814: """
Laurent@814: class rect:
Laurent@814:     
Laurent@814:     def __init__(self, x=None, y=None, width=None, height=None):
Laurent@814:         self.x_min = x
Laurent@814:         self.x_max = None
Laurent@814:         self.y_min = y
Laurent@814:         self.y_max = None
Laurent@814:         if width is not None and x is not None:
Laurent@814:             self.x_max = x + width
Laurent@814:         if height is not None and y is not None:
Laurent@814:             self.y_max = y + height
Laurent@814:     
Laurent@814:     def update(self, x, y):
Laurent@814:         self.x_min = _init_and_compare(min, self.x_min, x)
Laurent@814:         self.x_max = _init_and_compare(max, self.x_max, x)
Laurent@814:         self.y_min = _init_and_compare(min, self.y_min, y)
Laurent@814:         self.y_max = _init_and_compare(max, self.y_max, y)
Laurent@814:         
Laurent@814:     def union(self, rect):
Laurent@814:         self.x_min = _init_and_compare(min, self.x_min, rect.x_min)
Laurent@814:         self.x_max = _init_and_compare(max, self.x_max, rect.x_max)
Laurent@814:         self.y_min = _init_and_compare(min, self.y_min, rect.y_min)
Laurent@814:         self.y_max = _init_and_compare(max, self.y_max, rect.y_max)
Laurent@814:     
Laurent@814:     def bounding_box(self):
Laurent@814:         width = height = None
Laurent@814:         if self.x_min is not None and self.x_max is not None:
Laurent@814:             width = self.x_max - self.x_min
Laurent@814:         if self.y_min is not None and self.y_max is not None:
Laurent@814:             height = self.y_max - self.y_min
Laurent@814:         return self.x_min, self.y_min, width, height
Laurent@814: 
Laurent@814: def TextLenInRowColumn(text):
Laurent@814:     if text == "":
Laurent@814:         return (0, 0)
Laurent@814:     lines = text.split("\n")
Laurent@814:     return len(lines) - 1, len(lines[-1])
Laurent@814: 
Laurent@814: def TestTextElement(text, criteria):
Laurent@814:     lines = text.splitlines()
Laurent@814:     if not criteria["case_sensitive"]:
Laurent@814:         text = text.upper()
Laurent@814:     test_result = []
Laurent@814:     result = criteria["pattern"].search(text)
Laurent@814:     while result is not None:
Laurent@814:         start = TextLenInRowColumn(text[:result.start()])
Laurent@814:         end = TextLenInRowColumn(text[:result.end() - 1])
Laurent@814:         test_result.append((start, end, "\n".join(lines[start[0]:end[0] + 1])))
Laurent@814:         result = criteria["pattern"].search(text, result.end())
Laurent@814:     return test_result
Laurent@814: 
Laurent@814: PLCOpenClasses = GenerateClassesFromXSD(os.path.join(os.path.split(__file__)[0], "tc6_xml_v201.xsd"))
Laurent@814: 
Laurent@814: ElementNameToClass = {}
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("formattedText", None)
Laurent@814: if cls:
Laurent@814:     def updateElementName(self, old_name, new_name):
Laurent@966:         text = self.text
Laurent@814:         index = text.find(old_name)
Laurent@814:         while index != -1:
Laurent@814:             if index > 0 and (text[index - 1].isalnum() or text[index - 1] == "_"):
Laurent@814:                 index = text.find(old_name, index + len(old_name))
Laurent@814:             elif index < len(text) - len(old_name) and (text[index + len(old_name)].isalnum() or text[index + len(old_name)] == "_"):
Laurent@814:                 index = text.find(old_name, index + len(old_name))
Laurent@814:             else:
Laurent@814:                 text = text[:index] + new_name + text[index + len(old_name):]
Laurent@814:                 index = text.find(old_name, index + len(new_name))
Laurent@966:         self.text = text
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814:     
Laurent@814:     def updateElementAddress(self, address_model, new_leading):
Laurent@966:         text = self.text
Laurent@814:         startpos = 0
Laurent@814:         result = address_model.search(text, startpos)
Laurent@814:         while result is not None:
Laurent@814:             groups = result.groups()
Laurent@814:             new_address = groups[0] + new_leading + groups[2]
Laurent@814:             text = text[:result.start()] + new_address + text[result.end():]
Laurent@814:             startpos = result.start() + len(new_address)
Laurent@814:             result = address_model.search(self.text, startpos)
Laurent@966:         self.text = text
Laurent@814:     setattr(cls, "updateElementAddress", updateElementAddress)
Laurent@814:     
Laurent@1142:     def hasblock(self, block_type):
Laurent@1142:         text = self.text.upper()
Laurent@1142:         index = text.find(block_type.upper())
Laurent@1142:         while index != -1:
Laurent@1142:             if (not (index > 0 and (text[index - 1].isalnum() or text[index - 1] == "_")) and 
Laurent@1142:                 not (index < len(text) - len(block_type) and text[index + len(block_type)] != "(")):
Laurent@1142:                 return True
Laurent@1142:             index = text.find(block_type.upper(), index + len(block_type))
Laurent@1142:         return False
Laurent@1142:     setattr(cls, "hasblock", hasblock)
Laurent@1142:     
Laurent@814:     def Search(self, criteria, parent_infos):
Laurent@814:         return [(tuple(parent_infos),) + result for result in TestTextElement(self.gettext(), criteria)]
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814:     
Laurent@814: cls = PLCOpenClasses.get("project", None)
Laurent@814: if cls:
Laurent@814:     cls.singleLineAttributes = False
Laurent@814:     cls.EnumeratedDataTypeValues = {}
Laurent@814:     cls.CustomDataTypeRange = {}
Laurent@814:     cls.CustomTypeHierarchy = {}
Laurent@814:     cls.ElementUsingTree = {}
Laurent@814:     cls.CustomBlockTypes = []
Laurent@814:     
Laurent@814:     def setname(self, name):
Laurent@814:         self.contentHeader.setname(name)
Laurent@814:     setattr(cls, "setname", setname)
Laurent@814:         
Laurent@814:     def getname(self):
Laurent@814:         return self.contentHeader.getname()
Laurent@814:     setattr(cls, "getname", getname)
Laurent@814:     
Laurent@814:     def getfileHeader(self):
Laurent@814:         fileheader = {}
Laurent@814:         for name, value in [("companyName", self.fileHeader.getcompanyName()),
Laurent@814:                             ("companyURL", self.fileHeader.getcompanyURL()),
Laurent@814:                             ("productName", self.fileHeader.getproductName()),
Laurent@814:                             ("productVersion", self.fileHeader.getproductVersion()),
Laurent@814:                             ("productRelease", self.fileHeader.getproductRelease()),
Laurent@814:                             ("creationDateTime", self.fileHeader.getcreationDateTime()),
Laurent@814:                             ("contentDescription", self.fileHeader.getcontentDescription())]:
Laurent@814:             if value is not None:
Laurent@814:                 fileheader[name] = value
Laurent@814:             else:
Laurent@814:                 fileheader[name] = ""
Laurent@814:         return fileheader
Laurent@814:     setattr(cls, "getfileHeader", getfileHeader)
Laurent@814:     
Laurent@814:     def setfileHeader(self, fileheader):
Laurent@814:         if fileheader.has_key("companyName"):
Laurent@814:             self.fileHeader.setcompanyName(fileheader["companyName"])
Laurent@814:         if fileheader.has_key("companyURL"):
Laurent@814:             self.fileHeader.setcompanyURL(fileheader["companyURL"])
Laurent@814:         if fileheader.has_key("productName"):
Laurent@814:             self.fileHeader.setproductName(fileheader["productName"])
Laurent@814:         if fileheader.has_key("productVersion"):
Laurent@814:             self.fileHeader.setproductVersion(fileheader["productVersion"])
Laurent@814:         if fileheader.has_key("productRelease"):
Laurent@814:             self.fileHeader.setproductRelease(fileheader["productRelease"])
Laurent@814:         if fileheader.has_key("creationDateTime"):
Laurent@814:             self.fileHeader.setcreationDateTime(fileheader["creationDateTime"])
Laurent@814:         if fileheader.has_key("contentDescription"):
Laurent@814:             self.fileHeader.setcontentDescription(fileheader["contentDescription"])
Laurent@814:     setattr(cls, "setfileHeader", setfileHeader)
Laurent@814:     
Laurent@814:     def getcontentHeader(self):
Laurent@814:         contentheader = {}
Laurent@814:         for name, value in [("projectName", self.contentHeader.getname()),
Laurent@814:                             ("projectVersion", self.contentHeader.getversion()),
Laurent@814:                             ("modificationDateTime", self.contentHeader.getmodificationDateTime()),
Laurent@814:                             ("organization", self.contentHeader.getorganization()),
Laurent@814:                             ("authorName", self.contentHeader.getauthor()),
Laurent@814:                             ("language", self.contentHeader.getlanguage())]:
Laurent@814:             if value is not None:
Laurent@814:                 contentheader[name] = value
Laurent@814:             else:
Laurent@814:                 contentheader[name] = ""
Laurent@814:         contentheader["pageSize"] = self.contentHeader.getpageSize()
Laurent@814:         contentheader["scaling"] = self.contentHeader.getscaling()
Laurent@814:         return contentheader
Laurent@814:     setattr(cls, "getcontentHeader", getcontentHeader)
Laurent@814:     
Laurent@814:     def setcontentHeader(self, contentheader):
Laurent@814:         if contentheader.has_key("projectName"):
Laurent@814:             self.contentHeader.setname(contentheader["projectName"])
Laurent@814:         if contentheader.has_key("projectVersion"):
Laurent@814:             self.contentHeader.setversion(contentheader["projectVersion"])
Laurent@814:         if contentheader.has_key("modificationDateTime"):
Laurent@814:             self.contentHeader.setmodificationDateTime(contentheader["modificationDateTime"])
Laurent@814:         if contentheader.has_key("organization"):
Laurent@814:             self.contentHeader.setorganization(contentheader["organization"])
Laurent@814:         if contentheader.has_key("authorName"):
Laurent@814:             self.contentHeader.setauthor(contentheader["authorName"])
Laurent@814:         if contentheader.has_key("language"):
Laurent@814:             self.contentHeader.setlanguage(contentheader["language"])
Laurent@814:         if contentheader.has_key("pageSize"):
Laurent@814:             self.contentHeader.setpageSize(*contentheader["pageSize"])
Laurent@814:         if contentheader.has_key("scaling"):
Laurent@814:             self.contentHeader.setscaling(contentheader["scaling"])
Laurent@814:     setattr(cls, "setcontentHeader", setcontentHeader)
Laurent@814:     
Laurent@814:     def getdataTypes(self):
Laurent@814:         return self.types.getdataTypeElements()
Laurent@814:     setattr(cls, "getdataTypes", getdataTypes)
Laurent@814:     
Laurent@814:     def getdataType(self, name):
Laurent@814:         return self.types.getdataTypeElement(name)
Laurent@814:     setattr(cls, "getdataType", getdataType)
Laurent@814:     
Laurent@814:     def appenddataType(self, name):
Laurent@814:         if self.CustomTypeHierarchy.has_key(name):
Laurent@814:             raise ValueError, "\"%s\" Data Type already exists !!!"%name
Laurent@814:         self.types.appenddataTypeElement(name)
Laurent@814:         self.AddCustomDataType(self.getdataType(name))
Laurent@814:     setattr(cls, "appenddataType", appenddataType)
Laurent@814:         
Laurent@814:     def insertdataType(self, index, datatype):
Laurent@814:         self.types.insertdataTypeElement(index, datatype)
Laurent@814:         self.AddCustomDataType(datatype)
Laurent@814:     setattr(cls, "insertdataType", insertdataType)
Laurent@814:     
Laurent@814:     def removedataType(self, name):
Laurent@814:         self.types.removedataTypeElement(name)
Laurent@814:         self.RefreshDataTypeHierarchy()
Laurent@814:         self.RefreshElementUsingTree()
Laurent@814:     setattr(cls, "removedataType", removedataType)
Laurent@814:     
Laurent@814:     def getpous(self):
Laurent@814:         return self.types.getpouElements()
Laurent@814:     setattr(cls, "getpous", getpous)
Laurent@814:     
Laurent@814:     def getpou(self, name):
Laurent@814:         return self.types.getpouElement(name)
Laurent@814:     setattr(cls, "getpou", getpou)
Laurent@814:     
Laurent@814:     def appendpou(self, name, pou_type, body_type):
Laurent@814:         self.types.appendpouElement(name, pou_type, body_type)
Laurent@814:         self.AddCustomBlockType(self.getpou(name))
Laurent@814:     setattr(cls, "appendpou", appendpou)
Laurent@814:         
Laurent@814:     def insertpou(self, index, pou):
Laurent@814:         self.types.insertpouElement(index, pou)
Laurent@814:         self.AddCustomBlockType(pou)
Laurent@814:     setattr(cls, "insertpou", insertpou)
Laurent@814:     
Laurent@814:     def removepou(self, name):
Laurent@814:         self.types.removepouElement(name)
Laurent@814:         self.RefreshCustomBlockTypes()
Laurent@814:         self.RefreshElementUsingTree()
Laurent@814:     setattr(cls, "removepou", removepou)
Laurent@814: 
Laurent@814:     def getconfigurations(self):
Laurent@814:         configurations = self.instances.configurations.getconfiguration()
Laurent@814:         if configurations:
Laurent@814:             return configurations
Laurent@814:         return []
Laurent@814:     setattr(cls, "getconfigurations", getconfigurations)
Laurent@814: 
Laurent@814:     def getconfiguration(self, name):
Laurent@814:         for configuration in self.instances.configurations.getconfiguration():
Laurent@814:             if configuration.getname() == name:
Laurent@814:                 return configuration
Laurent@814:         return None
Laurent@814:     setattr(cls, "getconfiguration", getconfiguration)
Laurent@814: 
Laurent@814:     def addconfiguration(self, name):
Laurent@814:         for configuration in self.instances.configurations.getconfiguration():
Laurent@814:             if configuration.getname() == name:
Laurent@814:                 raise ValueError, _("\"%s\" configuration already exists !!!")%name
Laurent@814:         new_configuration = PLCOpenClasses["configurations_configuration"]()
Laurent@814:         new_configuration.setname(name)
Laurent@814:         self.instances.configurations.appendconfiguration(new_configuration)
Laurent@814:     setattr(cls, "addconfiguration", addconfiguration)    
Laurent@814: 
Laurent@814:     def removeconfiguration(self, name):
Laurent@814:         found = False
Laurent@814:         for idx, configuration in enumerate(self.instances.configurations.getconfiguration()):
Laurent@814:             if configuration.getname() == name:
Laurent@814:                 self.instances.configurations.removeconfiguration(idx)
Laurent@814:                 found = True
Laurent@814:                 break
Laurent@814:         if not found:
Laurent@814:             raise ValueError, ("\"%s\" configuration doesn't exist !!!")%name
Laurent@814:     setattr(cls, "removeconfiguration", removeconfiguration)
Laurent@814: 
Laurent@814:     def getconfigurationResource(self, config_name, name):
Laurent@814:         configuration = self.getconfiguration(config_name)
Laurent@814:         if configuration:
Laurent@814:             for resource in configuration.getresource():
Laurent@814:                 if resource.getname() == name:
Laurent@814:                     return resource
Laurent@814:         return None
Laurent@814:     setattr(cls, "getconfigurationResource", getconfigurationResource)
Laurent@814: 
Laurent@814:     def addconfigurationResource(self, config_name, name):
Laurent@814:         configuration = self.getconfiguration(config_name)
Laurent@814:         if configuration:
Laurent@814:             for resource in configuration.getresource():
Laurent@814:                 if resource.getname() == name:
Laurent@814:                     raise ValueError, _("\"%s\" resource already exists in \"%s\" configuration !!!")%(name, config_name)
Laurent@814:             new_resource = PLCOpenClasses["configuration_resource"]()
Laurent@814:             new_resource.setname(name)
Laurent@814:             configuration.appendresource(new_resource)
Laurent@814:     setattr(cls, "addconfigurationResource", addconfigurationResource)
Laurent@814: 
Laurent@814:     def removeconfigurationResource(self, config_name, name):
Laurent@814:         configuration = self.getconfiguration(config_name)
Laurent@814:         if configuration:
Laurent@814:             found = False
Laurent@814:             for idx, resource in enumerate(configuration.getresource()):
Laurent@814:                 if resource.getname() == name:
Laurent@814:                     configuration.removeresource(idx)
Laurent@814:                     found = True
Laurent@814:                     break
Laurent@814:             if not found:
Laurent@814:                 raise ValueError, _("\"%s\" resource doesn't exist in \"%s\" configuration !!!")%(name, config_name)
Laurent@814:     setattr(cls, "removeconfigurationResource", removeconfigurationResource)
Laurent@814: 
Laurent@814:     def updateElementName(self, old_name, new_name):
Laurent@814:         for datatype in self.types.getdataTypeElements():
Laurent@814:             datatype.updateElementName(old_name, new_name)
Laurent@814:         for pou in self.types.getpouElements():
Laurent@814:             pou.updateElementName(old_name, new_name)
Laurent@814:         for configuration in self.instances.configurations.getconfiguration():
Laurent@814:             configuration.updateElementName(old_name, new_name)
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814: 
Laurent@814:     def updateElementAddress(self, old_leading, new_leading):
Laurent@814:         address_model = re.compile(FILTER_ADDRESS_MODEL % old_leading)
Laurent@814:         for pou in self.types.getpouElements():
Laurent@814:             pou.updateElementAddress(address_model, new_leading)
Laurent@814:         for configuration in self.instances.configurations.getconfiguration():
Laurent@814:             configuration.updateElementAddress(address_model, new_leading)
Laurent@814:     setattr(cls, "updateElementAddress", updateElementAddress)
Laurent@814: 
Laurent@814:     def removeVariableByAddress(self, address):
Laurent@814:         for pou in self.types.getpouElements():
Laurent@814:             pou.removeVariableByAddress(address)
Laurent@814:         for configuration in self.instances.configurations.getconfiguration():
Laurent@814:             configuration.removeVariableByAddress(address)
Laurent@814:     setattr(cls, "removeVariableByAddress", removeVariableByAddress)
Laurent@814: 
Laurent@814:     def removeVariableByFilter(self, leading):
Laurent@814:         address_model = re.compile(FILTER_ADDRESS_MODEL % leading)
Laurent@814:         for pou in self.types.getpouElements():
Laurent@814:             pou.removeVariableByFilter(address_model)
Laurent@814:         for configuration in self.instances.configurations.getconfiguration():
Laurent@814:             configuration.removeVariableByFilter(address_model)
Laurent@814:     setattr(cls, "removeVariableByFilter", removeVariableByFilter)
Laurent@814: 
Laurent@814:     def RefreshDataTypeHierarchy(self):
Laurent@814:         self.EnumeratedDataTypeValues = {}
Laurent@814:         self.CustomDataTypeRange = {}
Laurent@814:         self.CustomTypeHierarchy = {}
Laurent@814:         for datatype in self.getdataTypes():
Laurent@814:             self.AddCustomDataType(datatype)
Laurent@814:     setattr(cls, "RefreshDataTypeHierarchy", RefreshDataTypeHierarchy)
Laurent@814: 
Laurent@814:     def AddCustomDataType(self, datatype):
Laurent@814:         name = datatype.getname()
Laurent@814:         basetype_content = datatype.getbaseType().getcontent()
Laurent@814:         if basetype_content["value"] is None:
Laurent@814:             self.CustomTypeHierarchy[name] = basetype_content["name"]
Laurent@814:         elif basetype_content["name"] in ["string", "wstring"]:
Laurent@814:             self.CustomTypeHierarchy[name] = basetype_content["name"].upper()
Laurent@814:         elif basetype_content["name"] == "derived":
Laurent@814:             self.CustomTypeHierarchy[name] = basetype_content["value"].getname()
Laurent@814:         elif basetype_content["name"] in ["subrangeSigned", "subrangeUnsigned"]:
Laurent@814:             range = (basetype_content["value"].range.getlower(), 
Laurent@814:                      basetype_content["value"].range.getupper())
Laurent@814:             self.CustomDataTypeRange[name] = range
Laurent@814:             base_type = basetype_content["value"].baseType.getcontent()
Laurent@814:             if base_type["value"] is None:
Laurent@814:                 self.CustomTypeHierarchy[name] = base_type["name"]
Laurent@814:             else:
Laurent@814:                 self.CustomTypeHierarchy[name] = base_type["value"].getname()
Laurent@814:         else:
Laurent@814:             if basetype_content["name"] == "enum":
Laurent@814:                 values = []
Laurent@814:                 for value in basetype_content["value"].values.getvalue():
Laurent@814:                     values.append(value.getname())
Laurent@814:                 self.EnumeratedDataTypeValues[name] = values
Laurent@814:             self.CustomTypeHierarchy[name] = "ANY_DERIVED"
Laurent@814:     setattr(cls, "AddCustomDataType", AddCustomDataType)
Laurent@814: 
Laurent@814:     # Update Block types with user-defined pou added
Laurent@814:     def RefreshCustomBlockTypes(self):
Laurent@814:         # Reset the tree of user-defined pou cross-use
Laurent@814:         self.CustomBlockTypes = []
Laurent@814:         for pou in self.getpous():
Laurent@814:             self.AddCustomBlockType(pou)
Laurent@814:     setattr(cls, "RefreshCustomBlockTypes", RefreshCustomBlockTypes)
Laurent@814: 
Laurent@814:     def AddCustomBlockType(self, pou): 
Laurent@814:         pou_name = pou.getname()
Laurent@814:         pou_type = pou.getpouType()
Laurent@814:         block_infos = {"name" : pou_name, "type" : pou_type, "extensible" : False,
Laurent@814:                        "inputs" : [], "outputs" : [], "comment" : pou.getdescription(),
Laurent@814:                        "generate" : generate_block, "initialise" : initialise_block}
Laurent@814:         if pou.getinterface():
Laurent@814:             return_type = pou.interface.getreturnType()
Laurent@814:             if return_type:
Laurent@814:                 var_type = return_type.getcontent()
Laurent@814:                 if var_type["name"] == "derived":
Laurent@854:                     block_infos["outputs"].append(("OUT", var_type["value"].getname(), "none"))
Laurent@814:                 elif var_type["name"] in ["string", "wstring"]:
Laurent@854:                     block_infos["outputs"].append(("OUT", var_type["name"].upper(), "none"))
Laurent@814:                 else:
Laurent@854:                     block_infos["outputs"].append(("OUT", var_type["name"], "none"))
Laurent@814:             for type, varlist in pou.getvars():
Laurent@814:                 if type == "InOut":
Laurent@814:                     for var in varlist.getvariable():
Laurent@814:                         var_type = var.type.getcontent()
Laurent@814:                         if var_type["name"] == "derived":
Laurent@814:                             block_infos["inputs"].append((var.getname(), var_type["value"].getname(), "none"))
Laurent@814:                             block_infos["outputs"].append((var.getname(), var_type["value"].getname(), "none"))
Laurent@814:                         elif var_type["name"] in ["string", "wstring"]:
Laurent@814:                             block_infos["inputs"].append((var.getname(), var_type["name"].upper(), "none"))
Laurent@814:                             block_infos["outputs"].append((var.getname(), var_type["name"].upper(), "none"))
Laurent@814:                         else:
Laurent@814:                             block_infos["inputs"].append((var.getname(), var_type["name"], "none"))
Laurent@814:                             block_infos["outputs"].append((var.getname(), var_type["name"], "none"))
Laurent@814:                 elif type == "Input":
Laurent@814:                     for var in varlist.getvariable():
Laurent@814:                         var_type = var.type.getcontent()
Laurent@814:                         if var_type["name"] == "derived":
Laurent@814:                             block_infos["inputs"].append((var.getname(), var_type["value"].getname(), "none"))
Laurent@814:                         elif var_type["name"] in ["string", "wstring"]:
Laurent@814:                             block_infos["inputs"].append((var.getname(), var_type["name"].upper(), "none"))
Laurent@814:                         else:
Laurent@814:                             block_infos["inputs"].append((var.getname(), var_type["name"], "none"))
Laurent@814:                 elif type == "Output":
Laurent@814:                     for var in varlist.getvariable():
Laurent@814:                         var_type = var.type.getcontent()
Laurent@814:                         if var_type["name"] == "derived":
Laurent@814:                             block_infos["outputs"].append((var.getname(), var_type["value"].getname(), "none"))
Laurent@814:                         elif var_type["name"] in ["string", "wstring"]:
Laurent@814:                             block_infos["outputs"].append((var.getname(), var_type["name"].upper(), "none"))
Laurent@814:                         else:
Laurent@814:                             block_infos["outputs"].append((var.getname(), var_type["name"], "none"))    
Laurent@814:         block_infos["usage"] = "\n (%s) => (%s)" % (", ".join(["%s:%s" % (input[1], input[0]) for input in block_infos["inputs"]]),
Laurent@814:                                                     ", ".join(["%s:%s" % (output[1], output[0]) for output in block_infos["outputs"]]))
Laurent@814:         self.CustomBlockTypes.append(block_infos)
Laurent@814:     setattr(cls, "AddCustomBlockType", AddCustomBlockType)
Laurent@814: 
Laurent@814:     def RefreshElementUsingTree(self):
Laurent@814:         # Reset the tree of user-defined element cross-use
Laurent@814:         self.ElementUsingTree = {}
Laurent@814:         pous = self.getpous()
Laurent@814:         datatypes = self.getdataTypes()
Laurent@814:         # Reference all the user-defined elementu names and initialize the tree of 
Laurent@814:         # user-defined elemnt cross-use
Laurent@814:         elementnames = [datatype.getname() for datatype in datatypes] + \
Laurent@814:                        [pou.getname() for pou in pous]
Laurent@814:         for name in elementnames:
Laurent@814:             self.ElementUsingTree[name] = []
Laurent@814:         # Analyze each datatype
Laurent@814:         for datatype in datatypes:
Laurent@814:             name = datatype.getname()
Laurent@814:             basetype_content = datatype.baseType.getcontent()
Laurent@814:             if basetype_content["name"] == "derived":
Laurent@814:                 typename = basetype_content["value"].getname()
Laurent@814:                 if name in self.ElementUsingTree[typename]:
Laurent@814:                     self.ElementUsingTree[typename].append(name)
Laurent@814:             elif basetype_content["name"] in ["subrangeSigned", "subrangeUnsigned", "array"]:
Laurent@814:                 base_type = basetype_content["value"].baseType.getcontent()
Laurent@814:                 if base_type["name"] == "derived":
Laurent@814:                     typename = base_type["value"].getname()
Laurent@814:                     if self.ElementUsingTree.has_key(typename) and name not in self.ElementUsingTree[typename]:
Laurent@814:                         self.ElementUsingTree[typename].append(name)
Laurent@814:             elif basetype_content["name"] == "struct":
Laurent@814:                 for element in basetype_content["value"].getvariable():
Laurent@814:                     type_content = element.type.getcontent()
Laurent@814:                     if type_content["name"] == "derived":
Laurent@814:                         typename = type_content["value"].getname()
Laurent@814:                         if self.ElementUsingTree.has_key(typename) and name not in self.ElementUsingTree[typename]:
Laurent@814:                             self.ElementUsingTree[typename].append(name)
Laurent@814:         # Analyze each pou
Laurent@814:         for pou in pous:
Laurent@814:             name = pou.getname()
Laurent@814:             if pou.interface:
Laurent@814:                 # Extract variables from every varLists
Laurent@814:                 for type, varlist in pou.getvars():
Laurent@814:                     for var in varlist.getvariable():
Laurent@814:                         vartype_content = var.gettype().getcontent()
Laurent@814:                         if vartype_content["name"] == "derived":
Laurent@814:                             typename = vartype_content["value"].getname()
Laurent@814:                             if self.ElementUsingTree.has_key(typename) and name not in self.ElementUsingTree[typename]:
Laurent@814:                                 self.ElementUsingTree[typename].append(name)
Laurent@1142:             for typename in self.ElementUsingTree.iterkeys():
Laurent@1142:                 if typename != name and pou.hasblock(block_type=typename) and name not in self.ElementUsingTree[typename]:
Laurent@1142:                     self.ElementUsingTree[typename].append(name)
Laurent@1142:         
Laurent@814:     setattr(cls, "RefreshElementUsingTree", RefreshElementUsingTree)
Laurent@814: 
Laurent@814:     def GetParentType(self, type):
Laurent@814:         if self.CustomTypeHierarchy.has_key(type):
Laurent@814:             return self.CustomTypeHierarchy[type]
Laurent@814:         elif TypeHierarchy.has_key(type):
Laurent@814:             return TypeHierarchy[type]
Laurent@814:         return None
Laurent@814:     setattr(cls, "GetParentType", GetParentType)
Laurent@814: 
Laurent@814:     def GetBaseType(self, type):
Laurent@814:         parent_type = self.GetParentType(type)
Laurent@814:         if parent_type is not None:
Laurent@814:             if parent_type.startswith("ANY"):
Laurent@814:                 return type
Laurent@814:             else:
Laurent@814:                 return self.GetBaseType(parent_type)
Laurent@814:         return None
Laurent@814:     setattr(cls, "GetBaseType", GetBaseType)
Laurent@814: 
Laurent@814:     def GetSubrangeBaseTypes(self, exclude):
Laurent@814:         derived = []
Laurent@814:         for type in self.CustomTypeHierarchy.keys():
Laurent@814:             for base_type in DataTypeRange.keys():
Laurent@814:                 if self.IsOfType(type, base_type) and not self.IsOfType(type, exclude):
Laurent@814:                     derived.append(type)
Laurent@814:                     break
Laurent@814:         return derived
Laurent@814:     setattr(cls, "GetSubrangeBaseTypes", GetSubrangeBaseTypes)
Laurent@814: 
Laurent@814:     """
Laurent@814:     returns true if the given data type is the same that "reference" meta-type or one of its types.
Laurent@814:     """
Laurent@814:     def IsOfType(self, type, reference):
Laurent@814:         if reference is None:
Laurent@814:             return True
Laurent@814:         elif type == reference:
Laurent@814:             return True
Laurent@814:         else:
Laurent@814:             parent_type = self.GetParentType(type)
Laurent@814:             if parent_type is not None:
Laurent@814:                 return self.IsOfType(parent_type, reference)
Laurent@814:         return False
Laurent@814:     setattr(cls, "IsOfType", IsOfType)
Laurent@814: 
Laurent@814:     # Return if pou given by name is used by another pou
Laurent@814:     def ElementIsUsed(self, name):
Laurent@814:         if self.ElementUsingTree.has_key(name):
Laurent@814:             return len(self.ElementUsingTree[name]) > 0
Laurent@814:         return False
Laurent@814:     setattr(cls, "ElementIsUsed", ElementIsUsed)
Laurent@814: 
Laurent@814:     def DataTypeIsDerived(self, name):
Laurent@814:         return name in self.CustomTypeHierarchy.values()
Laurent@814:     setattr(cls, "DataTypeIsDerived", DataTypeIsDerived)
Laurent@814: 
Laurent@814:     # Return if pou given by name is directly or undirectly used by the reference pou
Laurent@814:     def ElementIsUsedBy(self, name, reference):
Laurent@814:         if self.ElementUsingTree.has_key(name):
Laurent@814:             list = self.ElementUsingTree[name]
Laurent@814:             # Test if pou is directly used by reference
Laurent@814:             if reference in list:
Laurent@814:                 return True
Laurent@814:             else:
Laurent@814:                 # Test if pou is undirectly used by reference, by testing if pous 
Laurent@814:                 # that directly use pou is directly or undirectly used by reference
Laurent@814:                 used = False
Laurent@814:                 for element in list:
Laurent@814:                     used |= self.ElementIsUsedBy(element, reference)
Laurent@814:                 return used
Laurent@814:         return False
Laurent@814:     setattr(cls, "ElementIsUsedBy", ElementIsUsedBy)
Laurent@814: 
Laurent@814:     def GetDataTypeRange(self, type):
Laurent@814:         if self.CustomDataTypeRange.has_key(type):
Laurent@814:             return self.CustomDataTypeRange[type]
Laurent@814:         elif DataTypeRange.has_key(type):
Laurent@814:             return DataTypeRange[type]
Laurent@814:         else:
Laurent@814:             parent_type = self.GetParentType(type)
Laurent@814:             if parent_type is not None:
Laurent@814:                 return self.GetDataTypeRange(parent_type)
Laurent@814:         return None
Laurent@814:     setattr(cls, "GetDataTypeRange", GetDataTypeRange)
Laurent@814: 
Laurent@814:     def GetEnumeratedDataTypeValues(self, type = None):
Laurent@814:         if type is None:
Laurent@814:             all_values = []
Laurent@814:             for values in self.EnumeratedDataTypeValues.values():
Laurent@814:                 all_values.extend(values)
Laurent@814:             return all_values
Laurent@814:         elif self.EnumeratedDataTypeValues.has_key(type):
Laurent@814:             return self.EnumeratedDataTypeValues[type]
Laurent@814:         return []
Laurent@814:     setattr(cls, "GetEnumeratedDataTypeValues", GetEnumeratedDataTypeValues)
Laurent@814: 
Laurent@814:     # Function that returns the block definition associated to the block type given
Laurent@814:     def GetCustomBlockType(self, type, inputs = None):
Laurent@814:         for customblocktype in self.CustomBlockTypes:
Laurent@814:             if inputs is not None and inputs != "undefined":
Laurent@814:                 customblock_inputs = tuple([var_type for name, var_type, modifier in customblocktype["inputs"]])
Laurent@814:                 same_inputs = inputs == customblock_inputs
Laurent@814:             else:
Laurent@814:                 same_inputs = True
Laurent@814:             if customblocktype["name"] == type and same_inputs:
Laurent@814:                 return customblocktype
Laurent@814:         return None
Laurent@814:     setattr(cls, "GetCustomBlockType", GetCustomBlockType)
Laurent@814: 
Laurent@814:     # Return Block types checking for recursion
Laurent@814:     def GetCustomBlockTypes(self, exclude = "", onlyfunctions = False):
Laurent@814:         type = None
Laurent@814:         if exclude != "":
Laurent@814:             pou = self.getpou(exclude)
Laurent@814:             if pou is not None:
Laurent@814:                 type = pou.getpouType()
Laurent@814:         customblocktypes = []
Laurent@814:         for customblocktype in self.CustomBlockTypes:
Laurent@814:             if customblocktype["type"] != "program" and customblocktype["name"] != exclude and not self.ElementIsUsedBy(exclude, customblocktype["name"]) and not (onlyfunctions and customblocktype["type"] != "function"):
Laurent@814:                 customblocktypes.append(customblocktype)
Laurent@814:         return customblocktypes
Laurent@814:     setattr(cls, "GetCustomBlockTypes", GetCustomBlockTypes)
Laurent@814: 
Laurent@814:     # Return Function Block types checking for recursion
Laurent@814:     def GetCustomFunctionBlockTypes(self, exclude = ""):
Laurent@814:         customblocktypes = []
Laurent@814:         for customblocktype in self.CustomBlockTypes:
Laurent@814:             if customblocktype["type"] == "functionBlock" and customblocktype["name"] != exclude and not self.ElementIsUsedBy(exclude, customblocktype["name"]):
Laurent@814:                 customblocktypes.append(customblocktype["name"])
Laurent@814:         return customblocktypes
Laurent@814:     setattr(cls, "GetCustomFunctionBlockTypes", GetCustomFunctionBlockTypes)
Laurent@814: 
Laurent@814:     # Return Block types checking for recursion
Laurent@814:     def GetCustomBlockResource(self):
Laurent@814:         customblocktypes = []
Laurent@814:         for customblocktype in self.CustomBlockTypes:
Laurent@814:             if customblocktype["type"] == "program":
Laurent@814:                 customblocktypes.append(customblocktype["name"])
Laurent@814:         return customblocktypes
Laurent@814:     setattr(cls, "GetCustomBlockResource", GetCustomBlockResource)
Laurent@814: 
Laurent@814:     # Return Data Types checking for recursion
Laurent@814:     def GetCustomDataTypes(self, exclude = "", only_locatable = False):
Laurent@814:         customdatatypes = []
Laurent@814:         for customdatatype in self.getdataTypes():
Laurent@814:             if not only_locatable or self.IsLocatableType(customdatatype):
Laurent@814:                 customdatatype_name = customdatatype.getname()
Laurent@814:                 if customdatatype_name != exclude and not self.ElementIsUsedBy(exclude, customdatatype_name):
Laurent@814:                     customdatatypes.append({"name": customdatatype_name, "infos": customdatatype})
Laurent@814:         return customdatatypes
Laurent@814:     setattr(cls, "GetCustomDataTypes", GetCustomDataTypes)
Laurent@814: 
Laurent@814:     # Return if Data Type can be used for located variables
Laurent@814:     def IsLocatableType(self, datatype):
Laurent@814:         basetype_content = datatype.baseType.getcontent()
Laurent@814:         if basetype_content["name"] in ["enum", "struct"]:
Laurent@814:             return False
Laurent@814:         elif basetype_content["name"] == "derived":
Laurent@814:             base_type = self.getdataType(basetype_content["value"].getname())
Laurent@814:             if base_type is not None:
Laurent@814:                 return self.IsLocatableType(base_type)
Laurent@814:         elif basetype_content["name"] == "array":
Laurent@814:             array_base_type = basetype_content["value"].baseType.getcontent()
Laurent@814:             if array_base_type["value"] is not None and array_base_type["name"] not in ["string", "wstring"]:
Laurent@814:                 base_type = self.getdataType(array_base_type["value"].getname())
Laurent@814:                 if base_type is not None:
Laurent@814:                     return self.IsLocatableType(base_type)
Laurent@814:         return True
Laurent@814:     setattr(cls, "IsLocatableType", IsLocatableType)
Laurent@814: 
Laurent@814:     def Search(self, criteria, parent_infos=[]):
Laurent@814:         result = self.types.Search(criteria, parent_infos)
Laurent@814:         for configuration in self.instances.configurations.getconfiguration():
Laurent@814:             result.extend(configuration.Search(criteria, parent_infos))
Laurent@814:         return result
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("project_fileHeader", None)
Laurent@814: if cls:
Laurent@814:     cls.singleLineAttributes = False
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("project_contentHeader", None)
Laurent@814: if cls:
Laurent@814:     cls.singleLineAttributes = False
Laurent@814:     
Laurent@814:     def setpageSize(self, width, height):
Laurent@814:         self.coordinateInfo.setpageSize(width, height)
Laurent@814:     setattr(cls, "setpageSize", setpageSize)
Laurent@814:     
Laurent@814:     def getpageSize(self):
Laurent@814:         return self.coordinateInfo.getpageSize()
Laurent@814:     setattr(cls, "getpageSize", getpageSize)
Laurent@814: 
Laurent@814:     def setscaling(self, scaling):
Laurent@814:         for language, (x, y) in scaling.items():
Laurent@814:             self.coordinateInfo.setscaling(language, x, y)
Laurent@814:     setattr(cls, "setscaling", setscaling)
Laurent@814:     
Laurent@814:     def getscaling(self):
Laurent@814:         scaling = {}
Laurent@814:         scaling["FBD"] = self.coordinateInfo.getscaling("FBD")
Laurent@814:         scaling["LD"] = self.coordinateInfo.getscaling("LD")
Laurent@814:         scaling["SFC"] = self.coordinateInfo.getscaling("SFC")
Laurent@814:         return scaling
Laurent@814:     setattr(cls, "getscaling", getscaling)
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("contentHeader_coordinateInfo", None)
Laurent@814: if cls:
Laurent@814:     def setpageSize(self, width, height):
Laurent@814:         if width == 0 and height == 0:
Laurent@814:             self.deletepageSize()
Laurent@814:         else:
Laurent@814:             if self.pageSize is None:
Laurent@814:                 self.addpageSize()
Laurent@814:             self.pageSize.setx(width)
Laurent@814:             self.pageSize.sety(height)
Laurent@814:     setattr(cls, "setpageSize", setpageSize)
Laurent@814:     
Laurent@814:     def getpageSize(self):
Laurent@814:         if self.pageSize is not None:
Laurent@814:             return self.pageSize.getx(), self.pageSize.gety()
Laurent@814:         return 0, 0
Laurent@814:     setattr(cls, "getpageSize", getpageSize)
Laurent@814: 
Laurent@814:     def setscaling(self, language, x, y):
Laurent@814:         if language == "FBD":
Laurent@814:             self.fbd.scaling.setx(x)
Laurent@814:             self.fbd.scaling.sety(y)
Laurent@814:         elif language == "LD":
Laurent@814:             self.ld.scaling.setx(x)
Laurent@814:             self.ld.scaling.sety(y)
Laurent@814:         elif language == "SFC":
Laurent@814:             self.sfc.scaling.setx(x)
Laurent@814:             self.sfc.scaling.sety(y)
Laurent@814:     setattr(cls, "setscaling", setscaling)
Laurent@814:     
Laurent@814:     def getscaling(self, language):
Laurent@814:         if language == "FBD":
Laurent@814:             return self.fbd.scaling.getx(), self.fbd.scaling.gety()
Laurent@814:         elif language == "LD":
Laurent@814:             return self.ld.scaling.getx(), self.ld.scaling.gety()
Laurent@814:         elif language == "SFC":
Laurent@814:             return self.sfc.scaling.getx(), self.sfc.scaling.gety()
Laurent@814:         return 0, 0
Laurent@814:     setattr(cls, "getscaling", getscaling)
Laurent@814: 
Laurent@814: def _Search(attributes, criteria, parent_infos):
Laurent@814:     search_result = []
Laurent@814:     for attr, value in attributes:
Laurent@814:         if value is not None:
Laurent@814:             search_result.extend([(tuple(parent_infos + [attr]),) + result for result in TestTextElement(value, criteria)])
Laurent@814:     return search_result
Laurent@814: 
Laurent@814: def _updateConfigurationResourceElementName(self, old_name, new_name):
Laurent@814:     for varlist in self.getglobalVars():
Laurent@814:         for var in varlist.getvariable():
Laurent@814:             var_address = var.getaddress()
Laurent@814:             if var_address is not None:
Laurent@814:                 if var_address == old_name:
Laurent@814:                     var.setaddress(new_name)
Laurent@814:                 if var.getname() == old_name:
Laurent@814:                     var.setname(new_name)
Laurent@814: 
Laurent@814: def _updateConfigurationResourceElementAddress(self, address_model, new_leading):
Laurent@814:     for varlist in self.getglobalVars():
Laurent@814:         for var in varlist.getvariable():
Laurent@814:             var_address = var.getaddress()
Laurent@814:             if var_address is not None:
Laurent@814:                 var.setaddress(update_address(var_address, address_model, new_leading))
Laurent@814: 
Laurent@814: def _removeConfigurationResourceVariableByAddress(self, address):
Laurent@814:     for varlist in self.getglobalVars():
Laurent@814:         variables = varlist.getvariable()
Laurent@814:         for i in xrange(len(variables)-1, -1, -1):
Laurent@814:             if variables[i].getaddress() == address:
Laurent@814:                 variables.pop(i)
Laurent@814: 
Laurent@814: def _removeConfigurationResourceVariableByFilter(self, address_model):
Laurent@814:     for varlist in self.getglobalVars():
Laurent@814:         variables = varlist.getvariable()
Laurent@814:         for i in xrange(len(variables)-1, -1, -1):
Laurent@814:             var_address = variables[i].getaddress()
Laurent@814:             if var_address is not None:
Laurent@814:                 result = address_model.match(var_address)
Laurent@814:                 if result is not None:
Laurent@814:                     variables.pop(i)
Laurent@814: 
Laurent@814: def _SearchInConfigurationResource(self, criteria, parent_infos=[]):
Laurent@814:     search_result = _Search([("name", self.getname())], criteria, parent_infos)
Laurent@814:     var_number = 0
Laurent@814:     for varlist in self.getglobalVars():
Laurent@814:         variable_type = searchResultVarTypes.get("globalVars", "var_local")
Laurent@814:         variables = varlist.getvariable()
Laurent@814:         for modifier, has_modifier in [("constant", varlist.getconstant()),
Laurent@814:                                        ("retain", varlist.getretain()),
Laurent@814:                                        ("non_retain", varlist.getnonretain())]:
Laurent@814:             if has_modifier:
Laurent@814:                 for result in TestTextElement(modifier, criteria):
Laurent@814:                     search_result.append((tuple(parent_infos + [variable_type, (var_number, var_number + len(variables)), modifier]),) + result)
Laurent@814:                 break
Laurent@814:         for variable in variables:
Laurent@814:             search_result.extend(variable.Search(criteria, parent_infos + [variable_type, var_number]))
Laurent@814:             var_number += 1
Laurent@814:     return search_result
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("configurations_configuration", None)
Laurent@814: if cls:
Laurent@1171:     
Laurent@1171:     def addglobalVar(self, type, name, location="", description=""):
Laurent@1171:         globalvars = self.getglobalVars()
Laurent@1171:         if len(globalvars) == 0:
Laurent@1171:             globalvars.append(PLCOpenClasses["varList"]())
Laurent@1171:         var = PLCOpenClasses["varListPlain_variable"]()
Laurent@1171:         var.setname(name)
Laurent@1171:         var_type = PLCOpenClasses["dataType"]()
Laurent@1171:         if type in [x for x,y in TypeHierarchy_list if not x.startswith("ANY")]:
Laurent@1171:             if type == "STRING":
Laurent@1171:                 var_type.setcontent({"name" : "string", "value" : PLCOpenClasses["elementaryTypes_string"]()})
Laurent@1171:             elif type == "WSTRING":
Laurent@1171:                 var_type.setcontent({"name" : "wstring", "value" : PLCOpenClasses["elementaryTypes_wstring"]()})
Laurent@1171:             else:
Laurent@1171:                 var_type.setcontent({"name" : type, "value" : None})
Laurent@1171:         else:
Laurent@1171:             derived_type = PLCOpenClasses["derivedTypes_derived"]()
Laurent@1171:             derived_type.setname(type)
Laurent@1171:             var_type.setcontent({"name" : "derived", "value" : derived_type})
Laurent@1171:         var.settype(var_type)
Laurent@1171:         if location != "":
Laurent@1171:             var.setaddress(location)
Laurent@1171:         if description != "":
Laurent@1171:             ft = PLCOpenClasses["formattedText"]()
Laurent@1171:             ft.settext(description)
Laurent@1171:             var.setdocumentation(ft)
Laurent@1171:         globalvars[-1].appendvariable(var)
Laurent@1171:     setattr(cls, "addglobalVar", addglobalVar)
Laurent@1171:     
Laurent@814:     def updateElementName(self, old_name, new_name):
Laurent@814:         _updateConfigurationResourceElementName(self, old_name, new_name)
Laurent@814:         for resource in self.getresource():
Laurent@814:             resource.updateElementName(old_name, new_name)
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814: 
Laurent@814:     def updateElementAddress(self, address_model, new_leading):
Laurent@814:         _updateConfigurationResourceElementAddress(self, address_model, new_leading)
Laurent@814:         for resource in self.getresource():
Laurent@814:             resource.updateElementAddress(address_model, new_leading)
Laurent@814:     setattr(cls, "updateElementAddress", updateElementAddress)
Laurent@814: 
Laurent@814:     setattr(cls, "removeVariableByAddress", _removeConfigurationResourceVariableByAddress)
Laurent@814:     setattr(cls, "removeVariableByFilter", _removeConfigurationResourceVariableByFilter)
Laurent@814: 
Laurent@814:     def Search(self, criteria, parent_infos=[]):
Laurent@814:         search_result = []
Laurent@814:         parent_infos = parent_infos + ["C::%s" % self.getname()]
Laurent@814:         filter = criteria["filter"]
Laurent@814:         if filter == "all" or "configuration" in filter:
Laurent@814:             search_result = _SearchInConfigurationResource(self, criteria, parent_infos)
Laurent@814:             for resource in self.getresource():
Laurent@814:                 search_result.extend(resource.Search(criteria, parent_infos))
Laurent@814:         return search_result
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814:     
Laurent@814: cls = PLCOpenClasses.get("configuration_resource", None)
Laurent@814: if cls:
Laurent@814:     def updateElementName(self, old_name, new_name):
Laurent@814:         _updateConfigurationResourceElementName(self, old_name, new_name)
Laurent@814:         for instance in self.getpouInstance():
Laurent@814:             instance.updateElementName(old_name, new_name)
Laurent@814:         for task in self.gettask():
Laurent@814:             task.updateElementName(old_name, new_name)
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814: 
Laurent@814:     def updateElementAddress(self, address_model, new_leading):
Laurent@814:         _updateConfigurationResourceElementAddress(self, address_model, new_leading)
Laurent@814:         for task in self.gettask():
Laurent@814:             task.updateElementAddress(address_model, new_leading)
Laurent@814:     setattr(cls, "updateElementAddress", updateElementAddress)
Laurent@814: 
Laurent@814:     setattr(cls, "removeVariableByAddress", _removeConfigurationResourceVariableByAddress)
Laurent@814:     setattr(cls, "removeVariableByFilter", _removeConfigurationResourceVariableByFilter)
Laurent@814: 
Laurent@814:     def Search(self, criteria, parent_infos=[]):
Laurent@814:         parent_infos = parent_infos[:-1] + ["R::%s::%s" % (parent_infos[-1].split("::")[1], self.getname())]
Laurent@814:         search_result = _SearchInConfigurationResource(self, criteria, parent_infos)
Laurent@814:         task_number = 0
Laurent@814:         instance_number = 0
Laurent@814:         for task in self.gettask():
Laurent@814:             results = TestTextElement(task.getname(), criteria)
Laurent@814:             for result in results:
Laurent@814:                 search_result.append((tuple(parent_infos + ["task", task_number, "name"]),) + result)
Laurent@814:             search_result.extend(task.Search(criteria, parent_infos + ["task", task_number]))
Laurent@814:             task_number += 1
Laurent@814:             for instance in task.getpouInstance():
Laurent@814:                 search_result.extend(task.Search(criteria, parent_infos + ["instance", instance_number]))
Laurent@814:                 for result in results:
Laurent@814:                     search_result.append((tuple(parent_infos + ["instance", instance_number, "task"]),) + result)
Laurent@814:                 instance_number += 1
Laurent@814:         for instance in self.getpouInstance():
Laurent@814:             search_result.extend(instance.Search(criteria, parent_infos + ["instance", instance_number]))
Laurent@814:             instance_number += 1
Laurent@814:         return search_result
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("resource_task", None)
Laurent@814: if cls:
Laurent@814:     def compatibility(self, tree):
Laurent@814:         if tree.hasAttribute("interval"):
Laurent@814:             interval = GetAttributeValue(tree._attrs["interval"])
Laurent@814:             result = time_model.match(interval)
Laurent@814:             if result is not None:
Laurent@814:                 values = result.groups()
Laurent@814:                 time_values = [int(v) for v in values[:2]]
Laurent@814:                 seconds = float(values[2])
Laurent@814:                 time_values.extend([int(seconds), int((seconds % 1) * 1000000)])
Laurent@814:                 text = "t#"
Laurent@814:                 if time_values[0] != 0:
Laurent@814:                     text += "%dh"%time_values[0]
Laurent@814:                 if time_values[1] != 0:
Laurent@814:                     text += "%dm"%time_values[1]
Laurent@814:                 if time_values[2] != 0:
Laurent@814:                     text += "%ds"%time_values[2]
Laurent@814:                 if time_values[3] != 0:
Laurent@814:                     if time_values[3] % 1000 != 0:
Laurent@814:                         text += "%.3fms"%(float(time_values[3]) / 1000)
Laurent@814:                     else:
Laurent@814:                         text += "%dms"%(time_values[3] / 1000)
Laurent@814:                 NodeSetAttr(tree, "interval", text)
Laurent@814:     setattr(cls, "compatibility", compatibility)
Laurent@814:     
Laurent@814:     def updateElementName(self, old_name, new_name):
Laurent@814:         if self.single == old_name:
Laurent@814:             self.single = new_name
Laurent@814:         if self.interval == old_name:
Laurent@814:             self.interval = new_name
Laurent@814:         for instance in self.getpouInstance():
Laurent@814:             instance.updateElementName(old_name, new_name)
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814: 
Laurent@814:     def updateElementAddress(self, address_model, new_leading):
Laurent@814:         if self.single is not None:
Laurent@814:             self.single = update_address(self.single, address_model, new_leading)
Laurent@814:         if self.interval is not None:
Laurent@814:             self.interval = update_address(self.interval, address_model, new_leading)
Laurent@814:     setattr(cls, "updateElementAddress", updateElementAddress)
Laurent@814: 
Laurent@814:     def Search(self, criteria, parent_infos=[]):
Laurent@814:         return _Search([("single", self.getsingle()), 
Laurent@814:                         ("interval", self.getinterval()),
Laurent@814:                         ("priority", str(self.getpriority()))],
Laurent@814:                        criteria, parent_infos)
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("pouInstance", None)
Laurent@814: if cls:
Laurent@814:     def compatibility(self, tree):
Laurent@814:         if tree.hasAttribute("type"):
Laurent@814:             NodeRenameAttr(tree, "type", "typeName")
Laurent@814:     setattr(cls, "compatibility", compatibility)
Laurent@814:     
Laurent@814:     def updateElementName(self, old_name, new_name):
Laurent@814:         if self.typeName == old_name:
Laurent@814:             self.typeName = new_name
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814: 
Laurent@814:     def Search(self, criteria, parent_infos=[]):
Laurent@814:         return _Search([("name", self.getname()), 
Laurent@814:                         ("type", self.gettypeName())],
Laurent@814:                        criteria, parent_infos)
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("varListPlain_variable", None)
Laurent@814: if cls:
Laurent@814:     def gettypeAsText(self):
Laurent@814:         vartype_content = self.gettype().getcontent()
Laurent@814:         # Variable type is a user data type
Laurent@814:         if vartype_content["name"] == "derived":
Laurent@814:             return vartype_content["value"].getname()
Laurent@814:         # Variable type is a string type
Laurent@814:         elif vartype_content["name"] in ["string", "wstring"]:
Laurent@814:             return vartype_content["name"].upper()
Laurent@814:         # Variable type is an array
Laurent@814:         elif vartype_content["name"] == "array":
Laurent@814:             base_type = vartype_content["value"].baseType.getcontent()
Laurent@814:             # Array derived directly from a user defined type 
Laurent@814:             if base_type["name"] == "derived":
Laurent@814:                 basetype_name = base_type["value"].getname()
Laurent@814:             # Array derived directly from a string type 
Laurent@814:             elif base_type["name"] in ["string", "wstring"]:
Laurent@814:                 basetype_name = base_type["name"].upper()
Laurent@814:             # Array derived directly from an elementary type 
Laurent@814:             else:
Laurent@814:                 basetype_name = base_type["name"]
Laurent@814:             return "ARRAY [%s] OF %s" % (",".join(map(lambda x : "%s..%s" % (x.getlower(), x.getupper()), vartype_content["value"].getdimension())), basetype_name)
Laurent@814:         # Variable type is an elementary type
Laurent@814:         return vartype_content["name"]
Laurent@814:     setattr(cls, "gettypeAsText", gettypeAsText)
Laurent@814:     
Laurent@814:     def Search(self, criteria, parent_infos=[]):
Laurent@814:         search_result = _Search([("name", self.getname()), 
Laurent@814:                                  ("type", self.gettypeAsText()),
Laurent@814:                                  ("location", self.getaddress())],
Laurent@814:                                 criteria, parent_infos)
Laurent@814:         initial = self.getinitialValue()
Laurent@814:         if initial is not None:
Laurent@814:             search_result.extend(_Search([("initial value", initial.getvalue())], criteria, parent_infos))
Laurent@814:         doc = self.getdocumentation()
Laurent@814:         if doc is not None:
Laurent@814:             search_result.extend(doc.Search(criteria, parent_infos + ["documentation"]))
Laurent@814:         return search_result
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("project_types", None)
Laurent@814: if cls:
Laurent@814:     def getdataTypeElements(self):
Laurent@814:         return self.dataTypes.getdataType()
Laurent@814:     setattr(cls, "getdataTypeElements", getdataTypeElements)
Laurent@814:     
Laurent@814:     def getdataTypeElement(self, name):
Laurent@814:         elements = self.dataTypes.getdataType()
Laurent@814:         for element in elements:
Laurent@814:             if element.getname() == name:
Laurent@814:                 return element
Laurent@814:         return None
Laurent@814:     setattr(cls, "getdataTypeElement", getdataTypeElement)
Laurent@814: 
Laurent@814:     def appenddataTypeElement(self, name):
Laurent@814:         new_datatype = PLCOpenClasses["dataTypes_dataType"]()
Laurent@814:         new_datatype.setname(name)
Laurent@814:         new_datatype.baseType.setcontent({"name" : "BOOL", "value" : None})
Laurent@814:         self.dataTypes.appenddataType(new_datatype)
Laurent@814:     setattr(cls, "appenddataTypeElement", appenddataTypeElement)
Laurent@814:     
Laurent@814:     def insertdataTypeElement(self, index, dataType):
Laurent@814:         self.dataTypes.insertdataType(index, dataType)
Laurent@814:     setattr(cls, "insertdataTypeElement", insertdataTypeElement)
Laurent@814:     
Laurent@814:     def removedataTypeElement(self, name):
Laurent@814:         found = False
Laurent@814:         for idx, element in enumerate(self.dataTypes.getdataType()):
Laurent@814:             if element.getname() == name:
Laurent@814:                 self.dataTypes.removedataType(idx)
Laurent@814:                 found = True
Laurent@814:                 break
Laurent@814:         if not found:
Laurent@814:             raise ValueError, _("\"%s\" Data Type doesn't exist !!!")%name
Laurent@814:     setattr(cls, "removedataTypeElement", removedataTypeElement)
Laurent@814:     
Laurent@814:     def getpouElements(self):
Laurent@814:         return self.pous.getpou()
Laurent@814:     setattr(cls, "getpouElements", getpouElements)
Laurent@814:     
Laurent@814:     def getpouElement(self, name):
Laurent@814:         elements = self.pous.getpou()
Laurent@814:         for element in elements:
Laurent@814:             if element.getname() == name:
Laurent@814:                 return element
Laurent@814:         return None
Laurent@814:     setattr(cls, "getpouElement", getpouElement)
Laurent@814: 
Laurent@814:     def appendpouElement(self, name, pou_type, body_type):
Laurent@814:         for element in self.pous.getpou():
Laurent@814:             if element.getname() == name:
Laurent@814:                 raise ValueError, _("\"%s\" POU already exists !!!")%name
Laurent@814:         new_pou = PLCOpenClasses["pous_pou"]()
Laurent@814:         new_pou.setname(name)
Laurent@814:         new_pou.setpouType(pou_type)
Laurent@814:         new_pou.appendbody(PLCOpenClasses["body"]())
Laurent@814:         new_pou.setbodyType(body_type)
Laurent@814:         self.pous.appendpou(new_pou)
Laurent@814:     setattr(cls, "appendpouElement", appendpouElement)
Laurent@814:         
Laurent@814:     def insertpouElement(self, index, pou):
Laurent@814:         self.pous.insertpou(index, pou)
Laurent@814:     setattr(cls, "insertpouElement", insertpouElement)
Laurent@814:     
Laurent@814:     def removepouElement(self, name):
Laurent@814:         found = False
Laurent@814:         for idx, element in enumerate(self.pous.getpou()):
Laurent@814:             if element.getname() == name:
Laurent@814:                 self.pous.removepou(idx)
Laurent@814:                 found = True
Laurent@814:                 break
Laurent@814:         if not found:
Laurent@814:             raise ValueError, _("\"%s\" POU doesn't exist !!!")%name
Laurent@814:     setattr(cls, "removepouElement", removepouElement)
Laurent@814: 
Laurent@814:     def Search(self, criteria, parent_infos=[]):
Laurent@814:         search_result = []
Laurent@814:         filter = criteria["filter"]
Laurent@814:         for datatype in self.dataTypes.getdataType():
Laurent@814:             search_result.extend(datatype.Search(criteria, parent_infos))
Laurent@814:         for pou in self.pous.getpou():
Laurent@814:             search_result.extend(pou.Search(criteria, parent_infos))
Laurent@814:         return search_result
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814: 
Laurent@814: def _updateBaseTypeElementName(self, old_name, new_name):
Laurent@814:     self.baseType.updateElementName(old_name, new_name)
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("dataTypes_dataType", None)
Laurent@814: if cls:
Laurent@814:     setattr(cls, "updateElementName", _updateBaseTypeElementName)
Laurent@814:     
Laurent@814:     def Search(self, criteria, parent_infos=[]):
Laurent@814:         search_result = []
Laurent@814:         filter = criteria["filter"]
Laurent@814:         if filter == "all" or "datatype" in filter:
Laurent@814:             parent_infos = parent_infos + ["D::%s" % self.getname()]
Laurent@814:             search_result.extend(_Search([("name", self.getname())], criteria, parent_infos))
Laurent@814:             search_result.extend(self.baseType.Search(criteria, parent_infos))
Laurent@814:             if self.initialValue is not None:
Laurent@814:                 search_result.extend(_Search([("initial", self.initialValue.getvalue())], criteria, parent_infos))
Laurent@814:         return search_result
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("dataType", None)
Laurent@814: if cls:
Laurent@814:     
Laurent@814:     def updateElementName(self, old_name, new_name):
Laurent@814:         if self.content["name"] in ["derived", "array", "subrangeSigned", "subrangeUnsigned"]:
Laurent@814:             self.content["value"].updateElementName(old_name, new_name)
Laurent@814:         elif self.content["name"] == "struct":
Laurent@814:             for element in self.content["value"].getvariable():
Laurent@814:                 element_type = element.type.updateElementName(old_name, new_name)
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814: 
Laurent@814:     def Search(self, criteria, parent_infos=[]):
Laurent@814:         search_result = []
Laurent@814:         if self.content["name"] in ["derived", "array", "enum", "subrangeSigned", "subrangeUnsigned"]:
Laurent@814:             search_result.extend(self.content["value"].Search(criteria, parent_infos))
Laurent@814:         elif self.content["name"] == "struct":
Laurent@814:             for i, element in enumerate(self.content["value"].getvariable()):
Laurent@814:                 search_result.extend(element.Search(criteria, parent_infos + ["struct", i]))
Laurent@814:         else:
Laurent@814:             basetype = self.content["name"]
Laurent@814:             if basetype in ["string", "wstring"]:
Laurent@814:                 basetype = basetype.upper()
Laurent@814:             search_result.extend(_Search([("base", basetype)], criteria, parent_infos))
Laurent@814:         return search_result
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("derivedTypes_array", None)
Laurent@814: if cls:
Laurent@814:     setattr(cls, "updateElementName", _updateBaseTypeElementName)
Laurent@814:     
Laurent@814:     def Search(self, criteria, parent_infos=[]):
Laurent@814:         search_result = self.baseType.Search(criteria, parent_infos)
Laurent@814:         for i, dimension in enumerate(self.getdimension()):
Laurent@814:             search_result.extend(_Search([("lower", dimension.getlower()),
Laurent@814:                                           ("upper", dimension.getupper())],
Laurent@814:                                          criteria, parent_infos + ["range", i]))
Laurent@814:         return search_result
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814: 
Laurent@814: def _SearchInSubrange(self, criteria, parent_infos=[]):
Laurent@814:     search_result = self.baseType.Search(criteria, parent_infos)
Laurent@814:     search_result.extend(_Search([("lower", self.range.getlower()),
Laurent@814:                                   ("upper", self.range.getupper())],
Laurent@814:                                  criteria, parent_infos))
Laurent@814:     return search_result
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("derivedTypes_subrangeSigned", None)
Laurent@814: if cls:
Laurent@814:     setattr(cls, "updateElementName", _updateBaseTypeElementName)
Laurent@814:     setattr(cls, "Search", _SearchInSubrange)
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("derivedTypes_subrangeUnsigned", None)
Laurent@814: if cls:
Laurent@814:     setattr(cls, "updateElementName", _updateBaseTypeElementName)
Laurent@814:     setattr(cls, "Search", _SearchInSubrange)
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("derivedTypes_enum", None)
Laurent@814: if cls:
Laurent@814:     
Laurent@814:     def updateElementName(self, old_name, new_name):
Laurent@814:         pass
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814:     
Laurent@814:     def Search(self, criteria, parent_infos=[]):
Laurent@814:         search_result = []
Laurent@814:         for i, value in enumerate(self.values.getvalue()):
Laurent@814:             for result in TestTextElement(value.getname(), criteria):
Laurent@814:                 search_result.append((tuple(parent_infos + ["value", i]),) + result)
Laurent@814:         return search_result
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("pous_pou", None)
Laurent@814: if cls:
Laurent@814:     
Laurent@814:     def setdescription(self, description):
Laurent@814:         doc = self.getdocumentation()
Laurent@814:         if doc is None:
Laurent@814:             doc = PLCOpenClasses["formattedText"]()
Laurent@814:             self.setdocumentation(doc)
Laurent@814:         doc.settext(description)
Laurent@814:     setattr(cls, "setdescription", setdescription)
Laurent@814:     
Laurent@814:     def getdescription(self):
Laurent@814:         doc = self.getdocumentation()
Laurent@814:         if doc is not None:
Laurent@814:             return doc.gettext()
Laurent@814:         return ""
Laurent@814:     setattr(cls, "getdescription", getdescription)
Laurent@814:     
Laurent@814:     def setbodyType(self, type):
Laurent@814:         if len(self.body) > 0:
Laurent@814:             if type == "IL":
Laurent@814:                 self.body[0].setcontent({"name" : "IL", "value" : PLCOpenClasses["formattedText"]()})
Laurent@814:             elif type == "ST":
Laurent@814:                 self.body[0].setcontent({"name" : "ST", "value" : PLCOpenClasses["formattedText"]()})
Laurent@814:             elif type == "LD":
Laurent@814:                 self.body[0].setcontent({"name" : "LD", "value" : PLCOpenClasses["body_LD"]()})
Laurent@814:             elif type == "FBD":
Laurent@814:                 self.body[0].setcontent({"name" : "FBD", "value" : PLCOpenClasses["body_FBD"]()})
Laurent@814:             elif type == "SFC":
Laurent@814:                 self.body[0].setcontent({"name" : "SFC", "value" : PLCOpenClasses["body_SFC"]()})
Laurent@814:             else:
Laurent@814:                 raise ValueError, "%s isn't a valid body type!"%type
Laurent@814:     setattr(cls, "setbodyType", setbodyType)
Laurent@814:     
Laurent@814:     def getbodyType(self):
Laurent@814:         if len(self.body) > 0:
Laurent@814:             return self.body[0].getcontent()["name"]
Laurent@814:     setattr(cls, "getbodyType", getbodyType)
Laurent@814:     
Laurent@814:     def resetexecutionOrder(self):
Laurent@814:         if len(self.body) > 0:
Laurent@814:             self.body[0].resetexecutionOrder()
Laurent@814:     setattr(cls, "resetexecutionOrder", resetexecutionOrder)
Laurent@814:     
Laurent@814:     def compileexecutionOrder(self):
Laurent@814:         if len(self.body) > 0:
Laurent@814:             self.body[0].compileexecutionOrder()
Laurent@814:     setattr(cls, "compileexecutionOrder", compileexecutionOrder)
Laurent@814:     
Laurent@814:     def setelementExecutionOrder(self, instance, new_executionOrder):
Laurent@814:         if len(self.body) > 0:
Laurent@814:             self.body[0].setelementExecutionOrder(instance, new_executionOrder)
Laurent@814:     setattr(cls, "setelementExecutionOrder", setelementExecutionOrder)
Laurent@814:     
Laurent@814:     def addinstance(self, name, instance):
Laurent@814:         if len(self.body) > 0:
Laurent@814:             self.body[0].appendcontentInstance(name, instance)
Laurent@814:     setattr(cls, "addinstance", addinstance)
Laurent@814:     
Laurent@814:     def getinstances(self):
Laurent@814:         if len(self.body) > 0:
Laurent@814:             return self.body[0].getcontentInstances()
Laurent@814:         return []
Laurent@814:     setattr(cls, "getinstances", getinstances)
Laurent@814:     
Laurent@814:     def getinstance(self, id):
Laurent@814:         if len(self.body) > 0:
Laurent@814:             return self.body[0].getcontentInstance(id)
Laurent@814:         return None
Laurent@814:     setattr(cls, "getinstance", getinstance)
Laurent@814:     
Laurent@814:     def getrandomInstance(self, exclude):
Laurent@814:         if len(self.body) > 0:
Laurent@814:             return self.body[0].getcontentRandomInstance(exclude)
Laurent@814:         return None
Laurent@814:     setattr(cls, "getrandomInstance", getrandomInstance)
Laurent@814:     
Laurent@814:     def getinstanceByName(self, name):
Laurent@814:         if len(self.body) > 0:
Laurent@814:             return self.body[0].getcontentInstanceByName(name)
Laurent@814:         return None
Laurent@814:     setattr(cls, "getinstanceByName", getinstanceByName)
Laurent@814:     
Laurent@814:     def removeinstance(self, id):
Laurent@814:         if len(self.body) > 0:
Laurent@814:             self.body[0].removecontentInstance(id)
Laurent@814:     setattr(cls, "removeinstance", removeinstance)
Laurent@814:     
Laurent@814:     def settext(self, text):
Laurent@814:         if len(self.body) > 0:
Laurent@814:             self.body[0].settext(text)
Laurent@814:     setattr(cls, "settext", settext)
Laurent@814:     
Laurent@814:     def gettext(self):
Laurent@814:         if len(self.body) > 0:
Laurent@814:             return self.body[0].gettext()
Laurent@814:         return ""
Laurent@814:     setattr(cls, "gettext", gettext)
Laurent@814: 
Laurent@814:     def getvars(self):
Laurent@814:         vars = []
Laurent@814:         if self.interface is not None:
Laurent@814:             reverse_types = {}
Laurent@814:             for name, value in VarTypes.items():
Laurent@814:                 reverse_types[value] = name
Laurent@814:             for varlist in self.interface.getcontent():
Laurent@814:                 vars.append((reverse_types[varlist["name"]], varlist["value"]))
Laurent@814:         return vars
Laurent@814:     setattr(cls, "getvars", getvars)
Laurent@814:     
Laurent@814:     def setvars(self, vars):
Laurent@814:         if self.interface is None:
Laurent@814:             self.interface = PLCOpenClasses["pou_interface"]()
Laurent@814:         self.interface.setcontent([])
Laurent@814:         for vartype, varlist in vars:
Laurent@814:             self.interface.appendcontent({"name" : VarTypes[vartype], "value" : varlist})
Laurent@814:     setattr(cls, "setvars", setvars)
Laurent@814:     
Laurent@814:     def addpouLocalVar(self, type, name, location="", description=""):
Laurent@814:         self.addpouVar(type, name, location=location, description=description)
Laurent@814:     setattr(cls, "addpouLocalVar", addpouLocalVar)
Laurent@814:         
Laurent@814:     def addpouExternalVar(self, type, name):
Laurent@814:         self.addpouVar(type, name, "externalVars")
Laurent@814:     setattr(cls, "addpouExternalVar", addpouExternalVar)
Laurent@814:     
Laurent@814:     def addpouVar(self, type, name, var_class="localVars", location="", description=""):
Laurent@814:         if self.interface is None:
Laurent@814:             self.interface = PLCOpenClasses["pou_interface"]()
Laurent@814:         content = self.interface.getcontent()
Laurent@814:         if len(content) == 0 or content[-1]["name"] != var_class:
Laurent@814:             content.append({"name" : var_class, "value" : PLCOpenClasses["interface_%s" % var_class]()})
Laurent@814:         else:
Laurent@814:             varlist = content[-1]["value"]
Laurent@814:             variables = varlist.getvariable()
Laurent@814:             if varlist.getconstant() or varlist.getretain() or len(variables) > 0 and variables[0].getaddress():
Laurent@814:                 content.append({"name" : var_class, "value" : PLCOpenClasses["interface_%s" % var_class]()})
Laurent@814:         var = PLCOpenClasses["varListPlain_variable"]()
Laurent@814:         var.setname(name)
Laurent@814:         var_type = PLCOpenClasses["dataType"]()
Laurent@814:         if type in [x for x,y in TypeHierarchy_list if not x.startswith("ANY")]:
Laurent@814:             if type == "STRING":
Laurent@814:                 var_type.setcontent({"name" : "string", "value" : PLCOpenClasses["elementaryTypes_string"]()})
Laurent@814:             elif type == "WSTRING":
Laurent@814:                 var_type.setcontent({"name" : "wstring", "value" : PLCOpenClasses["elementaryTypes_wstring"]()})
Laurent@814:             else:
Laurent@814:                 var_type.setcontent({"name" : type, "value" : None})
Laurent@814:         else:
Laurent@814:             derived_type = PLCOpenClasses["derivedTypes_derived"]()
Laurent@814:             derived_type.setname(type)
Laurent@814:             var_type.setcontent({"name" : "derived", "value" : derived_type})
Laurent@814:         var.settype(var_type)
Laurent@814:         if location != "":
Laurent@814:             var.setaddress(location)
Laurent@814:         if description != "":
Laurent@814:             ft = PLCOpenClasses["formattedText"]()
Laurent@814:             ft.settext(description)
Laurent@814:             var.setdocumentation(ft)
Laurent@814:         
Laurent@814:         content[-1]["value"].appendvariable(var)
Laurent@814:     setattr(cls, "addpouVar", addpouVar)
Laurent@814:     
Laurent@814:     def changepouVar(self, old_type, old_name, new_type, new_name):
Laurent@814:         if self.interface is not None:
Laurent@814:             content = self.interface.getcontent()
Laurent@814:             for varlist in content:
Laurent@814:                 variables = varlist["value"].getvariable()
Laurent@814:                 for var in variables:
Laurent@814:                     if var.getname() == old_name:
Laurent@814:                         vartype_content = var.gettype().getcontent()
Laurent@814:                         if vartype_content["name"] == "derived" and vartype_content["value"].getname() == old_type:
Laurent@814:                             var.setname(new_name)
Laurent@814:                             vartype_content["value"].setname(new_type)
Laurent@814:                             return
Laurent@814:     setattr(cls, "changepouVar", changepouVar)
Laurent@814:     
Laurent@814:     def removepouVar(self, type, name):
Laurent@814:         if self.interface is not None:
Laurent@814:             content = self.interface.getcontent()
Laurent@814:             for varlist in content:
Laurent@814:                 variables = varlist["value"].getvariable()
Laurent@814:                 for var in variables:
Laurent@814:                     if var.getname() == name:
Laurent@814:                         vartype_content = var.gettype().getcontent()
Laurent@814:                         if vartype_content["name"] == "derived" and vartype_content["value"].getname() == type:
Laurent@814:                             variables.remove(var)
Laurent@814:                             break
Laurent@814:                 if len(varlist["value"].getvariable()) == 0:
Laurent@814:                     content.remove(varlist)
Laurent@814:                     break
Laurent@814:     setattr(cls, "removepouVar", removepouVar)
Laurent@814:     
Laurent@1142:     def hasblock(self, name=None, block_type=None):
Laurent@1142:         if self.getbodyType() in ["FBD", "LD", "SFC"]:
Laurent@814:             for instance in self.getinstances():
Laurent@1142:                 if (isinstance(instance, PLCOpenClasses["fbdObjects_block"]) and 
Laurent@1142:                     (name and instance.getinstanceName() == name or
Laurent@1142:                      block_type and instance.gettypeName() == block_type)):
Laurent@814:                     return True
Laurent@814:             if self.transitions:
Laurent@814:                 for transition in self.transitions.gettransition():
Laurent@1142:                     result = transition.hasblock(name, block_type)
Laurent@814:                     if result:
Laurent@814:                         return result
Laurent@814:             if self.actions:
Laurent@814:                 for action in self.actions.getaction():
Laurent@1142:                     result = action.hasblock(name, block_type)
Laurent@814:                     if result:
Laurent@814:                         return result
Laurent@1142:         elif block_type is not None and len(self.body) > 0:
Laurent@1142:             return self.body[0].hasblock(block_type)
Laurent@814:         return False
Laurent@814:     setattr(cls, "hasblock", hasblock)
Laurent@814:     
Laurent@814:     def addtransition(self, name, type):
Laurent@814:         if not self.transitions:
Laurent@814:             self.addtransitions()
Laurent@814:             self.transitions.settransition([])
Laurent@814:         transition = PLCOpenClasses["transitions_transition"]()
Laurent@814:         transition.setname(name)
Laurent@814:         transition.setbodyType(type)
Laurent@814:         if type == "ST":
Laurent@814:             transition.settext(":= ;")
Laurent@814:         elif type == "IL":
Laurent@814:             transition.settext("\tST\t%s"%name)
Laurent@814:         self.transitions.appendtransition(transition)
Laurent@814:     setattr(cls, "addtransition", addtransition)
Laurent@814:     
Laurent@814:     def gettransition(self, name):
Laurent@814:         if self.transitions:
Laurent@814:             for transition in self.transitions.gettransition():
Laurent@814:                 if transition.getname() == name:
Laurent@814:                     return transition
Laurent@814:         return None
Laurent@814:     setattr(cls, "gettransition", gettransition)
Laurent@814:         
Laurent@814:     def gettransitionList(self):
Laurent@814:         if self.transitions:
Laurent@814:             return self.transitions.gettransition()
Laurent@814:         return []
Laurent@814:     setattr(cls, "gettransitionList", gettransitionList)
Laurent@814:     
Laurent@814:     def removetransition(self, name):
Laurent@814:         if self.transitions:
Laurent@814:             transitions = self.transitions.gettransition()
Laurent@814:             i = 0
Laurent@814:             removed = False
Laurent@814:             while i < len(transitions) and not removed:
Laurent@814:                 if transitions[i].getname() == name:
laurent@824:                     if transitions[i].getbodyType() in ["FBD", "LD", "SFC"]:
laurent@824:                         for instance in transitions[i].getinstances():
laurent@824:                             if isinstance(instance, PLCOpenClasses["fbdObjects_block"]):
laurent@824:                                 self.removepouVar(instance.gettypeName(), 
laurent@824:                                                   instance.getinstanceName())
Laurent@814:                     transitions.pop(i)
Laurent@814:                     removed = True
Laurent@814:                 i += 1
Laurent@814:             if not removed:
Laurent@814:                 raise ValueError, _("Transition with name %s doesn't exist!")%name
Laurent@814:     setattr(cls, "removetransition", removetransition)
Laurent@814: 
Laurent@814:     def addaction(self, name, type):
Laurent@814:         if not self.actions:
Laurent@814:             self.addactions()
Laurent@814:             self.actions.setaction([])
Laurent@814:         action = PLCOpenClasses["actions_action"]()
Laurent@814:         action.setname(name)
Laurent@814:         action.setbodyType(type)
Laurent@814:         self.actions.appendaction(action)
Laurent@814:     setattr(cls, "addaction", addaction)
Laurent@814:     
Laurent@814:     def getaction(self, name):
Laurent@814:         if self.actions:
Laurent@814:             for action in self.actions.getaction():
Laurent@814:                 if action.getname() == name:
Laurent@814:                     return action
Laurent@814:         return None
Laurent@814:     setattr(cls, "getaction", getaction)
Laurent@814:     
Laurent@814:     def getactionList(self):
Laurent@814:         if self.actions:
Laurent@814:             return self.actions.getaction()
Laurent@814:         return []
Laurent@814:     setattr(cls, "getactionList", getactionList)
laurent@824:     
Laurent@814:     def removeaction(self, name):
Laurent@814:         if self.actions:
Laurent@814:             actions = self.actions.getaction()
Laurent@814:             i = 0
Laurent@814:             removed = False
Laurent@814:             while i < len(actions) and not removed:
Laurent@814:                 if actions[i].getname() == name:
laurent@824:                     if actions[i].getbodyType() in ["FBD", "LD", "SFC"]:
laurent@824:                         for instance in actions[i].getinstances():
laurent@824:                             if isinstance(instance, PLCOpenClasses["fbdObjects_block"]):
laurent@824:                                 self.removepouVar(instance.gettypeName(), 
laurent@824:                                                   instance.getinstanceName())
Laurent@814:                     actions.pop(i)
Laurent@814:                     removed = True
Laurent@814:                 i += 1
Laurent@814:             if not removed:
Laurent@814:                 raise ValueError, _("Action with name %s doesn't exist!")%name
Laurent@814:     setattr(cls, "removeaction", removeaction)
Laurent@814: 
Laurent@814:     def updateElementName(self, old_name, new_name):
Laurent@814:         if self.interface:
Laurent@814:             for content in self.interface.getcontent():
Laurent@814:                 for var in content["value"].getvariable():
Laurent@814:                     var_address = var.getaddress()
Laurent@814:                     if var_address is not None:
Laurent@814:                         if var_address == old_name:
Laurent@814:                             var.setaddress(new_name)
Laurent@814:                         if var.getname() == old_name:
Laurent@814:                             var.setname(new_name)
Laurent@814:                     var_type_content = var.gettype().getcontent()
Laurent@814:                     if var_type_content["name"] == "derived":
Laurent@814:                         if var_type_content["value"].getname() == old_name:
Laurent@814:                             var_type_content["value"].setname(new_name)
Laurent@814:         self.body[0].updateElementName(old_name, new_name)
Laurent@814:         for action in self.getactionList():
Laurent@814:             action.updateElementName(old_name, new_name)
Laurent@814:         for transition in self.gettransitionList():
Laurent@814:             transition.updateElementName(old_name, new_name)
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814: 
Laurent@814:     def updateElementAddress(self, address_model, new_leading):
Laurent@814:         if self.interface:
Laurent@814:             for content in self.interface.getcontent():
Laurent@814:                 for var in content["value"].getvariable():
Laurent@814:                     var_address = var.getaddress()
Laurent@814:                     if var_address is not None:
Laurent@814:                         var.setaddress(update_address(var_address, address_model, new_leading))
Laurent@814:         self.body[0].updateElementAddress(address_model, new_leading)
Laurent@814:         for action in self.getactionList():
Laurent@814:             action.updateElementAddress(address_model, new_leading)
Laurent@814:         for transition in self.gettransitionList():
Laurent@814:             transition.updateElementAddress(address_model, new_leading)
Laurent@814:     setattr(cls, "updateElementAddress", updateElementAddress)
Laurent@814: 
Laurent@814:     def removeVariableByAddress(self, address):
Laurent@814:         if self.interface:
Laurent@814:             for content in self.interface.getcontent():
Laurent@814:                 variables = content["value"].getvariable()
Laurent@814:                 for i in xrange(len(variables)-1, -1, -1):
Laurent@814:                     if variables[i].getaddress() == address:
Laurent@814:                         variables.pop(i)
Laurent@814:     setattr(cls, "removeVariableByAddress", removeVariableByAddress)
Laurent@814: 
Laurent@814:     def removeVariableByFilter(self, address_model):
Laurent@814:         if self.interface:
Laurent@814:             for content in self.interface.getcontent():
Laurent@814:                 variables = content["value"].getvariable()
Laurent@814:                 for i in xrange(len(variables)-1, -1, -1):
Laurent@814:                     var_address = variables[i].getaddress()
Laurent@814:                     if var_address is not None:
Laurent@814:                         result = address_model.match(var_address)
Laurent@814:                         if result is not None:
Laurent@814:                             variables.pop(i)
Laurent@814:     setattr(cls, "removeVariableByFilter", removeVariableByFilter)
Laurent@814:     
Laurent@814:     def Search(self, criteria, parent_infos=[]):
Laurent@814:         search_result = []
Laurent@814:         filter = criteria["filter"]
Laurent@814:         if filter == "all" or self.getpouType() in filter:
Laurent@814:             parent_infos = parent_infos + ["P::%s" % self.getname()]
Laurent@814:             search_result.extend(_Search([("name", self.getname())], criteria, parent_infos))
Laurent@814:             if self.interface is not None:
Laurent@814:                 var_number = 0
Laurent@814:                 for content in self.interface.getcontent():
Laurent@814:                     variable_type = searchResultVarTypes.get(content["value"], "var_local")
Laurent@814:                     variables = content["value"].getvariable()
Laurent@814:                     for modifier, has_modifier in [("constant", content["value"].getconstant()),
Laurent@814:                                                    ("retain", content["value"].getretain()),
Laurent@814:                                                    ("non_retain", content["value"].getnonretain())]:
Laurent@814:                         if has_modifier:
Laurent@814:                             for result in TestTextElement(modifier, criteria):
Laurent@814:                                 search_result.append((tuple(parent_infos + [variable_type, (var_number, var_number + len(variables)), modifier]),) + result)
Laurent@814:                             break
Laurent@814:                     for variable in variables:
Laurent@814:                         search_result.extend(variable.Search(criteria, parent_infos + [variable_type, var_number]))
Laurent@814:                         var_number += 1
Laurent@814:             if len(self.body) > 0:
Laurent@814:                 search_result.extend(self.body[0].Search(criteria, parent_infos))
Laurent@814:             for action in self.getactionList():
Laurent@814:                 search_result.extend(action.Search(criteria, parent_infos))
Laurent@814:             for transition in self.gettransitionList():
Laurent@814:                 search_result.extend(transition.Search(criteria, parent_infos))
Laurent@814:         return search_result
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814: 
Laurent@814: def setbodyType(self, type):
Laurent@814:     if type == "IL":
Laurent@814:         self.body.setcontent({"name" : "IL", "value" : PLCOpenClasses["formattedText"]()})
Laurent@814:     elif type == "ST":
Laurent@814:         self.body.setcontent({"name" : "ST", "value" : PLCOpenClasses["formattedText"]()})
Laurent@814:     elif type == "LD":
Laurent@814:         self.body.setcontent({"name" : "LD", "value" : PLCOpenClasses["body_LD"]()})
Laurent@814:     elif type == "FBD":
Laurent@814:         self.body.setcontent({"name" : "FBD", "value" : PLCOpenClasses["body_FBD"]()})
Laurent@814:     elif type == "SFC":
Laurent@814:         self.body.setcontent({"name" : "SFC", "value" : PLCOpenClasses["body_SFC"]()})
Laurent@814:     else:
Laurent@814:         raise ValueError, "%s isn't a valid body type!"%type
Laurent@814: 
Laurent@814: def getbodyType(self):
Laurent@814:     return self.body.getcontent()["name"]
Laurent@814: 
Laurent@814: def resetexecutionOrder(self):
Laurent@814:     self.body.resetexecutionOrder()
Laurent@814: 
Laurent@814: def compileexecutionOrder(self):
Laurent@814:     self.body.compileexecutionOrder()
Laurent@814: 
Laurent@814: def setelementExecutionOrder(self, instance, new_executionOrder):
Laurent@814:     self.body.setelementExecutionOrder(instance, new_executionOrder)
Laurent@814: 
Laurent@814: def addinstance(self, name, instance):
Laurent@814:     self.body.appendcontentInstance(name, instance)
Laurent@814: 
Laurent@814: def getinstances(self):
Laurent@814:     return self.body.getcontentInstances()
Laurent@814: 
Laurent@814: def getinstance(self, id):
Laurent@814:     return self.body.getcontentInstance(id)
Laurent@814: 
Laurent@814: def getrandomInstance(self, exclude):
Laurent@814:     return self.body.getcontentRandomInstance(exclude)
Laurent@814: 
Laurent@814: def getinstanceByName(self, name):
Laurent@814:     return self.body.getcontentInstanceByName(name)
Laurent@814: 
Laurent@814: def removeinstance(self, id):
Laurent@814:     self.body.removecontentInstance(id)
Laurent@814: 
Laurent@814: def settext(self, text):
Laurent@814:     self.body.settext(text)
Laurent@814: 
Laurent@814: def gettext(self):
Laurent@814:     return self.body.gettext()
Laurent@814: 
Laurent@1142: def hasblock(self, name=None, block_type=None):
Laurent@1142:     if self.getbodyType() in ["FBD", "LD", "SFC"]:
Laurent@1142:         for instance in self.getinstances():
Laurent@1142:             if (isinstance(instance, PLCOpenClasses["fbdObjects_block"]) and 
Laurent@1142:                 (name and instance.getinstanceName() == name or
Laurent@1142:                  block_type and instance.gettypeName() == block_type)):
Laurent@1142:                 return True
Laurent@1142:     elif block_type is not None:
Laurent@1142:         return self.body.hasblock(block_type)
Laurent@1142:     return False
Laurent@1142: 
Laurent@1142: def updateElementName(self, old_name, new_name):
Laurent@1142:     self.body.updateElementName(old_name, new_name)
Laurent@1142: 
Laurent@1142: def updateElementAddress(self, address_model, new_leading):
Laurent@1142:     self.body.updateElementAddress(address_model, new_leading)
Laurent@1142:     
Laurent@1142: 
Laurent@814: cls = PLCOpenClasses.get("transitions_transition", None)
Laurent@814: if cls:
Laurent@814:     setattr(cls, "setbodyType", setbodyType)
Laurent@814:     setattr(cls, "getbodyType", getbodyType)
Laurent@814:     setattr(cls, "resetexecutionOrder", resetexecutionOrder)
Laurent@814:     setattr(cls, "compileexecutionOrder", compileexecutionOrder)
Laurent@814:     setattr(cls, "setelementExecutionOrder", setelementExecutionOrder)
Laurent@814:     setattr(cls, "addinstance", addinstance)
Laurent@814:     setattr(cls, "getinstances", getinstances)
Laurent@814:     setattr(cls, "getinstance", getinstance)
Laurent@814:     setattr(cls, "getrandomInstance", getrandomInstance)
Laurent@814:     setattr(cls, "getinstanceByName", getinstanceByName)
Laurent@814:     setattr(cls, "removeinstance", removeinstance)
Laurent@814:     setattr(cls, "settext", settext)
Laurent@814:     setattr(cls, "gettext", gettext)
Laurent@1142:     setattr(cls, "hasblock", hasblock)
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814:     setattr(cls, "updateElementAddress", updateElementAddress)
Laurent@1142:     
Laurent@814:     def Search(self, criteria, parent_infos):
Laurent@814:         search_result = []
Laurent@814:         parent_infos = parent_infos[:-1] + ["T::%s::%s" % (parent_infos[-1].split("::")[1], self.getname())]
Laurent@814:         for result in TestTextElement(self.getname(), criteria):
Laurent@814:             search_result.append((tuple(parent_infos + ["name"]),) + result)
Laurent@814:         search_result.extend(self.body.Search(criteria, parent_infos))
Laurent@814:         return search_result
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("actions_action", None)
Laurent@814: if cls:
Laurent@814:     setattr(cls, "setbodyType", setbodyType)
Laurent@814:     setattr(cls, "getbodyType", getbodyType)
Laurent@814:     setattr(cls, "resetexecutionOrder", resetexecutionOrder)
Laurent@814:     setattr(cls, "compileexecutionOrder", compileexecutionOrder)
Laurent@814:     setattr(cls, "setelementExecutionOrder", setelementExecutionOrder)
Laurent@814:     setattr(cls, "addinstance", addinstance)
Laurent@814:     setattr(cls, "getinstances", getinstances)
Laurent@814:     setattr(cls, "getinstance", getinstance)
Laurent@814:     setattr(cls, "getrandomInstance", getrandomInstance)
Laurent@814:     setattr(cls, "getinstanceByName", getinstanceByName)
Laurent@814:     setattr(cls, "removeinstance", removeinstance)
Laurent@814:     setattr(cls, "settext", settext)
Laurent@814:     setattr(cls, "gettext", gettext)
Laurent@1142:     setattr(cls, "hasblock", hasblock)
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814:     setattr(cls, "updateElementAddress", updateElementAddress)
Laurent@1142:     
Laurent@814:     def Search(self, criteria, parent_infos):
Laurent@814:         search_result = []
Laurent@814:         parent_infos = parent_infos[:-1] + ["A::%s::%s" % (parent_infos[-1].split("::")[1], self.getname())]
Laurent@814:         for result in TestTextElement(self.getname(), criteria):
Laurent@814:             search_result.append((tuple(parent_infos + ["name"]),) + result)
Laurent@814:         search_result.extend(self.body.Search(criteria, parent_infos))
Laurent@814:         return search_result
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("body", None)
Laurent@814: if cls:
Laurent@814:     cls.currentExecutionOrderId = 0
Laurent@814:     
Laurent@814:     def resetcurrentExecutionOrderId(self):
Laurent@814:         object.__setattr__(self, "currentExecutionOrderId", 0)
Laurent@814:     setattr(cls, "resetcurrentExecutionOrderId", resetcurrentExecutionOrderId)
Laurent@814:     
Laurent@814:     def getnewExecutionOrderId(self):
Laurent@814:         object.__setattr__(self, "currentExecutionOrderId", self.currentExecutionOrderId + 1)
Laurent@814:         return self.currentExecutionOrderId
Laurent@814:     setattr(cls, "getnewExecutionOrderId", getnewExecutionOrderId)
Laurent@814:     
Laurent@814:     def resetexecutionOrder(self):
Laurent@814:         if self.content["name"] == "FBD":
Laurent@814:             for element in self.content["value"].getcontent():
Laurent@814:                 if not isinstance(element["value"], (PLCOpenClasses.get("commonObjects_comment", None), 
Laurent@814:                                                      PLCOpenClasses.get("commonObjects_connector", None), 
Laurent@814:                                                      PLCOpenClasses.get("commonObjects_continuation", None))):
Laurent@814:                     element["value"].setexecutionOrderId(0)
Laurent@814:         else:
Laurent@814:             raise TypeError, _("Can only generate execution order on FBD networks!")
Laurent@814:     setattr(cls, "resetexecutionOrder", resetexecutionOrder)
Laurent@814:     
Laurent@814:     def compileexecutionOrder(self):
Laurent@814:         if self.content["name"] == "FBD":
Laurent@814:             self.resetexecutionOrder()
Laurent@814:             self.resetcurrentExecutionOrderId()
Laurent@814:             for element in self.content["value"].getcontent():
Laurent@814:                 if isinstance(element["value"], PLCOpenClasses.get("fbdObjects_outVariable", None)) and element["value"].getexecutionOrderId() == 0:
Laurent@814:                     connections = element["value"].connectionPointIn.getconnections()
Laurent@814:                     if connections and len(connections) == 1:
Laurent@814:                         self.compileelementExecutionOrder(connections[0])
Laurent@814:                     element["value"].setexecutionOrderId(self.getnewExecutionOrderId())
Laurent@814:         else:
Laurent@814:             raise TypeError, _("Can only generate execution order on FBD networks!")
Laurent@814:     setattr(cls, "compileexecutionOrder", compileexecutionOrder)
Laurent@814:     
Laurent@814:     def compileelementExecutionOrder(self, link):
Laurent@814:         if self.content["name"] == "FBD":
Laurent@814:             localid = link.getrefLocalId()
Laurent@814:             instance = self.getcontentInstance(localid)
Laurent@814:             if isinstance(instance, PLCOpenClasses.get("fbdObjects_block", None)) and instance.getexecutionOrderId() == 0:
Laurent@814:                 for variable in instance.inputVariables.getvariable():
Laurent@814:                     connections = variable.connectionPointIn.getconnections()
Laurent@814:                     if connections and len(connections) == 1:
Laurent@814:                         self.compileelementExecutionOrder(connections[0])
Laurent@814:                 instance.setexecutionOrderId(self.getnewExecutionOrderId())
Laurent@814:             elif isinstance(instance, PLCOpenClasses.get("commonObjects_continuation", None)) and instance.getexecutionOrderId() == 0:
Laurent@814:                 name = instance.getname()
Laurent@814:                 for tmp_instance in self.getcontentInstances():
Laurent@814:                     if isinstance(tmp_instance, PLCOpenClasses.get("commonObjects_connector", None)) and tmp_instance.getname() == name and tmp_instance.getexecutionOrderId() == 0:
Laurent@814:                         connections = tmp_instance.connectionPointIn.getconnections()
Laurent@814:                         if connections and len(connections) == 1:
Laurent@814:                             self.compileelementExecutionOrder(connections[0])
Laurent@814:         else:
Laurent@814:             raise TypeError, _("Can only generate execution order on FBD networks!")
Laurent@814:     setattr(cls, "compileelementExecutionOrder", compileelementExecutionOrder)
Laurent@814:     
Laurent@814:     def setelementExecutionOrder(self, instance, new_executionOrder):
Laurent@814:         if self.content["name"] == "FBD":
Laurent@814:             old_executionOrder = instance.getexecutionOrderId()
Laurent@814:             if old_executionOrder is not None and old_executionOrder != 0 and new_executionOrder != 0:
Laurent@814:                 for element in self.content["value"].getcontent():
Laurent@814:                     if element["value"] != instance and not isinstance(element["value"], PLCOpenClasses.get("commonObjects_comment", None)):
Laurent@814:                         element_executionOrder = element["value"].getexecutionOrderId()
Laurent@814:                         if old_executionOrder <= element_executionOrder <= new_executionOrder:
Laurent@814:                             element["value"].setexecutionOrderId(element_executionOrder - 1)
Laurent@814:                         if new_executionOrder <= element_executionOrder <= old_executionOrder:
Laurent@814:                             element["value"].setexecutionOrderId(element_executionOrder + 1)
Laurent@814:             instance.setexecutionOrderId(new_executionOrder)
Laurent@814:         else:
Laurent@814:             raise TypeError, _("Can only generate execution order on FBD networks!")
Laurent@814:     setattr(cls, "setelementExecutionOrder", setelementExecutionOrder)
Laurent@814:     
Laurent@814:     def appendcontentInstance(self, name, instance):
Laurent@814:         if self.content["name"] in ["LD","FBD","SFC"]:
Laurent@814:             self.content["value"].appendcontent({"name" : name, "value" : instance})
Laurent@814:         else:
Laurent@814:             raise TypeError, _("%s body don't have instances!")%self.content["name"]
Laurent@814:     setattr(cls, "appendcontentInstance", appendcontentInstance)
Laurent@814:     
Laurent@814:     def getcontentInstances(self):
Laurent@814:         if self.content["name"] in ["LD","FBD","SFC"]:
Laurent@814:             instances = []
Laurent@814:             for element in self.content["value"].getcontent():
Laurent@814:                 instances.append(element["value"])
Laurent@814:             return instances
Laurent@814:         else:
Laurent@814:             raise TypeError, _("%s body don't have instances!")%self.content["name"]
Laurent@814:     setattr(cls, "getcontentInstances", getcontentInstances)
Laurent@814: 
Laurent@814:     def getcontentInstance(self, id):
Laurent@814:         if self.content["name"] in ["LD","FBD","SFC"]:
Laurent@814:             for element in self.content["value"].getcontent():
Laurent@814:                 if element["value"].getlocalId() == id:
Laurent@814:                     return element["value"]
Laurent@814:             return None
Laurent@814:         else:
Laurent@814:             raise TypeError, _("%s body don't have instances!")%self.content["name"]
Laurent@814:     setattr(cls, "getcontentInstance", getcontentInstance)
Laurent@814:     
Laurent@814:     def getcontentRandomInstance(self, exclude):
Laurent@814:         if self.content["name"] in ["LD","FBD","SFC"]:
Laurent@814:             for element in self.content["value"].getcontent():
Laurent@814:                 if element["value"].getlocalId() not in exclude:
Laurent@814:                     return element["value"]
Laurent@814:             return None
Laurent@814:         else:
Laurent@814:             raise TypeError, _("%s body don't have instances!")%self.content["name"]
Laurent@814:     setattr(cls, "getcontentRandomInstance", getcontentRandomInstance)
Laurent@814:     
Laurent@814:     def getcontentInstanceByName(self, name):
Laurent@814:         if self.content["name"] in ["LD","FBD","SFC"]:
Laurent@814:             for element in self.content["value"].getcontent():
Laurent@814:                 if isinstance(element["value"], PLCOpenClasses.get("fbdObjects_block", None)) and element["value"].getinstanceName() == name:
Laurent@814:                     return element["value"]
Laurent@814:         else:
Laurent@814:             raise TypeError, _("%s body don't have instances!")%self.content["name"]
Laurent@814:     setattr(cls, "getcontentInstanceByName", getcontentInstanceByName)
Laurent@814:     
Laurent@814:     def removecontentInstance(self, id):
Laurent@814:         if self.content["name"] in ["LD","FBD","SFC"]:
Laurent@814:             i = 0
Laurent@814:             removed = False
Laurent@814:             elements = self.content["value"].getcontent()
Laurent@814:             while i < len(elements) and not removed:
Laurent@814:                 if elements[i]["value"].getlocalId() == id:
Laurent@814:                     self.content["value"].removecontent(i)
Laurent@814:                     removed = True
Laurent@814:                 i += 1
Laurent@814:             if not removed:
Laurent@814:                 raise ValueError, _("Instance with id %d doesn't exist!")%id
Laurent@814:         else:
Laurent@814:             raise TypeError, "%s body don't have instances!"%self.content["name"]
Laurent@814:     setattr(cls, "removecontentInstance", removecontentInstance)
Laurent@814:     
Laurent@814:     def settext(self, text):
Laurent@814:         if self.content["name"] in ["IL","ST"]:
Laurent@814:             self.content["value"].settext(text)
Laurent@814:         else:
Laurent@814:             raise TypeError, _("%s body don't have text!")%self.content["name"]
Laurent@814:     setattr(cls, "settext", settext)
Laurent@814: 
Laurent@814:     def gettext(self):
Laurent@814:         if self.content["name"] in ["IL","ST"]:
Laurent@814:             return self.content["value"].gettext()
Laurent@814:         else:
Laurent@814:             raise TypeError, _("%s body don't have text!")%self.content["name"]
Laurent@814:     setattr(cls, "gettext", gettext)
Laurent@814:     
Laurent@1142:     def hasblock(self, block_type):
Laurent@1142:         if self.content["name"] in ["IL","ST"]:
Laurent@1142:             return self.content["value"].hasblock(block_type)
Laurent@1142:         else:
Laurent@1142:             raise TypeError, _("%s body don't have text!")%self.content["name"]
Laurent@1142:     setattr(cls, "hasblock", hasblock)
Laurent@1142:     
Laurent@814:     def updateElementName(self, old_name, new_name):
Laurent@814:         if self.content["name"] in ["IL", "ST"]:
Laurent@814:             self.content["value"].updateElementName(old_name, new_name)
Laurent@814:         else:
Laurent@814:             for element in self.content["value"].getcontent():
Laurent@814:                 element["value"].updateElementName(old_name, new_name)
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814: 
Laurent@814:     def updateElementAddress(self, address_model, new_leading):
Laurent@814:         if self.content["name"] in ["IL", "ST"]:
Laurent@814:             self.content["value"].updateElementAddress(address_model, new_leading)
Laurent@814:         else:
Laurent@814:             for element in self.content["value"].getcontent():
Laurent@814:                 element["value"].updateElementAddress(address_model, new_leading)
Laurent@814:     setattr(cls, "updateElementAddress", updateElementAddress)
Laurent@814: 
Laurent@814:     def Search(self, criteria, parent_infos=[]):
Laurent@814:         if self.content["name"] in ["IL", "ST"]:
Laurent@814:             search_result = self.content["value"].Search(criteria, parent_infos + ["body", 0])
Laurent@814:         else:
Laurent@814:             search_result = []
Laurent@814:             for element in self.content["value"].getcontent():
Laurent@814:                 search_result.extend(element["value"].Search(criteria, parent_infos))
Laurent@814:         return search_result
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814: 
Laurent@814: def getx(self):
Laurent@814:     return self.position.getx()
Laurent@814: 
Laurent@814: def gety(self):
Laurent@814:     return self.position.gety()
Laurent@814: 
Laurent@814: def setx(self, x):
Laurent@814:     self.position.setx(x)
Laurent@814:     
Laurent@814: def sety(self, y):
Laurent@814:     self.position.sety(y)
Laurent@814: 
Laurent@814: def _getBoundingBox(self):
Laurent@814:     return rect(self.getx(), self.gety(), self.getwidth(), self.getheight())
Laurent@814: 
Laurent@814: def _getConnectionsBoundingBox(connectionPointIn):
Laurent@814:     bbox = rect()
Laurent@814:     connections = connectionPointIn.getconnections()
Laurent@814:     if connections is not None:
Laurent@814:         for connection in connections:
Laurent@814:             for x, y in connection.getpoints():
Laurent@814:                 bbox.update(x, y)
Laurent@814:     return bbox
Laurent@814: 
Laurent@814: def _getBoundingBoxSingle(self):
Laurent@814:     bbox = _getBoundingBox(self)
Laurent@814:     if self.connectionPointIn is not None:
Laurent@814:         bbox.union(_getConnectionsBoundingBox(self.connectionPointIn))
Laurent@814:     return bbox
Laurent@814: 
Laurent@814: def _getBoundingBoxMultiple(self):
Laurent@814:     bbox = _getBoundingBox(self)
Laurent@814:     for connectionPointIn in self.getconnectionPointIn():
Laurent@814:         bbox.union(_getConnectionsBoundingBox(connectionPointIn))
Laurent@814:     return bbox
Laurent@814: 
Laurent@814: def _filterConnections(connectionPointIn, localId, connections):
Laurent@814:     in_connections = connectionPointIn.getconnections()
Laurent@814:     if in_connections is not None:
Laurent@814:         to_delete = []
Laurent@814:         for i, connection in enumerate(in_connections):
Laurent@814:             connected = connection.getrefLocalId()
Laurent@814:             if not connections.has_key((localId, connected)) and \
Laurent@814:                not connections.has_key((connected, localId)):
Laurent@814:                 to_delete.append(i)
Laurent@814:         to_delete.reverse()
Laurent@814:         for i in to_delete:
Laurent@814:             connectionPointIn.removeconnection(i)
Laurent@814: 
Laurent@814: def _filterConnectionsSingle(self, connections):
Laurent@814:     if self.connectionPointIn is not None:
Laurent@814:         _filterConnections(self.connectionPointIn, self.localId, connections)
Laurent@814: 
Laurent@814: def _filterConnectionsMultiple(self, connections):
Laurent@814:     for connectionPointIn in self.getconnectionPointIn():
Laurent@814:         _filterConnections(connectionPointIn, self.localId, connections)
Laurent@814: 
Laurent@814: def _getconnectionsdefinition(instance, connections_end):
Laurent@814:     id = instance.getlocalId()
Laurent@814:     return dict([((id, end), True) for end in connections_end])
Laurent@814: 
Laurent@814: def _updateConnectionsId(connectionPointIn, translation):
Laurent@814:     connections_end = []
Laurent@814:     connections = connectionPointIn.getconnections()
Laurent@814:     if connections is not None:
Laurent@814:         for connection in connections:
Laurent@814:             refLocalId = connection.getrefLocalId()
Laurent@814:             new_reflocalId = translation.get(refLocalId, refLocalId)
Laurent@814:             connection.setrefLocalId(new_reflocalId)
Laurent@814:             connections_end.append(new_reflocalId)
Laurent@814:     return connections_end
Laurent@814: 
Laurent@814: def _updateConnectionsIdSingle(self, translation):
Laurent@814:     connections_end = []
Laurent@814:     if self.connectionPointIn is not None:
Laurent@814:         connections_end = _updateConnectionsId(self.connectionPointIn, translation)
Laurent@814:     return _getconnectionsdefinition(self, connections_end)
Laurent@814: 
Laurent@814: def _updateConnectionsIdMultiple(self, translation):
Laurent@814:     connections_end = []
Laurent@814:     for connectionPointIn in self.getconnectionPointIn():
Laurent@814:         connections_end.extend(_updateConnectionsId(connectionPointIn, translation))
Laurent@814:     return _getconnectionsdefinition(self, connections_end)
Laurent@814: 
Laurent@814: def _translate(self, dx, dy):
Laurent@814:     self.setx(self.getx() + dx)
Laurent@814:     self.sety(self.gety() + dy)
Laurent@814:     
Laurent@814: def _translateConnections(connectionPointIn, dx, dy):
Laurent@814:     connections = connectionPointIn.getconnections()
Laurent@814:     if connections is not None:
Laurent@814:         for connection in connections:
Laurent@814:             for position in connection.getposition():
Laurent@814:                 position.setx(position.getx() + dx)
Laurent@814:                 position.sety(position.gety() + dy)
Laurent@814: 
Laurent@814: def _translateSingle(self, dx, dy):
Laurent@814:     _translate(self, dx, dy)
Laurent@814:     if self.connectionPointIn is not None:
Laurent@814:         _translateConnections(self.connectionPointIn, dx, dy)
Laurent@814: 
Laurent@814: def _translateMultiple(self, dx, dy):
Laurent@814:     _translate(self, dx, dy)
Laurent@814:     for connectionPointIn in self.getconnectionPointIn():
Laurent@814:         _translateConnections(connectionPointIn, dx, dy)
Laurent@814: 
Laurent@814: def _updateElementName(self, old_name, new_name):
Laurent@814:     pass
Laurent@814: 
Laurent@814: def _updateElementAddress(self, address_model, new_leading):
Laurent@814:     pass
Laurent@814: 
Laurent@814: def _SearchInElement(self, criteria, parent_infos=[]):
Laurent@814:     return []
Laurent@814: 
Laurent@814: _connectionsFunctions = {
Laurent@814:     "bbox": {"none": _getBoundingBox,
Laurent@814:              "single": _getBoundingBoxSingle,
Laurent@814:              "multiple": _getBoundingBoxMultiple},
Laurent@814:     "translate": {"none": _translate,
Laurent@814:                "single": _translateSingle,
Laurent@814:                "multiple": _translateMultiple},
Laurent@814:     "filter": {"none": lambda self, connections: None,
Laurent@814:                "single": _filterConnectionsSingle,
Laurent@814:                "multiple": _filterConnectionsMultiple},
Laurent@814:     "update": {"none": lambda self, translation: {},
Laurent@814:                "single": _updateConnectionsIdSingle,
Laurent@814:                "multiple": _updateConnectionsIdMultiple},
Laurent@814: }
Laurent@814: 
Laurent@814: def _initElementClass(name, classname, connectionPointInType="none"):
Laurent@814:     ElementNameToClass[name] = classname
Laurent@814:     cls = PLCOpenClasses.get(classname, None)
Laurent@814:     if cls:
Laurent@814:         setattr(cls, "getx", getx)
Laurent@814:         setattr(cls, "gety", gety)
Laurent@814:         setattr(cls, "setx", setx)
Laurent@814:         setattr(cls, "sety", sety)
Laurent@814:         setattr(cls, "updateElementName", _updateElementName)
Laurent@814:         setattr(cls, "updateElementAddress", _updateElementAddress)
Laurent@814:         setattr(cls, "getBoundingBox", _connectionsFunctions["bbox"][connectionPointInType])
Laurent@814:         setattr(cls, "translate", _connectionsFunctions["translate"][connectionPointInType])
Laurent@814:         setattr(cls, "filterConnections", _connectionsFunctions["filter"][connectionPointInType])
Laurent@814:         setattr(cls, "updateConnectionsId", _connectionsFunctions["update"][connectionPointInType])
Laurent@814:         setattr(cls, "Search", _SearchInElement)
Laurent@814:     return cls
Laurent@814: 
Laurent@814: def _getexecutionOrder(instance, specific_values):
Laurent@814:     executionOrder = instance.getexecutionOrderId()
Laurent@814:     if executionOrder is None:
Laurent@814:         executionOrder = 0
Laurent@814:     specific_values["executionOrder"] = executionOrder
Laurent@814:     
Laurent@814: def _getdefaultmodifiers(instance, infos):
Laurent@814:     infos["negated"] = instance.getnegated()
Laurent@814:     infos["edge"] = instance.getedge()
Laurent@814: 
Laurent@814: def _getinputmodifiers(instance, infos):
Laurent@814:     infos["negated"] = instance.getnegatedIn()
Laurent@814:     infos["edge"] = instance.getedgeIn()
Laurent@814: 
Laurent@814: def _getoutputmodifiers(instance, infos):
Laurent@814:     infos["negated"] = instance.getnegatedOut()
Laurent@814:     infos["edge"] = instance.getedgeOut()
Laurent@814: 
Laurent@814: MODIFIERS_FUNCTIONS = {"default": _getdefaultmodifiers,
Laurent@814:                        "input": _getinputmodifiers,
Laurent@814:                        "output": _getoutputmodifiers}
Laurent@814: 
Laurent@814: def _getconnectioninfos(instance, connection, links=False, modifiers=None, parameter=False):
Laurent@814:     infos = {"position": connection.getrelPositionXY()}
Laurent@814:     if parameter:
Laurent@814:         infos["name"] = instance.getformalParameter()
Laurent@814:     MODIFIERS_FUNCTIONS.get(modifiers, lambda x, y: None)(instance, infos)
Laurent@814:     if links:
Laurent@814:         infos["links"] = []
Laurent@814:         connections = connection.getconnections()
Laurent@814:         if connections is not None:
Laurent@814:             for link in connections:
Laurent@814:                 dic = {"refLocalId": link.getrefLocalId(),
Laurent@814:                        "points": link.getpoints(),
Laurent@814:                        "formalParameter": link.getformalParameter()}
Laurent@814:                 infos["links"].append(dic)
Laurent@814:     return infos
Laurent@814: 
Laurent@814: def _getelementinfos(instance):
Laurent@814:     return {"id": instance.getlocalId(),
Laurent@814:             "x": instance.getx(),
Laurent@814:             "y": instance.gety(),
Laurent@814:             "height": instance.getheight(),
Laurent@814:             "width": instance.getwidth(),
Laurent@814:             "specific_values": {},
Laurent@814:             "inputs": [],
Laurent@814:             "outputs": []}
Laurent@814: 
Laurent@814: def _getvariableinfosFunction(type, input, output):
Laurent@814:     def getvariableinfos(self):
Laurent@814:         infos = _getelementinfos(self)
Laurent@814:         infos["type"] = type
Laurent@814:         specific_values = infos["specific_values"]
Laurent@814:         specific_values["name"] = self.getexpression()
Laurent@814:         _getexecutionOrder(self, specific_values)
Laurent@814:         if input and output:
Laurent@814:             infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True, "input"))
Laurent@814:             infos["outputs"].append(_getconnectioninfos(self, self.connectionPointOut, False, "output"))
Laurent@814:         elif input:
Laurent@814:             infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True, "default"))
Laurent@814:         elif output:
Laurent@814:             infos["outputs"].append(_getconnectioninfos(self, self.connectionPointOut, False, "default"))
Laurent@814:         return infos
Laurent@814:     return getvariableinfos
Laurent@814: 
Laurent@814: def _getconnectorinfosFunction(type):
Laurent@814:     def getvariableinfos(self):
Laurent@814:         infos = _getelementinfos(self)
Laurent@814:         infos["type"] = type
Laurent@814:         infos["specific_values"]["name"] = self.getname()
Laurent@814:         if type == "connector":
Laurent@814:             infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True))
Laurent@814:         elif type == "continuation":
Laurent@814:             infos["outputs"].append(_getconnectioninfos(self, self.connectionPointOut))
Laurent@814:         return infos
Laurent@814:     return getvariableinfos
Laurent@814: 
Laurent@814: def _getpowerrailinfosFunction(type):
Laurent@814:     def getpowerrailinfos(self):
Laurent@814:         infos = _getelementinfos(self)
Laurent@814:         infos["type"] = type
Laurent@814:         if type == "rightPowerRail":
Laurent@814:             for connectionPointIn in self.getconnectionPointIn():
Laurent@814:                 infos["inputs"].append(_getconnectioninfos(self, connectionPointIn, True))
Laurent@814:             infos["specific_values"]["connectors"] = len(infos["inputs"])
Laurent@814:         elif type == "leftPowerRail":
Laurent@814:             for connectionPointOut in self.getconnectionPointOut():
Laurent@814:                 infos["outputs"].append(_getconnectioninfos(self, connectionPointOut))
Laurent@814:             infos["specific_values"]["connectors"] = len(infos["outputs"])
Laurent@814:         return infos
Laurent@814:     return getpowerrailinfos
Laurent@814: 
Laurent@814: def _getldelementinfosFunction(type):
Laurent@814:     def getldelementinfos(self):
Laurent@814:         infos = _getelementinfos(self)
Laurent@814:         infos["type"] = type
Laurent@814:         specific_values = infos["specific_values"]
Laurent@814:         specific_values["name"] = self.getvariable()
Laurent@814:         _getexecutionOrder(self, specific_values)
Laurent@814:         specific_values["negated"] = self.getnegated()
Laurent@814:         specific_values["edge"] = self.getedge()
Laurent@814:         if type == "coil":
Laurent@814:             specific_values["storage"] = self.getstorage()
Laurent@814:         infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True))
Laurent@814:         infos["outputs"].append(_getconnectioninfos(self, self.connectionPointOut))
Laurent@814:         return infos
Laurent@814:     return getldelementinfos
Laurent@814: 
Laurent@814: DIVERGENCE_TYPES = {(True, True): "simultaneousDivergence",
Laurent@814:                     (True, False): "selectionDivergence",
Laurent@814:                     (False, True): "simultaneousConvergence",
Laurent@814:                     (False, False): "selectionConvergence"}
Laurent@814: 
Laurent@814: def _getdivergenceinfosFunction(divergence, simultaneous):
Laurent@814:     def getdivergenceinfos(self):
Laurent@814:         infos = _getelementinfos(self)
Laurent@814:         infos["type"] = DIVERGENCE_TYPES[(divergence, simultaneous)]
Laurent@814:         if divergence:
Laurent@814:             infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True))
Laurent@814:             for connectionPointOut in self.getconnectionPointOut():
Laurent@814:                 infos["outputs"].append(_getconnectioninfos(self, connectionPointOut))
Laurent@814:             infos["specific_values"]["connectors"] = len(infos["outputs"])
Laurent@814:         else:
Laurent@814:             for connectionPointIn in self.getconnectionPointIn():
Laurent@814:                 infos["inputs"].append(_getconnectioninfos(self, connectionPointIn, True))
Laurent@814:             infos["outputs"].append(_getconnectioninfos(self, self.connectionPointOut))
Laurent@814:             infos["specific_values"]["connectors"] = len(infos["inputs"])
Laurent@814:         return infos
Laurent@814:     return getdivergenceinfos
Laurent@814: 
Laurent@814: cls = _initElementClass("comment", "commonObjects_comment")
Laurent@814: if cls:
Laurent@814:     def getinfos(self):
Laurent@814:         infos = _getelementinfos(self)
Laurent@814:         infos["type"] = "comment"
Laurent@814:         infos["specific_values"]["content"] = self.getcontentText()
Laurent@814:         return infos
Laurent@814:     setattr(cls, "getinfos", getinfos)
Laurent@814:     
Laurent@814:     def setcontentText(self, text):
Laurent@814:         self.content.settext(text)
Laurent@814:     setattr(cls, "setcontentText", setcontentText)
Laurent@814:         
Laurent@814:     def getcontentText(self):
Laurent@814:         return self.content.gettext()
Laurent@814:     setattr(cls, "getcontentText", getcontentText)
Laurent@814:     
Laurent@814:     def updateElementName(self, old_name, new_name):
Laurent@814:         self.content.updateElementName(old_name, new_name)
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814: 
Laurent@814:     def updateElementAddress(self, address_model, new_leading):
Laurent@814:         self.content.updateElementAddress(address_model, new_leading)
Laurent@814:     setattr(cls, "updateElementAddress", updateElementAddress)
Laurent@814: 
Laurent@814:     def Search(self, criteria, parent_infos=[]):
Laurent@814:         return self.content.Search(criteria, parent_infos + ["comment", self.getlocalId(), "content"])
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814: 
Laurent@814: cls = _initElementClass("block", "fbdObjects_block")
Laurent@814: if cls:
Laurent@814:     def getBoundingBox(self):
Laurent@814:         bbox = _getBoundingBox(self)
Laurent@814:         for input in self.inputVariables.getvariable():
Laurent@814:             bbox.union(_getConnectionsBoundingBox(input.connectionPointIn))
Laurent@814:         return bbox
Laurent@814:     setattr(cls, "getBoundingBox", getBoundingBox)
Laurent@814: 
Laurent@814:     def getinfos(self):
Laurent@814:         infos = _getelementinfos(self)
Laurent@814:         infos["type"] = self.gettypeName()
Laurent@814:         specific_values = infos["specific_values"]
Laurent@814:         specific_values["name"] = self.getinstanceName()
Laurent@814:         _getexecutionOrder(self, specific_values)
Laurent@814:         for variable in self.inputVariables.getvariable():
Laurent@814:             infos["inputs"].append(_getconnectioninfos(variable, variable.connectionPointIn, True, "default", True))
Laurent@814:         for variable in self.outputVariables.getvariable():
Laurent@814:             infos["outputs"].append(_getconnectioninfos(variable, variable.connectionPointOut, False, "default", True))
Laurent@814:         return infos
Laurent@814:     setattr(cls, "getinfos", getinfos)
Laurent@814: 
Laurent@814:     def updateElementName(self, old_name, new_name):
Laurent@814:         if self.typeName == old_name:
Laurent@814:             self.typeName = new_name
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814: 
Laurent@814:     def filterConnections(self, connections):
Laurent@814:         for input in self.inputVariables.getvariable():
Laurent@814:             _filterConnections(input.connectionPointIn, self.localId, connections)
Laurent@814:     setattr(cls, "filterConnections", filterConnections)
Laurent@814: 
Laurent@814:     def updateConnectionsId(self, translation):
Laurent@814:         connections_end = []
Laurent@814:         for input in self.inputVariables.getvariable():
Laurent@814:             connections_end.extend(_updateConnectionsId(input.connectionPointIn, translation))
Laurent@814:         return _getconnectionsdefinition(self, connections_end)
Laurent@814:     setattr(cls, "updateConnectionsId", updateConnectionsId)
Laurent@814: 
Laurent@814:     def translate(self, dx, dy):
Laurent@814:         _translate(self, dx, dy)
Laurent@814:         for input in self.inputVariables.getvariable():
Laurent@814:             _translateConnections(input.connectionPointIn, dx, dy)
Laurent@814:     setattr(cls, "translate", translate)
Laurent@814: 
Laurent@814:     def Search(self, criteria, parent_infos=[]):
Laurent@814:         parent_infos = parent_infos + ["block", self.getlocalId()]
Laurent@814:         search_result = _Search([("name", self.getinstanceName()),
Laurent@814:                                  ("type", self.gettypeName())],
Laurent@814:                                 criteria, parent_infos)
Laurent@814:         for i, variable in enumerate(self.inputVariables.getvariable()):
Laurent@814:             for result in TestTextElement(variable.getformalParameter(), criteria):
Laurent@814:                 search_result.append((tuple(parent_infos + ["input", i]),) + result)
Laurent@814:         for i, variable in enumerate(self.outputVariables.getvariable()):
Laurent@814:             for result in TestTextElement(variable.getformalParameter(), criteria):
Laurent@814:                 search_result.append((tuple(parent_infos + ["output", i]),) + result)
Laurent@814:         return search_result
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814: 
Laurent@814: cls = _initElementClass("leftPowerRail", "ldObjects_leftPowerRail")
Laurent@814: if cls:
Laurent@814:     setattr(cls, "getinfos", _getpowerrailinfosFunction("leftPowerRail"))
Laurent@814: 
Laurent@814: cls = _initElementClass("rightPowerRail", "ldObjects_rightPowerRail", "multiple")
Laurent@814: if cls:
Laurent@814:     setattr(cls, "getinfos", _getpowerrailinfosFunction("rightPowerRail"))
Laurent@814: 
Laurent@814: cls = _initElementClass("contact", "ldObjects_contact", "single")
Laurent@814: if cls:
Laurent@814:     setattr(cls, "getinfos", _getldelementinfosFunction("contact"))
Laurent@814:     
Laurent@814:     def updateElementName(self, old_name, new_name):
Laurent@814:         if self.variable == old_name:
Laurent@814:             self.variable = new_name
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814:     
Laurent@814:     def updateElementAddress(self, address_model, new_leading):
Laurent@814:         self.variable = update_address(self.variable, address_model, new_leading)
Laurent@814:     setattr(cls, "updateElementAddress", updateElementAddress)
Laurent@814:     
Laurent@814:     def Search(self, criteria, parent_infos=[]):
Laurent@814:         return _Search([("reference", self.getvariable())], criteria, parent_infos + ["contact", self.getlocalId()])
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814: 
Laurent@814: cls = _initElementClass("coil", "ldObjects_coil", "single")
Laurent@814: if cls:
Laurent@814:     setattr(cls, "getinfos", _getldelementinfosFunction("coil"))
Laurent@814:     
Laurent@814:     def updateElementName(self, old_name, new_name):
Laurent@814:         if self.variable == old_name:
Laurent@814:             self.variable = new_name
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814: 
Laurent@814:     def updateElementAddress(self, address_model, new_leading):
Laurent@814:         self.variable = update_address(self.variable, address_model, new_leading)
Laurent@814:     setattr(cls, "updateElementAddress", updateElementAddress)
Laurent@814: 
Laurent@814:     def Search(self, criteria, parent_infos=[]):
Laurent@814:         return _Search([("reference", self.getvariable())], criteria, parent_infos + ["coil", self.getlocalId()])
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814: 
Laurent@814: cls = _initElementClass("step", "sfcObjects_step", "single")
Laurent@814: if cls:
Laurent@814:     def getinfos(self):
Laurent@814:         infos = _getelementinfos(self)
Laurent@814:         infos["type"] = "step"
Laurent@814:         specific_values = infos["specific_values"]
Laurent@814:         specific_values["name"] = self.getname()
Laurent@814:         specific_values["initial"] = self.getinitialStep()
Laurent@814:         if self.connectionPointIn:
Laurent@814:             infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True))
Laurent@814:         if self.connectionPointOut:
Laurent@814:             infos["outputs"].append(_getconnectioninfos(self, self.connectionPointOut))
Laurent@814:         if self.connectionPointOutAction:
Laurent@814:             specific_values["action"] = _getconnectioninfos(self, self.connectionPointOutAction)
Laurent@814:         return infos
Laurent@814:     setattr(cls, "getinfos", getinfos)
Laurent@814: 
Laurent@814:     def Search(self, criteria, parent_infos=[]):
Laurent@814:         return _Search([("name", self.getname())], criteria, parent_infos + ["step", self.getlocalId()])
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("transition_condition", None)
Laurent@814: if cls:
Laurent@814:     def compatibility(self, tree):
Laurent@814:         connections = []
Laurent@814:         for child in tree.childNodes:
Laurent@814:             if child.nodeName == "connection":
Laurent@814:                 connections.append(child)
Laurent@814:         if len(connections) > 0:
Laurent@814:             node = CreateNode("connectionPointIn")
Laurent@814:             relPosition = CreateNode("relPosition")
Laurent@814:             NodeSetAttr(relPosition, "x", "0")
Laurent@814:             NodeSetAttr(relPosition, "y", "0")
Laurent@814:             node.childNodes.append(relPosition)
Laurent@814:             node.childNodes.extend(connections)
Laurent@814:             tree.childNodes = [node]
Laurent@814:     setattr(cls, "compatibility", compatibility)
Laurent@814: 
Laurent@891: cls = _initElementClass("transition", "sfcObjects_transition")
Laurent@814: if cls:
Laurent@814:     def getinfos(self):
Laurent@814:         infos = _getelementinfos(self)
Laurent@814:         infos["type"] = "transition"
Laurent@814:         specific_values = infos["specific_values"]
Laurent@814:         priority = self.getpriority()
Laurent@814:         if priority is None:
Laurent@814:             priority = 0
Laurent@814:         specific_values["priority"] = priority
Laurent@814:         condition = self.getconditionContent()
Laurent@814:         specific_values["condition_type"] = condition["type"]
Laurent@814:         if specific_values["condition_type"] == "connection":
Laurent@814:             specific_values["connection"] = _getconnectioninfos(self, condition["value"], True)
Laurent@814:         else:
Laurent@814:             specific_values["condition"] = condition["value"]
Laurent@814:         infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True))
Laurent@814:         infos["outputs"].append(_getconnectioninfos(self, self.connectionPointOut))
Laurent@814:         return infos
Laurent@814:     setattr(cls, "getinfos", getinfos)
Laurent@814: 
Laurent@814:     def setconditionContent(self, type, value):
Laurent@814:         if not self.condition:
Laurent@814:             self.addcondition()
Laurent@814:         if type == "reference":
Laurent@814:             condition = PLCOpenClasses["condition_reference"]()
Laurent@814:             condition.setname(value)
Laurent@814:         elif type == "inline":
Laurent@814:             condition = PLCOpenClasses["condition_inline"]()
Laurent@814:             condition.setcontent({"name" : "ST", "value" : PLCOpenClasses["formattedText"]()})
Laurent@814:             condition.settext(value)
Laurent@814:         elif type == "connection":
Laurent@814:             type = "connectionPointIn"
Laurent@814:             condition = PLCOpenClasses["connectionPointIn"]()
Laurent@814:         self.condition.setcontent({"name" : type, "value" : condition})
Laurent@814:     setattr(cls, "setconditionContent", setconditionContent)
Laurent@814:         
Laurent@814:     def getconditionContent(self):
Laurent@814:         if self.condition:
Laurent@814:             content = self.condition.getcontent()
Laurent@814:             values = {"type" : content["name"]}
Laurent@814:             if values["type"] == "reference":
Laurent@814:                 values["value"] = content["value"].getname()
Laurent@814:             elif values["type"] == "inline":
Laurent@814:                 values["value"] = content["value"].gettext()
Laurent@814:             elif values["type"] == "connectionPointIn":
Laurent@814:                 values["type"] = "connection"
Laurent@814:                 values["value"] = content["value"]
Laurent@814:             return values
Laurent@814:         return ""
Laurent@814:     setattr(cls, "getconditionContent", getconditionContent)
Laurent@814: 
Laurent@891:     def getconditionConnection(self):
Laurent@891:         if self.condition:
Laurent@891:             content = self.condition.getcontent()
Laurent@891:             if content["name"] == "connectionPointIn":
Laurent@891:                 return content["value"]
Laurent@891:         return None
Laurent@891:     setattr(cls, "getconditionConnection", getconditionConnection)
Laurent@891: 
Laurent@891:     def getBoundingBox(self):
Laurent@891:         bbox = _getBoundingBoxSingle(self)
Laurent@891:         condition_connection = self.getconditionConnection()
Laurent@891:         if condition_connection:
Laurent@891:             bbox.union(_getConnectionsBoundingBox(condition_connection))
Laurent@891:         return bbox
Laurent@891:     setattr(cls, "getBoundingBox", getBoundingBox)
Laurent@891:     
Laurent@891:     def translate(self, dx, dy):
Laurent@891:         _translateSingle(self, dx, dy)
Laurent@891:         condition_connection = self.getconditionConnection()
Laurent@891:         if condition_connection:
Laurent@891:             _translateConnections(condition_connection, dx, dy)
Laurent@891:     setattr(cls, "translate", translate)
Laurent@891:     
Laurent@891:     def filterConnections(self, connections):
Laurent@891:         _filterConnectionsSingle(self, connections)
Laurent@891:         condition_connection = self.getconditionConnection()
Laurent@891:         if condition_connection:
Laurent@891:             _filterConnections(condition_connection, self.localId, connections)
Laurent@891:     setattr(cls, "filterConnections", filterConnections)
Laurent@891:     
Laurent@891:     def updateConnectionsId(self, translation):
Laurent@891:         connections_end = []
Laurent@891:         if self.connectionPointIn is not None:
Laurent@891:             connections_end = _updateConnectionsId(self.connectionPointIn, translation)
Laurent@891:         condition_connection = self.getconditionConnection()
Laurent@891:         if condition_connection:
Laurent@891:             connections_end.extend(_updateConnectionsId(condition_connection, translation))
Laurent@891:         return _getconnectionsdefinition(self, connections_end)
Laurent@891:     setattr(cls, "updateConnectionsId", updateConnectionsId)
Laurent@891: 
Laurent@814:     def updateElementName(self, old_name, new_name):
Laurent@814:         if self.condition:
Laurent@814:             content = self.condition.getcontent()
Laurent@814:             if content["name"] == "reference":
Laurent@814:                 if content["value"].getname() == old_name:
Laurent@814:                     content["value"].setname(new_name)
Laurent@814:             elif content["name"] == "inline":
Laurent@814:                 content["value"].updateElementName(old_name, new_name)
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814: 
Laurent@814:     def updateElementAddress(self, address_model, new_leading):
Laurent@814:         if self.condition:
Laurent@814:             content = self.condition.getcontent()
Laurent@814:             if content["name"] == "reference":
Laurent@814:                 content["value"].setname(update_address(content["value"].getname(), address_model, new_leading))
Laurent@814:             elif content["name"] == "inline":
Laurent@814:                 content["value"].updateElementAddress(address_model, new_leading)
Laurent@814:     setattr(cls, "updateElementAddress", updateElementAddress)
Laurent@814: 
Laurent@814:     def getconnections(self):
Laurent@891:         condition_connection = self.getconditionConnection()
Laurent@891:         if condition_connection:
Laurent@891:             return condition_connection.getconnections()
Laurent@891:         return None
Laurent@814:     setattr(cls, "getconnections", getconnections)
Laurent@814:     
Laurent@814:     def Search(self, criteria, parent_infos=[]):
Laurent@814:         parent_infos = parent_infos + ["transition", self.getlocalId()]
Laurent@814:         search_result = []
Laurent@814:         content = self.condition.getcontent()
Laurent@814:         if content["name"] == "reference":
Laurent@814:             search_result.extend(_Search([("reference", content["value"].getname())], criteria, parent_infos))
Laurent@814:         elif content["name"] == "inline":
Laurent@814:             search_result.extend(content["value"].Search(criteria, parent_infos + ["inline"]))
Laurent@814:         return search_result
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814:     
Laurent@814: cls = _initElementClass("selectionDivergence", "sfcObjects_selectionDivergence", "single")
Laurent@814: if cls:
Laurent@814:     setattr(cls, "getinfos", _getdivergenceinfosFunction(True, False))
Laurent@814: 
Laurent@814: cls = _initElementClass("selectionConvergence", "sfcObjects_selectionConvergence", "multiple")
Laurent@814: if cls:
Laurent@814:     setattr(cls, "getinfos", _getdivergenceinfosFunction(False, False))
Laurent@814: 
Laurent@814: cls = _initElementClass("simultaneousDivergence", "sfcObjects_simultaneousDivergence", "single")
Laurent@814: if cls:
Laurent@814:     setattr(cls, "getinfos", _getdivergenceinfosFunction(True, True))
Laurent@814: 
Laurent@814: cls = _initElementClass("simultaneousConvergence", "sfcObjects_simultaneousConvergence", "multiple")
Laurent@814: if cls:
Laurent@814:     setattr(cls, "getinfos", _getdivergenceinfosFunction(False, True))
Laurent@814: 
Laurent@814: cls = _initElementClass("jumpStep", "sfcObjects_jumpStep", "single")
Laurent@814: if cls:
Laurent@814:     def getinfos(self):
Laurent@814:         infos = _getelementinfos(self)
Laurent@814:         infos["type"] = "jump"
Laurent@814:         infos["specific_values"]["target"] = self.gettargetName()
Laurent@814:         infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True))
Laurent@814:         return infos
Laurent@814:     setattr(cls, "getinfos", getinfos)
Laurent@814: 
Laurent@814:     def Search(self, criteria, parent_infos):
Laurent@814:         return _Search([("target", self.gettargetName())], criteria, parent_infos + ["jump", self.getlocalId()])
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("actionBlock_action", None)
Laurent@814: if cls:
Laurent@814:     def compatibility(self, tree):
Laurent@814:         relPosition = reduce(lambda x, y: x | (y.nodeName == "relPosition"), tree.childNodes, False)
Laurent@814:         if not tree.hasAttribute("localId"):
Laurent@814:             NodeSetAttr(tree, "localId", "0")
Laurent@814:         if not relPosition:
Laurent@814:             node = CreateNode("relPosition")
Laurent@814:             NodeSetAttr(node, "x", "0")
Laurent@814:             NodeSetAttr(node, "y", "0")
Laurent@814:             tree.childNodes.insert(0, node)
Laurent@814:     setattr(cls, "compatibility", compatibility)
Laurent@814:     
Laurent@814:     def setreferenceName(self, name):
Laurent@814:         if self.reference:
Laurent@814:             self.reference.setname(name)
Laurent@814:     setattr(cls, "setreferenceName", setreferenceName)
Laurent@814:     
Laurent@814:     def getreferenceName(self):
Laurent@814:         if self.reference:
Laurent@814:             return self.reference.getname()
Laurent@814:         return None
Laurent@814:     setattr(cls, "getreferenceName", getreferenceName)
Laurent@814: 
Laurent@814:     def setinlineContent(self, content):
Laurent@814:         if self.inline:
Laurent@814:             self.inline.setcontent({"name" : "ST", "value" : PLCOpenClasses["formattedText"]()})
Laurent@814:             self.inline.settext(content)
Laurent@814:     setattr(cls, "setinlineContent", setinlineContent)
Laurent@814:     
Laurent@814:     def getinlineContent(self):
Laurent@814:         if self.inline:
Laurent@814:             return self.inline.gettext()
Laurent@814:         return None
Laurent@814:     setattr(cls, "getinlineContent", getinlineContent)
Laurent@814: 
Laurent@814:     def updateElementName(self, old_name, new_name):
Laurent@814:         if self.reference and self.reference.getname() == old_name:
Laurent@814:             self.reference.setname(new_name)
Laurent@814:         if self.inline:
Laurent@814:             self.inline.updateElementName(old_name, new_name)
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814: 
Laurent@814:     def updateElementAddress(self, address_model, new_leading):
Laurent@814:         if self.reference:
Laurent@814:             self.reference.setname(update_address(self.reference.getname(), address_model, new_leading))
Laurent@814:         if self.inline:
Laurent@814:             self.inline.updateElementAddress(address_model, new_leading)
Laurent@814:     setattr(cls, "updateElementAddress", updateElementAddress)
Laurent@814: 
Laurent@814:     def Search(self, criteria, parent_infos=[]):
Laurent@814:         qualifier = self.getqualifier()
Laurent@814:         if qualifier is None:
Laurent@814:             qualifier = "N"
Laurent@814:         return _Search([("inline", self.getinlineContent()),
Laurent@814:                         ("reference", self.getreferenceName()), 
Laurent@814:                         ("qualifier", qualifier),
Laurent@814:                         ("duration", self.getduration()),
Laurent@814:                         ("indicator", self.getindicator())],
Laurent@814:                        criteria, parent_infos)
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814: 
Laurent@814: cls = _initElementClass("actionBlock", "commonObjects_actionBlock", "single")
Laurent@814: if cls:
Laurent@814:     def compatibility(self, tree):
Laurent@814:         for child in tree.childNodes[:]:
Laurent@814:             if child.nodeName == "connectionPointOut":
Laurent@814:                 tree.childNodes.remove(child)
Laurent@814:     setattr(cls, "compatibility", compatibility)
Laurent@814:     
Laurent@814:     def getinfos(self):
Laurent@814:         infos = _getelementinfos(self)
Laurent@814:         infos["type"] = "actionBlock"
Laurent@814:         infos["specific_values"]["actions"] = self.getactions()
Laurent@814:         infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True))
Laurent@814:         return infos
Laurent@814:     setattr(cls, "getinfos", getinfos)
Laurent@814:     
Laurent@814:     def setactions(self, actions):
Laurent@814:         self.action = []
Laurent@814:         for params in actions:
Laurent@814:             action = PLCOpenClasses["actionBlock_action"]()
Laurent@814:             action.setqualifier(params["qualifier"])
Laurent@814:             if params["type"] == "reference":
Laurent@814:                 action.addreference()
Laurent@814:                 action.setreferenceName(params["value"])
Laurent@814:             else:
Laurent@814:                 action.addinline()
Laurent@814:                 action.setinlineContent(params["value"])
Laurent@814:             if params.has_key("duration"):
Laurent@814:                 action.setduration(params["duration"])
Laurent@814:             if params.has_key("indicator"):
Laurent@814:                 action.setindicator(params["indicator"])
Laurent@814:             self.action.append(action)
Laurent@814:     setattr(cls, "setactions", setactions)
Laurent@814: 
Laurent@814:     def getactions(self):
Laurent@814:         actions = []
Laurent@814:         for action in self.action:
Laurent@814:             params = {}
Laurent@814:             params["qualifier"] = action.getqualifier()
Laurent@814:             if params["qualifier"] is None:
Laurent@814:                 params["qualifier"] = "N"
Laurent@814:             if action.getreference():
Laurent@814:                 params["type"] = "reference"
Laurent@814:                 params["value"] = action.getreferenceName()
Laurent@814:             elif action.getinline():
Laurent@814:                 params["type"] = "inline"
Laurent@814:                 params["value"] = action.getinlineContent()
Laurent@814:             duration = action.getduration()
Laurent@814:             if duration:
Laurent@814:                 params["duration"] = duration
Laurent@814:             indicator = action.getindicator()
Laurent@814:             if indicator:
Laurent@814:                 params["indicator"] = indicator
Laurent@814:             actions.append(params)
Laurent@814:         return actions
Laurent@814:     setattr(cls, "getactions", getactions)
Laurent@814: 
Laurent@814:     def updateElementName(self, old_name, new_name):
Laurent@814:         for action in self.action:
Laurent@814:             action.updateElementName(old_name, new_name)
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814: 
Laurent@814:     def updateElementAddress(self, address_model, new_leading):
Laurent@814:         for action in self.action:
Laurent@814:             action.updateElementAddress(address_model, new_leading)
Laurent@814:     setattr(cls, "updateElementAddress", updateElementAddress)
Laurent@814: 
Laurent@814:     def Search(self, criteria, parent_infos=[]):
Laurent@814:         parent_infos = parent_infos + ["action_block", self.getlocalId()]
Laurent@814:         search_result = []
Laurent@814:         for idx, action in enumerate(self.action):
Laurent@814:             search_result.extend(action.Search(criteria, parent_infos + ["action", idx]))
Laurent@814:         return search_result
Laurent@814:     setattr(cls, "Search", Search)
Laurent@814: 
Laurent@814: def _SearchInIOVariable(self, criteria, parent_infos=[]):
Laurent@814:     return _Search([("expression", self.getexpression())], criteria, parent_infos + ["io_variable", self.getlocalId()])
Laurent@814: 
Laurent@814: cls = _initElementClass("inVariable", "fbdObjects_inVariable")
Laurent@814: if cls:
Laurent@814:     setattr(cls, "getinfos", _getvariableinfosFunction("input", False, True))
Laurent@814:     
Laurent@814:     def updateElementName(self, old_name, new_name):
Laurent@814:         if self.expression == old_name:
Laurent@814:             self.expression = new_name
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814: 
Laurent@814:     def updateElementAddress(self, address_model, new_leading):
Laurent@814:         self.expression = update_address(self.expression, address_model, new_leading)
Laurent@814:     setattr(cls, "updateElementAddress", updateElementAddress)
Laurent@814: 
Laurent@814:     setattr(cls, "Search", _SearchInIOVariable)
Laurent@814: 
Laurent@814: cls = _initElementClass("outVariable", "fbdObjects_outVariable", "single")
Laurent@814: if cls:
Laurent@814:     setattr(cls, "getinfos", _getvariableinfosFunction("output", True, False))
Laurent@814:     
Laurent@814:     def updateElementName(self, old_name, new_name):
Laurent@814:         if self.expression == old_name:
Laurent@814:             self.expression = new_name
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814: 
Laurent@814:     def updateElementAddress(self, address_model, new_leading):
Laurent@814:         self.expression = update_address(self.expression, address_model, new_leading)
Laurent@814:     setattr(cls, "updateElementAddress", updateElementAddress)
Laurent@814: 
Laurent@814:     setattr(cls, "Search", _SearchInIOVariable)
Laurent@814: 
Laurent@814: cls = _initElementClass("inOutVariable", "fbdObjects_inOutVariable", "single")
Laurent@814: if cls:
Laurent@814:     setattr(cls, "getinfos", _getvariableinfosFunction("inout", True, True))
Laurent@814:     
Laurent@814:     def updateElementName(self, old_name, new_name):
Laurent@814:         if self.expression == old_name:
Laurent@814:             self.expression = new_name
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814: 
Laurent@814:     def updateElementAddress(self, address_model, new_leading):
Laurent@814:         self.expression = update_address(self.expression, address_model, new_leading)
Laurent@814:     setattr(cls, "updateElementAddress", updateElementAddress)
Laurent@814: 
Laurent@814:     setattr(cls, "Search", _SearchInIOVariable)
Laurent@814: 
Laurent@814: 
Laurent@814: def _SearchInConnector(self, criteria, parent_infos=[]):
Laurent@814:     return _Search([("name", self.getname())], criteria, parent_infos + ["connector", self.getlocalId()])
Laurent@814: 
Laurent@814: cls = _initElementClass("continuation", "commonObjects_continuation")
Laurent@814: if cls:
Laurent@814:     setattr(cls, "getinfos", _getconnectorinfosFunction("continuation"))
Laurent@814:     setattr(cls, "Search", _SearchInConnector)
Laurent@814: 
Laurent@814:     def updateElementName(self, old_name, new_name):
Laurent@814:         if self.name == old_name:
Laurent@814:             self.name = new_name
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814: 
Laurent@814: cls = _initElementClass("connector", "commonObjects_connector", "single")
Laurent@814: if cls:
Laurent@814:     setattr(cls, "getinfos", _getconnectorinfosFunction("connector"))
Laurent@814:     setattr(cls, "Search", _SearchInConnector)
Laurent@814: 
Laurent@814:     def updateElementName(self, old_name, new_name):
Laurent@814:         if self.name == old_name:
Laurent@814:             self.name = new_name
Laurent@814:     setattr(cls, "updateElementName", updateElementName)
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("connection", None)
Laurent@814: if cls:
Laurent@814:     def setpoints(self, points):
Laurent@814:         self.position = []
Laurent@814:         for point in points:
Laurent@814:             position = PLCOpenClasses["position"]()
Laurent@814:             position.setx(point.x)
Laurent@814:             position.sety(point.y)
Laurent@814:             self.position.append(position)
Laurent@814:     setattr(cls, "setpoints", setpoints)
Laurent@814: 
Laurent@814:     def getpoints(self):
Laurent@814:         points = []
Laurent@814:         for position in self.position:
Laurent@814:             points.append((position.getx(),position.gety()))
Laurent@814:         return points
Laurent@814:     setattr(cls, "getpoints", getpoints)
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("connectionPointIn", None)
Laurent@814: if cls:
Laurent@814:     def setrelPositionXY(self, x, y):
Laurent@814:         self.relPosition = PLCOpenClasses["position"]()
Laurent@814:         self.relPosition.setx(x)
Laurent@814:         self.relPosition.sety(y)
Laurent@814:     setattr(cls, "setrelPositionXY", setrelPositionXY)
Laurent@814: 
Laurent@814:     def getrelPositionXY(self):
Laurent@814:         if self.relPosition:
Laurent@814:             return self.relPosition.getx(), self.relPosition.gety()
Laurent@814:         else:
Laurent@814:             return self.relPosition
Laurent@814:     setattr(cls, "getrelPositionXY", getrelPositionXY)
Laurent@814: 
Laurent@814:     def addconnection(self):
Laurent@814:         if not self.content:
Laurent@814:             self.content = {"name" : "connection", "value" : [PLCOpenClasses["connection"]()]}
Laurent@814:         else:
Laurent@814:             self.content["value"].append(PLCOpenClasses["connection"]())
Laurent@814:     setattr(cls, "addconnection", addconnection)
Laurent@814: 
Laurent@814:     def removeconnection(self, idx):
Laurent@814:         if self.content:
Laurent@814:             self.content["value"].pop(idx)
Laurent@814:         if len(self.content["value"]) == 0:
Laurent@814:             self.content = None
Laurent@814:     setattr(cls, "removeconnection", removeconnection)
Laurent@814: 
Laurent@814:     def removeconnections(self):
Laurent@814:         if self.content:
Laurent@814:             self.content = None
Laurent@814:     setattr(cls, "removeconnections", removeconnections)
Laurent@814:     
Laurent@814:     def getconnections(self):
Laurent@814:         if self.content:
Laurent@814:             return self.content["value"]
Laurent@814:     setattr(cls, "getconnections", getconnections)
Laurent@814:     
Laurent@814:     def setconnectionId(self, idx, id):
Laurent@814:         if self.content:
Laurent@814:             self.content["value"][idx].setrefLocalId(id)
Laurent@814:     setattr(cls, "setconnectionId", setconnectionId)
Laurent@814:     
Laurent@814:     def getconnectionId(self, idx):
Laurent@814:         if self.content:
Laurent@814:             return self.content["value"][idx].getrefLocalId()
Laurent@814:         return None
Laurent@814:     setattr(cls, "getconnectionId", getconnectionId)
Laurent@814:     
Laurent@814:     def setconnectionPoints(self, idx, points):
Laurent@814:         if self.content:
Laurent@814:             self.content["value"][idx].setpoints(points)
Laurent@814:     setattr(cls, "setconnectionPoints", setconnectionPoints)
Laurent@814: 
Laurent@814:     def getconnectionPoints(self, idx):
Laurent@814:         if self.content:
Laurent@814:             return self.content["value"][idx].getpoints()
Laurent@814:         return None
Laurent@814:     setattr(cls, "getconnectionPoints", getconnectionPoints)
Laurent@814: 
Laurent@814:     def setconnectionParameter(self, idx, parameter):
Laurent@814:         if self.content:
Laurent@814:             self.content["value"][idx].setformalParameter(parameter)
Laurent@814:     setattr(cls, "setconnectionParameter", setconnectionParameter)
Laurent@814:     
Laurent@814:     def getconnectionParameter(self, idx):
Laurent@814:         if self.content:
Laurent@814:             return self.content["value"][idx].getformalParameter()
Laurent@814:         return None
Laurent@814:     setattr(cls, "getconnectionParameter", getconnectionParameter)
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("connectionPointOut", None)
Laurent@814: if cls:
Laurent@814:     def setrelPositionXY(self, x, y):
Laurent@814:         self.relPosition = PLCOpenClasses["position"]()
Laurent@814:         self.relPosition.setx(x)
Laurent@814:         self.relPosition.sety(y)
Laurent@814:     setattr(cls, "setrelPositionXY", setrelPositionXY)
Laurent@814: 
Laurent@814:     def getrelPositionXY(self):
Laurent@814:         if self.relPosition:
Laurent@814:             return self.relPosition.getx(), self.relPosition.gety()
Laurent@814:         return self.relPosition
Laurent@814:     setattr(cls, "getrelPositionXY", getrelPositionXY)
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("value", None)
Laurent@814: if cls:
Laurent@814:     def setvalue(self, value):
Laurent@814:         value = value.strip()
Laurent@814:         if value.startswith("[") and value.endswith("]"):
Laurent@814:             arrayValue = PLCOpenClasses["value_arrayValue"]()
Laurent@814:             self.content = {"name" : "arrayValue", "value" : arrayValue}
Laurent@814:         elif value.startswith("(") and value.endswith(")"):
Laurent@814:             structValue = PLCOpenClasses["value_structValue"]()
Laurent@814:             self.content = {"name" : "structValue", "value" : structValue}
Laurent@814:         else:
Laurent@814:             simpleValue = PLCOpenClasses["value_simpleValue"]()
Laurent@814:             self.content = {"name" : "simpleValue", "value": simpleValue}
Laurent@814:         self.content["value"].setvalue(value)
Laurent@814:     setattr(cls, "setvalue", setvalue)
Laurent@814:     
Laurent@814:     def getvalue(self):
Laurent@814:         return self.content["value"].getvalue()
Laurent@814:     setattr(cls, "getvalue", getvalue)
Laurent@814: 
Laurent@814: def extractValues(values):
Laurent@814:     items = values.split(",")
Laurent@814:     i = 1
Laurent@814:     while i < len(items):
Laurent@814:         opened = items[i - 1].count("(") + items[i - 1].count("[")
Laurent@814:         closed = items[i - 1].count(")") + items[i - 1].count("]")
Laurent@814:         if opened > closed:
Laurent@814:             items[i - 1] = ','.join([items[i - 1], items.pop(i)])
Laurent@814:         elif opened == closed:
Laurent@814:             i += 1
Laurent@814:         else:
Laurent@814:             raise ValueError, _("\"%s\" is an invalid value!")%value
Laurent@814:     return items
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("value_arrayValue", None)
Laurent@814: if cls:
Laurent@814:     arrayValue_model = re.compile("([0-9]*)\((.*)\)$")
Laurent@814:     
Laurent@814:     def setvalue(self, value):
Laurent@814:         self.value = []
Laurent@814:         for item in extractValues(value[1:-1]):
Laurent@814:             item = item.strip()
Laurent@814:             element = PLCOpenClasses["arrayValue_value"]()
Laurent@814:             result = arrayValue_model.match(item)
Laurent@814:             if result is not None:
Laurent@814:                 groups = result.groups()
Laurent@814:                 element.setrepetitionValue(groups[0])
Laurent@814:                 element.setvalue(groups[1].strip())
Laurent@814:             else:
Laurent@814:                 element.setvalue(item)
Laurent@814:             self.value.append(element)
Laurent@814:     setattr(cls, "setvalue", setvalue)
Laurent@814:     
Laurent@814:     def getvalue(self):
Laurent@814:         values = []
Laurent@814:         for element in self.value:
Laurent@814:             repetition = element.getrepetitionValue()
Laurent@814:             if repetition is not None and int(repetition) > 1:
Laurent@814:                 value = element.getvalue()
Laurent@814:                 if value is None:
Laurent@814:                     value = ""
Laurent@814:                 values.append("%s(%s)"%(repetition, value))
Laurent@814:             else:
Laurent@814:                 values.append(element.getvalue())
Laurent@814:         return "[%s]"%", ".join(values)
Laurent@814:     setattr(cls, "getvalue", getvalue)
Laurent@814: 
Laurent@814: cls = PLCOpenClasses.get("value_structValue", None)
Laurent@814: if cls:
Laurent@814:     structValue_model = re.compile("(.*):=(.*)")
Laurent@814:     
Laurent@814:     def setvalue(self, value):
Laurent@814:         self.value = []
Laurent@814:         for item in extractValues(value[1:-1]):
Laurent@814:             result = structValue_model.match(item)
Laurent@814:             if result is not None:
Laurent@814:                 groups = result.groups()
Laurent@814:                 element = PLCOpenClasses["structValue_value"]()
Laurent@814:                 element.setmember(groups[0].strip())
Laurent@814:                 element.setvalue(groups[1].strip())
Laurent@814:                 self.value.append(element)
Laurent@814:     setattr(cls, "setvalue", setvalue)
Laurent@814:     
Laurent@814:     def getvalue(self):
Laurent@814:         values = []
Laurent@814:         for element in self.value:
Laurent@814:             values.append("%s := %s"%(element.getmember(), element.getvalue()))
Laurent@814:         return "(%s)"%", ".join(values)
Laurent@814:     setattr(cls, "getvalue", getvalue)