laurent@442: #!/usr/bin/env python laurent@442: # -*- coding: utf-8 -*- laurent@442: laurent@442: __version__ = "$Revision$" laurent@442: laurent@442: import os, sys, getopt, wx, tempfile laurent@442: from types import TupleType, StringType, UnicodeType laurent@442: laurent@442: CWD = os.path.split(os.path.realpath(__file__))[0] laurent@442: laurent@442: def Bpath(*args): laurent@442: return os.path.join(CWD,*args) laurent@442: laurent@442: if __name__ == '__main__': laurent@442: def usage(): laurent@442: print "\nUsage of LPCBeremiz.py :" laurent@442: print "\n %s [Projectpath] [Buildpath]\n"%sys.argv[0] laurent@442: laurent@442: try: laurent@442: opts, args = getopt.getopt(sys.argv[1:], "h", ["help"]) laurent@442: except getopt.GetoptError: laurent@442: # print help information and exit: laurent@442: usage() laurent@442: sys.exit(2) laurent@442: laurent@442: for o, a in opts: laurent@442: if o in ("-h", "--help"): laurent@442: usage() laurent@442: sys.exit() laurent@442: laurent@442: if len(args) > 2: laurent@442: usage() laurent@442: sys.exit() laurent@442: elif len(args) == 1: laurent@442: projectOpen = args[0] laurent@442: buildpath = None laurent@442: elif len(args) == 2: laurent@442: projectOpen = args[0] laurent@442: buildpath = args[1] laurent@442: else: laurent@442: projectOpen = None laurent@442: buildpath = None laurent@442: laurent@442: class PseudoLocale: laurent@442: LocaleDirs = [] laurent@442: Domains = [] laurent@442: laurent@442: def AddCatalogLookupPathPrefix(self, localedir): laurent@442: self.LocaleDirs.append(localedir) laurent@442: laurent@442: def AddCatalog(self, domain): laurent@442: self.Domains.append(domain) laurent@442: laurent@442: # Import module for internationalization laurent@442: import gettext laurent@442: import __builtin__ laurent@442: laurent@442: # Define locale for wx laurent@442: __builtin__.__dict__['loc'] = PseudoLocale() laurent@442: laurent@442: if __name__ == '__main__': laurent@442: __builtin__.__dict__['_'] = wx.GetTranslation#unicode_translation laurent@442: laurent@442: from Beremiz import * laurent@442: from plugger import PluginsRoot, PlugTemplate, opjimg laurent@442: from plcopen.structures import LOCATIONDATATYPES laurent@442: from PLCControler import LOCATION_PLUGIN, LOCATION_MODULE, LOCATION_GROUP,\ laurent@442: LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, LOCATION_VAR_MEMORY laurent@442: from PLCOpenEditor import IDEFrame laurent@442: laurent@442: #------------------------------------------------------------------------------- laurent@442: # LPCModule Class laurent@442: #------------------------------------------------------------------------------- laurent@442: laurent@442: def _GetModuleChildren(module): laurent@442: children = [] laurent@442: for child in module["children"]: laurent@442: if child["type"] == LOCATION_GROUP: laurent@442: children.extend(child["children"]) laurent@442: else: laurent@442: children.append(child) laurent@442: return children laurent@442: laurent@442: def _GetLastModuleGroup(module): laurent@442: group = module laurent@442: for child in module["children"]: laurent@442: if child["type"] == LOCATION_GROUP: laurent@442: group = child laurent@442: return group["children"] laurent@442: laurent@442: def _GetModuleBySomething(module, something, toks): laurent@442: for child in _GetModuleChildren(module): laurent@442: if child.get(something) == toks[0]: laurent@442: if len(toks) > 1: laurent@442: return _GetModuleBySomething(child, something, toks[1:]) laurent@442: return child laurent@442: return None laurent@442: laurent@442: def _GetModuleVariable(module, location): laurent@442: for child in _GetModuleChildren(module): laurent@442: if child["location"] == location: laurent@442: return child laurent@442: return None laurent@442: laurent@442: def _RemoveModuleChild(module, child): laurent@442: if child in module["children"]: laurent@442: module["children"].remove(child) laurent@442: else: laurent@442: for group in module["children"]: laurent@442: if group["type"] == LOCATION_GROUP and child in group["children"]: laurent@442: group["children"].remove(child) laurent@442: laurent@442: LOCATION_TYPES = {"I": LOCATION_VAR_INPUT, laurent@442: "Q": LOCATION_VAR_OUTPUT, laurent@442: "M": LOCATION_VAR_MEMORY} laurent@442: laurent@442: LOCATION_DIRS = dict([(dir, size) for size, dir in LOCATION_TYPES.iteritems()]) laurent@442: laurent@442: LOCATION_SIZES = {} laurent@442: for size, types in LOCATIONDATATYPES.iteritems(): laurent@442: for type in types: laurent@442: LOCATION_SIZES[type] = size laurent@442: laurent@442: BUS_TEXT = """/* Code generated by LPCBus plugin */ laurent@442: laurent@442: /* LPCBus plugin includes */ laurent@442: #include "app_glue.h" laurent@442: #ifdef _WINDOWS_H laurent@442: #include "iec_types.h" laurent@442: #else laurent@442: #include "iec_std_lib.h" laurent@442: #endif laurent@442: laurent@442: %(declare_code)s laurent@442: laurent@442: /* LPCBus plugin user variables definition */ laurent@442: %(var_decl)s laurent@442: laurent@442: /* LPCBus plugin functions */ laurent@442: int __init_%(location_str)s(int argc,char **argv) laurent@442: { laurent@442: return 0; laurent@442: } laurent@442: laurent@442: void __cleanup_%(location_str)s(void) laurent@442: { laurent@442: } laurent@442: laurent@442: void __retrieve_%(location_str)s(void) laurent@442: { laurent@442: %(retrieve_code)s laurent@442: } laurent@442: laurent@442: void __publish_%(location_str)s(void) laurent@442: { laurent@442: %(publish_code)s laurent@442: } laurent@442: """ laurent@442: laurent@442: class LPCBus(object): laurent@442: laurent@442: def __init__(self): laurent@442: self.VariableLocationTree = [] laurent@442: self.ResetUsedLocations() laurent@442: self.Icon = None laurent@442: laurent@442: def __getitem__(self, key): laurent@442: if key == "children": laurent@442: return self.VariableLocationTree laurent@442: raise KeyError, "Only 'children' key is available" laurent@442: laurent@442: def SetIcon(self, icon): laurent@442: self.Icon = icon laurent@442: laurent@442: def _GetChildBySomething(self, something, toks): laurent@442: return _GetModuleBySomething({"children" : self.VariableLocationTree}, something, toks) laurent@442: laurent@442: def GetBaseTypes(self): laurent@442: return self.GetPlugRoot().GetBaseTypes() laurent@442: laurent@442: def GetSizeOfType(self, type): laurent@442: return LOCATION_SIZES[self.GetPlugRoot().GetBaseType(type)] laurent@442: laurent@442: def _GetVariableLocationTree(self, current_location, infos): laurent@442: if infos["type"] == LOCATION_MODULE: laurent@442: location = current_location + (infos["IEC_Channel"],) laurent@442: return {"name": infos["name"], laurent@442: "type": infos["type"], laurent@442: "location": ".".join(map(str, location + ("x",))), laurent@442: "icon": infos["icon"], laurent@442: "children": [self._GetVariableLocationTree(location, child) for child in infos["children"]]} laurent@442: elif infos["type"] == LOCATION_GROUP: laurent@442: return {"name": infos["name"], laurent@442: "type": infos["type"], laurent@442: "location": "", laurent@442: "icon": infos["icon"], laurent@442: "children": [self._GetVariableLocationTree(current_location, child) for child in infos["children"]]} laurent@442: else: laurent@442: size = self.GetSizeOfType(infos["IEC_type"]) laurent@442: location = "%" + LOCATION_DIRS[infos["type"]] + size + ".".join(map(str, current_location + infos["location"])) laurent@442: return {"name": infos["name"], laurent@442: "type": infos["type"], laurent@442: "size": size, laurent@442: "IEC_type": infos["IEC_type"], laurent@442: "location": location, laurent@442: "description": infos["description"], laurent@442: "children": []} laurent@442: laurent@442: def GetVariableLocationTree(self): laurent@442: return {"name": self.BaseParams.getName(), laurent@442: "type": LOCATION_PLUGIN, laurent@442: "location": self.GetFullIEC_Channel(), laurent@442: "icon": self.Icon, laurent@442: "children": [self._GetVariableLocationTree(self.GetCurrentLocation(), child) laurent@442: for child in self.VariableLocationTree]} laurent@442: laurent@442: def PlugTestModified(self): laurent@442: return False laurent@442: laurent@442: def PlugMakeDir(self): laurent@442: pass laurent@442: laurent@442: def PlugRequestSave(self): laurent@442: return None laurent@442: laurent@442: def ResetUsedLocations(self): laurent@442: self.UsedLocations = {} laurent@442: laurent@442: def _AddUsedLocation(self, parent, location): laurent@442: num = location.pop(0) laurent@442: if not parent.has_key(num): laurent@442: parent[num] = {"used": False, "children": {}} laurent@442: if len(location) > 0: laurent@442: self._AddUsedLocation(parent[num]["children"], location) laurent@442: else: laurent@442: parent[num]["used"] = True laurent@442: laurent@442: def AddUsedLocation(self, location): laurent@442: if len(location) > 0: laurent@442: self._AddUsedLocation(self.UsedLocations, list(location)) laurent@442: laurent@442: def _CheckLocationConflicts(self, parent, location): laurent@442: num = location.pop(0) laurent@442: if not parent.has_key(num): laurent@442: return False laurent@442: if len(location) > 0: laurent@442: if parent[num]["used"]: laurent@442: return True laurent@442: return self._CheckLocationConflicts(parent[num]["children"], location) laurent@442: elif len(parent[num]["children"]) > 0: laurent@442: return True laurent@442: return False laurent@442: laurent@442: def CheckLocationConflicts(self, location): laurent@442: if len(location) > 0: laurent@442: return self._CheckLocationConflicts(self.UsedLocations, list(location)) laurent@442: return False laurent@442: laurent@442: def PlugGenerate_C(self, buildpath, locations): laurent@442: """ laurent@442: Generate C code laurent@442: @param current_location: Tupple containing plugin IEC location : %I0.0.4.5 => (0,0,4,5) laurent@442: @param locations: List of complete variables locations \ laurent@442: [{"IEC_TYPE" : the IEC type (i.e. "INT", "STRING", ...) laurent@442: "NAME" : name of the variable (generally "__IW0_1_2" style) laurent@442: "DIR" : direction "Q","I" or "M" laurent@442: "SIZE" : size "X", "B", "W", "D", "L" laurent@442: "LOC" : tuple of interger for IEC location (0,1,2,...) laurent@442: }, ...] laurent@442: @return: [(C_file_name, CFLAGS),...] , LDFLAGS_TO_APPEND laurent@442: """ laurent@442: current_location = self.GetCurrentLocation() laurent@442: # define a unique name for the generated C file laurent@442: location_str = "_".join(map(str, current_location)) laurent@442: laurent@442: code_str = {"location_str": location_str, laurent@442: "var_decl": "", laurent@442: "declare_code": "", laurent@442: "retrieve_code": "", laurent@442: "publish_code": "", laurent@442: } laurent@442: laurent@442: # Adding variables laurent@442: vars = [] laurent@442: self.ResetUsedLocations() laurent@442: for location in locations: laurent@442: loc = location["LOC"][len(current_location):] laurent@442: group = next = self laurent@442: i = 0 laurent@442: while next is not None and i < len(loc): laurent@442: next = self._GetChildBySomething("IEC_Channel", loc[:i + 1]) laurent@442: if next is not None: laurent@442: i += 1 laurent@442: group = next laurent@442: var_loc = loc[i:] laurent@442: for variable in group["children"]: laurent@442: if variable["location"] == var_loc: laurent@442: if location["DIR"] != LOCATION_DIRS[variable["type"]]: laurent@442: raise Exception, "Direction conflict in variable definition" laurent@442: if location["IEC_TYPE"] != variable["IEC_type"]: laurent@442: raise Exception, "Type conflict in variable definition" laurent@442: if location["DIR"] == "Q": laurent@442: if self.CheckLocationConflicts(location["LOC"]): laurent@442: raise Exception, "BYTE and BIT from the same BYTE can't be used together" laurent@442: self.AddUsedLocation(location["LOC"]) laurent@442: vars.append({"location": location["NAME"], laurent@442: "Type": variable["IEC_type"], laurent@442: "Declare": variable["declare"], laurent@442: "Retrieve": variable["retrieve"], laurent@442: "Publish": variable["publish"], laurent@442: }) laurent@442: break laurent@442: base_types = self.GetPlugRoot().GetBaseTypes() laurent@442: for var in vars: laurent@442: prefix = "" laurent@442: if var["Type"] in base_types: laurent@442: prefix = "IEC_" laurent@442: code_str["var_decl"] += "%s%s beremiz%s;\n"%(prefix, var["Type"], var["location"]) laurent@442: code_str["var_decl"] += "%s%s *%s = &beremiz%s;\n"%(prefix, var["Type"], var["location"], var["location"]) laurent@442: if var["Declare"] != "": laurent@442: code_str["declare_code"] += var["Declare"] + "\n" laurent@442: if var["Retrieve"] != "": laurent@442: code_str["retrieve_code"] += var["Retrieve"] % ("*" + var["location"]) + "\n" laurent@442: if var["Publish"] != "": laurent@442: code_str["publish_code"] += var["Publish"] % ("*" + var["location"]) + "\n" laurent@442: laurent@442: Gen_Module_path = os.path.join(buildpath, "Module_%s.c"%location_str) laurent@442: module = open(Gen_Module_path,'w') laurent@442: module.write(BUS_TEXT % code_str) laurent@442: module.close() laurent@442: laurent@442: matiec_flags = '"-I%s"'%os.path.abspath(self.GetPlugRoot().GetIECLibPath()) laurent@442: return [(Gen_Module_path, matiec_flags)],"",True laurent@442: laurent@442: #------------------------------------------------------------------------------- laurent@442: # LPCPluginsRoot Class laurent@442: #------------------------------------------------------------------------------- laurent@442: laurent@442: def mycopytree(src, dst): laurent@442: """ laurent@442: Copy content of a directory to an other, omit hidden files laurent@442: @param src: source directory laurent@442: @param dst: destination directory laurent@442: """ laurent@442: for i in os.listdir(src): laurent@442: if not i.startswith('.'): laurent@442: srcpath = os.path.join(src,i) laurent@442: dstpath = os.path.join(dst,i) laurent@442: if os.path.isdir(srcpath): laurent@442: os.makedirs(dstpath) laurent@442: mycopytree(srcpath, dstpath) laurent@442: elif os.path.isfile(srcpath): laurent@442: shutil.copy2(srcpath, dstpath) laurent@442: laurent@442: class LPCPluginsRoot(PluginsRoot): laurent@442: laurent@442: PlugChildsTypes = [("LPCBus", LPCBus, "LPC bus")] laurent@442: laurent@442: PluginMethods = [ laurent@442: {"bitmap" : opjimg("Build"), laurent@442: "name" : _("Build"), laurent@442: "tooltip" : _("Build project into build folder"), laurent@442: "method" : "_build"}, laurent@442: {"bitmap" : opjimg("Clean"), laurent@442: "name" : _("Clean"), laurent@442: "enabled" : False, laurent@442: "tooltip" : _("Clean project build folder"), laurent@442: "method" : "_Clean"}, laurent@442: ] laurent@442: laurent@442: def GetProjectName(self): laurent@442: return self.Project.getname() laurent@442: laurent@442: def GetDefaultTarget(self): laurent@442: target = self.Classes["BeremizRoot_TargetType"]() laurent@442: target_value = self.Classes["TargetType_Makefile"]() laurent@442: target_value.setBuildPath(self.BuildPath) laurent@442: target.setcontent({"name": "Makefile", "value": target_value}) laurent@442: return target laurent@442: laurent@442: def SetProjectName(self, name): laurent@442: return self.Project.setname(name) laurent@442: laurent@442: def LoadProject(self, ProjectPath, BuildPath=None): laurent@442: """ laurent@442: Load a project XML file laurent@442: @param ProjectPath: path of the project xml file laurent@442: """ laurent@442: # Load PLCOpen file laurent@442: result = self.OpenXMLFile(ProjectPath) laurent@442: if result: laurent@442: return result laurent@442: # Change XSD into class members laurent@442: self._AddParamsMembers() laurent@442: self.PluggedChilds = {} laurent@442: # Keep track of the root plugin (i.e. project path) laurent@442: self.ProjectPath = ProjectPath laurent@442: laurent@442: self.BuildPath = tempfile.mkdtemp() laurent@442: if BuildPath is not None: laurent@442: mycopytree(BuildPath, self.BuildPath) laurent@442: laurent@442: self.RefreshPluginsBlockLists() laurent@442: laurent@442: if os.path.exists(self._getBuildPath()): laurent@442: self.EnableMethod("_Clean", True) laurent@442: laurent@442: def SaveProject(self): laurent@442: self.SaveXMLFile(self.ProjectPath) laurent@442: laurent@442: #------------------------------------------------------------------------------- laurent@442: # LPCBeremiz Class laurent@442: #------------------------------------------------------------------------------- laurent@442: laurent@442: class LPCBeremiz(Beremiz): laurent@442: laurent@442: def _init_coll_FileMenu_Items(self, parent): laurent@442: AppendMenu(parent, help='', id=wx.ID_SAVE, laurent@442: kind=wx.ITEM_NORMAL, text=_(u'Save\tCTRL+S')) laurent@442: AppendMenu(parent, help='', id=wx.ID_CLOSE, laurent@442: kind=wx.ITEM_NORMAL, text=_(u'Close Tab\tCTRL+W')) laurent@442: parent.AppendSeparator() laurent@442: AppendMenu(parent, help='', id=wx.ID_PAGE_SETUP, laurent@442: kind=wx.ITEM_NORMAL, text=_(u'Page Setup')) laurent@442: AppendMenu(parent, help='', id=wx.ID_PREVIEW, laurent@442: kind=wx.ITEM_NORMAL, text=_(u'Preview')) laurent@442: AppendMenu(parent, help='', id=wx.ID_PRINT, laurent@442: kind=wx.ITEM_NORMAL, text=_(u'Print')) laurent@442: parent.AppendSeparator() laurent@442: AppendMenu(parent, help='', id=wx.ID_PROPERTIES, laurent@442: kind=wx.ITEM_NORMAL, text=_(u'Properties')) laurent@442: parent.AppendSeparator() laurent@442: AppendMenu(parent, help='', id=wx.ID_EXIT, laurent@442: kind=wx.ITEM_NORMAL, text=_(u'Quit\tCTRL+Q')) laurent@442: laurent@442: self.Bind(wx.EVT_MENU, self.OnSaveProjectMenu, id=wx.ID_SAVE) laurent@442: self.Bind(wx.EVT_MENU, self.OnCloseTabMenu, id=wx.ID_CLOSE) laurent@442: self.Bind(wx.EVT_MENU, self.OnPageSetupMenu, id=wx.ID_PAGE_SETUP) laurent@442: self.Bind(wx.EVT_MENU, self.OnPreviewMenu, id=wx.ID_PREVIEW) laurent@442: self.Bind(wx.EVT_MENU, self.OnPrintMenu, id=wx.ID_PRINT) laurent@442: self.Bind(wx.EVT_MENU, self.OnPropertiesMenu, id=wx.ID_PROPERTIES) laurent@442: self.Bind(wx.EVT_MENU, self.OnQuitMenu, id=wx.ID_EXIT) laurent@442: laurent@442: def _init_ctrls(self, prnt): laurent@442: IDEFrame._init_ctrls(self, prnt) laurent@442: laurent@442: self.Bind(wx.EVT_MENU, self.OnOpenWidgetInspector, id=ID_BEREMIZINSPECTOR) laurent@442: accel = wx.AcceleratorTable([wx.AcceleratorEntry(wx.ACCEL_CTRL|wx.ACCEL_ALT, ord('I'), ID_BEREMIZINSPECTOR)]) laurent@442: self.SetAcceleratorTable(accel) laurent@442: laurent@442: self.PLCConfig = wx.ScrolledWindow(id=ID_BEREMIZPLCCONFIG, laurent@442: name='PLCConfig', parent=self.LeftNoteBook, pos=wx.Point(0, 0), laurent@442: size=wx.Size(-1, -1), style=wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER|wx.HSCROLL|wx.VSCROLL) laurent@442: self.PLCConfig.SetBackgroundColour(wx.WHITE) laurent@442: self.PLCConfig.Bind(wx.EVT_LEFT_DOWN, self.OnPanelLeftDown) laurent@442: self.PLCConfig.Bind(wx.EVT_SIZE, self.OnMoveWindow) laurent@442: self.LeftNoteBook.InsertPage(0, self.PLCConfig, _("Topology"), True) laurent@442: laurent@442: self.LogConsole = wx.TextCtrl(id=ID_BEREMIZLOGCONSOLE, value='', laurent@442: name='LogConsole', parent=self.BottomNoteBook, pos=wx.Point(0, 0), laurent@442: size=wx.Size(0, 0), style=wx.TE_MULTILINE|wx.TE_RICH2) laurent@442: self.LogConsole.Bind(wx.EVT_LEFT_DCLICK, self.OnLogConsoleDClick) laurent@442: self.BottomNoteBook.AddPage(self.LogConsole, _("Log Console")) laurent@442: laurent@442: self._init_beremiz_sizers() laurent@442: laurent@442: def OnCloseFrame(self, event): laurent@442: global frame, lpcberemiz_cmd laurent@442: frame = None laurent@442: self.PluginRoot.ResetAppFrame(lpcberemiz_cmd.Log) laurent@442: laurent@442: self.KillLocalRuntime() laurent@442: laurent@442: event.Skip() laurent@442: laurent@442: def RefreshFileMenu(self): laurent@442: if self.PluginRoot is not None: laurent@442: selected = self.TabsOpened.GetSelection() laurent@442: if selected >= 0: laurent@442: graphic_viewer = isinstance(self.TabsOpened.GetPage(selected), Viewer) laurent@442: else: laurent@442: graphic_viewer = False laurent@442: if self.TabsOpened.GetPageCount() > 0: laurent@442: self.FileMenu.Enable(wx.ID_CLOSE, True) laurent@442: if graphic_viewer: laurent@442: self.FileMenu.Enable(wx.ID_PREVIEW, True) laurent@442: self.FileMenu.Enable(wx.ID_PRINT, True) laurent@442: else: laurent@442: self.FileMenu.Enable(wx.ID_PREVIEW, False) laurent@442: self.FileMenu.Enable(wx.ID_PRINT, False) laurent@442: else: laurent@442: self.FileMenu.Enable(wx.ID_CLOSE, False) laurent@442: self.FileMenu.Enable(wx.ID_PREVIEW, False) laurent@442: self.FileMenu.Enable(wx.ID_PRINT, False) laurent@442: self.FileMenu.Enable(wx.ID_PAGE_SETUP, True) laurent@442: self.FileMenu.Enable(wx.ID_SAVE, True) laurent@442: self.FileMenu.Enable(wx.ID_PROPERTIES, True) laurent@442: else: laurent@442: self.FileMenu.Enable(wx.ID_CLOSE, False) laurent@442: self.FileMenu.Enable(wx.ID_PAGE_SETUP, False) laurent@442: self.FileMenu.Enable(wx.ID_PREVIEW, False) laurent@442: self.FileMenu.Enable(wx.ID_PRINT, False) laurent@442: self.FileMenu.Enable(wx.ID_SAVE, False) laurent@442: self.FileMenu.Enable(wx.ID_PROPERTIES, False) laurent@442: laurent@442: def RefreshPLCParams(self): laurent@442: self.Freeze() laurent@442: self.ClearSizer(self.PLCParamsSizer) laurent@442: laurent@442: if self.PluginRoot is not None: laurent@442: plcwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1)) laurent@442: if self.PluginRoot.PlugTestModified(): laurent@442: bkgdclr = CHANGED_TITLE_COLOUR laurent@442: else: laurent@442: bkgdclr = TITLE_COLOUR laurent@442: laurent@442: if self.PluginRoot not in self.PluginInfos: laurent@442: self.PluginInfos[self.PluginRoot] = {"right_visible" : False} laurent@442: laurent@442: plcwindow.SetBackgroundColour(TITLE_COLOUR) laurent@442: plcwindow.Bind(wx.EVT_LEFT_DOWN, self.OnPanelLeftDown) laurent@442: self.PLCParamsSizer.AddWindow(plcwindow, 0, border=0, flag=wx.GROW) laurent@442: laurent@442: plcwindowsizer = wx.BoxSizer(wx.HORIZONTAL) laurent@442: plcwindow.SetSizer(plcwindowsizer) laurent@442: laurent@442: st = wx.StaticText(plcwindow, -1) laurent@442: st.SetFont(wx.Font(faces["size"], wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"])) laurent@442: st.SetLabel(self.PluginRoot.GetProjectName()) laurent@442: plcwindowsizer.AddWindow(st, 0, border=5, flag=wx.ALL|wx.ALIGN_CENTER) laurent@442: laurent@442: plcwindowmainsizer = wx.BoxSizer(wx.VERTICAL) laurent@442: plcwindowsizer.AddSizer(plcwindowmainsizer, 0, border=5, flag=wx.ALL) laurent@442: laurent@442: plcwindowbuttonsizer = wx.BoxSizer(wx.HORIZONTAL) laurent@442: plcwindowmainsizer.AddSizer(plcwindowbuttonsizer, 0, border=0, flag=wx.ALIGN_CENTER) laurent@442: laurent@442: msizer = self.GenerateMethodButtonSizer(self.PluginRoot, plcwindow, not self.PluginInfos[self.PluginRoot]["right_visible"]) laurent@442: plcwindowbuttonsizer.AddSizer(msizer, 0, border=0, flag=wx.GROW) laurent@442: laurent@442: self.PLCConfigMainSizer.Layout() laurent@442: self.RefreshScrollBars() laurent@442: self.Thaw() laurent@442: laurent@442: def GenerateTreeBranch(self, plugin): laurent@442: leftwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1)) laurent@442: if plugin.PlugTestModified(): laurent@442: bkgdclr=CHANGED_WINDOW_COLOUR laurent@442: else: laurent@442: bkgdclr=WINDOW_COLOUR laurent@442: laurent@442: leftwindow.SetBackgroundColour(bkgdclr) laurent@442: laurent@442: if plugin not in self.PluginInfos: laurent@442: self.PluginInfos[plugin] = {"expanded" : False, "left_visible" : False, "right_visible" : False} laurent@442: laurent@442: self.PluginInfos[plugin]["children"] = plugin.IECSortedChilds() laurent@442: plugin_infos = plugin.GetVariableLocationTree() laurent@442: plugin_locations = [] laurent@442: if len(self.PluginInfos[plugin]["children"]) == 0: laurent@442: plugin_locations = plugin_infos["children"] laurent@442: if not self.PluginInfos[plugin].has_key("locations_infos"): laurent@442: self.PluginInfos[plugin]["locations_infos"] = {"root": {"expanded" : False}} laurent@442: laurent@442: self.PluginInfos[plugin]["locations_infos"]["root"]["children"] = [] laurent@442: laurent@442: self.PluginTreeSizer.AddWindow(leftwindow, 0, border=0, flag=wx.GROW) laurent@442: laurent@442: leftwindowsizer = wx.BoxSizer(wx.HORIZONTAL) laurent@442: leftwindow.SetSizer(leftwindowsizer) laurent@442: laurent@442: st = wx.StaticText(leftwindow, -1) laurent@442: st.SetFont(wx.Font(faces["size"], wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"])) laurent@442: st.SetLabel(plugin.GetFullIEC_Channel()) laurent@442: leftwindowsizer.AddWindow(st, 0, border=5, flag=wx.RIGHT) laurent@442: laurent@442: expandbutton_id = wx.NewId() laurent@442: expandbutton = wx.lib.buttons.GenBitmapToggleButton(id=expandbutton_id, bitmap=wx.Bitmap(Bpath( 'images', 'plus.png')), laurent@442: name='ExpandButton', parent=leftwindow, pos=wx.Point(0, 0), laurent@442: size=wx.Size(13, 13), style=wx.NO_BORDER) laurent@442: expandbutton.labelDelta = 0 laurent@442: expandbutton.SetBezelWidth(0) laurent@442: expandbutton.SetUseFocusIndicator(False) laurent@442: expandbutton.SetBitmapSelected(wx.Bitmap(Bpath( 'images', 'minus.png'))) laurent@442: laurent@442: if len(self.PluginInfos[plugin]["children"]) > 0: laurent@442: expandbutton.SetToggle(self.PluginInfos[plugin]["expanded"]) laurent@442: def togglebutton(event): laurent@442: if expandbutton.GetToggle(): laurent@442: self.ExpandPlugin(plugin) laurent@442: else: laurent@442: self.CollapsePlugin(plugin) laurent@442: self.PluginInfos[plugin]["expanded"] = expandbutton.GetToggle() laurent@442: self.PLCConfigMainSizer.Layout() laurent@442: self.RefreshScrollBars() laurent@442: event.Skip() laurent@442: expandbutton.Bind(wx.EVT_BUTTON, togglebutton, id=expandbutton_id) laurent@442: elif len(plugin_locations) > 0: laurent@442: locations_infos = self.PluginInfos[plugin]["locations_infos"] laurent@442: expandbutton.SetToggle(locations_infos["root"]["expanded"]) laurent@442: def togglebutton(event): laurent@442: if expandbutton.GetToggle(): laurent@442: self.ExpandLocation(locations_infos, "root") laurent@442: else: laurent@442: self.CollapseLocation(locations_infos, "root") laurent@442: self.PluginInfos[plugin]["expanded"] = expandbutton.GetToggle() laurent@442: locations_infos["root"]["expanded"] = expandbutton.GetToggle() laurent@442: self.PLCConfigMainSizer.Layout() laurent@442: self.RefreshScrollBars() laurent@442: event.Skip() laurent@442: expandbutton.Bind(wx.EVT_BUTTON, togglebutton, id=expandbutton_id) laurent@442: else: laurent@442: expandbutton.Enable(False) laurent@442: leftwindowsizer.AddWindow(expandbutton, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL) laurent@442: laurent@442: sb = wx.StaticBitmap(leftwindow, -1) laurent@442: icon = plugin_infos.get("icon", None) laurent@442: if icon is None: laurent@442: icon = os.path.join(base_folder, "plcopeneditor", 'Images', '%s.png' % self.LOCATION_BITMAP[plugin_infos["type"]]) laurent@442: sb.SetBitmap(wx.Bitmap(icon)) laurent@442: leftwindowsizer.AddWindow(sb, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL) laurent@442: laurent@442: st_id = wx.NewId() laurent@442: st = wx.StaticText(leftwindow, st_id, size=wx.DefaultSize, style=wx.NO_BORDER) laurent@442: st.SetFont(wx.Font(faces["size"] * 0.75, wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"])) laurent@442: st.SetLabel(plugin.MandatoryParams[1].getName()) laurent@442: leftwindowsizer.AddWindow(st, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL) laurent@442: laurent@442: rightwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1)) laurent@442: rightwindow.SetBackgroundColour(bkgdclr) laurent@442: laurent@442: self.PluginTreeSizer.AddWindow(rightwindow, 0, border=0, flag=wx.GROW) laurent@442: laurent@442: self.PluginInfos[plugin]["left"] = leftwindow laurent@442: self.PluginInfos[plugin]["right"] = rightwindow laurent@442: for child in self.PluginInfos[plugin]["children"]: laurent@442: self.GenerateTreeBranch(child) laurent@442: if not self.PluginInfos[child]["expanded"]: laurent@442: self.CollapsePlugin(child) laurent@442: if len(plugin_locations) > 0: laurent@442: locations_infos = self.PluginInfos[plugin]["locations_infos"] laurent@442: for location in plugin_locations: laurent@442: locations_infos["root"]["children"].append("root.%s" % location["name"]) laurent@442: self.GenerateLocationTreeBranch(locations_infos, "root", location) laurent@442: if not locations_infos["root"]["expanded"]: laurent@442: self.CollapseLocation(locations_infos, "root") laurent@442: laurent@442: frame = None laurent@442: laurent@442: def BeremizStartProc(plugin_root): laurent@442: global frame laurent@442: laurent@442: app = wx.PySimpleApp() laurent@442: app.SetAppName('beremiz') laurent@442: wx.InitAllImageHandlers() laurent@442: laurent@442: # Get the english language laurent@442: langid = wx.LANGUAGE_ENGLISH laurent@442: # Import module for internationalization laurent@442: import gettext laurent@442: import __builtin__ laurent@442: laurent@442: # Define locale for wx laurent@442: loc = wx.Locale(langid) laurent@442: for localedir in PseudoLocale.LocaleDirs: laurent@442: loc.AddCatalogLookupPathPrefix(localedir) laurent@442: for domain in PseudoLocale.Domains: laurent@442: loc.AddCatalog(domain) laurent@442: laurent@442: __builtin__.__dict__['_'] = wx.GetTranslation#unicode_translation laurent@442: laurent@442: # Install a exception handle for bug reports laurent@442: AddExceptHook(os.getcwd(),__version__) laurent@442: laurent@442: frame = LPCBeremiz(None, plugin_root=plugin_root, debug=False) laurent@442: plugin_root.SetAppFrame(frame, frame.Log) laurent@442: frame.Show() laurent@442: laurent@442: app.MainLoop() laurent@442: laurent@442: class StdoutPseudoFile: laurent@442: """ Base class for file like objects to facilitate StdOut for the Shell.""" laurent@442: def write(self, s, style = None): laurent@442: if s != '': laurent@442: print s laurent@442: laurent@442: def write_warning(self, s): laurent@442: self.write(s) laurent@442: laurent@442: def write_error(self, s): laurent@442: self.write(s) laurent@442: laurent@442: def flush(self): laurent@442: pass laurent@442: laurent@442: def isatty(self): laurent@442: return false laurent@442: laurent@442: if __name__ == '__main__': laurent@442: laurent@442: from threading import Thread, Timer laurent@442: import cmd laurent@442: laurent@442: class LPCBeremiz_Cmd(cmd.Cmd): laurent@442: laurent@442: prompt = "" laurent@442: Log = StdoutPseudoFile() laurent@442: RefreshTimer = None laurent@442: laurent@442: def __init__(self, projectOpen, buildpath): laurent@442: cmd.Cmd.__init__(self) laurent@442: self.PluginRoot = LPCPluginsRoot(None, self.Log) laurent@442: if projectOpen is not None and os.path.isfile(projectOpen): laurent@442: result = self.PluginRoot.LoadProject(projectOpen, buildpath) laurent@442: if result: laurent@442: print "Error: Invalid project directory", result laurent@442: else: laurent@442: print "Error: No such file or directory" laurent@442: laurent@442: def RestartTimer(self): laurent@442: if self.RefreshTimer is not None: laurent@442: self.RefreshTimer.cancel() laurent@442: self.RefreshTimer = Timer(0.1, self.Refresh) laurent@442: self.RefreshTimer.start() laurent@442: laurent@442: def Exit(self): laurent@442: self.Close() laurent@442: return True laurent@442: laurent@442: def do_EOF(self, line): laurent@442: return self.Exit() laurent@442: laurent@442: def Show(self): laurent@442: beremiz_thread=Thread(target=BeremizStartProc, args=[self.PluginRoot]) laurent@442: beremiz_thread.start() laurent@442: laurent@442: def Refresh(self): laurent@442: global frame laurent@442: if frame is not None: laurent@442: wx.CallAfter(frame.RefreshAll) laurent@442: laurent@442: def Close(self): laurent@442: global frame laurent@442: laurent@442: self.PluginRoot.ResetAppFrame(self.Log) laurent@442: if frame is not None: laurent@442: wx.CallAfter(frame.Close) laurent@442: laurent@442: def Compile(self): laurent@442: if wx.GetApp() is None: laurent@442: self.PluginRoot._build() laurent@442: else: laurent@442: wx.CallAfter(self.PluginRoot._build) laurent@442: laurent@442: def SetProjectName(self, name): laurent@442: self.PluginRoot.SetProjectName(name) laurent@442: self.RestartTimer() laurent@442: laurent@442: def AddBus(self, iec_channel, name, icon=None): laurent@442: for child in self.PluginRoot.IterChilds(): laurent@442: if child.BaseParams.getName() == name: laurent@442: return "Error: A bus named %s already exists" % name laurent@442: elif child.BaseParams.getIEC_Channel() == iec_channel: laurent@442: return "Error: A bus with IEC_channel %d already exists" % iec_channel laurent@442: bus = self.PluginRoot.PlugAddChild(name, "LPCBus", iec_channel) laurent@442: if bus is None: laurent@442: return "Error: Unable to create bus" laurent@442: bus.SetIcon(icon) laurent@442: self.RestartTimer() laurent@442: laurent@442: def RenameBus(self, iec_channel, name): laurent@442: bus = self.PluginRoot.GetChildByIECLocation((iec_channel,)) laurent@442: if bus is None: laurent@442: return "Error: No bus found" laurent@442: for child in self.PluginRoot.IterChilds(): laurent@442: if child != bus and child.BaseParams.getName() == name: laurent@442: return "Error: A bus named %s already exists" % name laurent@442: bus.BaseParams.setName(name) laurent@442: self.RestartTimer() laurent@442: laurent@442: def ChangeBusIECChannel(self, old_iec_channel, new_iec_channel): laurent@442: bus = self.PluginRoot.GetChildByIECLocation((old_iec_channel,)) laurent@442: if bus is None: laurent@442: return "Error: No bus found" laurent@442: for child in self.PluginRoot.IterChilds(): laurent@442: if child != bus and child.BaseParams.getIEC_Channel() == new_iec_channel: laurent@442: return "Error: A bus with IEC_channel %d already exists" % new_iec_channel laurent@442: bus.BaseParams.setIEC_Channel(new_iec_channel) laurent@442: self.RestartTimer() laurent@442: laurent@442: def RemoveBus(self, iec_channel): laurent@442: bus = self.PluginRoot.GetChildByIECLocation((iec_channel,)) laurent@442: if bus is None: laurent@442: return "Error: No bus found" laurent@442: self.PluginRoot.PluggedChilds["LPCBus"].remove(bus) laurent@442: self.RestartTimer() laurent@442: laurent@442: def AddModule(self, parent, iec_channel, name, icon=None): laurent@442: module = self.PluginRoot.GetChildByIECLocation(parent) laurent@442: if module is None: laurent@442: return "Error: No parent found" laurent@442: for child in _GetModuleChildren(module): laurent@442: if child["name"] == name: laurent@442: return "Error: A module named %s already exists" % name laurent@442: elif child["IEC_Channel"] == iec_channel: laurent@442: return "Error: A module with IEC_channel %d already exists" % iec_channel laurent@442: _GetLastModuleGroup(module).append({"name": name, laurent@442: "type": LOCATION_MODULE, laurent@442: "IEC_Channel": iec_channel, laurent@442: "icon": icon, laurent@442: "children": []}) laurent@442: self.RestartTimer() laurent@442: laurent@442: def RenameModule(self, iec_location, name): laurent@442: module = self.PluginRoot.GetChildByIECLocation(iec_location) laurent@442: if module is None: laurent@442: return "Error: No module found" laurent@442: parent = self.PluginRoot.GetChildByIECLocation(iec_location[:-1]) laurent@442: if parent is self.PluginRoot: laurent@442: return "Error: No module found" laurent@442: if module["name"] != name: laurent@442: for child in _GetModuleChildren(parent): laurent@442: if child["name"] == name: laurent@442: return "Error: A module named %s already exists" % name laurent@442: module["name"] = name laurent@442: self.RestartTimer() laurent@442: laurent@442: def ChangeModuleIECChannel(self, old_iec_location, new_iec_channel): laurent@442: module = self.PluginRoot.GetChildByIECLocation(old_iec_location) laurent@442: if module is None: laurent@442: return "Error: No module found" laurent@442: parent = self.PluginRoot.GetChildByIECLocation(old_iec_location[:-1]) laurent@442: if parent is self.PluginRoot: laurent@442: return "Error: No module found" laurent@442: if module["IEC_Channel"] != new_iec_channel: laurent@442: for child in _GetModuleChildren(parent): laurent@442: if child["IEC_Channel"] == new_iec_channel: laurent@442: return "Error: A module with IEC_channel %d already exists" % new_iec_channel laurent@442: module["IEC_Channel"] = new_iec_channel laurent@442: self.RestartTimer() laurent@442: laurent@442: def RemoveModule(self, parent, iec_channel): laurent@442: module = self.PluginRoot.GetChildByIECLocation(parent) laurent@442: if module is None: laurent@442: return "Error: No parent found" laurent@442: child = _GetModuleBySomething(module, "IEC_Channel", (iec_channel,)) laurent@442: if child is None: laurent@442: return "Error: No module found" laurent@442: _RemoveModuleChild(module, child) laurent@442: self.RestartTimer() laurent@442: laurent@442: def StartGroup(self, parent, name, icon=None): laurent@442: module = self.PluginRoot.GetChildByIECLocation(parent) laurent@442: if module is None: laurent@442: return "Error: No parent found" laurent@442: for child in module["children"]: laurent@442: if child["type"] == LOCATION_GROUP and child["name"] == name: laurent@442: return "Error: A group named %s already exists" % name laurent@442: module["children"].append({"name": name, laurent@442: "type": LOCATION_GROUP, laurent@442: "icon": icon, laurent@442: "children": []}) laurent@442: self.RestartTimer() laurent@442: laurent@442: def AddVariable(self, parent, location, name, direction, type, dcode, rcode, pcode, description=""): laurent@442: module = self.PluginRoot.GetChildByIECLocation(parent) laurent@442: if module is None: laurent@442: return "Error: No parent found" laurent@442: for child in _GetModuleChildren(module): laurent@442: if child["name"] == name: laurent@442: return "Error: A variable named %s already exists" % name laurent@442: if child["location"] == location: laurent@442: return "Error: A variable with location %s already exists" % ".".join(map(str, location)) laurent@442: _GetLastModuleGroup(module).append({"name": name, laurent@442: "location": location, laurent@442: "type": LOCATION_TYPES[direction], laurent@442: "IEC_type": type, laurent@442: "description": description, laurent@442: "declare": dcode, laurent@442: "retrieve": rcode, laurent@442: "publish": pcode}) laurent@442: self.RestartTimer() laurent@442: laurent@442: def ChangeVariableParams(self, parent, location, new_name, new_direction, new_type, new_dcode, new_rcode, new_pcode, new_description=None): laurent@442: module = self.PluginRoot.GetChildByIECLocation(parent) laurent@442: if module is None: laurent@442: return "Error: No parent found" laurent@442: variable = None laurent@442: for child in _GetModuleChildren(module): laurent@442: if child["location"] == location: laurent@442: variable = child laurent@442: elif child["name"] == new_name: laurent@442: return "Error: A variable named %s already exists" % new_name laurent@442: if variable is None: laurent@442: return "Error: No variable found" laurent@442: variable["name"] = new_name laurent@442: variable["type"] = LOCATION_TYPES[new_direction] laurent@442: variable["IEC_type"] = new_type laurent@442: variable["declare"] = new_dcode laurent@442: variable["retrieve"] = new_rcode laurent@442: variable["publish"] = new_pcode laurent@442: if new_description is not None: laurent@442: variable["description"] = new_description laurent@442: self.RestartTimer() laurent@442: laurent@442: def RemoveVariable(self, parent, location): laurent@442: module = self.PluginRoot.GetChildByIECLocation(parent) laurent@442: if module is None: laurent@442: return "Error: No parent found" laurent@442: child = _GetModuleVariable(module, location) laurent@442: if child is None: laurent@442: return "Error: No variable found" laurent@442: _RemoveModuleChild(module, child) laurent@442: self.RestartTimer() laurent@442: laurent@442: def location(loc): laurent@442: return tuple(map(int, loc.split("."))) laurent@442: laurent@442: def GetCmdFunction(function, arg_types, opt=0): laurent@442: arg_number = len(arg_types) laurent@442: def CmdFunction(self, line): laurent@442: args_toks = line.split('"') laurent@442: if len(args_toks) % 2 == 0: laurent@442: print "Error: Invalid command" laurent@442: return laurent@442: args = [] laurent@442: for num, arg in enumerate(args_toks): laurent@442: if num % 2 == 0: laurent@442: stripped = arg.strip() laurent@442: if stripped: laurent@442: args.extend(stripped.split(" ")) laurent@442: else: laurent@442: args.append(arg) laurent@442: number = None laurent@442: extra = "" laurent@442: if opt == 0 and len(args) != arg_number: laurent@442: number = arg_number laurent@442: elif len(args) > arg_number: laurent@442: number = arg_number laurent@442: extra = " at most" laurent@442: elif len(args) < arg_number - opt: laurent@442: number = arg_number - opt laurent@442: extra = " at least" laurent@442: if number is not None: laurent@442: if number == 0: laurent@442: print "Error: No argument%s expected" % extra laurent@442: elif number == 1: laurent@442: print "Error: 1 argument%s expected" % extra laurent@442: else: laurent@442: print "Error: %d arguments%s expected" % (number, extra) laurent@442: return laurent@442: for num, arg in enumerate(args): laurent@442: try: laurent@442: args[num] = arg_types[num](arg) laurent@442: except: laurent@442: print "Error: Invalid value for argument %d" % (num + 1) laurent@442: return laurent@442: res = getattr(self, function)(*args) laurent@442: if isinstance(res, (StringType, UnicodeType)): laurent@442: print res laurent@442: return False laurent@442: else: laurent@442: return res laurent@442: return CmdFunction laurent@442: laurent@442: for function, (arg_types, opt) in {"Exit": ([], 0), laurent@442: "Show": ([], 0), laurent@442: "Refresh": ([], 0), laurent@442: "Close": ([], 0), laurent@442: "Compile": ([], 0), laurent@442: "SetProjectName": ([str], 0), laurent@442: "AddBus": ([int, str, str], 1), laurent@442: "RenameBus": ([int, str], 0), laurent@442: "ChangeBusIECChannel": ([int, int], 0), laurent@442: "RemoveBus": ([int], 0), laurent@442: "AddModule": ([location, int, str, str], 1), laurent@442: "RenameModule": ([location, str], 0), laurent@442: "ChangeModuleIECChannel": ([location, int], 0), laurent@442: "RemoveModule": ([location, int], 0), laurent@442: "StartGroup": ([location, str, str], 1), laurent@442: "AddVariable": ([location, location, str, str, str, str, str, str], 1), laurent@442: "ChangeVariableParams": ([location, location, str, str, str, str, str, str, str, str], 1), laurent@442: "RemoveVariable": ([location, location], 0)}.iteritems(): laurent@442: laurent@442: setattr(LPCBeremiz_Cmd, "do_%s" % function, GetCmdFunction(function, arg_types, opt)) laurent@442: laurent@442: lpcberemiz_cmd = LPCBeremiz_Cmd(projectOpen, buildpath) laurent@442: lpcberemiz_cmd.cmdloop() laurent@442: