def saveImage(multi=False):
    """Save an image to file.

    This will show the Save Image dialog, with the multisave mode checked if
    multi = True. Then, depending on the user's selection, it will either:
     - save the current Canvas/Window to file
     - start the multisave/autosave mode
     - do nothing
    """
    pat = map(utils.fileDescription, ['img','icon','all'])  
    dia = widgets.SaveImageDialog(GD.cfg['workdir'],pat,multi=multi)
    opt = dia.getResult()
    if opt:
        if opt.fm == 'From Extension':
            opt.fm = None
        if opt.qu < 0:
            opt.qu = -1
        updateSettings({'workdir':os.path.dirname(opt.fn)},save=True)
        image.save(filename=opt.fn,
                   format=opt.fm,
                   quality=opt.qu,
                   window=opt.wi,
                   multi=opt.mu,
                   hotkey=opt.hk,
                   autosave=opt.au,
                   border=opt.bo,
                   rootcrop=opt.rc
                   )
Beispiel #2
0
def runGUI():
    """Go into interactive mode"""

    egg = pf.cfg.get('gui/easter_egg',None)
    pf.debug('EGG: %s' % str(egg),pf.DEBUG.INFO)
    if egg:
        pf.debug('EGG')
        if type(egg) is str:
            pye = egg.endswith('pye')
            egg = open(egg).read()
        else:
            pye = True
            egg = ''.join(egg)
        draw.playScript(egg,pye=True)

    if os.path.isdir(pf.cfg['workdir']):
        # Make the workdir the current dir
        os.chdir(pf.cfg['workdir'])
        pf.debug("Setting workdir to %s" % pf.cfg['workdir'],pf.DEBUG.INFO)
    else:
        # Save the current dir as workdir
        prefMenu.updateSettings({'workdir':os.getcwd(),'_save_':True})

    pf.interactive = True
    pf.debug("Start main loop",pf.DEBUG.INFO)

    #utils.procInfo('runGUI')
    #from multiprocessing import Process
    #p = Process(target=pf.app.exec_)
    #p.start()
    #res = p.join()
    res = pf.app.exec_()
    pf.debug("Exit main loop with value %s" % res,pf.DEBUG.INFO)
    return res
Beispiel #3
0
def closeProject(save=None,clear=None):
    """Close the current project, saving it or not.

    Parameters:

    - `save`: None, True or False. Determines whether the project should be
      saved prior to closing it. If None, it will be asked from the user.
      Note that this parameter is only used for named Projects. Temporary
      Projects are never saved implicitely.
    - `clear`: None, True or False.
    """
    if pf.PF.filename is not None:
        if save is None:
            save = draw.ack("Save the current project before closing it?")
        pf.message("Closing project %s (save=%s)" % (pf.PF.filename,save))
        if save:
            saveProject()
            if pf.PF:
                listProject()
                if clear is None:
                    clear = draw.ask("What shall I do with the existing globals?",["Delete","Keep"]) == "Delete"

    if clear:
        pf.PF.clear()

    pf.PF.filename = None
    pf.GUI.setcurproj('None')
    updateSettings({
        'curproj':pf.PF.filename,
        },save=True)
def runGUI():
    """Go into interactive mode"""
    
    egg = pf.cfg.get('gui/easter_egg',None)
    pf.debug('EGG: %s' % str(egg))
    if egg:
        pf.debug('EGG')
        if type(egg) is str:
            pye = egg.endswith('pye')
            egg = file(egg).read()
        else:
            pye = True
            egg = ''.join(egg)
        draw.playScript(egg,pye=True)

    if os.path.isdir(pf.cfg['workdir']):
        # Make the workdir the current dir
        os.chdir(pf.cfg['workdir'])
        pf.debug("Setting workdir to %s" % pf.cfg['workdir'])
    else:
        # Save the current dir as workdir
        prefMenu.updateSettings({'workdir':os.getcwd(),'Save changes':True})

    pf.interactive = True
    pf.debug("Start main loop")

    #utils.procInfo('runGUI')
    #from multiprocessing import Process
    #p = Process(target=pf.app.exec_)
    #p.start()
    #res = p.join()
    res = pf.app.exec_()
    pf.debug("Exit main loop with value %s" % res)
    return res
