def startGui(args=[]): """Start the gui""" if pf.GUI is None: pf.debug("Starting the pyFormex GUI") from gui import guimain if guimain.startGUI(args) == 0: guimain.runGUI()
def startGui(args=[]): """Start the gui""" if pf.GUI is None: pf.debug("Starting the pyFormex GUI", pf.DEBUG.GUI) from gui import guimain if guimain.startGUI(args) == 0: guimain.runGUI()
def run(argv=[]): """This is a fairly generic main() function. It is responsible for reading the configuration file(s), processing the command line options and starting the application. The basic configuration file is 'pyformexrc' located in the pyformex directory. It should always be present and be left unchanged. You can copy this file to another location if you want to make changes. By default, pyformex will try to read the following extra configuration files (in this order: default settings: <pyformexdir>/pyformexrc system-wide settings: /etc/pyformexrc user settings: $HOME/.pyformex/pyformexrc local settings $PWD/.pyformexrc Also, an extra config file can be specified in the command line. Config file settings always override previous ones. On exit, the preferences that were changed are written to the last read config file. Changed settings are those that differ from the settings in all but the last one. """ # Create a config instance pyformex.cfg = Config() # Fill in the pyformexdir and homedir variables # (use a read, not an update) if os.name == 'posix': homedir = os.environ['HOME'] elif os.name == 'nt': homedir = os.environ['HOMEDRIVE']+os.environ['HOMEPATH'] pyformex.cfg.read("pyformexdir = '%s'\n" % pyformexdir) pyformex.cfg.read("homedir = '%s'\n" % homedir) # Read the defaults (before the options) defaults = os.path.join(pyformexdir,"pyformexrc") pyformex.cfg.read(defaults) # Process options import optparse from optparse import make_option as MO parser = optparse.OptionParser( # THE Qapp options are removed, because it does not seem to work !!! # SEE the comments in the gui.startGUI function usage = "usage: %prog [<options>] [ [ scriptname [scriptargs] ] ...]", version = utils.FullVersion(), description = pyformex.Description, formatter = optparse.TitledHelpFormatter(), option_list=[ MO("--gui", action="store_true", dest="gui", default=None, help="start the GUI (default if no scriptfile argument is given)", ), MO("--nogui", action="store_false", dest="gui", default=None, help="do not load the GUI (default if a scriptfile argument is given)", ), MO("--interactive",'-i', action="store_true", dest="interactive", default=False, help="Go into interactive mode after processing the command line parameters. This is implied by the --gui option.", ), MO("--force-dri", action="store_true", dest="dri", default=None, help="Force use of Direct Rendering", ), MO("--force-nodri", action="store_false", dest="dri", default=None, help="Disables the Direct Rendering", ), MO("--uselib", action="store_true", dest="uselib", default=None, help="Use the pyFormex C lib if available. This is the default.", ), MO("--nouselib", action="store_false", dest="uselib", default=None, help="Do not use the pyFormex C-lib.", ), MO("--fastencode", action="store_true", dest="fastencode", default=False, help="Use a fast algorithm to encode edges.", ), MO("--norst2html", action="store_false", dest="rst2html", default=True, help="Do not try to convert rst messages to html before displaying.", ), MO("--config", action="store", dest="config", default=None, help="Use file CONFIG for settings", ), MO("--nodefaultconfig", action="store_true", dest="nodefaultconfig", default=False, help="Skip the default site and user config files. This option can only be used in conjunction with the --config option.", ), MO("--redirect", action="store_true", dest="redirect", default=False, help="Redirect standard output to the message board (ignored with --nogui)", ), MO("--debug", action="store_const", dest="debug", const=-1, help="display debugging info to sys.stdout", ), MO("--debuglevel", action="store", dest="debug", type="int", default=0, help="display debugging info to sys.stdout", ), ## MO("--classify", ## action="store_true", dest="classify", default=False, ## help="classify the examples in categories", ## ), MO("--newviewports", action="store_true", dest="newviewports", default=False, help="Use the new multiple viewport canvas implementation. This is an experimental feature only intended for developers.", ), MO("--testmodule", action="store", dest="testmodule", default=None, help="Run the docstring tests for module TESTMODULE. TESTMODULE is the name of the module, using . as path separator.", ), MO("--test", action="store_true", dest="test", default=False, help="testing mode: only for developers!", ), MO("--testexecutor", action="store_true", dest="executor", default=False, help="test alternate executor: only for developers!", ), MO("--remove", action="store_true", dest="remove", default=False, help="remove the pyformex installation and exit", ), MO("--whereami", action="store_true", dest="whereami", default=False, help="show where the pyformex package is installed and exit", ), MO("--detect", action="store_true", dest="detect", default=False, help="show detected helper software and exit", ), ]) pyformex.options, args = parser.parse_args(argv) pyformex.print_help = parser.print_help # process options if pyformex.options.nodefaultconfig and not pyformex.options.config: print("\nInvalid options: --nodefaultconfig but no --config option\nDo pyformex --help for help on options.\n") sys.exit() pyformex.debug("Options: %s" % pyformex.options) ########## Process special options which will not start pyFormex ####### if pyformex.options.remove or \ pyformex.options.whereami or \ pyformex.options.detect or \ pyformex.options.testmodule: if pyformex.options.remove: remove_pyFormex(pyformexdir,pyformex.scriptdir) if pyformex.options.whereami or pyformex.options.debug : print("Script started from %s" % pyformex.scriptdir) print("I found pyFormex in %s " % pyformexdir) print("Current Python sys.path: %s" % sys.path) if pyformex.options.detect or pyformex.options.debug : print("Detecting all installed helper software") utils.checkExternal() print(utils.reportDetected()) if pyformex.options.testmodule: for a in pyformex.options.testmodule.split(','): test_module(a) sys.exit() ########### Read the config files #################### # These values should not be changed pyformex.cfg.userprefs = os.path.join(pyformex.cfg.userconfdir,'pyformexrc') pyformex.cfg.autorun = os.path.join(pyformex.cfg.userconfdir,'startup.py') # Set the config files if pyformex.options.nodefaultconfig: sysprefs = [] userprefs = [] else: sysprefs = [ pyformex.cfg.siteprefs ] userprefs = [ pyformex.cfg.userprefs ] if os.path.exists(pyformex.cfg.localprefs): userprefs.append(pyformex.cfg.localprefs) if pyformex.options.config: userprefs.append(pyformex.options.config) if len(userprefs) == 0: # We should always have a place to store the user preferences userprefs = [ pyformex.cfg.userprefs ] pyformex.preffile = os.path.abspath(userprefs[-1]) # Settings will be saved here # Read all but the last as reference for f in filter(os.path.exists,sysprefs + userprefs[:-1]): pyformex.debug("Reading config file %s" % f) pyformex.cfg.read(f) pyformex.refcfg = pyformex.cfg pyformex.debug("="*60) pyformex.debug("RefConfig: %s" % pyformex.refcfg) # Use the last as place to save preferences pyformex.prefcfg = Config(default=refLookup) if os.path.exists(pyformex.preffile): pyformex.debug("Reading config file %s" % pyformex.preffile) pyformex.prefcfg.read(pyformex.preffile) pyformex.debug("="*60) pyformex.debug("Config: %s" % pyformex.prefcfg) # Fix incompatible changes in configuration apply_config_changes(pyformex.prefcfg) # Create an empty one for the session settings pyformex.cfg = Config(default=prefLookup) # This should probably be changed to options overriding config # Set option from config if it was not explicitely given if pyformex.options.uselib is None: pyformex.options.uselib = pyformex.cfg['uselib'] # Set default --nogui if first remaining argument is a pyformex script. if pyformex.options.gui is None: pyformex.options.gui = not (len(args) > 0 and utils.is_pyFormex(args[0])) if pyformex.options.gui: pyformex.options.interactive = True # Set Revision and run svnclean if we run from an SVN version if svnversion: setRevision() svnclean = os.path.join(pyformexdir,'svnclean') if os.path.exists(svnclean): try: utils.runCommand(svnclean) except: print("Error while executing %s, we ignore it and continue" % svnclean) def getSVNURL(): sta,out = utils.runCommand("cd %s;svn info | grep -F 'URL:'"%pyformexdir) if sta == 0: return out else: return '' ## s = getSVNURL() ## print s ## import re ## m = re.match(".*//(?P<user>[^@]*)@svn\.berlios\.de.*",s) ## pyformex.svnuser = m.group('user') ## print pyformex.svnuser ###### We have the config and options all set up ############ filterWarnings() def _format_warning(message,category,filename,lineno,line=None): """Replace the default warnings.formatwarning This allows the warnings being called using a simple mnemonic string. The full message is then found from the message module. """ import messages message = messages.getMessage(message) message = """.. pyFormex Warning ================ %s `Called from:` %s `line:` %s """ % (message,filename,lineno) if line: message += "%s\n" % line return message if pyformex.cfg['warnings/nice']: import warnings warnings.formatwarning = _format_warning # Start the GUI if needed # Importing the gui should be done after the config is set !! if pyformex.options.gui: from gui import guimain pyformex.debug("GUI version") res = guimain.startGUI(args) if res != 0: print("Could not start the pyFormex GUI: %s" % res) return res # EXIT # Display the startup warnings and messages if startup_warnings: if pyformex.cfg['startup_warnings']: pyformex.warning(startup_warnings) else: print(startup_warnings) if startup_messages: print(startup_messages) pyformex.debug(utils.reportDetected()) #print(pyformex.cfg.keys()) #print(pyformex.refcfg.keys()) # # Qt4 may have changed the locale. # Since a LC_NUMERIC setting other than C may cause lots of troubles # with reading and writing files (formats become incompatible!) # we put it back to a sane setting # utils.setSaneLocale() # Initialize the libraries #print("NOW LOAIDNG LIBS") #import lib #lib.init_libs(pyformex.options.uselib,pyformex.options.gui) # Prepend the autorun scripts ar = pyformex.cfg.get('autorun','') if ar : if type(ar) is str: ar = [ ar ] # expand tilde, as would bash ar = map(utils.tildeExpand,ar) args[0:0] = [ fn for fn in ar if os.path.exists(fn) ] # remaining args are interpreted as scripts and their parameters res = 0 if args: pyformex.debug("Remaining args: %s" % args) from script import processArgs res = processArgs(args) if res: if pyformex.options.gui: pyformex.message("There was an error while executing a script") else: return res # EXIT else: pyformex.debug("stdin is a tty: %s" % sys.stdin.isatty()) # Play script from stdin # Can we check for interactive session: stdin connected to terminal? #from script import playScript #playScript(sys.stdin) # after processing all args, go into interactive mode if pyformex.options.gui and pyformex.app: res = guimain.runGUI() ## elif pyformex.options.interactive: ## print("Enter your script and end with CTRL-D") ## from script import playScript ## playScript(sys.stdin) #Save the preferences that have changed savePreferences() # Exit return res
def run(argv=[]): """This is a fairly generic main() function. It is responsible for reading the configuration file(s), processing the command line options and starting the application. The basic configuration file is 'pyformexrc' located in the pyformex directory. It should always be present and be left unchanged. You can copy this file to another location if you want to make changes. By default, pyformex will try to read the following extra configuration files (in this order: default settings: <pyformexdir>/pyformexrc system-wide settings: /etc/pyformexrc user settings: $HOME/.pyformex/pyformexrc local settings $PWD/.pyformexrc Also, an extra config file can be specified in the command line. Config file settings always override previous ones. On exit, the preferences that were changed are written to the last read config file. Changed settings are those that differ from the settings in all but the last one. """ # Create a config instance pf.cfg = Config() # Fill in the pyformexdir and homedir variables # (use a read, not an update) if os.name == 'posix': homedir = os.environ['HOME'] elif os.name == 'nt': homedir = os.environ['HOMEDRIVE'] + os.environ['HOMEPATH'] pf.cfg.read("pyformexdir = '%s'\n" % pyformexdir) pf.cfg.read("homedir = '%s'\n" % homedir) # Read the defaults (before the options) defaults = os.path.join(pyformexdir, "pyformexrc") pf.cfg.read(defaults) # Process options import optparse from optparse import make_option as MO parser = optparse.OptionParser( # THE Qapp options are removed, because it does not seem to work !!! # SEE the comments in the gui.startGUI function usage="usage: %prog [<options>] [ [ scriptname [scriptargs] ] ...]", version=pf.fullVersion(), description=pf.Description, formatter=optparse.TitledHelpFormatter(), option_list=[ MO( "--gui", action="store_true", dest="gui", default=None, help= "Start the GUI (this is the default when no scriptname argument is given)", ), MO( "--nogui", action="store_false", dest="gui", default=None, help= "Do not start the GUI (this is the default when a scriptname argument is given)", ), MO( "--interactive", action="store_true", dest="interactive", default=False, help= "Go into interactive mode after processing the command line parameters. This is implied by the --gui option.", ), MO( "--dri", action="store_true", dest="dri", default=None, help= "Use Direct Rendering Infrastructure. By default, direct rendering will be used if available.", ), MO( "--nodri", action="store_false", dest="dri", default=None, help= "Do not use the Direct Rendering Infrastructure. This may be used to turn off the direc rendering, e.g. to allow better capturing of images and movies.", ), MO( "--uselib", action="store_true", dest="uselib", default=None, help= "Use the pyFormex C lib if available. This is the default.", ), MO( "--nouselib", action="store_false", dest="uselib", default=None, help="Do not use the pyFormex C-lib.", ), MO( "--commands", action="store_true", dest="commands", default=False, help= "Use the commands module to execute external commands. Default is to use the subprocess module.", ), MO( "--config", action="store", dest="config", default=None, help="Use file CONFIG for settings", ), MO( "--nodefaultconfig", action="store_true", dest="nodefaultconfig", default=False, help= "Skip the default site and user config files. This option can only be used in conjunction with the --config option.", ), MO( "--redirect", action="store_true", dest="redirect", default=None, help= "Redirect standard output to the message board (ignored with --nogui)", ), MO( "--noredirect", action="store_false", dest="redirect", help="Do not redirect standard output to the message board.", ), MO( "--debug", action="store", dest="debug", default='', help= "Display debugging information to sys.stdout. The value is a comma-separated list of (case-insensitive) strings corresponding with the attributes of the DebugLevels class. The individual values are OR-ed together to produce a final debug value. The special value 'all' can be used to switch on all debug info.", ), MO( "--debuglevel", action="store", dest="debuglevel", type="int", default=0, help= "Display debugging info to sys.stdout. The value is an int with the bits of the requested debug levels set. A value of -1 switches on all debug info. If this option is used, it overrides the --debug option.", ), MO( "--newviewports", action="store_true", dest="newviewports", default=False, help= "Use the new multiple viewport canvas implementation. This is an experimental feature only intended for developers.", ), MO( "--testmodule", action="store", dest="testmodule", default=None, help= "Run the docstring tests for module TESTMODULE. TESTMODULE is the name of the module, using . as path separator.", ), MO( "--testcamera", action="store_true", dest="testcamera", default=False, help="Print camera settings whenever they change.", ), MO( "--testexecutor", action="store_true", dest="executor", default=False, help="Test alternate executor: only for developers!", ), MO( "--memtrack", action="store_true", dest="memtrack", default=False, help="Track memory for leaks. This is only for developers.", ), MO( "--fastnurbs", action="store_true", dest="fastnurbs", default=False, help="Test C library nurbs drawing: only for developers!", ), MO( "--pyside", action="store_true", dest="pyside", default=None, help="Use the PySide bindings for QT4 libraries", ), MO( "--pyqt4", action="store_false", dest="pyside", default=None, help="Use the PyQt4 bindings for QT4 libraries", ), MO( "--opengl2", action="store_true", dest="opengl2", default=False, help= "Use the new OpenGL rendering engine. This is an experimental feature only intended for developers.", ), MO( "--listfiles", action="store_true", dest="listfiles", default=False, help="List the pyformex Python source files.", ), MO( "--search", action="store_true", dest="search", default=False, help= "Search the pyformex source for a specified pattern and exit. This can optionally be followed by -- followed by options for the grep command and/or '-a' to search all files in the extended search path. The final argument is the pattern to search. '-e' before the pattern will interprete this as an extended regular expression. '-l' option only lists the names of the matching files.", ), MO( "--remove", action="store_true", dest="remove", default=False, help= "Remove the pyFormex installation and exit. This option only works when pyFormex was installed from a tarball release using the supplied install procedure. If you install from a distribution package (e.g. Debian), you should use your distribution's package tools to remove pyFormex. If you run pyFormex directly from SVN sources, you should just remove the whole checked out source tree.", ), MO( "--whereami", action="store_true", dest="whereami", default=False, help="Show where the pyformex package is installed and exit", ), MO( "--detect", action="store_true", dest="detect", default=False, help="Show detected helper software and exit", ), ]) pf.options, args = parser.parse_args(argv) pf.print_help = parser.print_help # Set debug level if pf.options.debug and not pf.options.debuglevel: pf.options.debuglevel = pf.debugLevel(pf.options.debug.split(',')) # process options if pf.options.nodefaultconfig and not pf.options.config: print( "\nInvalid options: --nodefaultconfig but no --config option\nDo pyformex --help for help on options.\n" ) sys.exit() pf.debug("Options: %s" % pf.options, pf.DEBUG.ALL) ########## Process special options which will not start pyFormex ####### if pf.options.testmodule: for a in pf.options.testmodule.split(','): test_module(a) return if pf.options.remove: remove_pyFormex(pyformexdir, pf.bindir) return if pf.options.whereami: # or pf.options.detect : pf.options.debuglevel |= pf.DEBUG.INFO pf.debug("pyformex script started from %s" % pf.bindir, pf.DEBUG.INFO) pf.debug("I found pyFormex installed in %s " % pyformexdir, pf.DEBUG.INFO) pf.debug("Current Python sys.path: %s" % sys.path, pf.DEBUG.INFO) if pf.options.detect: print("Detecting installed helper software") utils.checkExternal() print(utils.reportDetected()) if pf.options.whereami or pf.options.detect: return ########### Read the config files #################### # These values should not be changed pf.cfg.userprefs = os.path.join(pf.cfg.userconfdir, 'pyformexrc') # Set the config files if pf.options.nodefaultconfig: sysprefs = [] userprefs = [] else: sysprefs = [pf.cfg.siteprefs] userprefs = [pf.cfg.userprefs] if os.path.exists(pf.cfg.localprefs): userprefs.append(pf.cfg.localprefs) if pf.options.config: userprefs.append(pf.options.config) if len(userprefs) == 0: # We should always have a place to store the user preferences userprefs = [pf.cfg.userprefs] pf.preffile = os.path.abspath(userprefs[-1]) # Settings will be saved here # Read all but the last as reference for f in filter(os.path.exists, sysprefs + userprefs[:-1]): pf.debug("Reading config file %s" % f, pf.DEBUG.CONFIG) pf.cfg.read(f) pf.refcfg = pf.cfg pf.debug("=" * 60, pf.DEBUG.CONFIG) pf.debug("RefConfig: %s" % pf.refcfg, pf.DEBUG.CONFIG) # Use the last as place to save preferences pf.prefcfg = Config(default=refLookup) if os.path.exists(pf.preffile): pf.debug("Reading config file %s" % pf.preffile, pf.DEBUG.CONFIG) pf.prefcfg.read(pf.preffile) pf.debug("=" * 60, pf.DEBUG.CONFIG) pf.debug("Config: %s" % pf.prefcfg, pf.DEBUG.CONFIG) # Fix incompatible changes in configuration apply_config_changes(pf.prefcfg) # Create an empty one for the session settings pf.cfg = Config(default=prefLookup) #################################################################### ## Post config initialization ## # process non-starting options dependent on config if pf.options.search or pf.options.listfiles: if len(args) > 0: opts = [a for a in args if a.startswith('-')] args = [a for a in args if not a in opts] if '-a' in opts: opts.remove('-a') extended = True else: extended = False if len(args) > 1: files = args[1:] else: files = utils.sourceFiles(relative=True, extended=extended) if pf.options.listfiles: print('\n'.join(files)) else: cmd = "grep %s '%s' %s" % (' '.join(opts), args[0], ''.join( [" '%s'" % f for f in files])) #print(cmd) os.system(cmd) return # process other options dependent on config if pf.options.pyside is None: pf.options.pyside = pf.cfg['gui/bindings'].lower() == 'pyside' # process options that override the config if pf.options.redirect is not None: pf.cfg['gui/redirect'] = pf.options.redirect delattr(pf.options, 'redirect') # avoid abuse #print "REDIRECT",pf.cfg['gui/redirect'] ################################################################### # This should probably be changed to options overriding config # Set option from config if it was not explicitely given if pf.options.uselib is None: pf.options.uselib = pf.cfg['uselib'] # Set default --nogui if first remaining argument is a pyformex script. if pf.options.gui is None: pf.options.gui = not (len(args) > 0 and utils.is_pyFormex(args[0])) if pf.options.gui: pf.options.interactive = True # If we run from an source version, we should set the proper revision # number and run the svnclean procedure. if pf.installtype in 'SG': svnclean = os.path.join(pyformexdir, 'svnclean') if os.path.exists(svnclean): try: utils.system(svnclean) except: print("Error while executing %s, we ignore it and continue" % svnclean) ###### We have the config and options all set up ############ filterWarnings() def _format_warning(message, category, filename, lineno, line=None): """Replace the default warnings.formatwarning This allows the warnings being called using a simple mnemonic string. The full message is then found from the message module. """ import messages message = messages.getMessage(message) message = """.. pyFormex Warning ================ %s `Called from:` %s `line:` %s """ % (message, filename, lineno) if line: message += "%s\n" % line return message if pf.cfg['warnings/nice']: import warnings warnings.formatwarning = _format_warning utils.checkModule('numpy', fatal=True) # Make sure pf.PF is a Project from project import Project pf.PF = Project() utils.setSaneLocale() # Set application paths pf.debug("Loading AppDirs", pf.DEBUG.INFO) import apps apps.setAppDirs() # Start the GUI if needed # Importing the gui should be done after the config is set !! if pf.options.gui: from gui import guimain pf.debug("GUI version", pf.DEBUG.INFO) res = guimain.startGUI(args) if res != 0: print("Could not start the pyFormex GUI: %s" % res) return res # EXIT # Display the startup warnings and messages if startup_warnings: if pf.cfg['startup_warnings']: pf.warning(startup_warnings) else: print(startup_warnings) if startup_messages: print(startup_messages) if pf.options.debuglevel & pf.DEBUG.INFO: # NOTE: inside an if to avoid computing the report when not printed pf.debug(utils.reportDetected(), pf.DEBUG.INFO) # # Qt4 may have changed the locale. # Since a LC_NUMERIC setting other than C may cause lots of troubles # with reading and writing files (formats become incompatible!) # we put it back to a sane setting # utils.setSaneLocale() # Initialize the libraries #import lib #lib.init_libs(pf.options.uselib,pf.options.gui) # Prepend the autorun script ar = pf.cfg.get('autorun', '') if ar and os.path.exists(ar): args[0:0] = [ar] # remaining args are interpreted as scripts and their parameters res = 0 if args: pf.debug("Remaining args: %s" % args, pf.DEBUG.INFO) from script import processArgs res = processArgs(args) if res: if pf.options.gui: pf.message("There was an error while executing a script") else: return res # EXIT else: pf.debug("stdin is a tty: %s" % sys.stdin.isatty(), pf.DEBUG.INFO) # Play script from stdin # Can we check for interactive session: stdin connected to terminal? #from script import playScript #playScript(sys.stdin) # after processing all args, go into interactive mode if pf.options.gui and pf.app: res = guimain.runGUI() ## elif pf.options.interactive: ## print("Enter your script and end with CTRL-D") ## from script import playScript ## playScript(sys.stdin) #Save the preferences that have changed savePreferences() # Exit return res