def __init__(self, message): """ Initialize the dialog **Parameters:** * message: Error message to display """ ErrorDialog.REPORTER_ACTIVE = True # Get version from the app since the main window may be dead or # not even ready yet. #version = wx.GetApp().GetVersion() BaseDialog.__init__(self, Utilities.GetActiveWindow()) # Give message to ErrorReporter ErrorReporter().AddMessage(message) #self.SetIcon(wx.IconFromBitmap(CreateBitmap("GUI2Exe"))) self.SetTitle(_("Error/Crash Reporter")) # Attributes self.err_msg = "%s\n\n%s\n%s\n%s" % (Utilities.EnvironmentInfo(), \ "---- Traceback Info ----", \ ErrorReporter().GetErrorStack(), \ "---- End Traceback Info ----") self.textCtrl = wx.TextCtrl(self, value=self.err_msg, style=wx.TE_MULTILINE | wx.TE_READONLY) self.abortButton = wx.Button(self, wx.ID_CANCEL, size=(-1, 26)) self.sendButton = wx.Button(self, ID_SEND, _("Report Error"), size=(-1, 26)) self.sendButton.SetDefault() self.closeButton = wx.Button(self, wx.ID_CLOSE, size=(-1, 26)) # Layout self.DoLayout() # Event Handlers self.Bind(wx.EVT_BUTTON, self.OnButton) self.Bind(wx.EVT_CLOSE, self.OnClose) # Auto show at end of init self.CenterOnParent() self.ShowModal()
def recompile(modulename): """ recompile module from modulename """ ### modulename is file type if os.path.exists(modulename): zf = ZipManager.Zip(modulename) return zf.Recompile() else: ### first, see if the module can be imported at all... tmp = __import__(modulename, globals(), locals(), fromlist=[modulename.split(".")[-1]]) ### Use the imported module to determine its actual path pycfile = tmp.__file__ modulepath = string.replace(pycfile, ".pyc", ".py") ### Try to open the specified module as a file code = open(modulepath, "rU").read() ### see if the file we opened can compile. If not, return the error that it gives. ### if compile() fails, the module will not be replaced. try: compile(code, modulename, "exec") except: return ( "Error in compilation: " + str(sys.exc_info()[0]) + "\r\n" + Utilities.listf(format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) ) else: ### Ok, it compiled. But will it execute without error? try: execfile(modulepath) except Exception: # return "Error '%s' happened on line %d" % (info[0], info[1][1]) return ( "Error in execution: " + str(sys.exc_info()[0]) + "\r\n" + Utilities.listf(format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) ) else: ### at this point, the code both compiled and ran without error. Load it up ### replacing the original code. return reload(sys.modules[modulename])
def OnAdd(self, evt): path = self._dbb.GetValue() dName = os.path.basename(path) if not path.startswith('http') else filter(lambda a: a != '', path.split('/'))[-1] # si la lib n'est pas deja importee if not self.parent.tree.IsChildRoot(dName): if not self._d.has_key(dName) or (self._d.has_key(dName) and self._d[dName] != path): ### si importation a partir du local if os.path.isdir(path): self.DoAdd(path, dName) ### si importation a partir du web elif Utilities.checkURL(path): self.DoAdd(path, dName) ### gestion de l'erreur else: if path.startswith('http'): msg = _('%s is an invalid url') % path else: msg = _('%s directory does not exist') % dName dial = wx.MessageDialog(self, msg, _('Error'), wx.OK | wx.ICON_ERROR) dial.ShowModal() self._dbb.SetValue('') else: dial = wx.MessageDialog(self, _('%s is already imported') % dName, _('Info'), wx.OK) dial.ShowModal() self._dbb.SetValue('') else: dial = wx.MessageDialog(self, _('%s is already imported') % dName, _('Info'), wx.OK) dial.ShowModal() self._dbb.SetValue('') # on reactive le bouton pour un eventuel autre ajout self._btn_Add.Enable(True) ### ------------------------------------------------------------ # class TestApp(wx.App): # """ Testing application # """ # def OnInit(self): # import __builtin__ # import gettext # __builtin__.__dict__['HOME_PATH'] = os.getcwd() # __builtin__.__dict__['DOMAIN_PATH'] = 'Domain' # __builtin__.__dict__['_'] = gettext.gettext # frame = ImportLibrary(None, size=(600,600), id=-1, title="Test") # frame.Show() # return True # def OnQuit(self, event): # self.Close() # if __name__ == '__main__': # app = TestApp(0) # app.MainLoop()
def Populate(self, pluginsList): """ Populate method must be called just before construtor. """ if not self.is_populate: # all plugins file in plugins directory and already loaded # list of all file (without __init__.py) for root, dirs, files in pluginsList: ### dirs must contain python file if files: #for filename in filter(lambda f: not f.startswith('__') and f.endswith('.py'), files): for filename in filter(lambda f: f == "__init__.py", files): for basename in Utilities.getFileListFromInit( os.path.join(root, filename)): ### try to add dynamicaly pulgins #try: #t = threading.Thread(target=self.Importing, args=(root, basename,)) #t.start() #except Exception: #if wx.Platform == '__WXGTK__': ##i+=1 #wx.CallLater(500, self.Importing, root, basename,) #else: self.Importing(root, basename) self.is_populate = True
def CheckItem(self, path): """ """ item = self.ItemDico[path] file_path = "%s.py" % path info = Container.CheckClass(file_path) ### there is error in file if isinstance(info, tuple): ### Until it has parent, we redifine icon to inform user while item: ### change image self.SetItemImage(item, self.not_importedidx, wx.TreeItemIcon_Normal) ### next parent item item = self.GetItemParent(item) else: ### recompile if no error info = ReloadModule.recompile(Utilities.path_to_module(file_path)) ### if not error if not isinstance(info, (Exception, str)): ### change image self.SetItemImage(item, self.pythonfileidx, wx.TreeItemIcon_Normal)
def __init__(self, *args, **kwds): """ Constructor. """ kwds["style"] = wx.DEFAULT_FRAME_STYLE | wx.STAY_ON_TOP kwds["size"] = (400, 420) wx.Frame.__init__(self, *args, **kwds) self.panel = wx.Panel(self, wx.ID_ANY) self.button_clear = wx.Button(self.panel, wx.ID_CLEAR) self.button_step = wx.Button(self.panel, wx.ID_FORWARD) self.button_find = wx.Button(self.panel, wx.ID_FIND) self.button_selectall = wx.Button(self.panel, wx.ID_SELECTALL) self.txt = wx.TextCtrl(self.panel, wx.ID_ANY, style=wx.TE_MULTILINE | wx.TE_READONLY) Utilities.MoveFromParent(self, interval=10, direction='right') self.__set_properties() self.__do_layout() ### just for the start of the frame self.flag = True ### to close the frame when this attribute dont change self.lenght = self.txt.GetNumberOfLines() ### just for window self.SetClientSize(self.panel.GetBestSize()) self.Bind(wx.EVT_BUTTON, self.OnStep, id=self.button_step.GetId()) self.Bind(wx.EVT_BUTTON, self.OnClear, id=self.button_clear.GetId()) self.Bind(wx.EVT_BUTTON, self.OnSelectAll, id=self.button_selectall.GetId()) self.Bind(wx.EVT_BUTTON, self.OnFindReplace, id=self.button_find.GetId())
def AddItem(self, path, dName): """ Add item to the list """ index = self.InsertStringItem(sys.maxint, dName) self.SetStringItem(index, 1, str(Utilities.getDirectorySize(path)) if os.path.exists(path) else '0') self.SetStringItem(index, 2, 'local' if not path.startswith('http') else 'web') self.SetStringItem(index, 3, "..%s%s" % ( os.sep, os.path.basename(DOMAIN_PATH) if os.path.basename(DOMAIN_PATH) in path else os.path.basename(path))) self.SetData(index, path) self.SetItemData(index, index)
def PopulateDB(): """ """ subclasses = Utilities.itersubclasses(DumpBase) for cls in subclasses: for elem in cls.ext: # Impose un type de fichier par classe et non pas une classe par type de fichier. assert (elem not in DumpBase.DB.keys()) DumpBase.DB[elem] = cls
def OnItemDeselected(self, event): """ Item has been deselected """ line_number = self.getColumnText(self.currentItem, 2) python_path = self.getColumnText(self.currentItem, 4) if line_number != "": ### recuperation du model DEVS devs = Utilities.getInstance(Components.GetClass(python_path)) ### check error and change image if not isinstance(devs, tuple): self.SetItemImage(self.currentItem, self.idx2)
def OnItemRename(self, evt): item = self.GetSelection() path = self.GetItemPyData(item) bn = os.path.basename(path) dn = os.path.dirname(path) name, ext = os.path.splitext(bn) d = wx.TextEntryDialog(self, _('New file name'), defaultValue=name, style=wx.OK) d.ShowModal() ### new label new_label = d.GetValue() os.rename(path, os.path.join(dn, new_label) + ext) Utilities.replaceAll(os.path.join(dn, '__init__.py'), os.path.splitext(bn)[0], new_label) self.UpdateAll()
def AddItem(self, path, dName): """ Add item to the list """ index = self.InsertStringItem(sys.maxint, dName) self.SetStringItem( index, 1, str(Utilities.getDirectorySize(path)) if os.path.exists(path) else '0') self.SetStringItem(index, 2, 'local' if not path.startswith('http') else 'web') self.SetStringItem( index, 3, "..%s%s" % (os.sep, os.path.basename(DOMAIN_PATH) if os.path.basename( DOMAIN_PATH) in path else os.path.basename(path))) self.SetData(index, path) self.SetItemData(index, index)
def GetClass(elem): """ Get python class from filename. """ clsmembers = getClassMember(elem) if isinstance(clsmembers, dict): moduleName = Utilities.path_to_module(elem) for cls in clsmembers.values(): #print 'sdf', str(cls.__module__), moduleName, str(cls.__module__) in str(moduleName) if str(cls.__module__) in str(moduleName): return cls else: return clsmembers
def OnUpdate(self, evt): """ Update list has been invocked """ ### deep copy of data list D = copy.deepcopy(self.list.itemDataMap) ### update in error line self.list.itemDataMap for k, v in D.items(): line_number = v[2] if line_number != "": python_path = v[-1] devs = Utilities.getInstance(Components.GetClass(python_path)) ### check error and change image if not isinstance(devs, tuple): self.list.itemDataMap[k] = (v[0], "", "", v[3], v[4]) ### refresh items self.list.RefreshItems(-1, -1)
def InsertItem(self, root, basename): """ Insert plugin in list """ ### absolute name absname = os.path.join(root, "%s.py" % basename) ### file size size = Utilities.FormatSizeFile(os.path.getsize(absname)) ### date manager date = datetime.datetime.fromtimestamp(os.path.getmtime(absname)) if hasattr(self.mainW, 'language') and self.mainW.language == 'fr': date = date.strftime("%d/%m/%y") else: date = str(date.date()) # add to the CheckListCtrl index = self.InsertStringItem(sys.maxint, basename) self.SetStringItem(index, 1, size) self.SetStringItem(index, 2, date) return index
def DocDirectory(self, path): """ Return doc of all modules composing path directory by reading its __ini__.py """ ### init_file at first level ! init_file = os.path.join(path, '__init__.py') doc = "" ### if init_file exists in module if os.path.exists(init_file): ### get list of content filename lst = Utilities.getFileListFromInit(init_file) if lst: # for each python filename, inspect its module info for fn in lst: fn_path = os.path.join(path, fn + '.py') t = inspect.getmoduleinfo(fn_path) if t is not None: name, suffix, mode, module_type = t doc += _("---------- %s module :\n") % fn + \ _("\tname : %s\n") % name + \ _("\tsuffix : %s\n") % suffix + \ _("\tmode : %s\n") % mode + \ _("\ttype of module : %s\n") % module_type + \ _("\tpath : %s\n\n") % fn_path else: doc += _( "----------%s module not inspectable !\n") % fn #else: #pass #doc += _("%s is empty !\n")%init_file #else: #pass #doc += _("%s dont exist !\n")%init_file ### TODO take in charge also amd and cmd ! return doc
def DocDirectory(self, path): """ Return doc of all modules composing path directory by reading its __ini__.py """ ### init_file at first level ! init_file = os.path.join(path, '__init__.py') doc = "" ### if init_file exists in module if os.path.exists(init_file): ### get list of content filename lst = Utilities.getFileListFromInit(init_file) if lst: # for each python filename, inspect its module info for fn in lst: fn_path = os.path.join(path, fn + '.py') t = inspect.getmoduleinfo(fn_path) if t is not None: name, suffix, mode, module_type = t doc += _("---------- %s module :\n") % fn + \ _("\tname : %s\n") % name + \ _("\tsuffix : %s\n") % suffix + \ _("\tmode : %s\n") % mode + \ _("\ttype of module : %s\n") % module_type + \ _("\tpath : %s\n\n") % fn_path else: doc += _("----------%s module not inspectable !\n") % fn #else: #pass #doc += _("%s is empty !\n")%init_file #else: #pass #doc += _("%s dont exist !\n")%init_file ### TODO take in charge also amd and cmd ! return doc
def Populate(self, pluginsList): """ Populate method must be called just before construtor. """ if not self.is_populate: # all plugins file in plugins directory and already loaded # list of all file (without __init__.py) for root, dirs, files in pluginsList: ### dirs must contain python file if files: #for filename in filter(lambda f: not f.startswith('__') and f.endswith('.py'), files): for filename in filter(lambda f: f == "__init__.py", files): for basename in Utilities.getFileListFromInit(os.path.join(root,filename)): ### try to add dynamicaly pulgins #try: #t = threading.Thread(target=self.Importing, args=(root, basename,)) #t.start() #except Exception: #if wx.Platform == '__WXGTK__': ##i+=1 #wx.CallLater(500, self.Importing, root, basename,) #else: self.Importing(root, basename) self.is_populate = True
def CreateBlock(*argv, **kwargs): """ Create Block from python_file and other info coming from wizard. """ import Core.Components.Container as Container python_file = kwargs['python_file'] canvas = kwargs['canvas'] if 'canvas' in kwargs else None x = kwargs['x'] if 'x' in kwargs else None y = kwargs['y'] if 'y' in kwargs else None # associated python class cls = GetClass(python_file) if inspect.isclass(cls): # adding devs model on good graphical model if issubclass(cls, DomainBehavior.DomainBehavior): amd = AMDComponent(*argv, **kwargs) m = amd.Create() ### move AMD model if canvas and x and y: ### convert coordinate depending on the canvas x, y = canvas.GetXY(m, x, y) # move model from mouse position m.move(x, y) return m elif issubclass(cls, DomainStructure.DomainStructure): cmd = CMDComponent(*argv, **kwargs) m = cmd.Create() ### move CMD model if canvas and x and y: ### convert coordinate depending on the canvas x, y = canvas.GetXY(m, x, y) # move model from mouse position m.move(x, y) return m elif 'IPort' in cls.__name__: label = kwargs['label'] iid = kwargs['id'] if 'id' in kwargs else canvas.GetDiagram( ).GetiPortCount() m = Container.iPort(label="%s %d" % (label, iid)) m.id = iid m.move(x - 70, y - 70) return m elif 'OPort' in cls.__name__: label = kwargs['label'] oid = kwargs['id'] if 'id' in kwargs else canvas.GetDiagram( ).GetoPortCount() m = Container.oPort(label="%s %d" % (label, oid)) m.id = oid m.move(x - 70, y - 70) return m else: dial = wx.MessageDialog( None, _('Object not instantiated !\n\n Perhaps there is bad imports.' ), _('Exclamation'), wx.OK | wx.ICON_EXCLAMATION) dial.ShowModal() return False ### inform user of the existance of error and return None else: MsgBoxError(None, Utilities.GetActiveWindow(), cls) return None
def __init__(self, parent=None, id=wx.ID_ANY, title="", data=None): """ @data : [(x,y)...] """ if not data: data = [] # total time duree = data[-1][0] signal = [c[1] for c in data] Nb_pts = len(signal) #interpolation B-splines #dx = 1 #newx = r_[0:Nb_pts:duree] #y = array(self.signal) #newy = cspline1d_eval(cspline1d(y),newx,dx = dx,x0 = y[0]) #self.signal = newy # nombre de points pour la fft p = 1 while pow(2, p) <= Nb_pts: p += 1 N = float(pow(2, p)) assert (pow(2, p) >= Nb_pts) #application d'une fenetre signal = Utilities.smooth(array(signal), window_len=10, window="hamming") # frequence d'echantillonnage Fe = 1.0 / (float(duree) / float(len(signal))) #FFT Y = fft.fft(signal, int(N)) Y = abs(fft.fftshift(Y)) F = [Fe * i / N for i in xrange(int(-N / 2), int(N / 2))] # normalisation Max = max(Y) Y = [20 * math.log(i / Max, 10) for i in Y] #frequence max et min pour le plot FMin, FMax = 0, 200 F_plot, Y_plot = [], [] for i in xrange(len(F)): if FMin < F[i] < FMax: F_plot.append(F[i]) Y_plot.append(Y[i]) # formate les donnees pour Plot self.data = map(lambda a, b: (a, b), F_plot, Y_plot) # invoque la frame StaticPlot.__init__(self, parent, id, title, self.data, xLabel=_('Frequency [Hz]'), yLabel=_('Amplitude [dB]')) self.OnPlotLine() # range for fred and amplitude self.sldh.SetRange(1, 300) self.sldv.SetRange(0, 150) # start freq 100 self.sldh.SetValue(100) # start amplitude 0 self.sldv.SetValue(0) # Bind the Sliders self.Bind(wx.EVT_SLIDER, self.sliderUpdate, id=self.sldh.GetId()) self.Bind(wx.EVT_SLIDER, self.sliderUpdate, id=self.sldv.GetId())
try: zf = ZipManager.Zip(fileName) ### create or update fileName if os.path.exists(fileName): zf.Update(replace_files=[fn, python_path, image_path]) else: zf.Create(add_files=[fn, python_path, image_path]) os.remove(fn) ## chemin absolu du repertoir contenant le fichier a exporter (str() pour eviter l'unicode) newExportPath = str(os.path.dirname(fileName)) mainW = Utilities.getTopLevelWindow() ### si export dans un repertoir local on insert le chemin dans le fichier de config if not os.path.basename(DOMAIN_PATH) in newExportPath.split(os.sep): ### mise a jour du fichier .devsimpy mainW.exportPathsList = eval(mainW.cfg.Read("exportPathsList")) if newExportPath not in mainW.exportPathsList: mainW.exportPathsList.append(str(newExportPath)) mainW.cfg.Write("exportPathsList", str(eval("mainW.exportPathsList"))) ### si la librairie est deja charger dans l'environnement on met a jour ces modeles mainW.tree.UpdateDomain(newExportPath) except Exception, info: sys.stderr.write(_("Problem saving (during the zip handling): %s -- %s\n") % (str(fileName), info)) return False
def OnEditor(self, event): """ Method that edit the python code of associated devs model of the Block """ python_path = self.python_path model_path = os.path.dirname(python_path) name = os.path.basename(python_path) ### trying to get parent window mainW = Utilities.GetActiveWindow(event) if isinstance(mainW, ShapeCanvas.ShapeCanvas): mainW = mainW.GetParent() if __builtin__.__dict__['LOCAL_EDITOR'] and not zipfile.is_zipfile( model_path) and not python_path.startswith('http'): dial = wx.MessageDialog( mainW, _('Do you want to use your local programmer software?\n\n If you want always use the DEVSimPy code editor\n change the option in Editor panel preferences.' ), 'Question', wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) val = dial.ShowModal() else: val = wx.ID_NO ### si local editor choisi dans les preferences et pas de zip file et pas de fichier provenant du server ftp if val == wx.ID_YES: ### open with local editor if wx.Platform == '__WXMAC__': os.system("open " + python_path) elif "wxMSW" in wx.PlatformInfo: os.startfile(python_path) elif "wxGTK" in wx.PlatformInfo: ### on est dans gnome if os.system('pidof gnome-session') != 256: try: soft = which('gnome-open') except: sys.stdout.write( _("Local programmer software not found!\n")) else: os.system(soft + " openURL " + python_path) ### on est dans kde elif os.system('pidof ksmserver') != 256: try: soft = which('kfmclient') except: sys.stdout.write( _("Local programmer software not found!\n")) else: os.system(soft + " openURL " + python_path) else: sys.stdout.write(_("Unknown Windows Manager!\n")) elif val != wx.ID_CANCEL: # chargement du fichier dans la fenetre d'edition (self.text) try: editorFrame = Editor.GetEditor(mainW, wx.ID_ANY, name, obj=self, file_type='block') # if zipfile.is_zipfile(model_path): # importer = zipimport.zipimporter(model_path) # text = importer.get_source(os.path.splitext(name)[0]) if not zipfile.is_zipfile(model_path): ### if file is localized on the net if python_path.startswith('http'): ### with internet python file, the editorFrame is read only editorFrame.SetReadOnly(True) printOnStatusBar(editorFrame.statusbar, {0: _('read only')}) ### parse url to extract the path(/devsimpy/domain...) and the network location (lcapocchi.free.fr) o = urlparse(python_path) ### open conenction c = httplib.HTTPConnection(o.netloc) ### request with GET mode c.request('GET', o.path) ### get response of request r = c.getresponse() ### convert file into string text = r.read() else: ### if python_path is not found (because have an external origine) if not os.path.exists(python_path): if os.path.basename( DOMAIN_PATH) in python_path.split(os.sep): python_path = os.path.join( HOME_PATH, python_path[python_path.index( os.path.basename(DOMAIN_PATH)):].strip( '[]')) self.python_path = python_path # ### only with python 2.6 # with codecs.open(python_path, 'r', 'utf-8') as f: # text = f.read() name = os.path.basename(python_path) editorFrame.AddEditPage(name, python_path) editorFrame.Show() printOnStatusBar(editorFrame.statusbar, {1: ''}) return editorFrame except Exception, info: dlg = wx.MessageDialog( mainW, _('Editor frame not instanciated: %s\n' % info), _("Error"), wx.OK | wx.ICON_ERROR) dlg.ShowModal() return False
def GetModelList(self, dName): """ Get the list of files from dName directory. """ ### list of py file from __init__.py if LibraryTree.EXT_LIB_PYTHON_FLAG: ### lsit of py file from url if dName.startswith('http'): o = urlparse(dName) c = httplib.HTTPConnection(o.netloc) c.request('GET', o.path + '/__init__.py') r = c.getresponse() code = r.read() if r.status == 200: exec code tmp = filter( lambda s: s.replace('\n', '').replace('\t', ''). replace(',', '').replace('"', "").replace( '\'', "").strip(), __all__) ### test if the content of __init__.py file is python file (isfile equivalent) py_file_list = [ s for s in tmp if 'python' in urllib.urlopen(dName + '/' + s + '.py').info().type ] else: py_file_list = [] return py_file_list else: try: name_list = Utilities.getFileListFromInit( os.path.join(dName, '__init__.py')) py_file_list = [] for s in name_list: python_file = os.path.join(dName, s + '.py') ### test if tmp is only composed by python file (case of the user write into the __init__.py file directory name is possible ! then we delete the directory names) if os.path.isfile(python_file): cls = Components.GetClass(python_file) if cls is not None and not isinstance(cls, tuple): ### only model that herite from DomainBehavior is shown in lib if issubclass(cls, DomainBehavior.DomainBehavior): py_file_list.append(s) ### If cls is tuple, there is an error but we load the model to correct it. ### If its not DEVS model, the Dnd don't allows the instantiation and when the error is corrected, it don't appear before a update. else: py_file_list.append(s) except Exception: py_file_list = [] # if dName contains a python file, __init__.py is forced for f in os.listdir(dName): if f.endswith('.py'): #sys.stderr.write(_("%s not imported : %s \n"%(dName,info))) break else: py_file_list = [] # list of amd and cmd files devsimpy_file_list = [ f for f in os.listdir(dName) if os.path.isfile(os.path.join(dName, f)) and (f[:2] != '__') and ( f.endswith(LibraryTree.EXT_LIB_FILE)) ] return py_file_list + devsimpy_file_list
def OnAdd(self, evt): path = self._dbb.GetValue() dName = os.path.basename( path) if not path.startswith('http') else filter( lambda a: a != '', path.split('/'))[-1] # si la lib n'est pas deja importee if not self.parent.tree.IsChildRoot(dName): if not self._d.has_key(dName) or (self._d.has_key(dName) and self._d[dName] != path): ### si importation a partir du local if os.path.isdir(path): self.DoAdd(path, dName) ### si importation a partir du web elif Utilities.checkURL(path): self.DoAdd(path, dName) ### gestion de l'erreur else: if path.startswith('http'): msg = _('%s is an invalid url') % path else: msg = _('%s directory does not exist') % dName dial = wx.MessageDialog(self, msg, _('Error'), wx.OK | wx.ICON_ERROR) dial.ShowModal() self._dbb.SetValue('') else: dial = wx.MessageDialog(self, _('%s is already imported') % dName, _('Info'), wx.OK) dial.ShowModal() self._dbb.SetValue('') else: dial = wx.MessageDialog(self, _('%s is already imported') % dName, _('Info'), wx.OK) dial.ShowModal() self._dbb.SetValue('') # on reactive le bouton pour un eventuel autre ajout self._btn_Add.Enable(True) ### ------------------------------------------------------------ # class TestApp(wx.App): # """ Testing application # """ # def OnInit(self): # import __builtin__ # import gettext # __builtin__.__dict__['HOME_PATH'] = os.getcwd() # __builtin__.__dict__['DOMAIN_PATH'] = 'Domain' # __builtin__.__dict__['_'] = gettext.gettext # frame = ImportLibrary(None, size=(600,600), id=-1, title="Test") # frame.Show() # return True # def OnQuit(self, event): # self.Close() # if __name__ == '__main__': # app = TestApp(0) # app.MainLoop()
class Zip: def __init__(self, fn, files=None): """ Constructor """ if not files: files = [] ### local copy self.fn = fn if files: self.Create(files) def Create(self, add_files=None): if not add_files: add_files = [] dir_name, base_name = os.path.split(self.fn) name, ext = os.path.splitext(base_name) ### output zip file zout = zipfile.ZipFile(self.fn, "w") ### for all files wich could be added for fn in filter(lambda f: os.path.exists(f) or zipfile.is_zipfile(os.path.dirname(f)), add_files): fn_dir_name, fn_base_name = os.path.split(fn) fn_name, fn_ext = os.path.splitext(fn_base_name) ### if adding file is compressed, we decompress and add it if zipfile.is_zipfile(fn_dir_name): zin = zipfile.ZipFile(fn_dir_name, 'r') buffer = zin.read(fn_base_name) ### if not .dat file and the name of file is not the same with the zip file #if fn_ext == '.py': #zout.writestr("%s%s"%(name,fn_ext), buffer) #else: zout.writestr(fn_base_name, buffer) zin.close() else: zout.write(fn, fn_base_name) zout.close() def Update(self, replace_files=None): """ Update zip archive with the new replace file names """ if not replace_files: replace_files = [] ### delete empty fileName replace_files = filter(lambda f: f != '', replace_files) # call this function because : http://www.digi.com/wiki/developer/index.php/Error_messages self.ClearCache() zin = zipfile.ZipFile(self.fn, 'r') zout = zipfile.ZipFile("new_arch.zip", 'w') exclude_file = [] ### write all replace file in the new archive for fn in replace_files: dir_name, base_name = os.path.split(fn) if zipfile.is_zipfile(dir_name): #print '1' z = zipfile.ZipFile(dir_name, 'r') data = z.read(base_name) ### this line is in comment because is zip file contain image file we can not encode it. zout.writestr(base_name, data.encode('utf-8')) #zout.writestr(base_name, data) z.close() #print '11' #sys.stdout.write("update %s from compressed %s\n"%(base_name, fn)) elif os.path.exists(fn): #print '2' zout.write(fn, base_name) #print '22' #sys.stdout.write("update %s from %s\n"%(base_name, fn)) elif os.path.exists(base_name) and dir_name != "": #print '3' zout.write(base_name, fn) #print '33' #sys.stdout.write("update %s from %s\n"%(fn, base_name)) else: exclude_file.append(replace_files.index(fn)) #sys.stdout.write("%s unknown\n"%(fn)) ### try to rewrite not replaced files from original zip info_list = zin.infolist() for item in info_list: s = os.path.basename(item.filename) if s not in map(os.path.basename, replace_files) and info_list.index(item) not in exclude_file: buffer = zin.read(item.filename) zout.writestr(item, buffer) sys.stdout.write("%s rewrite\n" % item.filename) ### close all files zout.close() zin.close() ### remove and rename the zip file self.ClearFiles() def Delete(self, delete_files=None): """ Remove file in zip archive """ if not delete_files: delete_files = [] ### delete empty fileName delete_files = filter(lambda f: f != '', delete_files) # call this function because : http://www.digi.com/wiki/developer/index.php/Error_messages self.ClearCache() zin = zipfile.ZipFile(self.fn, 'r') zout = zipfile.ZipFile("new_arch.zip", 'w') ### info_list = zin.infolist() for item in info_list: if item.filename not in delete_files: buffer = zin.read(item.filename) zout.writestr(item, buffer) ##sys.stdout.write("%s rewrite\n"%(item.filename)) ### close all files zout.close() zin.close() ### remove and rename the zip file self.ClearFiles() def GetImage(self, scaleW=16, scaleH=16): """ Get image object from image file stored in zip file. scaleH and scaleW are used to rescale image """ zf = zipfile.ZipFile(self.fn, 'r') ### find if python file has same name of model file L = filter(lambda f: f.endswith(('.jpg', 'jpeg', 'png', 'bmp')), zf.namelist()) if L: f = zf.open(L.pop()) buf = f.read() f.close() sbuf = StringIO.StringIO(buf) image = wx.ImageFromStream(sbuf) image.Rescale(scaleW, scaleH) zf.close() return image else: return None @staticmethod def GetPluginFile(fn): """ TODO: comment """ ### zipfile (amd or cmd) zf = zipfile.ZipFile(fn, 'r') nl = zf.namelist() zf.close() L = filter(lambda a: a != [], map(lambda s: re.findall("^(plugins[/]?[\w]*.py)$", s), nl)) return L.pop(0)[0] if L != [] else "" @staticmethod def HasPlugin(fn): """ TODO: comment """ ### zipfile (amd or cmd) zf = zipfile.ZipFile(fn, 'r') nl = zf.namelist() zf.close() ### plugin file is plugins.pi in root of zipfile or in plugins zipedd directory return any(map(lambda s: re.search("^(plugins[/]*[\w]*.py)$", s), nl)) # BDD Test---------------------------------------------------------------------- @staticmethod def HasTests(fn): """ TODO: comment """ name = os.path.basename(getPythonModelFileName(fn)).split('.')[0] zf = zipfile.ZipFile(fn, 'r') nl = zf.namelist() zf.close() return any(map(lambda s: re.search("^(BDD/[\w*/]*\.py|BDD/[\w*/]*\.feature)$", s), nl)) @staticmethod def GetTests(fn): """ Return feature, steps and environment files from .amd """ zf = zipfile.ZipFile(fn, 'r') nl = zf.namelist() zf.close() ### tests_files = filter(lambda a: a != [], map(lambda s: re.findall("^(BDD/[\w*/]*\.py|BDD/[\w*/]*\.feature)$", s), nl)) tests_files = [a[0] for a in tests_files] return tests_files #### find feature and steps file #feat = None #steps = None #env = None #feat = filter(lambda t: t.endswith('.feature'), zf.namelist())[0] #if 'steps.py' in zf.namelist(): #steps = "steps.py" #if 'environment.py' in zf.namelist(): #env = "environment.py" #zf.close() #return feat, steps, env # ------------------------------------------------------------------------------ def GetModule(self, rcp=False): """ Load module from zip file corresponding to the amd or cmd model. It used when the tree library is created. """ # get module name try: module_name = getPythonModelFileName(self.fn) except Exception, info: sys.stderr.write(_("Error in ZipManager class for GetModule: no python file in the archive\n")) return info # if necessary, recompile (for update after editing code source of model) #if rcp: recompile(module_name) # import module try: ### clear to clean the import after exporting model (amd or cmd) and reload within the same instrance of DEVSimPy zipimport._zip_directory_cache.clear() importer = zipimport.zipimporter(self.fn) module = importer.load_module(module_name.split('.py')[0]) module.__name__ = Utilities.path_to_module(module_name) except Exception, info: sys.stderr.write(_("Error in execution: ") + str(sys.exc_info()[0]) + "\r\n" + Utilities.listf( format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))) return info