Beispiel #5
0
def closeProject(save=None, clear=None):
    """Close the current project, saving it or not.

    Parameters:

    - `save`: None, True or False. Determines whether the project should be
      saved prior to closing it. If None, it will be asked from the user.
      Note that this parameter is only used for named Projects. Temporary
      Projects are never saved implicitely.
    - `clear`: None, True or False.
    """
    if pf.PF.filename is not None:
        if save is None:
            save = draw.ack("Save the current project before closing it?")
        pf.message("Closing project %s (save=%s)" % (pf.PF.filename, save))
        if save:
            saveProject()
            if pf.PF:
                listProject()
                if clear is None:
                    clear = draw.ask(
                        "What shall I do with the existing globals?",
                        ["Delete", "Keep"]) == "Delete"

    if clear:
        pf.PF.clear()

    pf.PF.filename = None
    pf.GUI.setcurproj('None')
    updateSettings({
        'curproj': pf.PF.filename,
    }, save=True)
Beispiel #6
0
def saveImage(multi=False):
    """Save an image to file.

    This will show the Save Image dialog, with the multisave mode checked if
    multi = True. Then, depending on the user's selection, it will either:
     - save the current Canvas/Window to file
     - start the multisave/autosave mode
     - do nothing
    """
    pat = map(utils.fileDescription, ['img', 'icon', 'all'])
    dia = widgets.SaveImageDialog(pf.cfg['workdir'], pat, multi=multi)
    opt = dia.getResult()
    if opt:
        if opt.fm == 'From Extension':
            if utils.fileTypeFromExt(opt.fn) == '':
                opt.fn += '.png'
            opt.fm = None
        if opt.qu < 0:
            opt.qu = -1
        updateSettings({'workdir': os.path.dirname(opt.fn)}, save=True)
        image.save(filename=opt.fn,
                   format=opt.fm,
                   quality=opt.qu,
                   size=opt.sz,
                   window=opt.wi,
                   multi=opt.mu,
                   hotkey=opt.hk,
                   autosave=opt.au,
                   border=opt.bo,
                   rootcrop=opt.rc)
Beispiel #7
0
def saveAsProject():
    proj = openProject(pf.PF.filename,exist=False,access=['w'],default='w')
    if proj is not None: # even if empty
        pf.PF.filename = proj.filename
        pf.PF.gzip = proj.gzip
        pf.PF.signature = proj.signature  # put new signature inside
        saveProject()
    if pf.PF.filename is not None:
        updateSettings({
            'curproj':pf.PF.filename,
            'workdir':os.path.dirname(pf.PF.filename),
            },save=True)
    pf.GUI.setcurproj(pf.PF.filename)
Beispiel #8
0
 def accept(save=False):
     dia.acceptData()
     res = dia.results
     vp = getVp(res['viewport'])
     pf.debug("Changing Canvas settings for viewport %s to:\n%s"%(pf.GUI.viewports.viewIndex(vp),res),pf.DEBUG.CANVAS)
     pf.canvas.settings.update(res,strict=False)
     pf.canvas.redrawAll()
     pf.canvas.update()
     if save:
         res = utils.prefixDict(res,'canvas/')
         print(res)
         res['_save_'] = save
         prefMenu.updateSettings(res)
Beispiel #9
0
def saveAsProject():
    proj = openProject(pf.PF.filename, exist=False, access=['w'], default='w')
    if proj is not None:  # even if empty
        pf.PF.filename = proj.filename
        pf.PF.gzip = proj.gzip
        pf.PF.signature = proj.signature  # put new signature inside
        saveProject()
    if pf.PF.filename is not None:
        updateSettings(
            {
                'curproj': pf.PF.filename,
                'workdir': os.path.dirname(pf.PF.filename),
            },
            save=True)
    pf.GUI.setcurproj(pf.PF.filename)
Beispiel #10
0
def setBackground(mode,color1,color2,color3,color4,showimage,image,_save_):
    if mode == 'solid':
        color = color1
    elif mode == 'vertical':
        color = [color1,color1,color4,color4]
    elif mode == 'horizontal':
        color = [color1,color2,color2,color1]
    else:
        color = [color1,color2,color3,color4]
    if not showimage:
        image = None
    pf.canvas.setBackground(color=color,image=image)
    pf.canvas.update()
    if _save_:
        prefMenu.updateSettings({
            'canvas/bgmode':mode,
            'canvas/bgcolor':color,
            'canvas/bgimage':image,
            '_save_':_save_})
