def runApp(args): """Create and run the qt application.""" GD.app = QtGui.QApplication(args) QtCore.QObject.connect(GD.app,QtCore.SIGNAL("lastWindowClosed()"),GD.app,QtCore.SLOT("quit()")) QtCore.QObject.connect(GD.app,QtCore.SIGNAL("aboutToQuit()"),quit) # Set some globals GD.image_formats_qt = map(str,QtGui.QImageWriter.supportedImageFormats()) GD.image_formats_qtr = map(str,QtGui.QImageReader.supportedImageFormats()) if GD.cfg.get('imagesfromeps',False): GD.image_formats_qt = [] if GD.options.debug: print "Qt image types for saving: ",GD.image_formats_qt print "Qt image types for input: ",GD.image_formats_qtr print "gl2ps image types:",GD.image_formats_gl2ps print "image types converted from EPS:",GD.image_formats_fromeps # Load the splash image splash = None if os.path.exists(GD.cfg['gui/splash']): GD.debug('Loading splash %s' % GD.cfg['gui/splash']) splashimage = QtGui.QPixmap(GD.cfg['gui/splash']) splash = QtGui.QSplashScreen(splashimage) splash.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) splash.setFont(QtGui.QFont("Helvetica",24)) splash.showMessage(GD.Version,QtCore.Qt.AlignHCenter,QtCore.Qt.red) splash.show() # create GUI, show it, run it viewport.setOpenGLFormat() dri = viewport.opengl_format.directRendering() windowname = GD.Version count = 0 while windowExists(windowname): if count > 255: print "Can not open the main window --- bailing out" return 1 count += 1 windowname = '%s (%s)' % (GD.Version,count) if count > 0: warning = """ Another instance of pyFormex is already running on this screen. This may be a leftover from a previously crashed program. In that case you should bail out now and first kill the crashed program. On the other hand, if you really want to run another pyFormex in parallel, you can just continue now. """ actions = ['Really Continue','Bail out and fix the problem'] if dri: answer = draw.ask(warning,actions) if not dri: warning += """ I have detected that the Direct Rendering Infrastructure is not activated on your system. Continuing with a second instance of pyFormex may crash you XWindow system. You should seriously consider to bail out now!!! """ answer = draw.warning(warning,actions) if answer != 'Really Continue': return 1 GD.gui = GUI(windowname, GD.cfg.get('gui/size',(800,600)), GD.cfg.get('gui/pos',(0,0)), GD.cfg.get('gui/bdsize',(800,600)) ) # set the appearence GD.gui.setStyle(GD.cfg.get('gui/style','Plastique')) font = GD.cfg.get('gui/font',None) if font: GD.gui.setFont(font) else: fontfamily = GD.cfg.get('gui/fontfamily',None) if fontfamily: GD.gui.setFontFamily(fontfamily) fontsize = GD.cfg.get('gui/fontsize',None) if fontsize: GD.gui.setFontSize(fontsize) GD.gui.viewports.changeLayout(1) GD.gui.viewports.setCurrent(0) GD.board = GD.gui.board GD.board.write("""%s (C) B. Verhegghe pyFormex comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. See Help->License or the file COPYING for details. """ % GD.Version) GD.gui.show() GD.debug("Using window name %s" % GD.gui.windowTitle()) # Create additional menus (put them in a list to save) # History Menu history = GD.cfg.get('history',None) if type(history) == list: GD.gui.history = scriptsMenu.ScriptsMenu('History',files=history,max=20) if GD.cfg.get('gui/history_in_main_menu',False): before = GD.gui.menu.item('help').menuAction() GD.gui.menu.insertMenu(before,GD.gui.history) else: filemenu = GD.gui.menu.item('file') before = filemenu.item('---1') filemenu.insertMenu(before,GD.gui.history) # Create a menu with pyFormex examples # and insert it before the help menu menus = [] scriptdirs = GD.cfg['scriptdirs'] knownscriptdirs = { 'examples': GD.cfg['examplesdir'] } if GD.cfg.get('gui/separate_script_dirs',False): # This will create separate menus for all scriptdirs pass else: # The default is to collect all scriptdirs in a single main menu if len(scriptdirs) > 1: scriptsmenu = widgets.Menu('Scripts',GD.gui.menu) before = GD.gui.menu.item('help').menuAction() GD.gui.menu.insertMenu(before,scriptsmenu) before = None else: scriptsmenu = GD.gui.menu before = scriptsmenu.itemAction('help') for title,dirname in scriptdirs: GD.debug("Loading script dir %s" % dirname) if not dirname: dirname = knownscriptdirs[title.lower()] if os.path.exists(dirname): m = scriptsMenu.ScriptsMenu(title,dirname,autoplay=True) scriptsmenu.insert_menu(m,before) menus.append(m) # Needed to keep m linked to a name, # else the menu is destroyed! # Set interaction functions GD.message = draw.message GD.warning = draw.warning draw.reset() # Load plugins, ignore if not found import plugins for p in GD.cfg.get('gui/plugins',[]): try: m = getattr(plugins,p) if hasattr(m,'show_menu'): m.show_menu() except: GD.debug('ERROR while loading plugin %s' % p) GD.gui.setBusy(False) GD.gui.update() # remove the splash window if splash is not None: splash.finish(GD.gui) # Add the autorun script to the remaining args if GD.gui.easter_egg: draw.playScript(utils.mergeme(*GD.gui.easter_egg)) ar = GD.cfg.get('autorun','') if ar: if type(ar) == str: ar = [ar] args = ar + args # remaining args are interpreted as scripts for arg in args: if os.path.exists(arg): draw.play(arg) GD.gui.setBusy(False) GD.gui.update() if os.path.isdir(GD.cfg['workdir']): # Make the workdir the current dir os.chdir(GD.cfg['workdir']) else: # Save the current dir as workdir GD.cfg['workdir'] = os.getcwd() GD.app_started = True GD.app.exec_() # Cleanup draw.drawrelease() GD.gui.setBusy(False) # store the history and main window size/pos GD.cfg['history'] = GD.gui.history.files # Sometimes, a negative value is stored, making restart partially obscured x,y = Pos(GD.gui) if x < 0: x = 0 if y < 0: y = 0 GD.cfg.update({'size':Size(GD.gui), 'pos':(x,y), 'bdsize':Size(GD.gui.board), },name='gui') return 0
def playScript(scr,name=None,filename=None,argv=[],pye=False): """Play a pyformex script scr. scr should be a valid Python text. There is a lock to prevent multiple scripts from being executed at the same time. This implies that pyFormex scripts can currently not be recurrent. If a name is specified, set the global variable pyformex.scriptName to it when the script is started. If a filename is specified, set the global variable __file__ to it. If step==True, an indefinite pause will be started after each line of the script that starts with 'draw'. Also (in this case), each line (including comments) is echoed to the message board. """ from geometry import Geometry global exitrequested # (We only allow one script executing at a time!) # and scripts are non-reentrant global scriptThread if scriptThread is not None and scriptThread.isAlive(): pf.message("Not executing this script because another one is already running") return if len(scriptlock) > 0: pf.message("!!Not executing because a script lock has been set: %s" % scriptlock) return scriptLock('__auto__') exitrequested = False if pf.GUI: global stepmode,exportNames,starttime #pf.debug('GUI SCRIPT MODE %s'% (stepmode)) pf.GUI.drawlock.allow() pf.canvas.update() pf.GUI.actions['Play'].setEnabled(False) pf.GUI.actions['Continue'].setEnabled(True) pf.GUI.actions['Stop'].setEnabled(True) pf.app.processEvents() # Get the globals g = Globals() if pf.GUI: modname = 'draw' # by default, we run the script in the current GUI viewport pf.canvas = pf.GUI.viewports.current else: modname = 'script' g.update({'__name__':modname}) if filename: g.update({'__file__':filename}) g.update({'argv':argv}) # Make this directory available pf._PF_ = g # Now we can execute the script using these collected globals exportNames = [] pf.scriptName = name exitall = False starttime = time.clock() pf.debug('STARTING SCRIPT (%s)' % starttime) #pf.debug(scr) #pf.debug(pye) try: try: if pf.GUI and stepmode: #pf.debug("STEPPING THROUGH SCRIPT") step_script(scr,g,True) else: if pye: if type(scr) is file: scr = scr.read() + '\n' n = len(scr) // 2 scr = utils.mergeme(scr[:n],scr[n:]) if pf.options.executor: scriptThread = threading.Thread(None,executeScript,'script-0',(scr,g)) scriptThread.daemon = True print "OK, STARTING THREAD" scriptThread.start() print "OK, STARTED THREAD" else: exec scr in g except _Exit: print "EXIT FROM SCRIPT" pass except _ExitAll: exitall = True except: raise finally: # honour the exit function if g.has_key('atExit'): atExit = g['atExit'] try: atExit() except: pf.debug('Error while calling script exit function') if pf.cfg['autoglobals']: exportNames.extend(listAll(clas=Geometry,dic=g)) pf.PF.update([(k,g[k]) for k in exportNames]) scriptRelease('__auto__') # release the lock elapsed = time.clock() - starttime pf.debug('SCRIPT RUNTIME : %s seconds' % elapsed) if pf.GUI: stepmode = False pf.GUI.drawlock.release() # release the lock pf.GUI.actions['Play'].setEnabled(True) #pf.GUI.actions['Step'].setEnabled(False) pf.GUI.actions['Continue'].setEnabled(False) pf.GUI.actions['Stop'].setEnabled(False) if exitall: pf.debug("Calling quit() from playscript") quit()
def playScript(scr,name=None,filename=None,argv=[],pye=False): """Play a pyformex script scr. scr should be a valid Python text. There is a lock to prevent multiple scripts from being executed at the same time. This implies that pyFormex scripts can currently not be recurrent. If a name is specified, set the global variable pyformex.scriptName to it when the script is started. If a filename is specified, set the global variable __file__ to it. If step==True, an indefinite pause will be started after each line of the script that starts with 'draw'. Also (in this case), each line (including comments) is echoed to the message board. """ global scriptDisabled,scriptRunning,exitrcrequested #pyformex.debug('SCRIPT MODE %s,%s,%s'% (scriptDisabled,scriptRunning,exitrequested)) # (We only allow one script executing at a time!) # and scripts are non-reentrant if scriptRunning or scriptDisabled : pyformex.message("Not executing this script because another one is already running") return scriptRunning = True exitrequested = False if pyformex.GUI: global stepmode,exportNames,starttime #pyformex.debug('GUI SCRIPT MODE %s'% (stepmode)) pyformex.GUI.drawlock.allow() pyformex.canvas.update() pyformex.GUI.actions['Play'].setEnabled(False) pyformex.GUI.actions['Continue'].setEnabled(True) pyformex.GUI.actions['Stop'].setEnabled(True) pyformex.app.processEvents() # Get the globals g = Globals() if pyformex.GUI: modname = 'draw' else: modname = 'script' g.update({'__name__':modname}) if filename: g.update({'__file__':filename}) g.update({'argv':argv}) # Make this directory available pyformex._PF_ = g # Now we can execute the script using these collected globals exportNames = [] pyformex.scriptName = name exitall = False starttime = time.clock() pyformex.debug('STARTING SCRIPT (%s)' % starttime) #pyformex.debug(scr) #pyformex.debug(pye) try: try: if pyformex.GUI and stepmode: #pyformex.debug("STEPPING THROUGH SCRIPT") step_script(scr,g,True) else: if pyformex.options.executor: import sys print(name,filename) n = os.path.split(name) m = os.path.basename(name) m = os.path.basename(name) print(n) o = os.path.split(n[0]) print(o) sys.path.insert(0,n[0]) print(sys.path) print(m) s = m.replace('.py','') print(s) __import__(s,g) else: if pye: if type(scr) is file: scr = scr.read() + '\n' n = len(scr) // 2 scr = utils.mergeme(scr[:n],scr[n:]) exec scr in g except _Exit: pass except _ExitAll: exitall = True except: raise finally: # honour the exit function if g.has_key('atExit'): atExit = g['atExit'] try: atExit() except: GD.debug('Error while calling script exit function') if pyformex.cfg['autoglobals']: exportNames.extend(listAll(clas=formex.Formex,dic=g)) pyformex.PF.update([(k,g[k]) for k in exportNames]) scriptRunning = False # release the lock in case of an error elapsed = time.clock() - starttime pyformex.debug('SCRIPT RUNTIME : %s seconds' % elapsed) if pyformex.GUI: stepmode = False pyformex.GUI.drawlock.release() # release the lock pyformex.GUI.actions['Play'].setEnabled(True) #pyformex.GUI.actions['Step'].setEnabled(False) pyformex.GUI.actions['Continue'].setEnabled(False) pyformex.GUI.actions['Stop'].setEnabled(False) if exitall: pyformex.debug("Calling exit() from playscript") exit()
def runApp(args): """Create and run the qt application.""" # # FIX FOR A BUG IN NUMPY (It's always sane anyway) # import locale GD.debug("LC_NUMERIC = %s" % locale.setlocale(locale.LC_NUMERIC)) # GD.app = QtGui.QApplication(args) # GD.debug("LC_NUMERIC = %s" % locale.setlocale(locale.LC_NUMERIC)) locale.setlocale(locale.LC_NUMERIC, 'C') GD.debug("LC_NUMERIC = %s" % locale.setlocale(locale.LC_NUMERIC)) # # # QtCore.QObject.connect(GD.app,QtCore.SIGNAL("lastWindowClosed()"),GD.app,QtCore.SLOT("quit()")) QtCore.QObject.connect(GD.app,QtCore.SIGNAL("aboutToQuit()"),quit) # Load the splash image splash = None if os.path.exists(GD.cfg['gui/splash']): GD.debug('Loading splash %s' % GD.cfg['gui/splash']) splashimage = QtGui.QPixmap(GD.cfg['gui/splash']) splash = QtGui.QSplashScreen(splashimage) splash.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) splash.setFont(QtGui.QFont("Helvetica",24)) splash.showMessage(GD.Version,QtCore.Qt.AlignHCenter,QtCore.Qt.red) splash.show() # create GUI, show it, run it viewport.setOpenGLFormat() dri = viewport.opengl_format.directRendering() windowname = GD.Version count = 0 while windowExists(windowname): if count > 255: print "Can not open the main window --- bailing out" return 1 count += 1 windowname = '%s (%s)' % (GD.Version,count) if count > 0: warning = """ Another instance of pyFormex is already running on this screen. This may be a leftover from a previously crashed program. In that case you should bail out now and first kill the crashed program. On the other hand, if you really want to run another pyFormex in parallel, you can just continue now. """ actions = ['Really Continue','Bail out and fix the problem'] if dri: answer = draw.ask(warning,actions) if not dri: warning += """ I have detected that the Direct Rendering Infrastructure is not activated on your system. Continuing with a second instance of pyFormex may crash you XWindow system. You should seriously consider to bail out now!!! """ answer = draw.warning(warning,actions) if answer != 'Really Continue': return 1 GD.gui = GUI(windowname, GD.cfg.get('gui/size',(800,600)), GD.cfg.get('gui/pos',(0,0)), GD.cfg.get('gui/bdsize',(800,600)) ) # set the appearence GD.gui.setStyle(GD.cfg.get('gui/style','Plastique')) font = GD.cfg.get('gui/font',None) if font: GD.gui.setFont(font) else: fontfamily = GD.cfg.get('gui/fontfamily',None) if fontfamily: GD.gui.setFontFamily(fontfamily) fontsize = GD.cfg.get('gui/fontsize',None) if fontsize: GD.gui.setFontSize(fontsize) GD.gui.viewports.changeLayout(1) GD.gui.viewports.setCurrent(0) GD.board = GD.gui.board GD.board.write("""%s (C) Benedict Verhegghe pyFormex comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under the conditions of the GNU General Public License, version 3 or later. See Help->License or the file COPYING for details. """ % GD.Version) GD.gui.show() GD.debug("Using window name %s" % GD.gui.windowTitle()) # Create additional menus (put them in a list to save) # History Menu history = GD.cfg.get('history',None) if type(history) == list: GD.gui.history = scriptsMenu.ScriptsMenu('History',files=history,max=20) if GD.cfg.get('gui/history_in_main_menu',False): before = GD.gui.menu.item('help').menuAction() GD.gui.menu.insertMenu(before,GD.gui.history) else: filemenu = GD.gui.menu.item('file') before = filemenu.item('---1') filemenu.insertMenu(before,GD.gui.history) # Script menu scriptmenu = createScriptMenu() # Set interaction functions GD.message = draw.message GD.warning = draw.warning draw.reset() # Load plugins, ignore if not found import plugins for p in GD.cfg.get('gui/plugins',[]): try: m = getattr(plugins,p) if hasattr(m,'show_menu'): m.show_menu() except: GD.debug('ERROR while loading plugin %s' % p) GD.gui.setBusy(False) GD.gui.update() GD.gui.addStatusBarButtons() # remove the splash window if splash is not None: splash.finish(GD.gui) GD.gui.setBusy(False) GD.gui.update() if os.path.isdir(GD.cfg['workdir']): # Make the workdir the current dir os.chdir(GD.cfg['workdir']) else: # Save the current dir as workdir GD.cfg['workdir'] = os.getcwd() GD.app_started = True if GD.gui.easter_egg: draw.playScript(utils.mergeme(*GD.gui.easter_egg)) # remaining args are interpreted as scripts and their parameters script.runApp(args) # Go into interactive mode GD.debug("Start main loop") GD.app.exec_() GD.debug("Exit main loop") return 0
def playScript(scr, name=None, filename=None, argv=[], pye=False): """Play a pyformex script scr. scr should be a valid Python text. There is a lock to prevent multiple scripts from being executed at the same time. This implies that pyFormex scripts can currently not be recurrent. If a name is specified, set the global variable pyformex.scriptName to it when the script is started. If a filename is specified, set the global variable __file__ to it. """ utils.warn('print_function') global exportNames, starttime global exitrequested # (We only allow one script executing at a time!) # and scripts are non-reentrant global scriptThread if scriptThread is not None and scriptThread.isAlive(): pf.message( "Not executing this script because another one is already running") return if len(pf.scriptlock) > 0: pf.message("!!Not executing because a script lock has been set: %s" % pf.scriptlock) #print(pf.scriptlock) return scriptLock('__auto__') exitrequested = False if pf.GUI: pf.GUI.startRun() # Get the globals g = Globals() if pf.GUI: modname = 'draw' else: modname = 'script' g.update({'__name__': modname}) if filename: g.update({'__file__': filename}) g.update({'argv': argv}) # Now we can execute the script using these collected globals exportNames = [] pf.scriptName = name exitall = False memu = memUsed() vmsiz = vmSize() pf.debug("MemUsed = %s; vmSize = %s" % (memu, vmsiz), pf.DEBUG.MEM) #starttime = time.clock() try: try: if pye: if type(scr) is file: scr = scr.read() + '\n' n = (len(scr) + 1) // 2 scr = utils.mergeme(scr[:n], scr[n:]) exec scr in g except _Exit: #print "EXIT FROM SCRIPT" pass except _ExitAll: exitall = True except: raise finally: # honour the exit function if 'atExit' in g: atExit = g['atExit'] try: atExit() except: pf.debug('Error while calling script exit function', pf.DEBUG.SCRIPT) if pf.cfg['autoglobals']: exportNames.extend(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("MemUsed = %s; vmSize = %s" % (memUsed(), vmSize()), pf.DEBUG.MEM) pf.debug( "Diff MemUsed = %s; diff vmSize = %s" % (memUsed() - memu, vmSize() - vmsiz), pf.DEBUG.MEM) if exitall: pf.debug("Calling quit() from playscript", pf.DEBUG.SCRIPT) quit()
def playScript(scr,name=None,filename=None,argv=[],pye=False): """Play a pyformex script scr. scr should be a valid Python text. There is a lock to prevent multiple scripts from being executed at the same time. This implies that pyFormex scripts can currently not be recurrent. If a name is specified, set the global variable pyformex.scriptName to it when the script is started. If a filename is specified, set the global variable __file__ to it. """ utils.warn('print_function') global exportNames,starttime global exitrequested # (We only allow one script executing at a time!) # and scripts are non-reentrant global scriptThread if scriptThread is not None and scriptThread.isAlive(): pf.message("Not executing this script because another one is already running") return if len(pf.scriptlock) > 0: pf.message("!!Not executing because a script lock has been set: %s" % pf.scriptlock) #print(pf.scriptlock) return scriptLock('__auto__') exitrequested = False if pf.GUI: pf.GUI.startRun() # Get the globals g = Globals() if pf.GUI: modname = 'draw' else: modname = 'script' g.update({'__name__':modname}) if filename: g.update({'__file__':filename}) g.update({'argv':argv}) # Now we can execute the script using these collected globals exportNames = [] pf.scriptName = name exitall = False memu = memUsed() vmsiz = vmSize() pf.debug("MemUsed = %s; vmSize = %s" % (memu,vmsiz),pf.DEBUG.MEM) #starttime = time.clock() try: try: if pye: if type(scr) is file: scr = scr.read() + '\n' n = (len(scr)+1) // 2 scr = utils.mergeme(scr[:n],scr[n:]) exec scr in g except _Exit: #print "EXIT FROM SCRIPT" pass except _ExitAll: exitall = True except: raise finally: # honour the exit function if 'atExit' in g: atExit = g['atExit'] try: atExit() except: pf.debug('Error while calling script exit function',pf.DEBUG.SCRIPT) if pf.cfg['autoglobals']: exportNames.extend(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("MemUsed = %s; vmSize = %s" % (memUsed(),vmSize()),pf.DEBUG.MEM) pf.debug("Diff MemUsed = %s; diff vmSize = %s" % (memUsed()-memu,vmSize()-vmsiz),pf.DEBUG.MEM) if exitall: pf.debug("Calling quit() from playscript",pf.DEBUG.SCRIPT) quit()