LPCBeremiz.py
changeset 547 5748d695beee
parent 543 3dec6ff88620
child 549 5dd92bd6e6e5
equal deleted inserted replaced
546:093a20ea5ffc 547:5748d695beee
    40         buildpath = args[1]
    40         buildpath = args[1]
    41     else:
    41     else:
    42         projectOpen = None
    42         projectOpen = None
    43         buildpath = None
    43         buildpath = None
    44     
    44     
    45 class PseudoLocale:
    45 
    46     LocaleDirs = []
    46 app = wx.PySimpleApp()
    47     Domains = []
    47 app.SetAppName('beremiz')
    48     
    48 wx.InitAllImageHandlers()
    49     def AddCatalogLookupPathPrefix(self, localedir):
       
    50         self.LocaleDirs.append(localedir)
       
    51     
       
    52     def AddCatalog(self, domain):
       
    53         self.Domains.append(domain)
       
    54 
    49 
    55 # Import module for internationalization
    50 # Import module for internationalization
    56 import gettext
    51 import gettext
    57 import __builtin__
    52 import __builtin__
    58 
       
    59 # Define locale for wx
       
    60 __builtin__.__dict__['loc'] = PseudoLocale()
       
    61 
    53 
    62 if __name__ == '__main__':
    54 if __name__ == '__main__':
    63     __builtin__.__dict__['_'] = wx.GetTranslation#unicode_translation
    55     __builtin__.__dict__['_'] = wx.GetTranslation#unicode_translation
    64 
    56 
    65 from Beremiz import *
    57 from Beremiz import *
  1057                 locations_infos["root"]["children"].append("root.%s" % location["name"])
  1049                 locations_infos["root"]["children"].append("root.%s" % location["name"])
  1058                 self.GenerateLocationTreeBranch(locations_infos, "root", location)
  1050                 self.GenerateLocationTreeBranch(locations_infos, "root", location)
  1059             if not locations_infos["root"]["expanded"]:
  1051             if not locations_infos["root"]["expanded"]:
  1060                 self.CollapseLocation(locations_infos, "root")
  1052                 self.CollapseLocation(locations_infos, "root")
  1061 
  1053 
  1062 frame = None
       
  1063 app = None
       
  1064 
       
  1065 def MainLoopProc(plugin_root):
       
  1066     global frame, app
       
  1067     
       
  1068     app = wx.PySimpleApp()
       
  1069     app.SetAppName('beremiz')
       
  1070     wx.InitAllImageHandlers()
       
  1071     
       
  1072     # Get the english language
       
  1073     langid = wx.LANGUAGE_ENGLISH
       
  1074     # Import module for internationalization
       
  1075     import gettext
       
  1076     import __builtin__
       
  1077     
       
  1078     # Define locale for wx
       
  1079     loc = wx.Locale(langid)
       
  1080     for localedir in PseudoLocale.LocaleDirs:
       
  1081         loc.AddCatalogLookupPathPrefix(localedir)
       
  1082     for domain in PseudoLocale.Domains:
       
  1083         loc.AddCatalog(domain)
       
  1084     
       
  1085     __builtin__.__dict__['_'] = wx.GetTranslation#unicode_translation
       
  1086     
       
  1087     # Install a exception handle for bug reports
       
  1088     AddExceptHook(os.getcwd(),__version__)
       
  1089     
       
  1090     frame = LPCBeremiz(None, plugin_root=plugin_root, debug=True)
       
  1091     
       
  1092     app.MainLoop()
       
  1093     
       
  1094 class StdoutPseudoFile:
  1054 class StdoutPseudoFile:
  1095     """ Base class for file like objects to facilitate StdOut for the Shell."""
  1055     """ Base class for file like objects to facilitate StdOut for the Shell."""
  1096     def write(self, s, style = None):
  1056     def write(self, s, style = None):
  1097         if s != '':
  1057         if s != '':
  1098             print s
  1058             print s
  1109     def isatty(self):
  1069     def isatty(self):
  1110         return false
  1070         return false
  1111 
  1071 
  1112 if __name__ == '__main__':
  1072 if __name__ == '__main__':
  1113     
  1073     
  1114     from threading import Thread, Timer
  1074     from threading import Thread, Timer, Semaphore
  1115     import cmd
  1075     import cmd
  1116 
  1076 
       
  1077     wx_eval_lock = Semaphore(0)
       
  1078     eval_res = None
       
  1079     def wx_evaluator(callable, *args, **kwargs):
       
  1080         global eval_res
       
  1081         eval_res = None
       
  1082         try:
       
  1083             eval_res=callable(*args,**kwargs)
       
  1084         finally:
       
  1085             wx_eval_lock.release()
       
  1086 
       
  1087     def evaluator(callable, *args, **kwargs):
       
  1088         global eval_res
       
  1089         wx.CallAfter(wx_evaluator,callable,*args,**kwargs)
       
  1090         wx_eval_lock.acquire()
       
  1091         return eval_res
       
  1092 
       
  1093     # Command log for debug, for viewing from wxInspector
       
  1094     __builtins__.cmdlog = []
       
  1095     cmdlogf=open("bmzcmdlog.txt","w")
       
  1096 
  1117     class LPCBeremiz_Cmd(cmd.Cmd):
  1097     class LPCBeremiz_Cmd(cmd.Cmd):
  1118         
  1098         
  1119         prompt = ""
  1099         prompt = ""
  1120         Log = StdoutPseudoFile()
       
  1121         RefreshTimer = None
  1100         RefreshTimer = None
  1122         
  1101         
  1123         def __init__(self, projectOpen, buildpath):
  1102         def __init__(self, PluginRoot, Log):
  1124             cmd.Cmd.__init__(self)
  1103             cmd.Cmd.__init__(self)
  1125             self.PluginRoot = LPCPluginsRoot(None, self.Log)
  1104             self.Log = Log
  1126             if projectOpen is not None and os.path.isdir(projectOpen):
  1105             self.PluginRoot = PluginRoot
  1127                 result = self.PluginRoot.LoadProject(projectOpen, buildpath)
       
  1128                 if result:
       
  1129                     print "Error: Invalid project directory", result
       
  1130             else:
       
  1131                 print "Error: No such file or directory"
       
  1132             beremiz_thread=Thread(target=MainLoopProc, args=[self.PluginRoot])
       
  1133             beremiz_thread.start()
       
  1134             
  1106             
  1135         def RestartTimer(self):
  1107         def RestartTimer(self):
  1136             if self.RefreshTimer is not None:
  1108             if self.RefreshTimer is not None:
  1137                 self.RefreshTimer.cancel()
  1109                 self.RefreshTimer.cancel()
  1138             self.RefreshTimer = Timer(0.1, self.Refresh)
  1110             self.RefreshTimer = Timer(0.1, wx.CallAfter, args = [self.Refresh])
  1139             self.RefreshTimer.start()
  1111             self.RefreshTimer.start()
  1140         
  1112         
  1141         def Exit(self):
  1113         def Exit(self):
  1142             global frame, app
  1114             global frame, app
  1143             self.Close()
  1115             self.Close()
  1149         
  1121         
  1150         def Show(self):
  1122         def Show(self):
  1151             global frame
  1123             global frame
  1152             if frame is not None:
  1124             if frame is not None:
  1153                 self.PluginRoot.SetAppFrame(frame, frame.Log)
  1125                 self.PluginRoot.SetAppFrame(frame, frame.Log)
  1154                 wx.CallAfter(frame.Show)
  1126                 frame.Show()
  1155                 wx.CallAfter(frame.Raise)
  1127                 frame.Raise()
  1156         
  1128         
  1157         def Refresh(self):
  1129         def Refresh(self):
  1158             global frame
  1130             global frame
  1159             if frame is not None:
  1131             if frame is not None:
  1160                 wx.CallAfter(frame._Refresh, TITLE, INSTANCESTREE, FILEMENU, EDITMENU)
  1132                 frame._Refresh(TITLE, INSTANCESTREE, FILEMENU, EDITMENU)
  1161                 wx.CallAfter(frame.RefreshEditor)
  1133                 frame.RefreshEditor()
  1162                 wx.CallAfter(frame.RefreshAll)
  1134                 frame.RefreshAll()
  1163         
  1135         
  1164         def Close(self):
  1136         def Close(self):
  1165             global frame
  1137             global frame
  1166             
  1138             
  1167             self.PluginRoot.ResetAppFrame(self.Log)
  1139             self.PluginRoot.ResetAppFrame(self.Log)
  1168             if frame is not None:
  1140             if frame is not None:
  1169                 wx.CallAfter(frame.Hide)
  1141                 frame.Hide()
  1170         
  1142         
  1171         def Compile(self):
  1143         def Compile(self):
  1172             wx.CallAfter(self.PluginRoot._build)
  1144             self.PluginRoot._build()
  1173         
  1145         
  1174         def SetProjectProperties(self, projectname, productname, productversion, companyname):
  1146         def SetProjectProperties(self, projectname, productname, productversion, companyname):
  1175             properties = self.PluginRoot.GetProjectProperties()
  1147             properties = self.PluginRoot.GetProjectProperties()
  1176             properties["projectName"] = projectname
  1148             properties["projectName"] = projectname
  1177             properties["productName"] = productname
  1149             properties["productName"] = productname
  1179             properties["companyName"] = companyname
  1151             properties["companyName"] = companyname
  1180             self.PluginRoot.SetProjectProperties(properties=properties)
  1152             self.PluginRoot.SetProjectProperties(properties=properties)
  1181             self.RestartTimer()
  1153             self.RestartTimer()
  1182         
  1154         
  1183         def SetOnlineMode(self, mode, path=None):
  1155         def SetOnlineMode(self, mode, path=None):
  1184             wx.CallAfter(self.PluginRoot.SetOnlineMode, mode, path)
  1156             self.PluginRoot.SetOnlineMode(mode, path)
  1185             self.RestartTimer()
  1157             self.RestartTimer()
  1186         
  1158         
  1187         def AddBus(self, iec_channel, name, icon=None):
  1159         def AddBus(self, iec_channel, name, icon=None):
  1188             for child in self.PluginRoot.IterChilds():
  1160             for child in self.PluginRoot.IterChilds():
  1189                 if child.BaseParams.getName() == name:
  1161                 if child.BaseParams.getName() == name:
  1215                     return "Error: A bus with IEC_channel %d already exists" % new_iec_channel
  1187                     return "Error: A bus with IEC_channel %d already exists" % new_iec_channel
  1216             if wx.GetApp() is None:
  1188             if wx.GetApp() is None:
  1217                 self.PluginRoot.UpdateProjectVariableLocation(str(old_iec_channel), 
  1189                 self.PluginRoot.UpdateProjectVariableLocation(str(old_iec_channel), 
  1218                                                               str(new_iec_channel))
  1190                                                               str(new_iec_channel))
  1219             else:
  1191             else:
  1220                 wx.CallAfter(self.PluginRoot.UpdateProjectVariableLocation,
  1192                 self.PluginRoot.UpdateProjectVariableLocation(
  1221                              str(old_iec_channel), 
  1193                              str(old_iec_channel), 
  1222                              str(new_iec_channel))
  1194                              str(new_iec_channel))
  1223             bus.BaseParams.setIEC_Channel(new_iec_channel)
  1195             bus.BaseParams.setIEC_Channel(new_iec_channel)
  1224             self.RestartTimer()
  1196             self.RestartTimer()
  1225         
  1197         
  1399                     args[num] = arg_types[num](arg)
  1371                     args[num] = arg_types[num](arg)
  1400                 except:
  1372                 except:
  1401                     print "Error: Invalid value for argument %d" % (num + 1)
  1373                     print "Error: Invalid value for argument %d" % (num + 1)
  1402                     sys.stdout.flush()
  1374                     sys.stdout.flush()
  1403                     return
  1375                     return
  1404             res = getattr(self, function)(*args)
  1376 
       
  1377             cmdlogf.write(str((function,line))+'\n')
       
  1378 
       
  1379             func = getattr(self, function)
       
  1380             res = evaluator(func,*args)
       
  1381 
       
  1382             # Keep log for debug
       
  1383             cmdlogf.write("--->"+str(res)+'\n')
       
  1384             cmdlog.append((function,line,res))
       
  1385             if len(cmdlog) > 100: #prevent debug log to grow too much
       
  1386                 cmdlog.pop(0) 
       
  1387 
  1405             if isinstance(res, (StringType, UnicodeType)):
  1388             if isinstance(res, (StringType, UnicodeType)):
  1406                 print res
  1389                 print res
  1407                 sys.stdout.flush()
  1390                 sys.stdout.flush()
  1408                 return False
  1391                 return False
  1409             else:
  1392             else:
  1410                 return res
  1393                 return res
  1411         return CmdFunction
  1394         return CmdFunction
  1412     
  1395 
  1413     for function, (arg_types, opt) in {"Exit": ([], 0),
  1396     def CmdThreadProc(PluginRoot, Log):
  1414                                        "Show": ([], 0),
  1397         for function, (arg_types, opt) in {"Exit": ([], 0),
  1415                                        "Refresh": ([], 0),
  1398                                            "Show": ([], 0),
  1416                                        "Close": ([], 0),
  1399                                            "Refresh": ([], 0),
  1417                                        "Compile": ([], 0),
  1400                                            "Close": ([], 0),
  1418                                        "SetProjectProperties": ([str, str, str, str], 0),
  1401                                            "Compile": ([], 0),
  1419                                        "SetOnlineMode": ([str, str], 1),
  1402                                            "SetProjectProperties": ([str, str, str, str], 0),
  1420                                        "AddBus": ([int, str, str], 1),
  1403                                            "SetOnlineMode": ([str, str], 1),
  1421                                        "RenameBus": ([int, str], 0),
  1404                                            "AddBus": ([int, str, str], 1),
  1422                                        "ChangeBusIECChannel": ([int, int], 0),
  1405                                            "RenameBus": ([int, str], 0),
  1423                                        "RemoveBus": ([int], 0),
  1406                                            "ChangeBusIECChannel": ([int, int], 0),
  1424                                        "AddModule": ([location, int, str, str], 1), 
  1407                                            "RemoveBus": ([int], 0),
  1425                                        "RenameModule": ([location, str], 0),
  1408                                            "AddModule": ([location, int, str, str], 1), 
  1426                                        "ChangeModuleIECChannel": ([location, int], 0),
  1409                                            "RenameModule": ([location, str], 0),
  1427                                        "RemoveModule": ([location, int], 0),
  1410                                            "ChangeModuleIECChannel": ([location, int], 0),
  1428                                        "StartGroup": ([location, str, str], 1),
  1411                                            "RemoveModule": ([location, int], 0),
  1429                                        "AddVariable": ([location, location, str, str, str, str, str, str, str], 1),
  1412                                            "StartGroup": ([location, str, str], 1),
  1430                                        "ChangeVariableParams": ([location, location, str, str, str, str, str, str, str], 1),
  1413                                            "AddVariable": ([location, location, str, str, str, str, str, str, str], 1),
  1431                                        "RemoveVariable": ([location, location], 0)}.iteritems():
  1414                                            "ChangeVariableParams": ([location, location, str, str, str, str, str, str, str], 1),
  1432         
  1415                                            "RemoveVariable": ([location, location], 0)}.iteritems():
  1433         setattr(LPCBeremiz_Cmd, "do_%s" % function, GetCmdFunction(function, arg_types, opt))
  1416             
  1434     
  1417             setattr(LPCBeremiz_Cmd, "do_%s" % function, GetCmdFunction(function, arg_types, opt))
  1435     lpcberemiz_cmd = LPCBeremiz_Cmd(projectOpen, buildpath)
  1418         lpcberemiz_cmd = LPCBeremiz_Cmd(PluginRoot, Log)
  1436     lpcberemiz_cmd.cmdloop()
  1419         lpcberemiz_cmd.cmdloop()
  1437 
  1420 
       
  1421     Log = StdoutPseudoFile()
       
  1422 
       
  1423     PluginRoot = LPCPluginsRoot(None, Log)
       
  1424     if projectOpen is not None and os.path.isdir(projectOpen):
       
  1425         result = PluginRoot.LoadProject(projectOpen, buildpath)
       
  1426         if result:
       
  1427             print "Error: Invalid project directory", result
       
  1428     else:
       
  1429         print "Error: No such file or directory"
       
  1430     
       
  1431     cmd_thread=Thread(target=CmdThreadProc, args=[PluginRoot, Log])
       
  1432     cmd_thread.start()
       
  1433 
       
  1434     # Install a exception handle for bug reports
       
  1435     AddExceptHook(os.getcwd(),__version__)
       
  1436     
       
  1437     frame = LPCBeremiz(None, plugin_root=PluginRoot, debug=True)
       
  1438     
       
  1439     app.MainLoop()
       
  1440