def load(self):
     if self.dir:
         files = os.listdir(self.dir)
     else:
         files = self.files
     filter1 = lambda s:s[-3:]==".py" and s[0]!='.' and s[0]!='_'
     if self.dir:
         filter2 = lambda s:utils.isPyFormex(os.path.join(self.dir,s))
     else:
         filter2 = utils.isPyFormex
     files = filter(filter1,files)
     files = filter(filter2,files)
     if self.dir:
         files.sort()
         files = map(lambda s:s[:-3],files)
     else:
         if self.max > 0 and len(files) > self.max:
             files = files[:self.max]
     self.files = files
     if GD.options.debug:
         print "Found Scripts in %s" % self.dir
         print self.files
     self.actions = [ self.addAction(f) for f in self.files ]           
     self.connect(self,QtCore.SIGNAL("triggered(QAction*)"),self.run)
     if self.dir:
         self.addSeparator()
         self.addAction('Run next script',self.runNext)
         self.addAction('Run all following scripts',self.runAllNext)
         self.addAction('Run all scripts',self.runAll)
         self.addAction('Reload scripts',self.reLoad)
     self.current = ""
    def filterFiles(self,files):
        """Filter a list of scripts"""
        filtr = lambda s:utils.isPyFormex(self.fileName(s))
        files = filter(filtr,files)

        if self.max > 0 and len(files) > self.max:
            files = files[:self.max]

        return files
Esempio n. 3
0
def runApp(args):
    """Run the application without gui."""
    # remaining args are interpreted as scripts, possibly interspersed
    # with arguments for the scripts.
    # each script should pop the required arguments from the list,
    # and return the remainder
    while len(args) > 0:
        if os.path.exists(args[0]) and utils.isPyFormex(args[0]):
            args = play(args[0],argv=args[1:])
            #print "Returned args: %s" % args
        if type(args) != list:
            args = []
Esempio n. 4
0
def runApp(args):
    """Run the application without gui."""
    # remaining args are interpreted as scripts, possibly interspersed
    # with arguments for the scripts.
    # each script should pop the required arguments from the list,
    # and return the remainder
##    GD.message = message

    while len(args) > 0:
        scr = args.pop(0) 
        if os.path.exists(scr) and utils.isPyFormex(scr):
            play(scr,args)
        else:
            raise RuntimeError,"No such pyFormex script found: %s" % scr
Esempio n. 5
0
def processArgs(args):
    """Run the application without gui.

    Arguments are interpreted as names of script files, possibly interspersed
    with arguments for the scripts.
    Each running script should pop the required arguments from the list.
    """
    while len(args) > 0:
        fn = args.pop(0)
        if not os.path.exists(fn) or not utils.isPyFormex(fn):
            GD.message("Skipping %s: does not exist or is not a pyFormex script" % fn)
            continue
        try:
            playFile(fn, args)
        except:
            GD.message("Error during execution of script %s" % fn)

    return 0
    def getFiles(self):
        """Get a list of scripts in self.dir"""
        files = os.listdir(self.dir)
        filtr = lambda s: s[0]!='.' and s[0]!='_'
        files = filter(filtr,files)
        if self.ext:
            filtr = lambda s: s.endswith(self.ext)
            files = filter(filtr,files)
            n = len(self.ext)
            files = [ f[:-n] for f in files ]

        filtr = lambda s:utils.isPyFormex(self.fileName(s))
        files = filter(filtr,files)

        if self.max > 0 and len(files) > self.max:
            files = files[:self.max]

        files.sort()
        return files
Esempio n. 7
0
    def setcurfile(self,filename=None):
        """Set the current file and check whether it is a pyFormex script.

        The checking is done by the function isPyFormex().
        A file that is not a pyFormex script can be loaded in the editor,
        but it can not be played as a pyFormex script.
        """
        if filename:
            GD.cfg['curfile'] = filename
        else:
            filename = GD.cfg.get('curfile','')
        if filename:
            GD.canPlay = utils.isPyFormex(filename)
            self.curfile.setText(os.path.basename(filename))
            self.actions['Play'].setEnabled(GD.canPlay)
            if GD.canPlay:
                icon = 'happy'
            else:
                icon = 'unhappy'
            self.smiley.setPixmap(QtGui.QPixmap(os.path.join(GD.cfg['icondir'],icon)+GD.cfg['gui/icontype']))
 def load(self,dir):
     self.dir = dir
     files = os.listdir(dir)
     filter1 = lambda s:s[-3:]==".py" and s[0]!='.' and s[0]!='_'
     filter2 = lambda s:utils.isPyFormex(os.path.join(dir,s))
     files = filter(filter1,files)
     files = filter(filter2,files)
     files.sort()
     self.files = map(lambda s:s[:-3],files)
     if GD.options.debug:
         print "Found Examples in %s" % dir
         print self.files
     for f in self.files:
         self.addAction(f)
     self.connect(self,QtCore.SIGNAL("triggered(QAction*)"),self.run)
     self.addSeparator()
     self.addAction('Run next example',self.runNext)
     self.addAction('Run all examples',self.runAll)
     self.addAction('Reload examples',self.reLoad)
     self.current = ""