Beispiel #11
0
def openScript(fn=None, exist=True, create=False):
    """Open a pyFormex script and set it as the current script.

    If no filename is specified, a file selection dialog is started to select
    an existing script, or allow to create a new file if exist is False.

    If the file exists and is a pyFormex script, it is set ready to execute.

    If create is True, a default pyFormex script template will be written
    to the file, overwriting the contents if the file existed. Then, the
    script is loaded into the editor.

    We encourage the use of createScript() to create new scripts and leave
    openScript() to open existing scripts.
    """
    if fn is None:
        cur = pf.cfg['curfile']
        if cur is None:
            cur = pf.cfg['workdir']
        if cur is None:
            cur = '.'
        typ = utils.fileDescription('pyformex')
        fn = widgets.FileSelection(cur, typ, exist=exist).getFilename()
    if fn:
        if create:
            if not exist and os.path.exists(fn) and not draw.ack(
                    "The file %s already exists.\n Are you sure you want to overwrite it?"
                    % fn):
                return None
            template = pf.cfg['scripttemplate']
            if (os.path.exists(template)):
                shutil.copyfile(template, fn)
        updateSettings({'workdir': os.path.dirname(fn)}, save=True)
        pf.GUI.setcurfile(fn)
        pf.GUI.scripthistory.add(fn)
        if create:
            draw.editFile(fn)
    return fn
def openScript(fn=None,exist=True,create=False):
    """Open a pyFormex script and set it as the current script.

    If no filename is specified, a file selection dialog is started to select
    an existing script, or allow to create a new file if exist is False.

    If the file exists and is a pyFormex script, it is set ready to execute.

    If create is True, a default pyFormex script template will be written
    to the file, overwriting the contents if the file existed. Then, the
    script is loaded into the editor.

    We encourage the use of createScript() to create new scripts and leave
    openScript() to open existing scripts.
    """
    if fn is None:
        cur = GD.cfg['curfile']
        if cur is None:
            cur = GD.cfg['workdir']
        if cur is None:
            cur  = '.'
        typ = utils.fileDescription('pyformex')
        fn = widgets.FileSelection(cur,typ,exist=exist).getFilename()
    if fn:
        if create:
            if not exist and os.path.exists(fn) and not draw.ack("The file %s already exists.\n Are you sure you want to overwrite it?" % fn):
                return None
            template = GD.cfg['scripttemplate']
            if (os.path.exists(template)):
                shutil.copyfile(template,fn)
        updateSettings({'workdir':os.path.dirname(fn)},save=True)
        GD.GUI.setcurfile(fn)
        GD.GUI.history.add(fn)
        if create:
            editScript(fn)
    return fn
