def editApp(appname=None): """Edit an application source file. If no appname is specified, the current application is used. This loads the application module, gets its file name, and if it is a source file or the the corresponding source file exists, that file is loaded into the editor. """ if appname is None: appname = pf.cfg['curfile'] if utils.is_script(appname): # this is a script, not an app fn = appname else: import apps app = apps.load(appname) if app is None: fn = apps.findAppSource(appname) else: fn = apps.findAppSource(app) if not os.path.exists(fn): draw.warning("The file '%s' does not exist" % fn) return draw.editFile(fn)
def add(self,name,strict=True,skipconfig=True): """Add a new filename to the front of the menu. This function is used to add app/scripts to the history menus. By default, only legal pyFormex apps or scripts can be added, and scripts from the user config will not be added. Setting strict and or skipconfig to False will skip the filter(s). """ if strict: if self.mode == 'app': appname = self.fullAppName(name) app = apps.load(appname) if app is None: print("%s is NO MODULE!" % appname) return else: if not utils.is_pyFormex(name): return if skipconfig: # This is here to skip the startup script if os.path.dirname(os.path.abspath(name)) == pf.cfg.userconfdir: return files = self.files olist.toFront(files,name) if self.max > 0 and len(files) > self.max: files = files[:self.max] while len(self.my_actions) < len(files): self.my_actions.append(self.addAction(name)) for a,f in zip(self.my_actions,self.files): a.setText(f)
def add(self, name, strict=True, skipconfig=True): """Add a new filename to the front of the menu. This function is used to add app/scripts to the history menus. By default, only legal pyFormex apps or scripts can be added, and scripts from the user config will not be added. Setting strict and or skipconfig to False will skip the filter(s). """ if strict: if self.mode == 'app': appname = self.fullAppName(name) app = apps.load(appname) if app is None: print("%s is NO MODULE!" % appname) return else: if not utils.is_pyFormex(name): return if skipconfig: # This is here to skip the startup script if os.path.dirname( os.path.abspath(name)) == pf.cfg.userconfdir: return files = self.files olist.toFront(files, name) if self.max > 0 and len(files) > self.max: files = files[:self.max] while len(self.my_actions) < len(files): self.my_actions.append(self.addAction(name)) for a, f in zip(self.my_actions, self.files): a.setText(f)
def classify(appdir,pkg,nmax=0): """Classify the files in submenus according to keywords. """ class failed(object): """A class to allow failing examples in the catalog""" _status = 'failed' all_apps = sorted(apps.detect(appdir)) kat = ['status','level','topics','techniques','all'] cat = dict([ (k,set()) for k in kat]) cat['status'] = [ 'failed', 'checked', 'unchecked' ] cat['level'] = [ 'beginner', 'normal', 'advanced' ] col = {} if nmax > 9: # Do not exagerate! # split the full collection in alphabetical groups of length nmax lbl,grp = splitAlpha(all_apps,nmax) cat['all'] = lbl for l,g in zip(lbl,grp): col['all/'+l] = g for i,appname in enumerate(all_apps): #col['all'].update([appname]) try: app = apps.load(pkg+'.'+appname) except: app = failed print("Failed to load app '%s'" % (str(pkg)+'.'+appname)) for k in kat: if hasattr(app,'_'+k): v = getattr(app,'_'+k) if type(v) is list: v = [ vi.lower() for vi in v ] else: v = v.lower() if k in ['status','level']: v = [v] else: cat[k].update(v) for i in v: ki = '%s/%s' % (k,i) if not ki in col.keys(): col[ki] = set() col[ki].update([appname]) sortSets(cat) sortSets(col) return all_apps,kat,cat,col
def classify(appdir, pkg, nmax=0): """Classify the files in submenus according to keywords. """ class failed(object): """A class to allow failing examples in the catalog""" _status = 'failed' all_apps = sorted(apps.detect(appdir)) kat = ['status', 'level', 'topics', 'techniques', 'all'] cat = dict([(k, set()) for k in kat]) cat['status'] = ['failed', 'checked', 'unchecked'] cat['level'] = ['beginner', 'normal', 'advanced'] col = {} if nmax > 9: # Do not exagerate! # split the full collection in alphabetical groups of length nmax lbl, grp = splitAlpha(all_apps, nmax) cat['all'] = lbl for l, g in zip(lbl, grp): col['all/' + l] = g for i, appname in enumerate(all_apps): #col['all'].update([appname]) try: app = apps.load(pkg + '.' + appname) except: app = failed print("Failed to load app '%s'" % (str(pkg) + '.' + appname)) for k in kat: if hasattr(app, '_' + k): v = getattr(app, '_' + k) if type(v) is list: v = [vi.lower() for vi in v] else: v = v.lower() if k in ['status', 'level']: v = [v] else: cat[k].update(v) for i in v: ki = '%s/%s' % (k, i) if not ki in col.keys(): col[ki] = set() col[ki].update([appname]) sortSets(cat) sortSets(col) return all_apps, kat, cat, col
def setcurfile(self,appname): """Set the current application or script. appname is either an application module name or a script file. """ is_app = not utils.is_script(appname) if is_app: # application label = 'App:' name = appname import apps app = apps.load(appname) if app is None: self.canPlay = False try: self.canEdit = os.path.exists(apps.findAppSource(appname)) except: self.canEdit = False else: self.canPlay = hasattr(app,'run') self.canEdit = os.path.exists(apps.findAppSource(app)) else: # script file label = 'Script:' name = os.path.basename(appname) self.canPlay = self.canEdit = utils.is_pyFormex(appname) or appname.endswith('.pye') pf.prefcfg['curfile'] = appname #self.curfile.label.setText(label) self.curfile.setText(label,0) self.curfile.setText(name,1) self.enableButtons(self.actions,['Play','Info'],self.canPlay) self.enableButtons(self.actions,['Edit'],self.canEdit) self.enableButtons(self.actions,['ReRun'],is_app and(self.canEdit or self.canPlay)) self.enableButtons(self.actions,['Step','Continue'],False) icon = 'ok' if self.canPlay else 'notok' self.curfile.setIcon(QtGui.QIcon(QtGui.QPixmap(os.path.join(pf.cfg['icondir'],icon)+pf.cfg['gui/icontype'])),1)
def runApp(appname, argv=[], refresh=False): global exitrequested if len(pf.scriptlock) > 0: pf.message("!!Not executing because a script lock has been set: %s" % pf.scriptlock) #print(pf.scriptlock) return import apps from timer import Timer t = Timer() pf.message("Loading application %s with refresh=%s" % (appname, refresh)) app = apps.load(appname, refresh=refresh) if app is None: errmsg = "An error occurred while loading application %s" % appname if pf.GUI: if apps._traceback and pf.cfg['showapploaderrors']: print(apps._traceback) from gui import draw fn = apps.findAppSource(appname) if os.path.exists(fn): errmsg += "\n\nYou may try executing the application as a script,\n or you can load the source file in the editor." res = draw.ask(errmsg, choices=[ 'Run as script', 'Load in editor', "Don't bother" ]) if res[0] in 'RL': if res[0] == 'L': draw.editFile(fn) elif res[0] == 'R': pf.GUI.setcurfile(fn) draw.runScript(fn) else: errmsg += "and I can not find the application source file." draw.error(errmsg) else: error(errmsg) return if hasattr(app, '_status') and app._status == 'unchecked': pf.warning( "This looks like an Example script that has been automatically converted to the pyFormex Application model, but has not been checked yet as to whether it is working correctly in App mode.\nYou can help here by running and rerunning the example, checking that it works correctly, and where needed fixing it (or reporting the failure to us). If the example runs well, you can change its status to 'checked'" ) scriptLock('__auto__') msg = "Running application '%s' from %s" % (appname, app.__file__) pf.scriptName = appname if pf.GUI: pf.GUI.startRun() pf.GUI.apphistory.add(appname) pf.board.write(msg, color='green') else: message(msg) pf.debug(" Passing arguments: %s" % argv, pf.DEBUG.SCRIPT) app._args_ = argv try: try: res = app.run() except _Exit: pass except _ExitSeq: exitrequested = True except: raise finally: if hasattr(app, 'atExit'): app.atExit() if pf.cfg['autoglobals']: g = app.__dict__ exportNames = listAll(clas=Geometry, dic=g) pf.PF.update([(k, g[k]) for k in exportNames]) scriptRelease('__auto__') # release the lock if pf.GUI: pf.GUI.stopRun() pf.debug(" Arguments left after execution: %s" % argv, pf.DEBUG.SCRIPT) msg = "Finished %s in %s seconds" % (appname, t.seconds()) if pf.GUI: pf.board.write(msg, color='green') else: message(msg) pf.debug("Memory: %s" % vmSize(), pf.DEBUG.MEM)
def runApp(appname,argv=[],refresh=False): global exitrequested if len(pf.scriptlock) > 0: pf.message("!!Not executing because a script lock has been set: %s" % pf.scriptlock) #print(pf.scriptlock) return import apps from timer import Timer t = Timer() pf.message("Loading application %s with refresh=%s" % (appname,refresh)) app = apps.load(appname,refresh=refresh) if app is None: errmsg = "An error occurred while loading application %s" % appname if pf.GUI: if apps._traceback and pf.cfg['showapploaderrors']: print(apps._traceback) from gui import draw fn = apps.findAppSource(appname) if os.path.exists(fn): errmsg += "\n\nYou may try executing the application as a script,\n or you can load the source file in the editor." res = draw.ask(errmsg,choices=['Run as script', 'Load in editor', "Don't bother"]) if res[0] in 'RL': if res[0] == 'L': draw.editFile(fn) elif res[0] == 'R': pf.GUI.setcurfile(fn) draw.runScript(fn) else: errmsg += "and I can not find the application source file." draw.error(errmsg) else: error(errmsg) return if hasattr(app,'_status') and app._status == 'unchecked': pf.warning("This looks like an Example script that has been automatically converted to the pyFormex Application model, but has not been checked yet as to whether it is working correctly in App mode.\nYou can help here by running and rerunning the example, checking that it works correctly, and where needed fixing it (or reporting the failure to us). If the example runs well, you can change its status to 'checked'") scriptLock('__auto__') msg = "Running application '%s' from %s" % (appname,app.__file__) pf.scriptName = appname if pf.GUI: pf.GUI.startRun() pf.GUI.apphistory.add(appname) pf.board.write(msg,color='green') else: message(msg) pf.debug(" Passing arguments: %s" % argv,pf.DEBUG.SCRIPT) app._args_ = argv try: try: res = app.run() except _Exit: pass except _ExitSeq: exitrequested = True except: raise finally: if hasattr(app,'atExit'): app.atExit() if pf.cfg['autoglobals']: g = app.__dict__ exportNames = listAll(clas=Geometry,dic=g) pf.PF.update([(k,g[k]) for k in exportNames]) scriptRelease('__auto__') # release the lock if pf.GUI: pf.GUI.stopRun() pf.debug(" Arguments left after execution: %s" % argv,pf.DEBUG.SCRIPT) msg = "Finished %s in %s seconds" % (appname,t.seconds()) if pf.GUI: pf.board.write(msg,color='green') else: message(msg) pf.debug("Memory: %s" % vmSize(),pf.DEBUG.MEM)