Esempio n. 9
0
    def setcurfile(self,filename=''):
        """Set the current file and check whether it is a pyFormex script.

        The checking is done by the function isPyFormex().
        A file that is not a pyFormex script can be loaded in the editor,
        but it can not be played as a pyFormex script.
        """
        if filename:
            GD.cfg['curfile'] = filename
        else:
            filename = GD.cfg.get('curfile','')
        if filename:
            self.canPlay = utils.isPyFormex(filename) or filename.endswith('.pye')
            self.curfile.setText(os.path.basename(filename))
            self.actions['Play'].setEnabled(self.canPlay)
            self.actions['Step'].setEnabled(self.canPlay)
            if self.canPlay:
                icon = 'ok'
            else:
                icon = 'notok'
            self.curfile.setIcon(QtGui.QIcon(QtGui.QPixmap(os.path.join(GD.cfg['icondir'],icon)+GD.cfg['gui/icontype'])),0)
Esempio n. 10
0
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
    from optparse import OptionParser, make_option as MO

    parser = OptionParser(
        usage="usage: %prog [<options>] [ --  <Qapp-options> ] [[ scriptname [scriptargs]] ...]",
        version=pyformex.Version,
        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(
                "--safelib",
                action="store_true",
                dest="safelib",
                default=True,
                help="Convert data types to match C-lib. This is the default.",
            ),
            MO(
                "--unsafelib",
                action="store_false",
                dest="safelib",
                default=True,
                help="Do not convert data types to match C-lib. BEWARE: this may make the C-lib calls impossible. Use only for debugging purposes.",
            ),
            MO(
                "--fastencode",
                action="store_true",
                dest="fastencode",
                default=False,
                help="Use a fast algorithm to encode edges.",
            ),
            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(
                "--detect",
                action="store_true",
                dest="detect",
                default=False,
                help="Detect helper software and print report.",
            ),
            MO(
                "--debug", action="store_true", dest="debug", default=False, help="display debugging info to sys.stdout"
            ),
            MO(
                "--classify",
                action="store_true",
                dest="classify",
                default=False,
                help="classify the examples in categories",
            ),
            MO(
                "--whereami",
                action="store_true",
                dest="whereami",
                default=False,
                help="show where the pyformex package is located",
            ),
            MO("--remove", action="store_true", dest="remove", default=False, help="remove the pyformex installation"),
            MO("--test", action="store_true", dest="test", default=False, help="testing mode: only for developers!"),
            MO(
                "--testhighlight",
                action="store_true",
                dest="testhighlight",
                default=False,
                help="highlight testing mode: only for developers!",
            ),
            MO(
                "--executor",
                action="store_true",
                dest="executor",
                default=False,
                help="test alternate executor: only for developers!",
            ),
        ],
    )
    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()

    if pyformex.options.whereami:
        print("Script started from %s" % pyformex.scriptdir)
        print("I found pyFormex in %s " % pyformexdir)
        print("Current Python sys.path: %s" % sys.path)
        sys.exit()

    if pyformex.options.remove:
        remove_pyFormex(pyformexdir, pyformex.scriptdir)

    if pyformex.options.detect:
        print("Detecting all installed helper software")
        utils.checkExternal()
        print(utils.reportDetected())
        sys.exit()

    pyformex.debug("Options: %s" % pyformex.options)

    ########### Read the config files  ####################

    # Create the user conf dir
    if not os.path.exists(pyformex.cfg.userconfdir):
        os.mkdir(pyformex.cfg.userconfdir)

    # 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")

    # Migrate old user prefs
    olduserprefs = os.path.join(pyformex.cfg.homedir, ".pyformexrc")
    if not os.path.exists(pyformex.cfg.userprefs) and os.path.exists(olduserprefs):
        import shutil

        print("Moving user preferences to new location")
        print("%s --> %s" % (olduserprefs, pyformex.cfg.userprefs))
        shutil.move(olduserprefs, pyformex.cfg.userprefs)

    # 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("RefConfig: %s" % pyformex.refcfg)

    # Use the last as place to save preferences
    pyformex.cfg = Config(default=refLookup)
    if os.path.exists(pyformex.preffile):
        pyformex.debug("Reading config file %s" % pyformex.preffile)
        pyformex.cfg.read(pyformex.preffile)
    pyformex.debug("Config: %s" % pyformex.cfg)

    # 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.isPyFormex(args[0]))

    if pyformex.options.gui:
        pyformex.options.interactive = True

    # Set Revision if we run from an SVN version
    if svnversion:
        setRevision()

    pyformex.debug(utils.reportDetected())

    # print("pyformex",utils.subDict(pyformex.cfg,'canvas/'))
    # print("DEFAULT",self.default)
    # print(pyformex.cfg.keys())
    # print(pyformex.refcfg.keys())

    # Start the GUI if needed
    # Importing the gui should be done after the config is set !!
    if pyformex.options.gui:
        pyformex.debug("GUI version")
        from gui import gui

        gui.startGUI(args)
    #
    # 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

    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:
        res = gui.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
Esempio n. 11
0
def runApp(args):
    """Run the application without gui."""
    # remaining args are interpreted as scripts
    for arg in args:
        if os.path.exists(arg) and utils.isPyFormex(arg):
            play(arg)