def startGUI(args):
    """Create the QT4 application and GUI.

    A (possibly empty) list of command line options should be provided.
    QT4 wil remove the recognized QT4 and X11 options.
    """
    # This seems to be the only way to make sure the numeric conversion is
    # always correct
    #
    QtCore.QLocale.setDefault(QtCore.QLocale.c())
    #
    #pf.options.debug = -1
    pf.debug("Arguments passed to the QApplication: %s" % args)
    pf.app = QtGui.QApplication(args)
    
    #
    pf.debug("Arguments left after constructing the QApplication: %s" % args)
    pf.debug("Arguments left after constructing the QApplication: %s" % pf.app.arguments().join('\n'))
    #pf.options.debug = 0
    # As far as I have been testing this, the args passed to the Qt application are
    # NOT acknowledged and neither are they removed!!


    pf.app.setOrganizationName("pyformex.org")
    pf.app.setOrganizationDomain("pyformex.org")
    pf.app.setApplicationName("pyFormex")
    pf.app.setApplicationVersion(pf.__version__)
    ## pf.settings = QtCore.QSettings("pyformex.org", "pyFormex")
    ## pf.settings.setValue("testje","testvalue")
    
    #QtCore.QObject.connect(pf.app,QtCore.SIGNAL("lastWindowClosed()"),pf.app,QtCore.SLOT("quit()"))
    QtCore.QObject.connect(pf.app,QtCore.SIGNAL("lastWindowClosed()"),quitGUI)
    #QtCore.QObject.connect(pf.app,QtCore.SIGNAL("aboutToQuit()"),quitGUI)

    # Check if we have DRI
    viewport.setOpenGLFormat()
    dri = viewport.opengl_format.directRendering()


    # Check for existing pyFormex processes
    windowname,running = findOldProcesses()

    while len(running) > 0:
        if len(running) >= 16:
            print("Too many open pyFormex windows --- bailing out")
            return -1

        pids = [ i[2] for i in running if i[2] is not None ]
        warning = """..

pyFormex is already running on this screen
------------------------------------------
A main pyFormex window already exists on your screen. 

If you really intended to start another instance of pyFormex, you
can just continue now.

The window might however be a leftover from a previously crashed pyFormex
session, in which case you might not even see the window anymore, nor be able
to shut down that running process. In that case, you would better bail out now
and try to fix the problem by killing the related process(es).

If you think you have already killed those processes, you may check it by
rerunning the tests.
"""
        actions = ['Really Continue','Rerun the tests','Bail out and fix the problem']
        if pids:
            warning += """

I have identified the process(es) by their PID as::

%s

If you trust me enough, you can also have me kill this processes for you.
""" % pids
            actions[2:2] = ['Kill the running processes']
            
        if dri:
            answer = draw.ask(warning,actions)
        else:
            warning += """
I have detected that the Direct Rendering Infrastructure
is not activated on your system. Continuing with a second
instance of pyFormex may crash your XWindow system.
You should seriously consider to bail out now!!!
"""
            answer = draw.warning(warning,actions)


        if answer == 'Really Continue':
            break # OK, Go ahead

        elif answer == 'Rerun the tests':
            windowname,running = findOldProcesses() # try again
        
        elif answer == 'Kill the running processes':
            killProcesses(pids)
            windowname,running = findOldProcesses() # try again
            
        else:
            return -1 # I'm out of here!

        
    # Load the splash image
    splash = None
    if os.path.exists(pf.cfg['gui/splash']):
        pf.debug('Loading splash %s' % pf.cfg['gui/splash'])
        splashimage = QtGui.QPixmap(pf.cfg['gui/splash'])
        splash = QtGui.QSplashScreen(splashimage)
        splash.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
        splash.setFont(QtGui.QFont("Helvetica",24))
        splash.showMessage(pf.Version,QtCore.Qt.AlignHCenter,QtCore.Qt.red)
        splash.show()

    # create GUI, show it, run it

    pf.GUI = GUI(windowname,
                 pf.cfg.get('gui/size',(800,600)),
                 pf.cfg.get('gui/pos',(0,0)),
                 pf.cfg.get('gui/bdsize',(800,600)),
                 )

    # set the appearance
    pf.GUI.setAppearence()


    # setup the message board
    pf.board = pf.GUI.board
    pf.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.
""" % pf.Version)
    
    # Set interaction functions
    
    def show_warning(message,category,filename,lineno,file=None,line=None):
        """Replace the default warnings.showwarning

        We display the warnings using our interactive warning widget.
        This feature can be turned off by setting
        cfg['warnings/popup'] = False
        """
        full_message = warnings.formatwarning(message,category,filename,lineno,line)
        ## from widgets import simpleInputItem as I
        ## res = draw.askItems([
        ##     I('message',message,itemtype='label',text='warning'),
        ##     I('filter',False,text='Suppress this message in future sessions'),
        ##     ],actions=[('OK',)],legacy=False)
        #print res
        pf.message(full_message)
        res,check = draw.showMessage(full_message,level='warning',check="Do not show this warning anymore in future sessions")
        if check[0]:
            oldfilters = pf.prefcfg['warnings/filters']
            newfilters = oldfilters + [(str(message),)]
            pf.prefcfg.update({'filters':newfilters},name='warnings')


##     def format_warning(message,category,filename,lineno,line=None):
##         """Replace the default warnings.formatwarning

