plugins/svgui/svgui.py
changeset 137 187a4e2412e5
parent 105 434aed8dc58d
child 138 3a6ebb01760a
equal deleted inserted replaced
136:f49f586a0a43 137:187a4e2412e5
     1 import os, sys
     1 import os, shutil, sys
     2 base_folder = os.path.split(sys.path[0])[0]
     2 base_folder = os.path.split(sys.path[0])[0]
     3 sys.path.append(os.path.join(base_folder, "wxsvg", "defeditor"))
     3 sys.path.append(os.path.join(base_folder, "wxsvg", "SVGUIEditor"))
     4 
     4 sys.path.append(os.path.join(base_folder, "plcopeneditor", "graphics"))
     5 from DEFControler import *
     5 
     6 from defeditor import *
     6 import wx
       
     7 
       
     8 from SVGUIControler import *
       
     9 from SVGUIEditor import *
     7 from FBD_Objects import *
    10 from FBD_Objects import *
     8 
    11 
     9 class _EditorFramePlug(EditorFrame):
    12 from wxPopen import ProcessLogger
       
    13 
       
    14 [ID_SVGUIEDITORFBDPANEL, 
       
    15 ] = [wx.NewId() for _init_ctrls in range(1)]
       
    16 
       
    17 SVGUIFB_Types = {ITEM_CONTAINER : "Container",
       
    18                  ITEM_BUTTON : "Button", 
       
    19                  ITEM_TEXT : "TextCtrl", 
       
    20                  ITEM_SCROLLBAR : "ScrollBar", 
       
    21                  ITEM_ROTATING : "RotatingCtrl", 
       
    22                  ITEM_NOTEBOOK : "NoteBook", 
       
    23                  ITEM_TRANSFORM : "Transform"}
       
    24 
       
    25 class _SVGUIEditor(SVGUIEditor):
    10     """
    26     """
    11     This Class add IEC specific features to the SVGUI DEFEditor :
    27     This Class add IEC specific features to the SVGUIEditor :
    12         - FDB preview
    28         - FDB preview
    13         - FBD begin drag 
    29         - FBD begin drag 
    14     """
    30     """
    15     def __init__(self,controller):
    31     
    16         EditorFrame.__init__(self,controller, solo_mode=False)
    32     def _init_coll_EditorGridSizer_Items(self, parent):
    17         self.FbdWindow = wx.Panel(name='fbdwindow',parent=self.EditorPanel,
    33         SVGUIEditor._init_coll_EditorGridSizer_Items(self, parent)
    18                                        pos=wx.Point(300, 355),size=wx.Size(240, 240),
    34         parent.AddWindow(self.FBDPanel, 0, border=0, flag=wx.GROW)
    19                                        style=wx.TAB_TRAVERSAL|wx.SIMPLE_BORDER)
    35     
    20         self.FbdWindow.SetBackgroundColour(wxColour(255,255,255))
    36     def _init_ctrls(self, prnt):
    21         self.FbdWindow.Bind(wx.EVT_LEFT_DOWN, self.OnFbdClick)
    37         SVGUIEditor._init_ctrls(self, prnt, False)
    22         wx.EVT_PAINT(self.FbdWindow,self.OnPaintFBD)
    38         
    23         
    39         self.FBDPanel = wx.Panel(id=ID_SVGUIEDITORFBDPANEL, 
    24         self.FbdData = None
    40                   name='FBDPanel', parent=self.EditorPanel, pos=wx.Point(0, 0),
    25         self.RefreshProjectTree()
    41                   size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL|wx.SIMPLE_BORDER)
    26         if (controller.SvgFilepath):
    42         self.FBDPanel.SetBackgroundColour(wx.WHITE)
    27             self.OpenSVGFile(controller.filepath)
    43         self.FBDPanel.Bind(wx.EVT_LEFT_DOWN, self.OnFBDPanelClick)
    28             self.mySVGctrl.Refresh()
    44         self.FBDPanel.Bind(wx.EVT_PAINT, self.OnPaintFBDPanel)
    29         self.OnNewFile()
    45         
    30         self.RefreshFBD()
    46         setattr(self.FBDPanel, "GetScaling", lambda: None) 
    31         
    47         
    32     def SetFbdDragData(self,selected_type):
    48         self._init_sizers()
    33         self.FbdBlock = FBD_Block(parent=self.FbdWindow,type=selected_type,name='')
    49     
    34         name = self.Controler.GetSelectedElementName()
    50     def __init__(self, parent, controler = None, fileOpen = None):
    35         self.FbdData = str((selected_type,"functionBlock", name))
    51         SVGUIEditor.__init__(self, parent, controler, fileOpen)
    36         
    52         
    37     def RefreshFBD(self):
    53         self.FBDBlock = None
    38         dc = wx.ClientDC(self.FbdWindow)
    54     
       
    55     def RefreshView(self, select_id = None):
       
    56         SVGUIEditor.RefreshView(self, select_id)
       
    57         self.FBDPanel.Refresh()
       
    58     
       
    59     def OnPaintFBDPanel(self,event):
       
    60         dc = wx.ClientDC(self.FBDPanel)
    39         dc.Clear()
    61         dc.Clear()
    40         if self.Controler.HasOpenedProject():
    62         selected = self.GetSelected()
    41             selected_type = self.Controler.GetSelectedElementType()
    63         if selected is not None:
    42             if selected_type:
    64             selected_type = self.Controler.GetElementType(selected)
    43                 self.SetFbdDragData(selected_type)
    65             if selected_type is not None:
    44                 self.FbdBlock = FBD_Block(parent=self.FbdWindow,type=selected_type,name='')
    66                 self.FBDBlock = FBD_Block(parent=self.FBDPanel,type=SVGUIFB_Types[selected_type],name=self.Controler.GetElementName(selected))
    45                 width,height = self.FbdBlock.GetMinSize()
    67                 width, height = self.FBDBlock.GetMinSize()
    46                 self.FbdBlock.SetSize(width,height)
    68                 self.FBDBlock.SetSize(width,height)
    47                 clientsize = self.FbdWindow.GetClientSize()
    69                 clientsize = self.FBDPanel.GetClientSize()
    48                 x = (clientsize.width - width) / 2
    70                 x = (clientsize.width - width) / 2
    49                 y = (clientsize.height - height) / 2
    71                 y = (clientsize.height - height) / 2
    50                 self.FbdBlock.SetPosition(x, y)
    72                 self.FBDBlock.SetPosition(x, y)
    51                 self.FbdBlock.Draw(dc)
    73                 self.FBDBlock.Draw(dc)
    52                 
    74         else:
    53     def OnPaintFBD(self,event):
    75             self.FBDBlock = None
    54         self.RefreshFBD()
       
    55         event.Skip()
    76         event.Skip()
    56         
    77         
    57     def OnFbdClick(self,event):
    78     def OnFBDPanelClick(self, event):
    58         if self.FbdData:
    79         if self.FBDBlock:
    59             data = wx.TextDataObject(self.FbdData)
    80             data = wx.TextDataObject(str((self.FBDBlock.GetType(), "functionBlock", self.FBDBlock.GetName())))
    60             DropSrc = wx.DropSource(self.FbdWindow)
    81             DropSrc = wx.DropSource(self.FBDPanel)
    61             DropSrc.SetData(data)
    82             DropSrc.SetData(data)
    62             DropSrc.DoDragDrop()
    83             DropSrc.DoDragDrop()
    63             
    84         event.Skip()
    64     def OnProjectTreeItemSelected(self,event):
    85     
    65         EditorFrame.OnProjectTreeItemSelected(self,event)
    86     def OnInterfaceTreeItemSelected(self, event):
    66         self.RefreshFBD()
    87         self.FBDPanel.Refresh()
    67         
    88         SVGUIEditor.OnInterfaceTreeItemSelected(self, event)
    68     def OnNew(self,event):
    89     
    69         EditorFrame.OnNew(self,event)
       
    70         self.RefreshFBD()
       
    71         
       
    72     def OnOpen(self,event):
       
    73         EditorFrame.OnOpen(self,event)
       
    74         self.RefreshFBD()
       
    75         
       
    76     def OnGenerate(self,event):
    90     def OnGenerate(self,event):
    77         self.SaveProject()
    91         self.SaveProject()
    78         self.Controler.PlugGenerate_C(sys.path[0],(0,0,4,5),None)
    92         self.Controler.PlugGenerate_C(sys.path[0],(0,0,4,5),None)
    79         event.Skip()    
    93         event.Skip()    
    80     
    94     
    81     def OnClose(self, event):
       
    82         self._onclose()
       
    83         event.Skip()
       
    84     
       
    85 """
       
    86 TYPECONVERSION = {"BOOL" : "X", "SINT" : "B", "INT" : "W", "DINT" : "D", "LINT" : "L",
    95 TYPECONVERSION = {"BOOL" : "X", "SINT" : "B", "INT" : "W", "DINT" : "D", "LINT" : "L",
    87     "USINT" : "B", "UINT" : "W", "UDINT" : "D", "ULINT" : "L", "REAL" : "D", "LREAL" : "L",
    96     "USINT" : "B", "UINT" : "W", "UDINT" : "D", "ULINT" : "L", "REAL" : "D", "LREAL" : "L",
    88     "STRING" : "B", "BYTE" : "B", "WORD" : "W", "DWORD" : "D", "LWORD" : "L", "WSTRING" : "W"}
    97     "STRING" : "B", "BYTE" : "B", "WORD" : "W", "DWORD" : "D", "LWORD" : "L", "WSTRING" : "W"}
    89 """
    98 
    90 TYPECONVERSION = {"BOOL" : "X", "UINT" : "W","REAL" : "D","STRING" : "B"}
       
    91 CTYPECONVERSION = {"BOOL" : "IEC_BOOL", "UINT" : "IEC_UINT", "STRING" : "IEC_STRING", "REAL" : "IEC_REAL"}
    99 CTYPECONVERSION = {"BOOL" : "IEC_BOOL", "UINT" : "IEC_UINT", "STRING" : "IEC_STRING", "REAL" : "IEC_REAL"}
    92 CPRINTTYPECONVERSION = {"BOOL" : "d", "UINT" : "d", "STRING" : "s", "REAL" : "f"}
   100 CPRINTTYPECONVERSION = {"BOOL" : "d", "UINT" : "d", "STRING" : "s", "REAL" : "f"}
    93 class RootClass(DEFControler):
   101 
       
   102 class RootClass(SVGUIControler):
    94 
   103 
    95     def __init__(self):
   104     def __init__(self):
    96         DEFControler.__init__(self)
   105         SVGUIControler.__init__(self)
    97         filepath = os.path.join(self.PlugPath(), "gui.def")
   106         filepath = os.path.join(self.PlugPath(), "gui.xml")
    98         
   107         
    99         if os.path.isfile(filepath):
   108         if os.path.isfile(filepath):
   100             svgfile = os.path.join(self.PlugPath(), "gui.svg")
   109             svgfile = os.path.join(self.PlugPath(), "gui.svg")
   101             if os.path.isfile(svgfile):
   110             if os.path.isfile(svgfile):
   102                 self.SvgFilepath = svgfile
   111                 self.SvgFilepath = svgfile
   103             self.OpenXMLFile(filepath)
   112             self.OpenXMLFile(filepath)
   104         else:
   113         else:
   105             self.CreateRootElement()
   114             self.CreateNewInterface()
   106             self.SetFilePath(filepath)
   115             self.SetFilePath(filepath)
       
   116 
       
   117     def GetElementIdFromName(self, name):
       
   118         element = self.GetElementByName(name)
       
   119         if element is not None:
       
   120             return element.getid()
       
   121         return None
   107 
   122 
   108     _View = None
   123     _View = None
   109     def _OpenView(self, logger):
   124     def _OpenView(self, logger):
   110         if not self._View:
   125         if not self._View:
   111             def _onclose():
   126             def _onclose():
   112                 self._View = None
   127                 self._View = None
   113             def _onsave():
   128             def _onsave():
   114                 self.GetPlugRoot().SaveProject()
   129                 self.GetPlugRoot().SaveProject()
   115             self._View = _EditorFramePlug(self)
   130             self._View = _SVGUIEditor(self.GetPlugRoot().AppFrame, self)
   116             self._View._onclose = _onclose
   131             self._View._onclose = _onclose
   117             self._View._onsave = _onsave
   132             self._View._onsave = _onsave
   118             filepath = os.path.join(self.PlugPath(), "gui.def")
       
   119             self._View.OpenSVGFile(filepath)
       
   120             self._View.Show()
   133             self._View.Show()
       
   134 
       
   135     def _ImportSVG(self, logger):
       
   136         if not self._View:
       
   137             dialog = wx.FileDialog(self.GetPlugRoot().AppFrame, "Choose a SVG file", os.getcwd(), "",  "SVG files (*.svg)|*.svg|All files|*.*", wx.OPEN)
       
   138             if dialog.ShowModal() == wx.ID_OK:
       
   139                 svgpath = dialog.GetPath()
       
   140                 if os.path.isfile(svgpath):
       
   141                     shutil.copy(svgpath, os.path.join(self.PlugPath(), "gui.svg"))
       
   142                 else:
       
   143                     logger.write_error("No such SVG file: %s\n"%svgpath)
       
   144             dialog.Destroy()
       
   145 
       
   146     def _ImportXML(self, logger):
       
   147         if not self._View:
       
   148             dialog = wx.FileDialog(self.GetPlugRoot().AppFrame, "Choose a XML file", os.getcwd(), "",  "XML files (*.xml)|*.xml|All files|*.*", wx.OPEN)
       
   149             if dialog.ShowModal() == wx.ID_OK:
       
   150                 xmlpath = dialog.GetPath()
       
   151                 if os.path.isfile(xmlpath):
       
   152                     shutil.copy(xmlpath, os.path.join(self.PlugPath(), "gui.xml"))
       
   153                 else:
       
   154                     logger.write_error("No such XML file: %s\n"%xmlpath)
       
   155             dialog.Destroy()
   121 
   156 
   122     PluginMethods = [
   157     PluginMethods = [
   123         {"bitmap" : os.path.join("images","HMIEditor"),
   158         {"bitmap" : os.path.join("images","HMIEditor"),
   124          "name" : "HMI Editor",
   159          "name" : "HMI Editor",
   125          "tooltip" : "HMI Editor",
   160          "tooltip" : "HMI Editor",
   126          "method" : "_OpenView"},
   161          "method" : "_OpenView"},
   127         {"bitmap" : os.path.join("images","ImportSVG"),
   162         {"bitmap" : os.path.join("images","ImportSVG"),
   128          "name" : "Import SVG",
   163          "name" : "Import SVG",
   129          "tooltip" : "Import SVG",
   164          "tooltip" : "Import SVG",
   130          "method" : "_OpenView"},
   165          "method" : "_ImportSVG"},
   131         {"bitmap" : os.path.join("images","ImportDEF"),
   166         {"bitmap" : os.path.join("images","ImportDEF"),
   132          "name" : "Import DEF",
   167          "name" : "Import XML",
   133          "tooltip" : "Import DEF",
   168          "tooltip" : "Import XML",
   134          "method" : "_OpenView"},
   169          "method" : "_InportXML"},
   135     ]
   170     ]
   136     
   171     
   137     def OnPlugSave(self):
   172     def OnPlugSave(self):
   138         self.SaveXMLFile()
   173         self.SaveXMLFile()
   139         return True
   174         return True
   140     
   175     
   141     def GenerateProgramHeadersPublicVars(self):
   176     def GenerateProgramHeadersPublicVars(self, elements):
   142         fct = ""
   177         text = """    void OnPlcOutEvent(wxEvent& event);
   143         fct += "    void OnPlcOutEvent(wxEvent& event);\n\n"
   178 
   144         fct += "    void Retrive();\n"
   179     void Retrieve();
   145         fct += "    void Publish();\n"
   180     void Publish();
   146         fct += "    void Initialize();\n"
   181     void Initialize();
   147 #        fct += "    void Print();\n"
   182 """
   148         return fct
   183 #        text += "    void Print();\n"
   149     
   184         return text
   150     def GenerateIECVars(self):
   185     
       
   186     def GenerateIECVars(self, elements):
   151         text = ""
   187         text = ""
   152         elementsTab = self.GetElementsTab()
   188         for element in elements:
   153         for element in elementsTab:
   189             text += "volatile int out_state_%d;\n"%element.getid()
   154             infos = element.getElementAttributes()
   190             text += "volatile int in_state_%d;\n"%element.getid()
   155             for info in infos:
       
   156                 if info["name"] == "id":
       
   157                     element_id = str(info["value"])
       
   158             text += "volatile int out_state_"+element_id+";\n"
       
   159             text += "volatile int in_state_"+element_id+";\n"
       
   160         text +="\n"
   191         text +="\n"
       
   192         current_location = "_".join(map(str, self.GetCurrentLocation()))
   161         #Declaration des variables
   193         #Declaration des variables
   162         for element in elementsTab:
   194         for element in elements:
   163             infos = element.getElementAttributes()
   195             block_infos = GetBlockType(SVGUIFB_Types[GetElementType(element)])
   164             for info in infos:
   196             block_id = element.getid()
   165                 if info["name"] == "id":
   197             for i, input in enumerate(block_infos["inputs"]):
   166                     element_id = str(info["value"])
       
   167             type = element.GetElementInfos()["type"]
       
   168             FbdBlock = self.GetBlockType(type)
       
   169             element_num_patte = 1
       
   170             for input in FbdBlock["inputs"]:
       
   171                 element_type = TYPECONVERSION[input[1]]
       
   172                 element_c_type = CTYPECONVERSION[input[1]]
   198                 element_c_type = CTYPECONVERSION[input[1]]
   173                 line = "__Q"+element_type+self.BusNumber+"_"+element_id+"_"+str(element_num_patte)+";\n"
   199                 variable = "__Q%s%s_%d_%d"%(TYPECONVERSION[input[1]], current_location, block_id, i + 1)
   174                 text += element_c_type+" "+line
   200                 text += "%s %s;\n"%(element_c_type, variable)
   175                 text += element_c_type+" _copy"+line
   201                 text += "%s _copy%s;\n"%(element_c_type, variable)
   176                 element_num_patte +=1
   202             for i, output in enumerate(block_infos["outputs"]):
   177             element_num_patte = 1
       
   178             for output in FbdBlock["outputs"]:
       
   179                 element_type = TYPECONVERSION[output[1]]
       
   180                 element_c_type = CTYPECONVERSION[output[1]]
   203                 element_c_type = CTYPECONVERSION[output[1]]
   181                     
   204                 variable = "__I%s%s_%d_%d"%(TYPECONVERSION[output[1]], current_location, block_id, i + 1)
   182                 line = "__I"+element_type+self.BusNumber+"_"+element_id+"_"+str(element_num_patte)+";\n"
   205                 text += "%s %s;\n"%(element_c_type, variable)
   183                 text += element_c_type+" "+line
   206                 text += "%s _copy%s;\n"%(element_c_type, variable)
   184                 text += element_c_type+" _copy"+line
       
   185                 element_num_patte +=1
       
   186             text +="\n"
   207             text +="\n"
   187         return text
   208         return text
   188     
   209     
   189     def GenerateGlobalVarsAndFuncs(self):
   210     def GenerateGlobalVarsAndFuncs(self, elements, size):
   190         text = "#include \"iec_types.h\"\n\n"
   211         text = "#include \"iec_std_lib.h\"\n\n"
   191         pri_vars = self.GenerateIECVars()
   212         
   192         if (pri_vars):
   213         text += self.GenerateIECVars(elements)
   193             text += pri_vars
   214         
   194 
   215         text += """IMPLEMENT_APP_NO_MAIN(SVGViewApp);
   195         text += "IMPLEMENT_APP_NO_MAIN(SVGViewApp);\n"
   216 IMPLEMENT_WX_THEME_SUPPORT;
   196         text += "IMPLEMENT_WX_THEME_SUPPORT;\n"
   217 SVGViewApp *myapp = NULL;
   197         text += "SVGViewApp *myapp = NULL;\n"
   218 pthread_t wxMainLoop;
   198         text += "pthread_t wxMainLoop;\n"
   219 """
   199 #        text += "pthread_t wxMainLoop,automate;\n"
   220 #        text += "pthread_t wxMainLoop,automate;\n"
   200         text += "int myargc = 0;\n"
   221         text += """int myargc = 0;
   201         text += "char** myargv = NULL;\n\n"
   222 char** myargv = NULL;
   202         
   223         
   203         text += "#define UNCHANGED 1 \n"
   224 #define UNCHANGED 1
   204         text += "#define PLC_BUSY 2 \n"
   225 #define PLC_BUSY 2
   205         text += "#define CHANGED 3 \n"
   226 #define CHANGED 3
   206         text += "#define GUI_BUSY 4 \n\n"
   227 #define GUI_BUSY 4
   207         
   228         
   208         
   229 void* InitWxEntry(void* args)
   209         text += "void* InitWxEntry(void* args)\n{\n"
   230 {
   210         text += "  wxEntry(myargc,myargv);\n"
   231   wxEntry(myargc,myargv);
   211         text += "  return args;\n"
   232   return args;
   212         text += "}\n\n"
   233 }
   213         
   234 
   214 #        text += "void* SimulAutomate(void* args)\n{\n"
   235 """
   215 #        text += "  while(1){\n"
   236 #        text += """void* SimulAutomate(void* args)
   216 #        text += "    myapp->frame->m_svgCtrl->IN_"+self.BusNumber+"();\n"
   237 #{
   217 #        text += "    //printf(\"AUTOMATE\\n\");\n"
   238 #  while(1){
   218 #        text += "    myapp->frame->m_svgCtrl->OUT_"+self.BusNumber+"();\n"
   239 #    myapp->frame->m_svgCtrl->IN_"+self.BusNumber+"();
   219 #        text += "    sleep(1);\n"
   240 #    //printf(\"AUTOMATE\\n\");
   220 #        text += "  }\n"
   241 #    myapp->frame->m_svgCtrl->OUT_"+self.BusNumber+"();
   221 #        text += "  return args;\n"
   242 #    sleep(1);
   222 #        text += "}\n\n"
   243 #  }
   223         
   244 #  return args;
   224 #        if (self.SVGUIRootElement):
   245 #}
   225 #            width = self.SVGUIRootElement.GetBBox().GetWidth()
   246 #
   226 #            height = self.SVGUIRootElement.GetBBox().GetHeight()
   247 #"""
   227 #        else :
   248       
   228 #            width = 250
   249         text += """bool SVGViewApp::OnInit()
   229 #            height = 350
   250 {
   230         text += "bool SVGViewApp::OnInit()\n{\n"
   251   #ifndef __WXMSW__
   231         text += "  #ifndef __WXMSW__\n"
   252     setlocale(LC_NUMERIC, "C");
   232         text += "    setlocale(LC_NUMERIC, \"C\");\n"
   253   #endif
   233         text += "  #endif\n"
   254 """
   234         #text += "  frame = new MainFrame(NULL, wxT(\"Program\"),wxDefaultPosition, wxSize((int)"+str(width)+", (int)"+str(height)+"));\n"
   255         #text += "  frame = new MainFrame(NULL, wxT(\"Program\"),wxDefaultPosition, wxSize(%d, %d));\n"%size
   235         text += "  frame = new MainFrame(NULL, wxT(\"Program\"),wxDefaultPosition, wxDefaultSize);\n"
   256         text += """  frame = new MainFrame(NULL, wxT("Program"),wxDefaultPosition, wxDefaultSize);
   236         text += "  myapp = this;\n"
   257   myapp = this;
       
   258 """
   237 #        text += "  pthread_create(&automate, NULL, SimulAutomate, NULL);\n"
   259 #        text += "  pthread_create(&automate, NULL, SimulAutomate, NULL);\n"
   238         text += "  return true;\n"
   260         text += """  return true;
   239         text += "}\n\n"
   261 }
   240         
   262 
   241         text += "int __init_"+self.BusNumber+"(int argc, char** argv)\n{\n"
   263 extern "C" {
   242         text += "  myargc = argc;\n"
   264 
   243         text += "  myargv = argv;\n"
   265 int __init_%(location)s(int argc, char** argv)
   244         text += "  pthread_create(&wxMainLoop, NULL, InitWxEntry, NULL);\n"
   266 {
   245         text += "}\n\n"
   267   myargc = argc;
   246 
   268   myargv = argv;
   247         text += "int __cleanup_"+self.BusNumber+"()\n{\n"
   269   pthread_create(&wxMainLoop, NULL, InitWxEntry, NULL);
   248         text += "}\n\n"
   270 }
   249 
   271 
   250         text += "int __retrive_"+self.BusNumber+"()\n{\n"
   272 void __cleanup_%(location)s()
   251         text += "  if(myapp){"
   273 {
   252         text += "    myapp->Retrive()"
   274 }
   253         text += "  }"        
   275 
   254         text += "}\n\n"
   276 void __retrieve_%(location)s()
   255 
   277 {
   256         text += "int __publish_"+self.BusNumber+"()\n{\n"
   278   if(myapp){
   257         text += "  if(myapp){"
   279     myapp->frame->m_svgCtrl->Retrieve();
   258         text += "    myapp->Publish()"
   280   }        
   259         text += "  }"        
   281 }
   260         text += "}\n\n"
   282 
   261 
   283 void __publish_%(location)s()
   262         text += "IEC_STRING wxStringToIEC_STRING(wxString s)\n"
   284 {
   263         text += "{\n"
   285   if(myapp){
   264         text += "  STRING res = {0,""};\n"
   286     myapp->frame->m_svgCtrl->Publish();
   265         text += "  for(int i=0; i<s.Length() && i<STR_MAX_LEN; i++)\n"
   287   }
   266         text += "    res.body[i] = s.GetChar(i);\n"
   288 }
   267         text += "  res.len = i;\n"
   289 
   268         text += "  return res;\n"
   290 }
   269         text += "}\n\n"
   291 
   270         
   292 IEC_STRING wxStringToIEC_STRING(wxString s)
       
   293 {
       
   294   STRING res = {0,""};
       
   295   int i;
       
   296   for(i = 0; i<s.Length() && i<STR_MAX_LEN; i++)
       
   297     res.body[i] = s.GetChar(i);
       
   298   res.len = i;
       
   299   return res;
       
   300 }
       
   301 
       
   302 """%{"location" : "_".join(map(str, self.GetCurrentLocation()))}
   271         
   303         
   272         return text
   304         return text
   273     
   305     
   274     def GenerateProgramEventTable(self):
   306     def GenerateProgramEventTable(self, elements):
   275         evt = ""        
   307         text = ""        
   276         elementsTab = self.GetElementsTab()
   308         #text += "wxEVT_PLCOUT = wxNewEventType();\n\n";
   277         #evt += "wxEVT_PLCOUT = wxNewEventType();\n\n";
   309         
   278         evt += "BEGIN_DECLARE_EVENT_TYPES()\n"
   310         text += """BEGIN_DECLARE_EVENT_TYPES()
   279         evt += "DECLARE_LOCAL_EVENT_TYPE( EVT_PLC, wxNewEventType() )\n"
   311 DECLARE_LOCAL_EVENT_TYPE( EVT_PLC, wxNewEventType() )
   280         evt += "END_DECLARE_EVENT_TYPES()\n\n"
   312 END_DECLARE_EVENT_TYPES()
   281          
   313          
   282         evt += "DEFINE_LOCAL_EVENT_TYPE( EVT_PLC )\n\n"
   314 DEFINE_LOCAL_EVENT_TYPE( EVT_PLC )
       
   315 
       
   316 """     
   283         #Event Table Declaration
   317         #Event Table Declaration
   284         evt += "BEGIN_EVENT_TABLE(Program, SVGUIWindow)\n"
   318         text += "BEGIN_EVENT_TABLE(Program, SVGUIWindow)\n"
   285         for element in elementsTab:
   319         for element in elements:
   286             infos = element.getElementAttributes()
   320             element_type = GetElementType(element)
   287             for info in infos:
   321             element_name = element.getname()
   288                 if info["name"] == "id":
   322             if element_type == ITEM_BUTTON:
   289                     element_id = str(info["value"])
   323                 text += "  EVT_BUTTON (SVGUIID(\"%s\"), Program::On%sClick)\n"%(element_name, element_name)
   290                 if info["name"] == "name":
   324             elif element_type in [ITEM_SCROLLBAR, ITEM_ROTATING]:
   291                     element_name = str(info["value"])
   325                 text += "  EVT_COMMAND_SCROLL_THUMBTRACK (SVGUIID(\"%s\"), Program::On%sChanged)\n"%(element_name, element_name)
   292             type = element.GetElementInfos()["type"]
   326             elif element_type == ITEM_NOTEBOOK:
   293             if type == "Button":
   327                 text += "  EVT_NOTEBOOK_PAGE_CHANGED (SVGUIID(\"%s\"), Program::On%sTabChanged)\n"%(element_name, element_name)
   294                 evt += "  EVT_BUTTON (SVGUIID(\""+element_id+"\"), Program::On"+element_name+"Click)\n"
   328 ##            elif element_type in [ITEM_CONTAINER, ITEM_TRANSFORM]:
   295             elif type == "ScrollBar":
   329 ##                text += "  EVT_PAINT(Program::On%sPaint)\n"%element_name
   296                 pass
   330         text += "  EVT_LEFT_UP (Program::OnClick)\n"
   297                 #evt += "  EVT_LEFT_UP (Program::OnClick)\n"
   331         text += "  EVT_CUSTOM( EVT_PLC, wxID_ANY, Program::OnPlcOutEvent )\n"
   298                 #evt += "  EVT_COMMAND_SCROLL_THUMBTRACK (SVGUIID(\""+element_id+"\"), Program::On"+element_name+"Changed)\n"
   332         text += "END_EVENT_TABLE()\n\n"
   299             elif type == "RotatingCtrl":
       
   300                 evt += "  EVT_COMMAND_SCROLL_THUMBTRACK (SVGUIID(\""+element_id+"\"), Program::On"+element_name+"Changed)\n"
       
   301             elif type == "NoteBook":
       
   302                 evt += "  EVT_NOTEBOOK_PAGE_CHANGED (SVGUIID(\""+element_id+"\"), Program::On"+element_name+"TabChanged)\n"
       
   303             elif type == "Container" or type == "Transform":
       
   304                 evt += "  EVT_PAINT(Program::On"+element_name+"Paint)\n"
       
   305         evt += "  EVT_LEFT_UP (Program::OnClick)\n"
       
   306         evt += "  EVT_CUSTOM( EVT_PLC, wxID_ANY, Program::OnPlcOutEvent )\n"
       
   307         evt += "END_EVENT_TABLE()\n\n"
       
   308         return evt
       
   309     
       
   310     def GenerateProgramInitFrame(self):
       
   311         text = "MainFrame::MainFrame(wxWindow *parent, const wxString& title, const wxPoint& pos,const wxSize& size, long style): wxFrame(parent, wxID_ANY, title, pos, size, style)\n{\n"
       
   312         text += "  m_svgCtrl = new Program(this);\n"
       
   313         text += "  if (m_svgCtrl->LoadFiles(wxT(\""+self.SvgFilepath+"\"), wxT(\""+self.filepath+"\")))\n"
       
   314         text += "  {\n"
       
   315         text += "    Show(true);\n"
       
   316         text += "    m_svgCtrl->SetFocus();\n"
       
   317         text += "    m_svgCtrl->SetFitToFrame(true);\n"
       
   318         text += "    m_svgCtrl->RefreshScale();\n"
       
   319         text += "    m_svgCtrl->InitScrollBars();\n"
       
   320         text += "    m_svgCtrl->Initialize();\n"
       
   321         text += "    m_svgCtrl->Update();\n"
       
   322         text += "    //m_svgCtrl->Print();\n"
       
   323         text += "  }\n"
       
   324         text += "  else\n"
       
   325         text += "  {\n"
       
   326         text += "    printf(\"Error while opening files\\n\");\n"
       
   327         text += "    exit(0);\n"
       
   328         text += "  }\n"
       
   329         text += "}\n\n\n"
       
   330         return text
   333         return text
   331     
   334     
   332     def GenerateProgramInitProgram(self):
   335     def GenerateProgramInitFrame(self, elements):
   333         elementsTab = self.GetElementsTab()
   336         text = """MainFrame::MainFrame(wxWindow *parent, const wxString& title, const wxPoint& pos,const wxSize& size, long style): wxFrame(parent, wxID_ANY, title, pos, size, style)
       
   337 {
       
   338   m_svgCtrl = new Program(this);
       
   339   if (m_svgCtrl->LoadFiles(wxT("%s"), wxT("%s")))
       
   340   {
       
   341     Show(true);
       
   342     m_svgCtrl->SetFocus();
       
   343     m_svgCtrl->SetFitToFrame(true);
       
   344     m_svgCtrl->RefreshScale();
       
   345     m_svgCtrl->InitScrollBars();
       
   346     m_svgCtrl->Initialize();
       
   347     m_svgCtrl->Update();
       
   348     //m_svgCtrl->Print();
       
   349   }
       
   350   else
       
   351   {
       
   352     printf("Error while opening files\\n");
       
   353     exit(0);
       
   354   }
       
   355 }
       
   356 
       
   357 
       
   358 """%(self.GetSVGFilePath(), self.GetFilePath())
       
   359 
       
   360         return text
       
   361     
       
   362     def GenerateProgramInitProgram(self, elements):
   334         text = "Program::Program(wxWindow* parent):SVGUIWindow(parent)\n{\n"
   363         text = "Program::Program(wxWindow* parent):SVGUIWindow(parent)\n{\n"
   335         for element in elementsTab:
   364         for element in elements:
   336             infos = element.getElementAttributes()
   365             text += "    out_state_%d = UNCHANGED;\n"%element.getid()
   337             for info in infos:
   366             text += "    in_state_%d = UNCHANGED;\n"%element.getid()
   338                 if info["name"] == "id":
       
   339                     element_id = str(info["value"])
       
   340             text += "    out_state_"+element_id+" = UNCHANGED;\n"
       
   341             text += "    in_state_"+element_id+" = UNCHANGED;\n"
       
   342         text += "}\n\n"
   367         text += "}\n\n"
   343         return text
   368         return text
   344     
   369     
   345     def GenerateProgramEventFunctions(self):
   370     def GenerateProgramEventFunctions(self, elements):
   346         fct=""
   371         text = ""
   347         elementsTab = self.GetElementsTab()
   372         current_location = "_".join(map(str, self.GetCurrentLocation()))
   348         for element in elementsTab:
   373         for element in elements:
   349             infos = element.getElementAttributes()
   374             element_type = GetElementType(element)
   350             for info in infos:
   375             element_state = "  in_state_%d = %s;\n"%(element.getid(), "%s")
   351                 if info["name"] == "id":
   376             element_name = element.getname()
   352                     element_id = str(info["value"])
   377                 
   353                     _lock   = "  in_state_"+element_id+" = GUI_BUSY;\n"
   378             block_infos = GetBlockType(SVGUIFB_Types[element_type])
   354                     _unlock = "  in_state_"+element_id+" = CHANGED;\n"
   379             if element_type == ITEM_BUTTON:
   355                 if info["name"] == "name":
   380                 text += """void Program::On%sClick(wxCommandEvent& event)
   356                     element_name = str(info["value"])
   381 {
   357             type = element.GetElementInfos()["type"]
   382   SVGUIButton* button = (SVGUIButton*)GetElementByName(wxT("%s"));\n"""%(element_name, element_name)
   358             FbdBlock = self.GetBlockType(type)
   383                 text += element_state%"GUI_BUSY"
   359             if type == "Button":
   384                 for i, output in enumerate(block_infos["outputs"]):
   360                 fct += "void Program::On"+element_name+"Click(wxCommandEvent& event)\n{\n"
       
   361                 fct += _lock
       
   362                 element_num_patte = 1
       
   363                 for output in FbdBlock["outputs"]:
       
   364                     element_type = TYPECONVERSION[output[1]]
   385                     element_type = TYPECONVERSION[output[1]]
   365                     fct += "  _copy__I"+element_type+self.BusNumber+"_"+element_id+"_"+str(element_num_patte)+" = true;\n"
   386                     if i == 0:
   366                     element_num_patte +=1
   387                         value = "button->IsVisible()"
   367                 fct += _unlock
   388                     elif i == 1:
   368                 fct += "  event.Skip();\n"
   389                         value = "button->GetToggle()"
   369                 fct += "}\n\n"               
   390                     else:
       
   391                         value = "0"
       
   392                     text += "  _copy__I%s%s_%d_%d = %s;\n"%(TYPECONVERSION[output[1]], current_location, element.getid(), i + 1, value)
       
   393                 text += element_state%"CHANGED"
       
   394                 text += "  event.Skip();\n}\n\n"
       
   395             elif element_type == ITEM_ROTATING:
       
   396                 text += """void Program::On%sChanged(wxScrollEvent& event)
       
   397 {
       
   398   SVGUIRotatingCtrl* rotating = (SVGUIRotatingCtrl*)GetElementByName(wxT("%s"));
       
   399   rotating->SendScrollEvent(event);
       
   400   double angle = rotating->GetAngle();
       
   401 """%(element_name, element_name)
       
   402                 text += element_state%"GUI_BUSY"
       
   403                 for i, output in enumerate(block_infos["outputs"]):
       
   404                     text += "  _copy__I%s%s_%d_%d = %s;\n"%(TYPECONVERSION[output[1]], current_location, element.getid(), i + 1, ["angle", "true"][value])
       
   405                 text += element_state%"CHANGED"
       
   406                 text += "  event.Skip();\n}\n\n"
       
   407             elif element_type == ITEM_NOTEBOOK:
       
   408                 text += """void Program::On%sTabChanged(wxNotebookEvent& event)
       
   409 {
       
   410   SVGUINoteBook* notebook = (SVGUINoteBook*)GetElementByName(wxT("%s"));
       
   411   notebook->SendNotebookEvent(event);
       
   412   unsigned int selected = notebook->GetCurrentPage();
       
   413 """%(element_name, element_name)
       
   414                 text += element_state%"GUI_BUSY"
       
   415                 for i, output in enumerate(block_infos["outputs"]):
       
   416                     text += "  _copy__I%s%s_%d_%d = %s;\n"%(TYPECONVERSION[output[1]], current_location, element.getid(), i + 1, ["selected", "true"][value])
       
   417                 text += element_state%"CHANGED"
       
   418                 text += "  event.Skip();\n}\n\n"
       
   419             elif element_type == ITEM_TRANSFORM:
       
   420                 text += """void Program::On%sPaint(wxPaintEvent& event)
       
   421 {
       
   422   SVGUITransform* transform = (SVGUITransform*)GetElementByName(wxT("%s"));
       
   423 """%(element_name, element_name)
       
   424                 text += element_state%"GUI_BUSY"
       
   425                 for i, output in enumerate(block_infos["outputs"]):
       
   426                     if i < 5:
       
   427                         texts = {"location" : current_location, "id" : element.getid(), 
       
   428                                  "pin" : i + 1, "param" : ["X", "Y", "XScale", "YScale", "Angle"][i]}
       
   429                     
       
   430                         text += """  if (transform->Get%(param)s() != _copy__ID%(location)s_%(id)d_%(pin)d)
       
   431   {
       
   432     _copy__ID%(location)s_%(id)d_%(pin)d = transform->Get%(param)s();
       
   433     _copy__IX%(location)s_%(id)d_6 = true;
       
   434   }
       
   435 """%texts
       
   436                 text += element_state%"CHANGED"
       
   437                 text += "  event.Skip();\n}\n\n"
       
   438             elif element_type == ITEM_CONTAINER:
       
   439                 text += """void Program::On%sPaint(wxPaintEvent& event)
       
   440 {
       
   441   SVGUIContainer* container = (SVGUIContainer*)GetElementByName(wxT("%s"));
       
   442   bool isvisible = container->IsVisible();
       
   443 """%(element_name, element_name)
       
   444                 text += element_state%"GUI_BUSY"
       
   445                 texts = {"location" : current_location, "id" : element.getid()}
   370                 
   446                 
   371             elif type == "RotatingCtrl":
   447                 text += """  if (isvisible != _copy__IX%(location)s_%(id)d_1)
   372                 fct += "void Program::On"+element_name+"Changed(wxScrollEvent& event)\n{\n"
   448   {    
   373                 fct += "  SVGUIRotatingCtrl* rotating = (SVGUIRotatingCtrl*)GetElementById(wxT(\""+element_id+"\"));\n"
   449     _copy__IX%(location)s_%(id)d_1 = container->IsVisible();
   374                 fct += "  rotating->SendScrollEvent(event);\n"
   450     _copy__IX%(location)s_%(id)d_2 = true;
   375                 fct += "  double angle = rotating->GetAngle();\n"
   451 """%texts
   376                 fct += _lock
   452                 text += "  %s  }\n  else {\n  %s  }\n"%(element_state%"CHANGED", element_state%"UNCHANGED")
   377                 element_num_patte = 1
   453                 text += "  event.Skip();\n}\n\n"
   378                 for output in FbdBlock["outputs"]:
   454 
   379                     element_type = TYPECONVERSION[output[1]]
   455 
   380                     
   456         text += """void Program::OnChar(wxKeyEvent& event)
   381                     if element_num_patte == 1:
   457 {
   382                         value = "angle"
   458   SVGUIContainer* container = GetSVGUIRootElement();
   383                     elif element_num_patte == 2:
   459   if (container->GetFocusedElementName() == wxT("TextCtrl"))
   384                         value = "true"
   460   {
   385                     fct += "  _copy__I"+element_type+self.BusNumber+"_"+element_id+"_"+str(element_num_patte)+" = "+value+";\n"
   461     wxString focusedId = container->GetFocusedElement();
   386                     element_num_patte +=1
   462     SVGUITextCtrl* text = (SVGUITextCtrl*)GetElementById(focusedId);
   387                 fct += _unlock
   463     text->SendKeyEvent(event);
   388                 fct += "}\n\n"
   464 """
   389             elif type == "NoteBook":
   465         for element in elements:
   390                 fct += "void Program::On"+element_name+"TabChanged(wxNotebookEvent& event)\n{\n"
   466             element_type = GetElementType(element)
   391                 fct += "  SVGUINoteBook* notebook = (SVGUINoteBook*)GetElementById(wxT(\""+element_id+"\"));\n"
   467             if element_type == ITEM_TEXT:
   392                 fct += "  notebook->SendNotebookEvent(event);\n"
   468                 texts = {"location" : current_location, "id" : element.getid()}
   393                 fct += "  unsigned int selected = notebook->GetCurrentPage();\n"
   469                 
   394                 fct += _lock
   470                 text += """    if (focusedId == wxT("%(id)d"))
   395                 element_num_patte = 1
   471     {
   396                 for output in FbdBlock["outputs"]:
   472       in_state_%(id)d = GUI_BUSY;
   397                     element_type = TYPECONVERSION[output[1]]
   473       _copy__IB%(location)s_%(id)d_1 = wxStringToIEC_STRING(text->GetValue());
   398                     
   474       _copy__IX%(location)s_%(id)d_2 = true;
   399                     if element_num_patte == 1:
   475       in_state_%(id)d = CHANGED;
   400                         value = "selected"
   476     }
   401                     elif element_num_patte == 2:
   477 """%texts
   402                         value = "true"
   478 
   403                     fct += "  _copy__I"+element_type+self.BusNumber+"_"+element_id+"_"+str(element_num_patte)+" = "+value+";\n"
   479         text += "  }\n  event.Skip();\n}\n\n"
   404                     element_num_patte +=1
   480 
   405                 fct += _unlock
   481 
   406                 fct += "}\n\n"
   482         text += """void Program::OnClick(wxMouseEvent& event)
   407             elif type == "Transform":
   483 {
   408                 fct += "void Program::On"+element_name+"Paint(wxPaintEvent& event)\n{\n"
   484   SVGUIContainer* container = GetSVGUIRootElement();
   409                 fct += "  SVGUITransform* transform = (SVGUITransform*)GetElementById(wxT(\""+element_id+"\"));\n"
   485   if (container->GetFocusedElementName() == wxT("ScrollBar"))
   410                 fct += _lock
   486   {
   411                 element_num_patte = 1
   487     wxString focusedId = container->GetFocusedElement();
   412                 for output in FbdBlock["outputs"]:                    
   488     SVGUIScrollBar* scrollbar = (SVGUIScrollBar*)GetElementById(focusedId);
   413                     if element_num_patte == 1:
   489     scrollbar->SendMouseEvent(event);
   414                         fct += "  if (transform->GetX() != _copy__ID"+self.BusNumber+"_"+element_id+"_1)\n"
   490 """
   415                         fct += "  {\n"
   491         for element in elements:
   416                         fct += "    _copy__ID"+self.BusNumber+"_"+element_id+"_1 = transform->GetX();\n"
   492             element_type = GetElementType(element)
   417                         fct += "    _copy__IX"+self.BusNumber+"_"+element_id+"_6 = true;\n"
   493             if element_type == ITEM_SCROLLBAR:
   418                         fct += "  }\n"
   494                 texts = {"location" : current_location, "id" : element.getid()}
   419                     elif element_num_patte == 2:
   495                 
   420                         fct += "  if (transform->GetY() != _copy__ID"+self.BusNumber+"_"+element_id+"_2)\n"
   496                 text += """    if (focusedId == wxT("%(id)d"))
   421                         fct += "  {\n"
   497     {
   422                         fct += "    _copy__ID"+self.BusNumber+"_"+element_id+"_2 = transform->GetY();\n"
   498       unsigned int scrollPos = scrollbar->GetThumbPosition();
   423                         fct += "    _copy__IX"+self.BusNumber+"_"+element_id+"_6 = true;\n"
   499       _copy__IW%(location)s_%(id)d_1 = scrollPos;
   424                         fct += "  }\n"
   500       _copy__IX%(location)s_%(id)d_2 = true;\n"
   425                     elif element_num_patte == 3:
   501     }
   426                         fct += "  if (transform->GetXScale() != _copy__ID"+self.BusNumber+"_"+element_id+"_3)\n"
   502 """%texts
   427                         fct += "  {\n"
   503 
   428                         fct += "    _copy__ID"+self.BusNumber+"_"+element_id+"_3 = transform->GetXScale();\n"
   504         text += "  }\n  event.Skip();\n}\n\n"
   429                         fct += "    _copy__IX"+self.BusNumber+"_"+element_id+"_6 = true;\n"
   505 
   430                         fct += "  }\n"
   506         
   431                     elif element_num_patte == 4:
   507         text += "/* OnPlcOutEvent update GUI with provided IEC __Q* PLC output variables */\n"
   432                         fct += "  if (transform->GetYScale() != _copy__ID"+self.BusNumber+"_"+element_id+"_4)\n"
   508         text += "void Program::OnPlcOutEvent(wxEvent& event)\n{\n  wxMutexGuiEnter();"
   433                         fct += "  {\n"
   509         for element in elements:
   434                         fct += "    _copy__ID"+self.BusNumber+"_"+element_id+"_4 = transform->GetYScale();\n"
   510             element_type = GetElementType(element)
   435                         fct += "    _copy__IX"+self.BusNumber+"_"+element_id+"_6 = true;\n"
   511             texts = {"location" : current_location, "id" : element.getid()}
   436                         fct += "  }\n"
   512             
   437                     elif element_num_patte == 5:
   513             element_lock = "  if (__sync_val_compare_and_swap (&out_state_%(id)d, CHANGED, GUI_BUSY) == CHANGED)\n  {\n"%texts
   438                         fct += "  if (transform->GetAngle() != _copy__ID"+self.BusNumber+"_"+element_id+"_5)\n"
   514             element_unlock = "    __sync_val_compare_and_swap (&out_state_%(id)d, GUI_BUSY, UNCHANGED);\n  }\n"%texts
   439                         fct += "  {\n"
   515             if element_type == ITEM_BUTTON:
   440                         fct += "    _copy__ID"+self.BusNumber+"_"+element_id+"_5 = transform->GetAngle();\n"
   516                 text += element_lock
   441                         fct += "    _copy__IX"+self.BusNumber+"_"+element_id+"_6 = true;\n"
   517                 text += """    SVGUIButton* button = (SVGUIButton*)GetElementById(wxT("%(id)d"));
   442                         fct += "  }\n"
   518     //if (_copy__QX%(location)s_%(id)d_1)
   443                     element_num_patte +=1
   519     //  button->Show();
   444                 fct += _unlock
   520     //else
   445                 fct += "  event.Skip();\n"
   521     //  button->Hide();
   446                 fct += "}\n\n"
   522     if (_copy__QX%(location)s_%(id)d_2 != button->GetToggle()) {
   447             elif type == "Container":
   523       button->SetToggle(_copy__QX%(location)s_%(id)d_2);
   448                 fct += "void Program::On"+element_name+"Paint(wxPaintEvent& event)\n{\n"
   524     }
   449                 fct += "  SVGUIContainer* container = (SVGUIContainer*)GetElementById(wxT(\""+element_id+"\"));\n"
   525 """%texts
   450                 fct += "  bool isvisible = container->IsVisible();\n"
   526                 text += element_unlock
   451                 fct += _lock
   527             elif element_type == ITEM_CONTAINER:
   452                 fct += "  if (isvisible != _copy__IX"+self.BusNumber+"_"+element_id+"_1)\n"
   528                 text += element_lock
   453                 fct += "  {\n"
   529                 text += """  if (_copy__QX%(location)s_%(id)d_2)
   454                 fct += "    _copy__IX"+self.BusNumber+"_"+element_id+"_1 = container->IsVisible();\n"
   530   {
   455                 fct += "    _copy__IX"+self.BusNumber+"_"+element_id+"_2 = true;\n"
   531     SVGUIContainer* container = (SVGUIContainer*)GetElementById(wxT("%(id)d"));
   456                 fct += "  }\n"
   532     //if (_copy__QX%(location)s_%(id)d_1)
   457                 fct += _unlock
   533     //  container->Show();
   458                 fct += "  event.Skip();\n"
   534     //else
   459                 fct += "}\n\n"
   535     //  container->Hide();
   460         
   536   }
   461         fct += "void Program::OnChar(wxKeyEvent& event)\n{\n"
   537 """%texts
   462         fct += "  SVGUIContainer* container = GetSVGUIRootElement();\n"
   538                 text += element_unlock
   463         fct += "  if (container->GetFocusedElementName() == wxT(\"TextCtrl\"))\n"
   539             elif element_type == ITEM_TEXT:
   464         fct += "  {\n"
   540                 text += element_lock
   465         fct += "    wxString focusedId = container->GetFocusedElement();\n"
   541                 text += """  if (_copy__QX%(location)s_%(id)d_2)
   466         fct += "    SVGUITextCtrl* text = (SVGUITextCtrl*)GetElementById(container->GetFocusedElement());\n"
   542   {
   467         fct += "    text->SendKeyEvent(event);\n"
   543     SVGUITextCtrl* text = (SVGUITextCtrl*)GetElementById(wxT("%(id)d"));
   468         for element in elementsTab:
   544     wxString str = wxString::FromAscii(_copy__QB%(location)s_%(id)d_1);
   469             infos = element.getElementAttributes()
   545     text->SetText(str);
   470             for info in infos:
   546   }
   471                 if info["name"] == "id":
   547 """%texts
   472                     element_id = str(info["value"])
   548                 text += element_unlock
   473                     _lock   = "      in_state_"+element_id+" = GUI_BUSY;\n"
   549             elif  element_type == ITEM_SCROLLBAR:
   474                     _unlock = "      in_state_"+element_id+" = CHANGED;\n"
   550                 text += element_lock
   475             type = element.GetElementInfos()["type"]
   551                 text += """  if (_copy__QX%(location)s_%(id)d_2)
   476             FbdBlock = self.GetBlockType(type)
   552   {
   477             if type == "TextCtrl":
   553     SVGUIScrollBar* scrollbar = (SVGUIScrollBar*)GetElementById(wxT("%(id)d"));
   478                 fct += "    if (focusedId == wxT(\""+element_id+"\"))\n"
   554     scrollbar->SetThumbPosition(_copy__QW%(location)s_%(id)d_1);\n"
   479                 fct += "    {\n"
   555   }
   480                 fct += _lock
   556 """%texts
   481                 fct += "      _copy__IB"+self.BusNumber+"_"+element_id+"_1 = wxStringToIEC_STRING(text->GetValue());\n"
   557                 text += element_unlock
   482                 fct += "      _copy__IX"+self.BusNumber+"_"+element_id+"_2 = true;\n"
   558             elif element_type == ITEM_ROTATING:
   483                 fct += _unlock
   559                 text += element_lock
   484                 fct += "    }\n"
   560                 text += """  if (_copy__QX%(location)s_%(id)d_2)
   485         fct += "  }\n"
   561   {
   486         fct += "}\n"
   562     SVGUIRotatingCtrl* rotating = (SVGUIRotatingCtrl*)GetElementById(wxT("%(id)d"));
   487 
   563     rotating->SetAngle(_copy__QD%(location)s_%(id)d_1);\n"
   488         
   564   }
   489         
   565 """%texts
   490         fct += "void Program::OnClick(wxMouseEvent& event)\n{\n"
   566                 text += element_unlock
   491         fct += "  SVGUIContainer* container = GetSVGUIRootElement();\n"
   567             elif elment_type == ITEM_NOTEBOOK:
   492         fct += "  if (container->GetFocusedElementName() == wxT(\"ScrollBar\"))\n"
   568                 text += element_lock
   493         fct += "  {\n"
   569                 text += """  if (copy__QX%(location)s_%(id)d_2)
   494         fct += "    wxString focusedId = container->GetFocusedElement();\n"
   570   {
   495         fct += "    SVGUIScrollBar* scrollbar = (SVGUIScrollBar*)GetElementById(focusedId);\n"
   571     SVGUINoteBook* notebook = (SVGUINoteBook*)GetElementById(wxT("%(id)d"));
   496         fct += "    scrollbar->SendMouseEvent(event);\n"
   572     notebook->SetCurrentPage(_copy__QB%(location)s_%(id)d_1);
   497         for element in elementsTab:
   573   }
   498             infos = element.getElementAttributes()
   574 """%texts
   499             for info in infos:
   575                 text += element_unlock
   500                 if info["name"] == "id":
   576             elif elment_type == ITEM_TRANSFORM:
   501                     element_id = str(info["value"])
   577                 text += element_lock
   502             type = element.GetElementInfos()["type"]
   578                 text += """  if (copy__QX%(location)s_%(id)d_6)
   503             FbdBlock = self.GetBlockType(type)
   579   {
   504             if type == "ScrollBar":
   580     SVGUITransform* transform = (SVGUITransform*)GetElementById(wxT("%(id)d"));
   505                 fct += "    if (focusedId == wxT(\""+element_id+"\"))\n"
   581     transform->Move(_copy__QD%(location)s_%(id)d_1, _copy__QD%(location)s_%(id)d_2);
   506                 fct += "    {\n"
   582     transform->Scale(_copy__QD%(location)s_%(id)d_3, _copy__QD%(location)s_%(id)d_4);
   507                 fct += "      unsigned int scrollPos = scrollbar->GetThumbPosition();\n"
   583     transform->Rotate(_copy__QD%(location)s_%(id)d_5);
   508                 fct += "      _copy__IW"+self.BusNumber+"_"+element_id+"_1 = scrollPos;\n"
   584   }
   509                 fct += "      _copy__IX"+self.BusNumber+"_"+element_id+"_2 = true;\n"
   585 """%texts
   510                 fct += "    }\n"
   586                 text += element_unlock
   511         fct += "  }\n"
   587         text += """  wxMutexGuiLeave();
   512         fct += "  event.Skip();\n"
   588   event.Skip();
   513         fct += "}\n"
   589 }
   514 
   590 
   515         
   591 """
   516         
   592         return text
   517         
   593     
   518         fct += "/* OnPlcOutEvent updatde GUI with provided IEC __Q* PLC output variables */\n"
   594     def GenerateProgramPrivateFunctions(self, elements):
   519         fct += "void Program::OnPlcOutEvent(wxEvent& event)\n{\n"
   595         current_location = "_".join(map(str, self.GetCurrentLocation()))
   520         for element in elementsTab:
   596         
   521             infos = element.getElementAttributes()
   597         text = "void Program::Retrieve()\n{\n"
   522             for info in infos:
   598         for element in elements:
   523                 if info["name"] == "id":
   599             element_type = GetElementType(element)
   524                     element_id = str(info["value"])
   600             texts = {"location" : current_location, "id" : element.getid()}
   525             _lock =   " if (__sync_val_compare_and_swap (&out_state_"+element_id+", CHANGED, GUI_BUSY) == CHANGED)"
   601             block_infos = GetBlockType(SVGUIFB_Types[GetElementType(element)])
   526             _lock +=  " {\n"
   602             
   527             _unlock = "  __sync_val_compare_and_swap (&out_state_"+element_id+", GUI_BUSY, UNCHANGED);\n"
   603             text += """  do{
   528             _unlock +=" }\n"
   604     if ( __sync_val_compare_and_swap (&in_state_%(id)d, CHANGED, PLC_BUSY) == CHANGED){
   529             type = element.GetElementInfos()["type"]
   605 """%texts
   530             FbdBlock = self.GetBlockType(type)
   606             for i, output in enumerate(block_infos["outputs"]):
   531             if type == "Button":
   607                 texts["type"] = TYPECONVERSION[output[1]]
   532                 fct += _lock
   608                 texts["pin"] = i + 1
   533                 fct += "  if (_copy__QX"+self.BusNumber+"_"+element_id+"_2)\n"
   609                 
   534                 fct += "  {\n"
   610                 variable = "__I%(type)s%(location)s_%(id)d_%(pin)d"%texts
   535                 fct += "    SVGUIButton* button = (SVGUIButton*)GetElementById(wxT(\""+element_id+"\"));\n"
   611                 text +="      %s = _copy%s;\n"%(variable, variable)
   536                 fct += "    if (_copy__QX"+self.BusNumber+"_"+element_id+"_1)\n"
   612             
   537                 fct += "      button->Show();\n"
   613             text += "      /* reset change status pin */\n"
   538                 fct += "    else\n"
   614             if element_type in [ITEM_BUTTON, ITEM_CONTAINER, ITEM_TEXT, ITEM_SCROLLBAR, ITEM_ROTATING, ITEM_NOTEBOOK]:
   539                 fct += "      button->Hide();\n"
   615                 text += "      _copy__IX%(location)s_%(id)d_2 = false;\n"%texts
   540                 fct += "  }\n"
   616             elif element_type == ITEM_TRANSFORM:
   541                 fct += _unlock
   617                 text += "      _copy__IX%(location)s_%(id)d_6 = false;\n"%texts
   542             elif type == "Container":
   618             text += """    }
   543                 fct += _lock
   619     else {
   544                 fct += "  if (_copy__QX"+self.BusNumber+"_"+element_id+"_2)\n"
   620       break;
   545                 fct += "  {\n"
   621     }
   546                 fct += "    SVGUIContainer* container = (SVGUIContainer*)GetElementById(wxT(\""+element_id+"\"));\n"
   622 """
   547                 fct += "    if (_copy__QX"+self.BusNumber+"_"+element_id+"_1)\n"
       
   548                 fct += "      container->Show();\n"
       
   549                 fct += "    else\n"
       
   550                 fct += "      container->Hide();\n"
       
   551                 fct += "  }\n"
       
   552                 fct += _unlock
       
   553             elif type == "TextCtrl":
       
   554                 fct += _lock
       
   555                 fct += "  if (_copy__QX"+self.BusNumber+"_"+element_id+"_2)\n"
       
   556                 fct += "  {\n"
       
   557                 fct += "    SVGUITextCtrl* text = (SVGUITextCtrl*)GetElementById(wxT(\""+element_id+"\"));\n"
       
   558                 fct += "    wxString str = wxString::FromAscii(_copy__QB"+self.BusNumber+"_"+element_id+"_1);\n"
       
   559                 fct += "    text->SetText(str);\n"
       
   560                 fct += "  }\n"
       
   561                 fct += _unlock
       
   562             elif type == "ScrollBar":
       
   563                 fct += _lock
       
   564                 fct += "  if (_copy__QX"+self.BusNumber+"_"+element_id+"_2)\n"
       
   565                 fct += "  {\n"
       
   566                 fct += "    SVGUIScrollBar* scrollbar = (SVGUIScrollBar*)GetElementById(wxT(\""+element_id+"\"));\n"
       
   567                 fct += "    scrollbar->SetThumbPosition(_copy__QW"+self.BusNumber+"_"+element_id+"_1);\n"
       
   568                 fct += "  }\n"
       
   569                 fct += _unlock
       
   570             elif type == "RotatingCtrl":
       
   571                 fct += _lock
       
   572                 fct += "  if (_copy__QX"+self.BusNumber+"_"+element_id+"_2)\n"
       
   573                 fct += "  {\n"
       
   574                 fct += "    SVGUIRotatingCtrl* rotating = (SVGUIRotatingCtrl*)GetElementById(wxT(\""+element_id+"\"));\n"
       
   575                 fct += "    rotating->SetAngle(_copy__QD"+self.BusNumber+"_"+element_id+"_1);\n"
       
   576                 fct += "  }\n"
       
   577                 fct += _unlock
       
   578             elif type == "NoteBook":
       
   579                 fct += _lock
       
   580                 fct += "  if (copy__QX"+self.BusNumber+"_"+element_id+"_2)\n"
       
   581                 fct += "  {\n"
       
   582                 fct += "    SVGUINoteBook* notebook = (SVGUINoteBook*)GetElementById(wxT(\""+element_id+"\"));\n"
       
   583                 fct += "    notebook->SetCurrentPage(_copy__QB"+self.BusNumber+"_"+element_id+"_1);\n"
       
   584                 fct += "  }\n"
       
   585                 fct += _unlock
       
   586             elif type == "Transform":
       
   587                 fct += _lock
       
   588                 fct += "  if (copy__QX"+self.BusNumber+"_"+element_id+"_6)\n"
       
   589                 fct += "  {\n"
       
   590                 fct += "    SVGUITransform* transform = (SVGUITransform*)GetElementById(wxT(\""+element_id+"\"));\n"
       
   591                 fct += "    transform->Move(_copy__QD"+self.BusNumber+"_"+element_id+"_1,_copy__QD"+self.BusNumber+"_"+element_id+"_2);\n"
       
   592                 fct += "    transform->Scale(_copy__QD"+self.BusNumber+"_"+element_id+"_3,_copy__QD"+self.BusNumber+"_"+element_id+"_4);\n"
       
   593                 fct += "    transform->Rotate(_copy__QD"+self.BusNumber+"_"+element_id+"_5);\n"
       
   594                 fct += "  }\n"
       
   595                 fct += _unlock
       
   596         fct += "  Update_Elements();\n"
       
   597         fct += "  Refresh();\n"
       
   598         fct += "  event.Skip();\n"
       
   599         fct += "}\n\n"
       
   600         return fct
       
   601     
       
   602     def GenerateProgramPrivateFunctions(self):
       
   603         elementsTab = self.GetElementsTab()
       
   604         fct = "void Program::Retrive()\n{\n"
       
   605         for element in elementsTab:
       
   606             infos = element.getElementAttributes()
       
   607             for info in infos:
       
   608                 if info["name"] == "id":
       
   609                     element_id = str(info["value"])
       
   610             type = element.GetElementInfos()["type"]
       
   611             FbdBlock = self.GetBlockType(type)
       
   612             fct += "  if ( __sync_val_compare_and_swap (&out_state_"+element_id+", UNCHANGED, PLC_BUSY) == UNCHANGED ||\n"
       
   613             fct += "       __sync_val_compare_and_swap (&out_state_"+element_id+", CHANGED, PLC_BUSY) == CHANGED){\n"
       
   614             fct += "    bool diff = False;\n"
       
   615             element_num_patte = 1
       
   616             for input in FbdBlock["inputs"]:
       
   617                 element_type = TYPECONVERSION[input[1]]
       
   618                 var = "__Q"+element_type+self.BusNumber+"_"+element_id+"_"+str(element_num_patte)
       
   619                 fct +="    diff |= _copy"+var+ " != "+var+";\n"
       
   620                 fct +="    _copy"+var+ " = "+var+";\n"
       
   621                 element_num_patte +=1
       
   622             fct += "    if(diff) out_state_"+element_id+" = CHANGED;\n"
       
   623             fct += "  }\n"
       
   624         fct +="  /*Replace this with determinist signal if called from RT*/;\n"
       
   625         fct +="  wxCommandEvent event( EVT_PLC );\n"
       
   626         fct +="  ProcessEvent(event);\n"
       
   627         fct +="};\n\n" 
       
   628         
       
   629         fct += "void Program::Publish()\n{\n"
       
   630 
       
   631         for element in elementsTab:
       
   632             infos = element.getElementAttributes()
       
   633             for info in infos:
       
   634                 if info["name"] == "id":
       
   635                     element_id = str(info["value"])
       
   636             type = element.GetElementInfos()["type"]
       
   637             FbdBlock = self.GetBlockType(type)
       
   638             fct += "  do{\n"
       
   639             fct += "    if ( __sync_val_compare_and_swap (&in_state_"+element_id+", CHANGED, PLC_BUSY) == CHANGED){\n"
       
   640             element_num_patte = 1
       
   641             for output in FbdBlock["outputs"]:
       
   642                 element_type = TYPECONVERSION[output[1]]
       
   643                 var = "__I"+element_type+self.BusNumber+"_"+element_id+"_"+str(element_num_patte)
       
   644                 fct +="      "+var+ " = _copy"+var+";\n"
       
   645                 element_num_patte +=1
       
   646             fct += "      /* reset change status pin */\n"
       
   647             if type == "Button":
       
   648                 fct += "      _copy__IX"+self.BusNumber+"_"+element_id+"_2 = false;\n"
       
   649             elif type == "Container":
       
   650                 fct += "      _copy__IX"+self.BusNumber+"_"+element_id+"_2 = false;\n"
       
   651             elif type == "TextCtrl":
       
   652                 fct += "      _copy__IX"+self.BusNumber+"_"+element_id+"_2 = false;\n"
       
   653             elif type == "ScrollBar":
       
   654                 fct += "      _copy__IX"+self.BusNumber+"_"+element_id+"_2 = false;\n"
       
   655             elif type == "RotatingCtrl":
       
   656                 fct += "      _copy__IX"+self.BusNumber+"_"+element_id+"_2 = false;\n"
       
   657             elif type == "NoteBook":
       
   658                 fct += "      _copy__IX"+self.BusNumber+"_"+element_id+"_2 = false;\n"
       
   659             elif type == "Transform":
       
   660                 fct += "      _copy__IX"+self.BusNumber+"_"+element_id+"_6 = false;\n"
       
   661             fct += "    }else{\n"
       
   662             fct += "      break;\n"
       
   663             fct += "    }\n"
       
   664             #If GUI did change data while publishing, do it again (in real-time this should be avoided with priority stuff)
   623             #If GUI did change data while publishing, do it again (in real-time this should be avoided with priority stuff)
   665             fct += "  }while(__sync_val_compare_and_swap (&in_state_"+element_id+", PLC_BUSY, UNCHANGED) != PLC_BUSY)\n"
   624             text += "  }while(__sync_val_compare_and_swap (&in_state_%(id)s, PLC_BUSY, UNCHANGED) != PLC_BUSY);\n"%texts
   666         fct +="};\n\n" 
   625         text += "}\n\n" 
   667         
   626 
   668         fct += "void Program::Initialize()\n{\n"
   627         text += """void Program::Publish()
       
   628 {
       
   629   bool refresh = false;
       
   630 """
       
   631         for element in elements:
       
   632             element_type = GetElementType(element)
       
   633             texts = {"location" : current_location, "id" : element.getid()}
       
   634             block_infos = GetBlockType(SVGUIFB_Types[GetElementType(element)])
       
   635             
       
   636             text += """  if ( __sync_bool_compare_and_swap (&out_state_%(id)d, UNCHANGED, PLC_BUSY) ||
       
   637        __sync_bool_compare_and_swap (&out_state_%(id)d, CHANGED, PLC_BUSY)) {
       
   638 """%texts
       
   639             for i, input in enumerate(block_infos["inputs"]):
       
   640                 texts["type"] = TYPECONVERSION[input[1]]
       
   641                 texts["pin"] = i + 1
       
   642                 variable = "__Q%(type)s%(location)s_%(id)d_%(pin)d"%texts
       
   643                 text += "    if (_copy%s != %s) {\n"%(variable, variable)
       
   644                 text += "      _copy%s = %s;\n"%(variable, variable)
       
   645                 text += "      out_state_%(id)d = CHANGED;\n    }\n"%texts
       
   646             text += """    if (out_state_%(id)d == CHANGED) {
       
   647       refresh = true;
       
   648     }
       
   649     else {
       
   650       out_state_%(id)d = UNCHANGED;
       
   651     }
       
   652   }
       
   653 """%texts
       
   654         
       
   655         text += """  /*Replace this with determinist signal if called from RT*/;
       
   656   if (refresh) {
       
   657     wxCommandEvent event( EVT_PLC );
       
   658     ProcessEvent(event);
       
   659   }
       
   660 };
       
   661 
       
   662 """
       
   663 
       
   664         text += "void Program::Initialize()\n{\n"
   669         button = False
   665         button = False
   670         container = False
   666         container = False
   671         textctrl = False
   667         textctrl = False
   672         scrollbar = False
   668         scrollbar = False
   673         rotatingctrl = False
   669         rotatingctrl = False
   674         notebook = False
   670         notebook = False
   675         transform = False
   671         transform = False
   676         for element in elementsTab:
   672         for element in elements:
   677             infos = element.getElementAttributes()
   673             element_type = GetElementType(element)
   678             for info in infos:
   674             texts = {"location" : current_location, "id" : element.getid()}
   679                 if info["name"] == "id":
   675             
   680                     element_id = str(info["value"])
   676             if element_type == ITEM_BUTTON:
   681             type = element.GetElementInfos()["type"]
       
   682             FbdBlock = self.GetBlockType(type)
       
   683             if type == "Button":
       
   684                 if (not button):
   677                 if (not button):
   685                     fct += "  SVGUIButton* button;\n"
   678                     text += "  SVGUIButton* button;\n"
   686                 fct += "  button = (SVGUIButton*)GetElementById(wxT(\""+element_id+"\"));\n"
   679                 text += """  button = (SVGUIButton*)GetElementById(wxT("%(id)d"));
   687                 fct += "  if (button->IsVisible())\n"
   680   if (button->IsVisible())
   688                 fct += "    _copy__IX"+self.BusNumber+"_"+element_id+"_1 = true;\n"
   681     _copy__IX%(location)s_%(id)d_1 = true;
   689                 fct += "  else\n"
   682   else
   690                 fct += "    _copy__IX"+self.BusNumber+"_"+element_id+"_1 = false;\n"
   683     _copy__IX%(location)s_%(id)d_1 = false;
   691                 fct += "  _copy__IX"+self.BusNumber+"_"+element_id+"_2 = true;\n\n"
   684   _copy__IX%(location)s_%(id)d_2 = false;
       
   685 
       
   686 """%texts
   692                 button = True
   687                 button = True
   693             elif type == "Container":
   688             elif element_type == ITEM_CONTAINER:
   694                 if (not container):
   689                 if (not container):
   695                     fct += "  SVGUIContainer* container;\n"
   690                     text += "  SVGUIContainer* container;\n"
   696                 fct += "  container = (SVGUIContainer*)GetElementById(wxT(\""+element_id+"\"));\n"
   691                 text += """  container = (SVGUIContainer*)GetElementById(wxT("%(id)d"));
   697                 fct += "  if (container->IsVisible())\n"
   692   if (container->IsVisible())
   698                 fct += "    _copy__IX"+self.BusNumber+"_"+element_id+"_1 = true;\n"
   693     _copy__IX%(location)s_%(id)d_1 = true;
   699                 fct += "  else\n"
   694   else
   700                 fct += "    _copy__IX"+self.BusNumber+"_"+element_id+"_1 = false;\n"
   695     _copy__IX%(location)s_%(id)d_1 = false;
   701                 fct += "  _copy__IX"+self.BusNumber+"_"+element_id+"_2 = true;\n\n"
   696   _copy__IX%(location)s_%(id)d_2 = true;
       
   697 
       
   698 """%texts
   702                 container = True
   699                 container = True
   703             elif type == "TextCtrl":
   700             elif element_type == ITEM_TEXT:
   704                 if (not textctrl):
   701                 if (not textctrl):
   705                     fct += "  SVGUITextCtrl* text;\n"
   702                     text += "  SVGUITextCtrl* text;\n"
   706                 fct += "  text = (SVGUITextCtrl*)GetElementById(wxT(\""+element_id+"\"));\n"
   703                 text += """  text = (SVGUITextCtrl*)GetElementById(wxT("%(id)d"));
   707                 fct += "  _copy__IB"+self.BusNumber+"_"+element_id+"_1 = wxStringToIEC_STRING(text->GetValue());\n"
   704   _copy__IB%(location)s_%(id)d_1 = wxStringToIEC_STRING(text->GetValue());
   708                 fct += "  _copy__IX"+self.BusNumber+"_"+element_id+"_2 = true;\n\n"
   705   _copy__IX%(location)s_%(id)d_2 = true;
       
   706 
       
   707 """%texts
   709                 textctrl = True
   708                 textctrl = True
   710             elif type == "ScrollBar":
   709             elif element_type == ITEM_SCROLLBAR:
   711                 if (not scrollbar):
   710                 if (not scrollbar):
   712                     fct += "  SVGUIScrollBar* scrollbar;\n"
   711                     text += "  SVGUIScrollBar* scrollbar;\n"
   713                 fct += "  scrollbar = (SVGUIScrollBar*)GetElementById(wxT(\""+element_id+"\"));\n"
   712                 text += """  scrollbar = (SVGUIScrollBar*)GetElementById(wxT("%(id)d"));
   714                 fct += "  _copy__IW"+self.BusNumber+"_"+element_id+"_1 = scrollbar->GetThumbPosition();\n"
   713   _copy__IW%(location)s_%(id)d_1 = scrollbar->GetThumbPosition();
   715                 fct += "  _copy__IX"+self.BusNumber+"_"+element_id+"_2 = true;\n\n"
   714   _copy__IX%(location)s_%(id)d_2 = true;
       
   715 
       
   716 """%texts
   716                 scrollbar = True
   717                 scrollbar = True
   717             elif type == "RotatingCtrl":
   718             elif element_type == ITEM_ROTATING:
   718                 if (not rotatingctrl):
   719                 if (not rotatingctrl):
   719                     fct += "  SVGUIRotatingCtrl* rotating;\n"
   720                     text += "  SVGUIRotatingCtrl* rotating;\n"
   720                 fct += "  rotating = (SVGUIRotatingCtrl*)GetElementById(wxT(\""+element_id+"\"));\n"
   721                 text += """  rotating = (SVGUIRotatingCtrl*)GetElementById(wxT("%(id)d"));
   721                 fct += "  _copy__ID"+self.BusNumber+"_"+element_id+"_1 = rotating->GetAngle();\n"
   722   _copy__ID%(location)s_%(id)d_1 = rotating->GetAngle();
   722                 fct += "  _copy__IX"+self.BusNumber+"_"+element_id+"_2 = true;\n\n"
   723   _copy__IX%(location)s_%(id)d_2 = true;
       
   724 
       
   725 """%texts
   723                 rotatingctrl = True
   726                 rotatingctrl = True
   724             elif type == "NoteBook":
   727             elif element_type == ITEM_NOTEBOOK:
   725                 if (not notebook):
   728                 if (not notebook):
   726                     fct += "  SVGUINoteBook* notebook;\n"
   729                     text += "  SVGUINoteBook* notebook;\n"
   727                 fct += "  notebook = (SVGUINoteBook*)GetElementById(wxT(\""+element_id+"\"));\n"
   730                 text += """  notebook = (SVGUINoteBook*)GetElementById(wxT("%(id)d"));
   728                 fct += "  _copy__IB"+self.BusNumber+"_"+element_id+"_1 = notebook->GetCurrentPage();\n"
   731   _copy__IB%(location)s_%(id)d_1 = notebook->GetCurrentPage();
   729                 fct += "  _copy__IX"+self.BusNumber+"_"+element_id+"_2 = true;\n\n"
   732   _copy__IX%(location)s_%(id)d_2 = true;
       
   733 
       
   734 """%texts
   730                 notebook = True
   735                 notebook = True
   731             elif type == "Transform":
   736             elif element_type == ITEM_TRANSFORM:
   732                 if (not transform):
   737                 if (not transform):
   733                     fct += "  SVGUITransform* transform;\n"
   738                     text += "  SVGUITransform* transform;\n"
   734                 fct += "  transform = (SVGUITransform*)GetElementById(wxT(\""+element_id+"\"));\n"
   739                 text += """  transform = (SVGUITransform*)GetElementById(wxT("%(id)d"));
   735                 fct += "  _copy__ID"+self.BusNumber+"_"+element_id+"_1 = transform->GetX();\n"
   740   _copy__ID%(location)s_%(id)d_1 = transform->GetX();
   736                 fct += "  _copy__ID"+self.BusNumber+"_"+element_id+"_2 = transform->GetY();\n"
   741   _copy__ID%(location)s_%(id)d_2 = transform->GetY();
   737                 fct += "  _copy__ID"+self.BusNumber+"_"+element_id+"_3 = transform->GetXScale();\n"
   742   _copy__ID%(location)s_%(id)d_3 = transform->GetXScale();
   738                 fct += "  _copy__ID"+self.BusNumber+"_"+element_id+"_4 = transform->GetYScale();\n"
   743   _copy__ID%(location)s_%(id)d_4 = transform->GetYScale();
   739                 fct += "  _copy__ID"+self.BusNumber+"_"+element_id+"_5 = transform->GetAngle();\n"
   744   _copy__ID%(location)s_%(id)d_5 = transform->GetAngle();
   740                 fct += "  _copy__IX"+self.BusNumber+"_"+element_id+"_6 = true;\n\n"
   745   _copy__IX%(location)s_%(id)d_6 = true;
       
   746 
       
   747 """%texts
   741                 transform = True
   748                 transform = True
   742         fct += "}\n\n"
   749         text += "}\n\n"
   743         
   750         
   744         #DEBUG Fonction d'affichage
   751         #DEBUG Fonction d'affichage
   745 #        fct += "void Program::Print()\n{\n"
   752 #        fct += "void Program::Print()\n{\n"
   746 #        for element in elementsTab:
   753 #        for element in elementsTab:
   747 #            infos = element.getElementAttributes()
   754 #            infos = element.getElementAttributes()
   764 #                var = "_copy__I"+element_type+self.BusNumber+"_"+element_id+"_"+str(element_num_patte)
   771 #                var = "_copy__I"+element_type+self.BusNumber+"_"+element_id+"_"+str(element_num_patte)
   765 #                fct +="  printf(\""+var+": %"+c_type+"\\n\","+var+");\n"
   772 #                fct +="  printf(\""+var+": %"+c_type+"\\n\","+var+");\n"
   766 #                element_num_patte +=1
   773 #                element_num_patte +=1
   767         #fct +="    wxPostEvent(Program,wxEVT_PLCOUT);\n"
   774         #fct +="    wxPostEvent(Program,wxEVT_PLCOUT);\n"
   768 #        fct +="};\n\n"    
   775 #        fct +="};\n\n"    
   769         return fct
   776         return text
   770     
   777     
   771     def PlugGenerate_C(self, buildpath, locations, logger):
   778     def PlugGenerate_C(self, buildpath, locations, logger):
   772         current_location = self.GetCurrentLocation()
   779         progname = "SVGUI_%s"%"_".join(map(str, self.GetCurrentLocation()))
   773         self.BusNumber = "_".join(map(lambda x:str(x), current_location))
   780         self.GenerateProgram((0, 0), buildpath, progname)
   774         progname = "SVGUI_" + self.BusNumber
       
   775         self.GenerateProgram(buildpath, progname)
       
   776         Gen_C_file = os.path.join(buildpath, progname+".cpp" )
   781         Gen_C_file = os.path.join(buildpath, progname+".cpp" )
   777         return [(Gen_C_file,"")],"",True
   782         
       
   783         status, result, err_result = ProcessLogger(logger, "wx-config --cxxflags", no_stdout=True).spin()
       
   784         if status:
       
   785             logger.write_error("Unable to get wx cxxflags\n")
       
   786         cxx_flags = result.strip() + " -I../matiec/lib"
       
   787         
       
   788         status, result, err_result = ProcessLogger(logger, "wx-config --libs", no_stdout=True).spin()
       
   789         if status:
       
   790             logger.write_error("Unable to get wx libs\n")
       
   791         libs = result.strip() + " -lwxsvg"
       
   792         
       
   793         return [(Gen_C_file, cxx_flags)],libs,True
   778     
   794     
   779     def BlockTypesFactory(self):
   795     def BlockTypesFactory(self):
   780         def generate_svgui_block(generator, block, body, link, order=False):
   796         def generate_svgui_block(generator, block, body, link, order=False):
   781             name = block.getInstanceName()
   797             name = block.getinstanceName()
   782             block_id = self.GetElementIdFromName(name)
   798             block_id = self.GetElementIdFromName(name)
   783             if block_id == None:
   799             if block_id == None:
   784                 raise ValueError, "No corresponding block found"
   800                 raise ValueError, "No corresponding block found"
   785             type = block.getTypeName()
   801             type = block.gettypeName()
   786             block_infos = self.GetBlockType(type)
   802             block_infos = GetBlockType(type)
   787             current_location = ".".join(map(str, self.GetCurrentLocation()))
   803             current_location = ".".join(map(str, self.GetCurrentLocation()))
   788             if not generator.ComputedBlocks.get(name, False) and not order:
   804             if not generator.ComputedBlocks.get(name, False) and not order:
   789                 for num, variable in enumerate(block.inputVariables.getVariable()):
   805                 for num, variable in enumerate(block.inputVariables.getvariable()):
   790                     connections = variable.connectionPointIn.getConnections()
   806                     connections = variable.connectionPointIn.getconnections()
   791                     if connections and len(connections) == 1:
   807                     if connections and len(connections) == 1:
   792                         parameter = "%sQ%s%s.%d.%d"%("%", TYPECONVERSION[block_infos["inputs"][num][1]], current_location, block_id, num+1)
   808                         parameter = "%sQ%s%s.%d.%d"%("%", TYPECONVERSION[block_infos["inputs"][num][1]], current_location, block_id, num+1)
   793                         value = generator.ComputeFBDExpression(body, connections[0])
   809                         value = generator.ComputeFBDExpression(body, connections[0])
   794                         generator.Program += ("  %s := %s;\n"%(parameter, generator.ExtractModifier(variable, value)))
   810                         generator.Program += ("  %s := %s;\n"%(parameter, generator.ExtractModifier(variable, value)))
   795                 generator.ComputedBlocks[block] = True
   811                 generator.ComputedBlocks[block] = True
   796             if link:
   812             if link:
   797                 connectionPoint = link.getPosition()[-1]
   813                 connectionPoint = link.getposition()[-1]
   798                 for num, variable in enumerate(block.outputVariables.getVariable()):
   814                 for num, variable in enumerate(block.outputVariables.getvariable()):
   799                     blockPointx, blockPointy = variable.connectionPointOut.getRelPosition()
   815                     blockPointx, blockPointy = variable.connectionPointOut.getrelPositionXY()
   800                     if block.getX() + blockPointx == connectionPoint.getX() and block.getY() + blockPointy == connectionPoint.getY():
   816                     if block.getx() + blockPointx == connectionPoint.getx() and block.gety() + blockPointy == connectionPoint.gety():
   801                         return "%sI%s%s.%d.%d"%("%", TYPECONVERSION[block_infos["outputs"][num][1]], current_location, block_id, num+1)
   817                         return "%sI%s%s.%d.%d"%("%", TYPECONVERSION[block_infos["outputs"][num][1]], current_location, block_id, num+1)
   802                 raise ValueError, "No output variable found"
   818                 raise ValueError, "No output variable found"
   803             else:
   819             else:
   804                 return None
   820                 return None
   805 
   821 
   806         def initialise_block(type, name):
   822         def initialise_block(type, name):
   807             block_id = self.GetElementIdFromName(name)
   823             block_id = self.GetElementIdFromName(name)
   808             if block_id == None:
   824             if block_id == None:
   809                 raise ValueError, "No corresponding block found"
   825                 raise ValueError, "No corresponding block found"
   810             block_infos = self.GetBlockType(type)
   826             block_infos = GetBlockType(type)
   811             current_location = ".".join(map(str, self.GetCurrentLocation()))
   827             current_location = ".".join(map(str, self.GetCurrentLocation()))
   812             variables = []
   828             variables = []
   813             for num, (input_name, input_type, input_modifier) in enumerate(block_infos["inputs"]):
   829             for num, (input_name, input_type, input_modifier) in enumerate(block_infos["inputs"]):
   814                 variables.append((input_type, None, "%sQ%s%s.%d.%d"%("%", TYPECONVERSION[input_type], current_location, block_id, num+1), None))
   830                 variables.append((input_type, None, "%sQ%s%s.%d.%d"%("%", TYPECONVERSION[input_type], current_location, block_id, num+1), None))
   815             for num, (output_name, output_type, output_modifier) in enumerate(block_infos["outputs"]):
   831             for num, (output_name, output_type, output_modifier) in enumerate(block_infos["outputs"]):
   816                 variables.append((output_type, None, "%sI%s%s.%d.%d"%("%", TYPECONVERSION[input_type], current_location, block_id, num+1), None))
   832                 variables.append((output_type, None, "%sI%s%s.%d.%d"%("%", TYPECONVERSION[input_type], current_location, block_id, num+1), None))
   817             return variables
   833             return variables
   818 
   834 
   819         return [{"name" : "SVGUI function blocks", "list" :
   835         return [{"name" : "SVGUI function blocks", "list" :
   820            [{"name" : "Container", "type" : "functionBlock", "extensible" : False, 
   836                 [{"name" : "Container", "type" : "functionBlock", "extensible" : False, 
   821                     "inputs" : [("Show","BOOL","none"),("Set State","BOOL","none")], 
   837                     "inputs" : [("Show","BOOL","none"),("SetState","BOOL","none")], 
   822                     "outputs" : [("Show","BOOL","none"),("State Changed","BOOL","none")],
   838                     "outputs" : [("Visible","BOOL","none"),("StateChanged","BOOL","none")],
   823                     "comment" : "SVGUI Container",
   839                     "comment" : "SVGUI Container",
   824                     "generate" : generate_svgui_block, "initialise" : initialise_block},
   840                     "generate" : generate_svgui_block, "initialise" : initialise_block},
   825                 {"name" : "Button", "type" : "functionBlock", "extensible" : False, 
   841                 {"name" : "Button", "type" : "functionBlock", "extensible" : False, 
   826                     "inputs" : [("Show","BOOL","none"),("Toggle","BOOL","none")], 
   842                     "inputs" : [("Show","BOOL","none"),("Toggle","BOOL","none")], 
   827                     "outputs" : [("Visible","BOOL","none"),("State","BOOL","none")],
   843                     "outputs" : [("Visible","BOOL","none"),("State","BOOL","none")],
   828                     "comment" : "SVGUI Button",
   844                     "comment" : "SVGUI Button",
   829                     "generate" : generate_svgui_block, "initialise" : initialise_block},
   845                     "generate" : generate_svgui_block, "initialise" : initialise_block},
   830                 {"name" : "TextCtrl", "type" : "functionBlock", "extensible" : False, 
   846                 {"name" : "TextCtrl", "type" : "functionBlock", "extensible" : False, 
   831                     "inputs" : [("Text","STRING","none"),("Set Text","BOOL","none")], 
   847                     "inputs" : [("Text","STRING","none"),("SetText","BOOL","none")], 
   832                     "outputs" : [("Text","STRING","none"),("Text Changed","BOOL","none")],
   848                     "outputs" : [("Text","STRING","none"),("TextChanged","BOOL","none")],
   833                     "comment" : "SVGUI Text Control",
   849                     "comment" : "SVGUI Text Control",
   834                     "generate" : generate_svgui_block, "initialise" : initialise_block},
   850                     "generate" : generate_svgui_block, "initialise" : initialise_block},
   835                 {"name" : "ScrollBar", "type" : "functionBlock", "extensible" : False, 
   851                 {"name" : "ScrollBar", "type" : "functionBlock", "extensible" : False, 
   836                     "inputs" : [("Position","UINT","none"),("Set Position","BOOL","none")], 
   852                     "inputs" : [("Position","UINT","none"),("SetPosition","BOOL","none")], 
   837                     "outputs" : [("Position","UINT","none"),("Position Changed","BOOL","none")],
   853                     "outputs" : [("Position","UINT","none"),("PositionChanged","BOOL","none")],
   838                     "comment" : "SVGUI ScrollBar",
   854                     "comment" : "SVGUI ScrollBar",
   839                     "generate" : generate_svgui_block, "initialise" : initialise_block},
   855                     "generate" : generate_svgui_block, "initialise" : initialise_block},
   840                 {"name" : "NoteBook", "type" : "functionBlock", "extensible" : False, 
   856                 {"name" : "NoteBook", "type" : "functionBlock", "extensible" : False, 
   841                     "inputs" : [("Selected","UINT","none"),("Set Selected","BOOL","none")], 
   857                     "inputs" : [("Selected","UINT","none"),("SetSelected","BOOL","none")], 
   842                     "outputs" : [("Selected","UINT","none"),("Selected Changed","BOOL","none")],
   858                     "outputs" : [("Selected","UINT","none"),("SelectedChanged","BOOL","none")],
   843                     "comment" : "SVGUI Notebook",
   859                     "comment" : "SVGUI Notebook",
   844                     "generate" : generate_svgui_block, "initialise" : initialise_block},
   860                     "generate" : generate_svgui_block, "initialise" : initialise_block},
   845                 {"name" : "RotatingCtrl", "type" : "functionBlock", "extensible" : False, 
   861                 {"name" : "RotatingCtrl", "type" : "functionBlock", "extensible" : False, 
   846                     "inputs" : [("Angle","REAL","none"),("Set Angle","BOOL","none")], 
   862                     "inputs" : [("Angle","REAL","none"),("SetAngle","BOOL","none")], 
   847                     "outputs" : [("Angle","REAL","none"),("Angle changed","BOOL","none")],
   863                     "outputs" : [("Angle","REAL","none"),("AngleChanged","BOOL","none")],
   848                     "comment" : "SVGUI Rotating Control",
   864                     "comment" : "SVGUI Rotating Control",
   849                     "generate" : generate_svgui_block, "initialise" : initialise_block},
   865                     "generate" : generate_svgui_block, "initialise" : initialise_block},
   850                 {"name" : "Transform", "type" : "functionBlock", "extensible" : False, 
   866                 {"name" : "Transform", "type" : "functionBlock", "extensible" : False, 
   851                     "inputs" : [("X","REAL","none"),("Y","REAL","none"),("Scale X","REAL","none"),("Scale Y","REAL","none"),("Angle","REAL","none"),("Set","BOOL","none")], 
   867                     "inputs" : [("X","REAL","none"),("Y","REAL","none"),("XScale","REAL","none"),("YScale","REAL","none"),("Angle","REAL","none"),("Set","BOOL","none")], 
   852                     "outputs" : [("X","REAL","none"),("Y","REAL","none"),("Scale X","REAL","none"),("Scale Y","REAL","none"),("Angle","REAL","none"),("Changed","BOOL","none")],
   868                     "outputs" : [("X","REAL","none"),("Y","REAL","none"),("XScale","REAL","none"),("YScale","REAL","none"),("Angle","REAL","none"),("Changed","BOOL","none")],
   853                     "comment" : "SVGUI Transform",
   869                     "comment" : "SVGUI Transform",
   854                     "generate" : generate_svgui_block, "initialise" : initialise_block},
   870                     "generate" : generate_svgui_block, "initialise" : initialise_block},
   855                ]}
   871                ]}
   856         ]
   872         ]
   857     
   873 
   858     def GetBlockType(self,type):
       
   859         for category in self.BlockTypesFactory():
       
   860             for blocktype in category["list"]:
       
   861                 if blocktype["name"] == type:
       
   862                     return blocktype
       
   863         return None
       
   864 
       
   865 #DEBUG
       
   866 if __name__ == '__main__':
       
   867     app = wxPySimpleApp()
       
   868     wxInitAllImageHandlers()
       
   869     
       
   870     # Install a exception handle for bug reports
       
   871     #wxAddExceptHook(os.getcwd(),__version__)
       
   872     
       
   873     cont = RootClass(sys.path[0])
       
   874     frame = _EditorFramePlug(cont)
       
   875 
       
   876     frame.Show()
       
   877     app.MainLoop()
       
   878 #DEBUG
       
   879 
       
   880 
       
   881 
       
   882 
       
   883