##         We display the warnings using our interactive warning widget.
##         This feature can be turned off by setting
##         cfg['nice_warnings'] = False
##         """
##         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']:
##         warnings.formatwarning = format_warning

    if pf.cfg['warnings/popup']:
        warnings.showwarning = show_warning
    
    
    pf.message = draw.message
    pf.warning = draw.warning

    # setup the canvas
    pf.GUI.viewports.changeLayout(1)
    pf.GUI.viewports.setCurrent(0)
    pf.canvas = pf.GUI.viewports.current
    draw.reset()

    # setup the status bar
    pf.GUI.addInputBox()
    pf.GUI.toggleInputBox(False)
    pf.GUI.addCoordsTracker()
    pf.GUI.toggleCoordsTracker(pf.cfg.get('gui/coordsbox',False))
    pf.debug("Using window name %s" % pf.GUI.windowTitle())
    
    # Create additional menus (put them in a list to save)
    
    # History Menu
    pf.GUI.history = scriptMenu.ScriptMenu('History',files=pf.cfg['gui/history'],max=pf.cfg['gui/history_max'])

    if pf.cfg.get('gui/history_in_main_menu',False):
        before = pf.GUI.menu.item('help')
        pf.GUI.menu.insertMenu(before,pf.GUI.history)
    else:
        filemenu = pf.GUI.menu.item('file')
        before = filemenu.item('---1')
        filemenu.insertMenu(before,pf.GUI.history)
    

    # Scripts menu
    pf.GUI.scriptmenu = scriptMenu.createScriptMenu(pf.GUI.menu,before='help')

    # Create databases
    createDatabases()
 
    # PLugin menus
    import plugins
    ## filemenu = pf.GUI.menu.item('file')
    ## pf.gui.saveobj = plugins.create_plugin_menus(filemenu,before='options')
    ## # Load configured plugins, ignore if not found
    plugins.loadConfiguredPlugins()
    #for p in pf.cfg['gui/plugins']:
    #    plugins.load(p)

    pf.GUI.setBusy(False)
    pf.GUI.addStatusBarButtons()

    # remove the splash window
    if splash is not None:
        splash.finish(pf.GUI)

    pf.GUI.setBusy(False)

    if os.path.isdir(pf.cfg['workdir']):
        # Make the workdir the current dir
        os.chdir(pf.cfg['workdir'])
        pf.debug("Setting workdir to %s" % pf.cfg['workdir'])
    else:
        # Save the current dir as workdir
        prefMenu.updateSettings({'workdir':os.getcwd(),'Save changes':True})

    pf.GUI.show()
    pf.GUI.update()
    pf.app_started = True
    pf.GUI.processEvents()
    return 0
def createProject(create=True,compression=0,addGlobals=None,makeDefault=True):
    """Open a file selection dialog and let the user select a project.

    The default will let the user create new project files as well as open
    existing ones.
    Use create=False or the convenience function openProject to only accept
    existing project files.

    If a compression level (1..9) is given, the contents will be compressed,
    resulting in much smaller project files at the cost of  

    Only one pyFormex project can be open at any time. The open project
    owns all the global data created and exported by any script.

    If makeDefault is True, an already open project will be closed and
    the opened project becomes the current project.
    If makeDefault is False, the project data are imported into GD.PF
    and the current project does not change. This means that if a project was
    open, the imported data will be added to it.
    
    If addGlobals is None, the user is asked whether the current globals
    should be added to the project. Set True or False to force or reject
    the adding without asking.
    """
    global the_project

    # ask filename from user
    if the_project is None:
        cur = GD.cfg.get('workdir','.')
    else:
        if makeDefault:
            options = ['Cancel','Close without saving','Save and Close']
            ans = draw.ask("Another project is still open. Shall I close it first?",
                        options)
            if ans == 'Cancel':
                return
            if ans == options[2]:
                the_project.save()
        cur = the_project.filename
    typ = utils.fileDescription(['pyf','all'])
    res = widgets.ProjectSelection(cur,typ,exist=not create).getResult()
    if res is None:
        # user canceled
        return

    fn = res.fn
    if not fn.endswith('.pyf'):
        fn += '.pyf'
    legacy = res.leg
    ignoresig = res.sig
    compression = res.cpr
    #print(fn,legacy,compression)

    if create and os.path.exists(fn):
        res = draw.ask("The project file '%s' already exists\nShall I delete the contents or add to it?" % fn,['Delete','Add','Cancel'])
        if res == 'Cancel':
            return
        if res == 'Add':
            create = False
    GD.message("Opening project %s" % fn)
    
    if GD.PF:
        GD.message("Exported symbols: %s" % GD.PF.keys())
        if addGlobals is None:
            res = draw.ask("pyFormex already contains exported symbols.\nShall I delete them or add them to your project?",['Delete','Add','Cancel'])
            if res == 'Cancel':
                # ESCAPE FROM CREATING THE PROJECT
                return

            addGlobals = res == 'Add'

    # OK, we have all data, now create/open the project
        
    updateSettings({'workdir':os.path.dirname(fn)},save=True)
    sig = GD.Version[:GD.Version.rfind('-')]
    if ignoresig:
        sig = ''

    proj = _open_project(fn,create,sig,compression,legacy)
        
    GD.message("Project contents: %s" % proj.keys())
    
    if hasattr(proj,'_autoscript_'):
        _ignore = "Ignore it!"
        _show = "Show it"
        _edit = "Load it in the editor"
        _exec = "Execute it"
        res = draw.ask("There is an autoscript stored inside the project.\nIf you received this project file from an untrusted source, you should probably not execute it.",[_ignore,_show,_edit,_exec])
        if res == _show:
            res = draw.showText(proj._autoscript_)#,actions=[_ignore,_edit,_show])
            return
        if res == _exec:
            draw.playScript(proj._autoscript_)
        elif res == _edit:
            fn = "_autoscript_.py"
            draw.checkWorkdir()
            f = file(fn,'w')
            f.write(proj._autoscript_)
            f.close()
            openScript(fn)
            editScript(fn)

    if hasattr(proj,'autofile') and draw.ack("The project has an autofile attribute: %s\nShall I execute this script?" % proj.autofile):
        processArgs([proj.autofile])

    if makeDefault:
        the_project = proj
        if GD.PF and addGlobals:
            the_project.update(GD.PF)
        GD.PF = the_project
        GD.GUI.setcurproj(fn)

    else:
        # Just import the data into current project
        GD.PF.update(proj)

    GD.message("Exported symbols: %s" % GD.PF.keys())
Beispiel #15
0
def setProject(proj):
    """Make the specified project the current project.

    proj is an open project.
    If a filename, the project file is opened.

    .. note: The remainder is obsolete

    The user is asked for a Project file name and the access modalities.
    Depending on the results of the dialog:

    - either an new project is create or an old is opened,
    - the old data may be discarded, added to the current pyFormex globals,
      or replace them
    - the opened Project may become the current Project, or its data are
      just imported in the current Project.


    The default will let the user create new project files as well as open
    existing ones.
    Use create=False or the convenience function openProject to only accept
    existing project files.

    If a compression level (1..9) is given, the contents will be compressed,
    resulting in much smaller project files at the cost of

    Only one pyFormex project can be open at any time. The open project
    owns all the global data created and exported by any script.

    If makeDefault is True, an already open project will be closed and
    the opened project becomes the current project.
    If makeDefault is False, the project data are imported into pf.PF
    and the current project does not change. This means that if a project was
    open, the imported data will be added to it.

    If addGlobals is None, the user is asked whether the current globals
    should be added to the project. Set True or False to force or reject
    the adding without asking.
    """
    pf.message("Setting current project to %s" % proj.filename)
    pf.message("Project contents: %s" % utils.sortedKeys(proj))
    keep = {}
    if pf.PF:
        pf.message("Current pyFormex globals: %s" % utils.sortedKeys(pf.PF))
        _delete = "Delete"
        _add = "Keep non existing"
        _overwrite = "Keep all (overwrite project)"
        res = draw.ask("What shall I do with the current pyFormex globals?",[_delete,_add,_overwrite])
        if res == _add:
            keep = utils.removeDict(pf.PF,proj)
        elif res == _overwrite:
            keep = pf.PF
    pf.PF = proj
    if keep:
        pf.PF.update(keep)
    if pf.PF.filename:
        updateSettings({
            'curproj':pf.PF.filename,
            'workdir':os.path.dirname(pf.PF.filename),
            },save=True)
    pf.GUI.setcurproj(pf.PF.filename)

    if hasattr(proj,'_autoscript_'):
        _ignore = "Ignore it!"
        _show = "Show it"
        _edit = "Load it in the editor"
        _exec = "Execute it"
        res = draw.ask("There is an autoscript stored inside the project.\nIf you received this project file from an untrusted source, you should probably not execute it.",[_ignore,_show,_edit,_exec])
        if res == _show:
            res = draw.showText(proj._autoscript_)#,actions=[_ignore,_edit,_show])
            return
        if res == _exec:
            draw.playScript(proj._autoscript_)
        elif res == _edit:
            fn = "_autoscript_.py"
            draw.checkWorkdir()
            f = open(fn,'w')
            f.write(proj._autoscript_)
            f.close()
            openScript(fn)
            editApp(fn)

    if hasattr(proj,'autofile') and draw.ack("The project has an autofile attribute: %s\nShall I execute this script?" % proj.autofile):
        draw.processArgs([proj.autofile])

    listProject()
Beispiel #16
0
def setProject(proj):
    """Make the specified project the current project.

    proj is an open project.
    If a filename, the project file is opened.

    .. note: The remainder is obsolete

    The user is asked for a Project file name and the access modalities.
    Depending on the results of the dialog:

    - either an new project is create or an old is opened,
    - the old data may be discarded, added to the current pyFormex globals,
      or replace them
    - the opened Project may become the current Project, or its data are
      just imported in the current Project.


    The default will let the user create new project files as well as open
    existing ones.
    Use create=False or the convenience function openProject to only accept
    existing project files.

    If a compression level (1..9) is given, the contents will be compressed,
    resulting in much smaller project files at the cost of

    Only one pyFormex project can be open at any time. The open project
    owns all the global data created and exported by any script.

    If makeDefault is True, an already open project will be closed and
    the opened project becomes the current project.
    If makeDefault is False, the project data are imported into pf.PF
    and the current project does not change. This means that if a project was
    open, the imported data will be added to it.

    If addGlobals is None, the user is asked whether the current globals
    should be added to the project. Set True or False to force or reject
    the adding without asking.
    """
    pf.message("Setting current project to %s" % proj.filename)
    pf.message("Project contents: %s" % utils.sortedKeys(proj))
    keep = {}
    if pf.PF:
        pf.message("Current pyFormex globals: %s" % utils.sortedKeys(pf.PF))
        _delete = "Delete"
        _add = "Keep non existing"
        _overwrite = "Keep all (overwrite project)"
        res = draw.ask("What shall I do with the current pyFormex globals?",
                       [_delete, _add, _overwrite])
        if res == _add:
            keep = utils.removeDict(pf.PF, proj)
        elif res == _overwrite:
            keep = pf.PF
    pf.PF = proj
    if keep:
        pf.PF.update(keep)
    if pf.PF.filename:
        updateSettings(
            {
                'curproj': pf.PF.filename,
                'workdir': os.path.dirname(pf.PF.filename),
            },
            save=True)
    pf.GUI.setcurproj(pf.PF.filename)

    if hasattr(proj, '_autoscript_'):
        _ignore = "Ignore it!"
        _show = "Show it"
        _edit = "Load it in the editor"
        _exec = "Execute it"
        res = draw.ask(
            "There is an autoscript stored inside the project.\nIf you received this project file from an untrusted source, you should probably not execute it.",
            [_ignore, _show, _edit, _exec])
        if res == _show:
            res = draw.showText(
                proj._autoscript_)  #,actions=[_ignore,_edit,_show])
            return
        if res == _exec:
            draw.playScript(proj._autoscript_)
        elif res == _edit:
            fn = "_autoscript_.py"
            draw.checkWorkdir()
            f = open(fn, 'w')
            f.write(proj._autoscript_)
            f.close()
            openScript(fn)
            editApp(fn)

    if hasattr(proj, 'autofile') and draw.ack(
            "The project has an autofile attribute: %s\nShall I execute this script?"
            % proj.autofile):
        draw.processArgs([proj.autofile])

    listProject()