Esempio n. 1
0
def askConfigPreferences(items,prefix=None,store=None):
    """Ask preferences stored in config variables.

    Items in list should only be keys. store is usually a dictionary, but
    can be any class that allow the setdefault method for lookup while
    setting the default, and the store[key]=val syntax for setting the
    value.
    If a prefix is given, actual keys will be 'prefix/key'.
    The current values are retrieved from the store, and the type returned
    will be in accordance.
    If no store is specified, the global config pf.cfg is used.

    This function can be used to change individual values by a simpler
    interface than the full settings dialog.
    """
    if store is None:
        store = pf.cfg
    if prefix:
        items = [ '%s/%s' % (prefix,i) for i in items ]
    itemlist = [ _I(i,store[i]) for i in items ] + [
        _I('_save_',True,text='Save changes')
        ]
    res = widgets.InputDialog(itemlist,'Config Dialog',pf.GUI).getResults()
    #pf.debug(res,pf.DEBUG.CONFIG)
    if res and store==pf.cfg:
        updateSettings(res)
    return res
Esempio n. 2
0
def askConfigPreferences(items, prefix=None, store=None):
    """Ask preferences stored in config variables.

    Items in list should only be keys. store is usually a dictionary, but
    can be any class that allow the setdefault method for lookup while
    setting the default, and the store[key]=val syntax for setting the
    value.
    If a prefix is given, actual keys will be 'prefix/key'.
    The current values are retrieved from the store, and the type returned
    will be in accordance.
    If no store is specified, the global config pf.cfg is used.

    This function can be used to change individual values by a simpler
    interface than the full settings dialog.
    """
    if store is None:
        store = pf.cfg
    if prefix:
        items = ['%s/%s' % (prefix, i) for i in items]
    itemlist = [_I(i, store[i])
                for i in items] + [_I('_save_', True, text='Save changes')]
    res = widgets.InputDialog(itemlist, 'Config Dialog', pf.GUI).getResults()
    #pf.debug(res,pf.DEBUG.CONFIG)
    if res and store == pf.cfg:
        updateSettings(res)
    return res
Esempio n. 3
0
def setCanvasSize():
    """Save the current viewport size"""
    res = draw.askItems([
        _I('w',pf.canvas.width()),
        _I('h',pf.canvas.height())
        ],'Set Canvas Size'
        )
    if res:
        draw.canvasSize(res['w'],res['h'])
Esempio n. 4
0
def searchText():
    from widgets import simpleInputItem as _I
    res = draw.askItems([
        _I('pattern','',text='String to grep'),
        _I('options','',text='Options',tooltip="Some cool options: -a (extended search), -i (ignore case), -f (literal string), -e (extended regexp)"),
        ])

    if res:
        out = utils.grepSource(relative=False,quiet=True,**res)
        draw.showText(out,mono=True,modal=False)
Esempio n. 5
0
def setTriade():
    try:
        pos = pf.canvas.triade.pos
        siz = pf.canvas.triade.siz
    except:
        pos = 'lb'
        siz = 100
    res = draw.askItems([
        _I('triade',True),
        _I('pos',pos,choices=['lt','lc','lb','ct','cc','cb','rt','rc','rb']),
        _I('size',siz),
        ])
    if res:
        draw.setTriade(res['triade'],res['pos'],res['size'])
Esempio n. 6
0
def searchText():
    from widgets import simpleInputItem as _I
    res = draw.askItems([
        _I('pattern', '', text='String to grep'),
        _I('options',
           '',
           text='Options',
           tooltip=
           "Some cool options: -a (extended search), -i (ignore case), -f (literal string), -e (extended regexp)"
           ),
    ])

    if res:
        out = utils.grepSource(relative=False, quiet=True, **res)
        draw.showText(out, mono=True, modal=False)
Esempio n. 7
0
def createLightDialogItems(light=0,enabled=True):
    keys = [ 'ambient', 'diffuse', 'specular', 'position' ]
    tgt = 'render/light%s'%light
    val = pf.cfg[tgt]
    print("LIGHT %s" % light)
    print("CFG %s " % val)

    items = [
        _I('enabled',enabled),
        ] + [
        _I(k,val[k],itemtype='slider',min=0,max=100,scale=0.01,func=set_light_value,data=light)  for k in [ 'ambient', 'diffuse',  'specular' ]
        ] + [
        _I('position',val['position']),
        ]
    return items
Esempio n. 8
0
def createDirsDialog(dircfg):
    """Create a Dialog to set a list of paths.

    dircfg is a config variable that is a list of directories.
    """
    _dia = None
    _table = None

    mode = dircfg[:-4]
    if mode == 'app':
        title = 'Application paths'
    else:
        title = 'Script paths'

    def insertRow():
        ww = widgets.FileSelection(pf.cfg['workdir'],
                                   '*',
                                   exist=True,
                                   dir=True)
        fn = ww.getFilename()
        if fn:
            _table.model().insertRows()
            _table.model()._data[-1] = [os.path.basename(fn).capitalize(), fn]
        _table.update()

    def removeRow():
        row = _table.currentIndex().row()
        _table.model().removeRows(row, 1)
        _table.update()

    def moveUp():
        row = _table.currentIndex().row()
        if row > 0:
            a, b = _table.model()._data[row - 1:row + 1]
            _table.model()._data[row - 1:row + 1] = b, a
        _table.setFocus()  # For some unkown reason, this seems needed to
        # immediately update the widget
        _table.update()
        pf.app.processEvents()

    def reloadMenu():
        import appMenu
        appMenu.reloadMenu(mode=mode)

    data = map(list, pf.cfg[dircfg])
    _dia = widgets.InputDialog(items=[
        _I(dircfg, data, itemtype='table', chead=['Label', 'Path']),
    ],
                               actions=[
                                   ('New', insertRow),
                                   ('Delete', removeRow),
                                   ('Move Up', moveUp),
                                   ('OK', ),
                                   ('Cancel', ),
                               ],
                               caption=title)
    _table = _dia[dircfg].input

    return _dia
Esempio n. 9
0
def setLineWidth():
    """Change the default line width."""
    res = draw.askItems(
        [_I('Line Width',pf.canvas.settings.linewidth)],
        'Choose default line width'
        )
    if res:
        pf.canvas.setLineWidth(res['Line Width'])
Esempio n. 10
0
def createDirsDialog(dircfg):
    """Create a Dialog to set a list of paths.

    dircfg is a config variable that is a list of directories.
    """
    _dia=None
    _table=None

    mode = dircfg[:-4]
    if mode == 'app':
        title = 'Application paths'
    else:
        title='Script paths'

    def insertRow():
        ww = widgets.FileSelection(pf.cfg['workdir'],'*',exist=True,dir=True)
        fn = ww.getFilename()
        if fn:
            _table.model().insertRows()
            _table.model()._data[-1] = [os.path.basename(fn).capitalize(),fn]
        _table.update()

    def removeRow():
        row = _table.currentIndex().row()
        _table.model().removeRows(row,1)
        _table.update()

    def moveUp():
        row = _table.currentIndex().row()
        if row > 0:
            a,b = _table.model()._data[row-1:row+1]
            _table.model()._data[row-1:row+1] = b,a
        _table.setFocus() # For some unkown reason, this seems needed to
                          # immediately update the widget
        _table.update()
        pf.app.processEvents()

    def reloadMenu():
        import appMenu
        appMenu.reloadMenu(mode=mode)

    data = map(list,pf.cfg[dircfg])
    _dia = widgets.InputDialog(
        items = [
            _I(dircfg,data,itemtype='table',chead = ['Label','Path']),
            ],
        actions = [
            ('New',insertRow),
            ('Delete',removeRow),
            ('Move Up',moveUp),
            ('OK',),
            ('Cancel',),
            ],
        caption=title)
    _table = _dia[dircfg].input


    return _dia
Esempio n. 11
0
def setOptions():
    options = ['redirect', 'debuglevel', 'rst2html']
    options = [o for o in options if hasattr(pf.options, o)]
    items = [_I(o, getattr(pf.options, o)) for o in options]
    res = draw.askItems(items)
    if res:
        print(res)
        for o in options:
            setattr(pf.options, o, res[o])
            print("Options: %s" % pf.options)
            if o == 'redirect':
                pf.GUI.board.redirect(pf.options.redirect)
Esempio n. 12
0
def setOptions():
    options = [ 'redirect','debuglevel','rst2html']
    options = [ o for o in options if hasattr(pf.options,o) ]
    items = [ _I(o,getattr(pf.options,o)) for o in options ]
    res = draw.askItems(items)
    if res:
        print(res)
        for o in options:
            setattr(pf.options,o,res[o])
            print("Options: %s" % pf.options)
            if o == 'redirect':
                pf.GUI.board.redirect(pf.options.redirect)
Esempio n. 13
0
    def createDialog():
        matnames = pf.GUI.materials.keys()
        mat = vp.material
        mat_items = [
            _I(a,text=a,value=getattr(mat,a),itemtype='slider',min=0,max=100,scale=0.01,func=set_mat_value) for a in [ 'ambient', 'diffuse', 'specular', 'emission']
            ] + [
            _I(a,text=a,value=getattr(mat,a),itemtype='slider',min=1,max=128,scale=1.,func=set_mat_value) for a in ['shininess']
            ]
        items = [
            _I('render/mode',vp.rendermode,text='Rendering Mode',itemtype='select',choices=draw.renderModes()),#,onselect=enableLightParams),
            _I('render/lighting',vp.settings.lighting,text='Use Lighting'),
            _I('render/ambient',vp.lightprof.ambient,text='Global Ambient Lighting'),
            _I('render/material',vp.material.name,text='Material',choices=matnames,onselect=updateLightParams),
            _G('material',text='Material Parameters',items=mat_items),
            ]

        enablers = [
            ('render/lighting',True,'render/ambient','render/material','material'),
            ]
        dia = widgets.InputDialog(
            caption='pyFormex Settings',
            enablers = enablers,
            #store=pf.cfg,
            items=items,
            #prefix='render/',
            autoprefix=True,
            actions=[
                ('Close',close),
                ('Apply and Save',acceptAndSave),
                ('Apply',accept),
                ]
            )
        enableLightParams(vp.rendermode)
        return dia
Esempio n. 14
0
def createLightDialogItems(light=0, enabled=True):
    keys = ['ambient', 'diffuse', 'specular', 'position']
    tgt = 'render/light%s' % light
    val = pf.cfg[tgt]
    print("LIGHT %s" % light)
    print("CFG %s " % val)

    items = [
        _I('enabled', enabled),
    ] + [
        _I(k,
           val[k],
           itemtype='slider',
           min=0,
           max=100,
           scale=0.01,
           func=set_light_value,
           data=light) for k in ['ambient', 'diffuse', 'specular']
    ] + [
        _I('position', val['position']),
    ]
    return items
Esempio n. 15
0
    def createDialog():
        matnames = pf.GUI.materials.keys()
        mat = vp.material
        mat_items = [
            _I(a,
               text=a,
               value=getattr(mat, a),
               itemtype='slider',
               min=0,
               max=100,
               scale=0.01,
               func=set_mat_value)
            for a in ['ambient', 'diffuse', 'specular', 'emission']
        ] + [
            _I(a,
               text=a,
               value=getattr(mat, a),
               itemtype='slider',
               min=1,
               max=128,
               scale=1.,
               func=set_mat_value) for a in ['shininess']
        ]
        items = [
            _I('render/mode',
               vp.rendermode,
               text='Rendering Mode',
               itemtype='select',
               choices=draw.renderModes()),  #,onselect=enableLightParams),
            _I('render/lighting', vp.settings.lighting, text='Use Lighting'),
            _I('render/ambient',
               vp.lightprof.ambient,
               text='Global Ambient Lighting'),
            _I('render/material',
               vp.material.name,
               text='Material',
               choices=matnames,
               onselect=updateLightParams),
            _G('material', text='Material Parameters', items=mat_items),
        ]

        enablers = [
            ('render/lighting', True, 'render/ambient', 'render/material',
             'material'),
        ]
        dia = widgets.InputDialog(
            caption='pyFormex Settings',
            enablers=enablers,
            #store=pf.cfg,
            items=items,
            #prefix='render/',
            autoprefix=True,
            actions=[
                ('Close', close),
                ('Apply and Save', acceptAndSave),
                ('Apply', accept),
            ])
        enableLightParams(vp.rendermode)
        return dia
Esempio n. 16
0
def openglSettings():
    dia = None
    def apply_():
        dia.acceptData()
        canvas.glSettings(dia.results)
    def close():
        dia.close()

    dia = widgets.InputDialog(
        caption='OpenGL Settings',
        items=[
            _I('Line Smoothing','Off',itemtype='radio',choices=['On','Off']),
            _I('Polygon Mode',None,itemtype='radio',choices=['Fill','Line']),
            _I('Polygon Fill',None,itemtype='radio',choices=['Front and Back','Front','Back']),
            _I('Culling','Off',itemtype='radio',choices=['On','Off']),
# These are currently set by the render mode
#            ('Shading',None,'radio',{'choices':['Smooth','Flat']}),
#            ('Lighting',None,'radio',{'choices':['On','Off']}),
            ],
        actions=[('Done',close),('Apply',apply_)]
        )
    dia.show()
Esempio n. 17
0
def viewportLayout():
    """Set the viewport layout."""
    directions = [ 'rowwise','columnwise' ]
    if pf.GUI.viewports.rowwise:
        current = directions[0]
    else:
        current = directions[1]
    res = draw.askItems(
        [_I('Number of viewports',len(pf.GUI.viewports.all)),
         _I('Viewport layout direction',current,choices=directions),
         _I('Number of viewports per row/column',pf.GUI.viewports.ncols),
         ],
        'Config Dialog')
    if res:
        pf.debug(res)
        nvps = res['Number of viewports']
        rowwise = res['Viewport layout direction'] == 'rowwise'
        ncols = res['Number of viewports per row/column']
        if rowwise:
            nrows = None
        else:
            nrows = ncols
            ncols = None
        pf.GUI.viewports.changeLayout(nvps,ncols,nrows)
Esempio n. 18
0
def setDebug():
    options = [ o for o in dir(pf.DEBUG) if o[0] != '_' ]
    options.remove('ALL')
    options.remove('NONE')
    values = [ getattr(pf.DEBUG,o) for o in options ]
    items = [ _I(o,bool(pf.options.debuglevel & v)) for o,v in zip(options,values) ]
    res = draw.askItems(items)
    if res:
        print(res)
        debug = 0
        for o,v in zip(options,values):
            if res[o]:
                debug |= v
        print("debuglevel = %s" % debug)
        pf.options.debuglevel = debug
Esempio n. 19
0
def setBgColor():
    """Interactively set the viewport background colors."""
    from gui.drawable import saneColorArray
    from numpy import resize
    import os
    bgmodes = pf.canvas.settings.bgcolormodes
    mode = pf.canvas.settings.bgmode
    color = saneColorArray(pf.canvas.settings.bgcolor,(4,))
    color = resize(color,(4,3))
    cur = pf.canvas.settings.bgimage
    showimage = os.path.exists(cur)
    if not showimage:
        cur = pf.cfg['gui/splash']
    viewer = widgets.ImageView(cur,maxheight=200)
    def changeImage(fn):
        fn = draw.askImageFile(fn)
        if fn:
            viewer.showImage(fn)
        return fn
    dialog = widgets.InputDialog(
        [
            _I('mode',mode,choices=bgmodes),
            _I('color1',color[0],itemtype='color',text='Background color 1 (Bottom Left)'),
            _I('color2',color[1],itemtype='color',text='Background color 2 (Bottom Right)'),
            _I('color3',color[2],itemtype='color',text='Background color 3 (Top Right)'),
            _I('color4',color[3],itemtype='color',text='Background color 4 (Top Left'),
            _I('showimage',showimage,text='Show background image'),
            _I('image',cur,text='Background image',itemtype='button',func=changeImage),
            viewer,
            _I('_save_',True,text='Save as default'),
            ],
        caption='Config Dialog',
        enablers=[
            ('mode','vertical','color4'),
            ('mode','horizontal','color2'),
            ('mode','full','color2','color3','color4'),
            ('showimage',True,'image'),
            ]
        )
    res = dialog.getResults()
    pf.debug(res)
    if res:
        setBackground(**res)
Esempio n. 20
0
def setDebug():
    options = [o for o in dir(pf.DEBUG) if o[0] != '_']
    options.remove('ALL')
    options.remove('NONE')
    values = [getattr(pf.DEBUG, o) for o in options]
    items = [
        _I(o, bool(pf.options.debuglevel & v))
        for o, v in zip(options, values)
    ]
    res = draw.askItems(items)
    if res:
        print(res)
        debug = 0
        for o, v in zip(options, values):
            if res[o]:
                debug |= v
        print("debuglevel = %s" % debug)
        pf.options.debuglevel = debug
Esempio n. 21
0
def drawOptions(d={}):
    """Set the Drawing options.

    A dictionary may be specified to override the current defaults.
    """
    draw.setDrawOptions(d)
    print(pf.canvas.options)
    res = draw.askItems(store=pf.canvas.options,items=[
        _I('view',choices=['None']+pf.canvas.view_angles.keys(),tooltip="Camera viewing direction"),
        _I('bbox',choices=['auto','last'],tooltip="Automatically focus/zoom on the last drawn object(s)"),
        _I('clear',tooltip="Clear the canvas on each drawing action"),
        _I('shrink',tooltip="Shrink all elements to make their borders better visible"),
        _I('shrink_factor'),
        _I('marksize'),
        ],enablers=[('shrink',True,'shrink_factor')]
    )
    if not res:
        return
    if res['view'] == 'None':
        res['view'] = None
    draw.setDrawOptions(res)
Esempio n. 22
0
def settings():
    """Interactively change the pyformex settings.

    Creates a dialog to change (most of) the pyformex user configuration.
    To change the canvas setttings, use viewportMenu.canvasSettings.
    """
    import plugins
    import sendmail
    from elements import elementTypes

    dia = None
    _actionbuttons = [ 'play', 'rerun', 'step', 'continue', 'stop', 'edit', 'info' ]

    def close():
        dia.close()

    def accept(save=False):
        dia.acceptData()
        res = dia.results
        res['_save_'] = save
        ok_plugins = utils.subDict(res,'_plugins/')
        res['gui/plugins'] = [ p for p in ok_plugins if ok_plugins[p]]
        res['gui/actionbuttons'] = [ t for t in _actionbuttons if res['_gui/%sbutton'%t ] ]
        if res['webgl/script'] == 'custom':
            res['webgl/script'] = 'file:'+res['_webgl_script']
        if res['webgl/guiscript'] == 'custom':
            res['webgl/guiscript'] = res['_webgl_guiscript']
        updateSettings(res)
        plugins.loadConfiguredPlugins()

    def acceptAndSave():
        accept(save=True)

    def autoSettings(keylist):
        return [_I(k,pf.cfg[k]) for k in keylist]

    def changeDirs(dircfg):
        """dircfg is a config variable that is a list of dirs"""
        setDirs(dircfg)
        dia.updateData({dircfg:pf.cfg[dircfg]})

    def changeScriptDirs():
        changeDirs('scriptdirs')
    def changeAppDirs():
        changeDirs('appdirs')

    enablers = []
    mouse_settings = autoSettings(['gui/rotfactor','gui/panfactor','gui/zoomfactor','gui/autozoomfactor','gui/dynazoom','gui/wheelzoom'])

    # Use _ to avoid adding these items in the config
    plugin_items = [ _I('_plugins/'+name,name in pf.cfg['gui/plugins'],text=text) for name,text in plugins.pluginMenus() ]

    bindings_choices = ['PyQt4','PySide']
    bindings_current =  bindings_choices[ 1 if pf.options.pyside else 0 ]
    appearance = [
        _I('gui/style',pf.app.currentStyle(),choices=pf.app.getStyles()),
        _I('gui/font',pf.app.font().toString(),'font'),
        ]

    toolbartip = "Currently, changing the toolbar position will only be in effect when you restart pyFormex"
    toolbars = [
        _I('gui/%s'%t,pf.cfg['gui/%s'%t],text=getattr(pf.GUI,t).windowTitle(),choices=['left','right','top','bottom'],tooltip=toolbartip) for t in [ 'camerabar','modebar','viewbar' ]
        ]
    # Use _ to avoid adding these items in the config
    actionbuttons = [
        _I('_gui/%sbutton'%t,t in pf.cfg['gui/actionbuttons'],text="%s Button" % t.capitalize()) for t in _actionbuttons
        ]

    # callback to set a filename
    def changeFilename(fn):
        fn = draw.askImageFile(fn)
        return fn

    cur = pf.cfg['gui/splash']
#    if not cur:
#        cur = pf.cfg.get('icondir','.')
    viewer = widgets.ImageView(cur,maxheight=200)

    def changeSplash(fn):
        fn = draw.askImageFile(fn)
        if fn:
            viewer.showImage(fn)
        return fn

    mail_settings = [
        _I('mail/sender',pf.cfg.get('mail/sender',sendmail.mail),text="My mail address"),
        _I('mail/server',pf.cfg.get('mail/server','localhost'),text="Outgoing mail server")
        ]

    xtkscripts = ["http://feops.ugent.be/pub/xtk/xtk.js", "http://get.goXTK.com/xtk_edge.js", "http://get.goXTK.com/xtk_release_10.js", 'custom']
    guiscripts = ["http://get.goXTK.com/xtk_xdat.gui.js", 'custom']
    webgl_settings = [
        _I('webgl/script',pf.cfg['webgl/script'],text='XTK base script',choices=xtkscripts),
        _I('_webgl_script','',text='Custom XTK URL',itemtype='button',func=changeFilename),
        _I('webgl/guiscript',pf.cfg['webgl/guiscript'],text='GUI base script',choices=guiscripts),
        _I('_webgl_guiscript','',text='Custom GUI URL'),
        _I('webgl/autogui',pf.cfg['webgl/autogui'],text='Always add a standard GUI'),
        _I('webgl/devel',pf.cfg['webgl/devel'],text='Use a source XTK version'),
        _I('webgl/devpath',pf.cfg['webgl/devpath'],text='Path to the XTK source'),
        ]
    enablers.extend([
        ('webgl/script','custom','_webgl_script'),
        ('webgl/guiscript','custom','_webgl_guiscript'),
        ('webgl/devel',True,'webgl/devpath'),
        ])

    dia = widgets.InputDialog(
        caption='pyFormex Settings',
        store=pf.cfg,
        items=[
            _T('General',[
                _I('syspath',tooltip="If you need to import modules from a non-standard path, you can supply additional paths to search here."),
                _I('editor',tooltip="The command to be used to edit a script file. The command will be executed with the path to the script file as argument."),
                _I('viewer',tooltip="The command to be used to view an HTML file. The command will be executed with the path to the HTML file as argument."),
                _I('browser',tooltip="The command to be used to browse the internet. The command will be executed with an URL as argument."),
                _I('help/docs'),
                _I('autorun',text='Startup script',tooltip='This script will automatically be run at pyFormex startup'),
                _I('scriptdirs',text='Script Paths',tooltip='pyFormex will look for scripts in these directories',buttons=[('Edit',changeScriptDirs)]),
                _I('appdirs',text='Applicationt Paths',tooltip='pyFormex will look for applications in these directories',buttons=[('Edit',changeAppDirs)]),
                _I('autoglobals',text='Auto Globals',tooltip='If checked, global Application variables of any Geometry type will automatically be copied to the pyFormex global variable dictionary (PF), and thus become available in the GUI'),
                _I('showapploaderrors',text='Show Application Load Error Traceback',tooltip='If checked, a traceback of exceptions occurring at Application Load time will be output. If unchecked, such exceptions will be suppressed, and the application will not run.'),
                _I('loadcurproj',text="Reload last project on startup"),
                _I('check_print',text="Check scripts for the use of the print statement"),
                _I('plot2d',text="Prefered 2D plot library",choices=['gnuplot','matplotlib']),
                _I('commands',text='Use commands module instead of subprocess',tooltip="If checked, pyFormex will use the Python 'commands' module for the execution of external commands. The default (unchecked) is to use the 'subprocess' module. If you notice a lot of command failures, or even hangups, you may want to switch."),
                ],
               ),
            _T('Startup',[
                _I('_info_01_','The settings on this page will only become active after restarting pyFormex',itemtype='info'),
                _I('gui/bindings',bindings_current,choices=bindings_choices,tooltip="The Python bindings for the Qt4 library"),
                _I('gui/splash',text='Splash image',itemtype='button',func=changeSplash),
                viewer,
                ]),
            _T('GUI',[
                _G('Appearance',appearance),
                _G('Components',toolbars+actionbuttons+[
                    _I('gui/coordsbox'),
                    _I('gui/showfocus',pf.cfg['gui/showfocus']),
                    _I('gui/runalloption',pf.cfg['gui/runalloption']),
                    _I('gui/timeoutbutton',pf.cfg['gui/timeoutbutton']),
                    _I('gui/timeoutvalue',pf.cfg['gui/timeoutvalue']),
                    ],
                 ),
                ]),
            _T('Canvas',[
                _I('_not_active_','The canvas settings can be set from the Viewport Menu',itemtype='info',text=''),
                ]),
            _T('Drawing',[
                _I('draw/rendermode',pf.cfg['draw/rendermode'],choices=canvas.CanvasSettings.RenderProfiles),
                _I('draw/wait',pf.cfg['draw/wait']),
                _I('draw/picksize',pf.cfg['draw/picksize']),
                _I('draw/disable_depth_test',pf.cfg['draw/disable_depth_test'],text='Disable depth testing for transparent actors'),
                _I('render/avgnormaltreshold',pf.cfg['render/avgnormaltreshold']),
                _I('_info_00_',itemtype='info',text='Changes to the options below will only become effective after restarting pyFormex!'),
                _I('draw/quadline',text='Draw as quadratic lines',itemtype='list',check=True,choices=elementTypes(1),tooltip='Line elements checked here will be drawn as quadratic lines whenever possible.'),
                _I('draw/quadsurf',text='Draw as quadratic surfaces',itemtype='list',check=True,choices=elementTypes(2)+elementTypes(3),tooltip='Surface and volume elements checked here will be drawn as quadratic surfaces whenever possible.'),
                ]),
            _T('Mouse',mouse_settings),
            _T('Plugins',plugin_items),
            _T('WebGL',webgl_settings),
            _T('Environment',[
                _G('Mail',mail_settings),
#                _G('Jobs',jobs_settings),
                ]),
            ],
        enablers=enablers,
        actions=[
            ('Close',close),
            ('Accept and Save',acceptAndSave),
            ('Accept',accept),
            ],
        )
    #dia.resize(800,400)
    dia.show()
Esempio n. 23
0
def settings():
    """Interactively change the pyformex settings.

    Creates a dialog to change (most of) the pyformex user configuration.
    To change the canvas setttings, use viewportMenu.canvasSettings.
    """
    import plugins
    import sendmail
    from elements import elementTypes

    dia = None
    _actionbuttons = [
        'play', 'rerun', 'step', 'continue', 'stop', 'edit', 'info'
    ]

    def close():
        dia.close()

    def accept(save=False):
        dia.acceptData()
        res = dia.results
        res['_save_'] = save
        ok_plugins = utils.subDict(res, '_plugins/')
        res['gui/plugins'] = [p for p in ok_plugins if ok_plugins[p]]
        res['gui/actionbuttons'] = [
            t for t in _actionbuttons if res['_gui/%sbutton' % t]
        ]
        if res['webgl/script'] == 'custom':
            res['webgl/script'] = 'file:' + res['_webgl_script']
        if res['webgl/guiscript'] == 'custom':
            res['webgl/guiscript'] = res['_webgl_guiscript']
        updateSettings(res)
        plugins.loadConfiguredPlugins()

    def acceptAndSave():
        accept(save=True)

    def autoSettings(keylist):
        return [_I(k, pf.cfg[k]) for k in keylist]

    def changeDirs(dircfg):
        """dircfg is a config variable that is a list of dirs"""
        setDirs(dircfg)
        dia.updateData({dircfg: pf.cfg[dircfg]})

    def changeScriptDirs():
        changeDirs('scriptdirs')

    def changeAppDirs():
        changeDirs('appdirs')

    enablers = []
    mouse_settings = autoSettings([
        'gui/rotfactor', 'gui/panfactor', 'gui/zoomfactor',
        'gui/autozoomfactor', 'gui/dynazoom', 'gui/wheelzoom'
    ])

    # Use _ to avoid adding these items in the config
    plugin_items = [
        _I('_plugins/' + name, name in pf.cfg['gui/plugins'], text=text)
        for name, text in plugins.pluginMenus()
    ]

    bindings_choices = ['PyQt4', 'PySide']
    bindings_current = bindings_choices[1 if pf.options.pyside else 0]
    appearance = [
        _I('gui/style', pf.app.currentStyle(), choices=pf.app.getStyles()),
        _I('gui/font',
           pf.app.font().toString(), 'font'),
    ]

    toolbartip = "Currently, changing the toolbar position will only be in effect when you restart pyFormex"
    toolbars = [
        _I('gui/%s' % t,
           pf.cfg['gui/%s' % t],
           text=getattr(pf.GUI, t).windowTitle(),
           choices=['left', 'right', 'top', 'bottom'],
           tooltip=toolbartip) for t in ['camerabar', 'modebar', 'viewbar']
    ]
    # Use _ to avoid adding these items in the config
    actionbuttons = [
        _I('_gui/%sbutton' % t,
           t in pf.cfg['gui/actionbuttons'],
           text="%s Button" % t.capitalize()) for t in _actionbuttons
    ]

    # callback to set a filename
    def changeFilename(fn):
        fn = draw.askImageFile(fn)
        return fn

    cur = pf.cfg['gui/splash']
    #    if not cur:
    #        cur = pf.cfg.get('icondir','.')
    viewer = widgets.ImageView(cur, maxheight=200)

    def changeSplash(fn):
        fn = draw.askImageFile(fn)
        if fn:
            viewer.showImage(fn)
        return fn

    mail_settings = [
        _I('mail/sender',
           pf.cfg.get('mail/sender', sendmail.mail),
           text="My mail address"),
        _I('mail/server',
           pf.cfg.get('mail/server', 'localhost'),
           text="Outgoing mail server")
    ]

    xtkscripts = [
        "http://feops.ugent.be/pub/xtk/xtk.js",
        "http://get.goXTK.com/xtk_edge.js",
        "http://get.goXTK.com/xtk_release_10.js", 'custom'
    ]
    guiscripts = ["http://get.goXTK.com/xtk_xdat.gui.js", 'custom']
    webgl_settings = [
        _I('webgl/script',
           pf.cfg['webgl/script'],
           text='XTK base script',
           choices=xtkscripts),
        _I('_webgl_script',
           '',
           text='Custom XTK URL',
           itemtype='button',
           func=changeFilename),
        _I('webgl/guiscript',
           pf.cfg['webgl/guiscript'],
           text='GUI base script',
           choices=guiscripts),
        _I('_webgl_guiscript', '', text='Custom GUI URL'),
        _I('webgl/autogui',
           pf.cfg['webgl/autogui'],
           text='Always add a standard GUI'),
        _I('webgl/devel',
           pf.cfg['webgl/devel'],
           text='Use a source XTK version'),
        _I('webgl/devpath',
           pf.cfg['webgl/devpath'],
           text='Path to the XTK source'),
    ]
    enablers.extend([
        ('webgl/script', 'custom', '_webgl_script'),
        ('webgl/guiscript', 'custom', '_webgl_guiscript'),
        ('webgl/devel', True, 'webgl/devpath'),
    ])

    dia = widgets.InputDialog(
        caption='pyFormex Settings',
        store=pf.cfg,
        items=[
            _T(
                'General',
                [
                    _I('syspath',
                       tooltip=
                       "If you need to import modules from a non-standard path, you can supply additional paths to search here."
                       ),
                    _I('editor',
                       tooltip=
                       "The command to be used to edit a script file. The command will be executed with the path to the script file as argument."
                       ),
                    _I('viewer',
                       tooltip=
                       "The command to be used to view an HTML file. The command will be executed with the path to the HTML file as argument."
                       ),
                    _I('browser',
                       tooltip=
                       "The command to be used to browse the internet. The command will be executed with an URL as argument."
                       ),
                    _I('help/docs'),
                    _I('autorun',
                       text='Startup script',
                       tooltip=
                       'This script will automatically be run at pyFormex startup'
                       ),
                    _I('scriptdirs',
                       text='Script Paths',
                       tooltip=
                       'pyFormex will look for scripts in these directories',
                       buttons=[('Edit', changeScriptDirs)]),
                    _I('appdirs',
                       text='Applicationt Paths',
                       tooltip=
                       'pyFormex will look for applications in these directories',
                       buttons=[('Edit', changeAppDirs)]),
                    _I('autoglobals',
                       text='Auto Globals',
                       tooltip=
                       'If checked, global Application variables of any Geometry type will automatically be copied to the pyFormex global variable dictionary (PF), and thus become available in the GUI'
                       ),
                    _I('showapploaderrors',
                       text='Show Application Load Error Traceback',
                       tooltip=
                       'If checked, a traceback of exceptions occurring at Application Load time will be output. If unchecked, such exceptions will be suppressed, and the application will not run.'
                       ),
                    _I('loadcurproj', text="Reload last project on startup"),
                    _I('check_print',
                       text="Check scripts for the use of the print statement"
                       ),
                    _I('plot2d',
                       text="Prefered 2D plot library",
                       choices=['gnuplot', 'matplotlib']),
                    _I('commands',
                       text='Use commands module instead of subprocess',
                       tooltip=
                       "If checked, pyFormex will use the Python 'commands' module for the execution of external commands. The default (unchecked) is to use the 'subprocess' module. If you notice a lot of command failures, or even hangups, you may want to switch."
                       ),
                ],
            ),
            _T('Startup', [
                _I('_info_01_',
                   'The settings on this page will only become active after restarting pyFormex',
                   itemtype='info'),
                _I('gui/bindings',
                   bindings_current,
                   choices=bindings_choices,
                   tooltip="The Python bindings for the Qt4 library"),
                _I('gui/splash',
                   text='Splash image',
                   itemtype='button',
                   func=changeSplash),
                viewer,
            ]),
            _T('GUI', [
                _G('Appearance', appearance),
                _G(
                    'Components',
                    toolbars + actionbuttons + [
                        _I('gui/coordsbox'),
                        _I('gui/showfocus', pf.cfg['gui/showfocus']),
                        _I('gui/runalloption', pf.cfg['gui/runalloption']),
                        _I('gui/timeoutbutton', pf.cfg['gui/timeoutbutton']),
                        _I('gui/timeoutvalue', pf.cfg['gui/timeoutvalue']),
                    ],
                ),
            ]),
            _T('Canvas', [
                _I('_not_active_',
                   'The canvas settings can be set from the Viewport Menu',
                   itemtype='info',
                   text=''),
            ]),
            _T('Drawing', [
                _I('draw/rendermode',
                   pf.cfg['draw/rendermode'],
                   choices=canvas.CanvasSettings.RenderProfiles),
                _I('draw/wait', pf.cfg['draw/wait']),
                _I('draw/picksize', pf.cfg['draw/picksize']),
                _I('draw/disable_depth_test',
                   pf.cfg['draw/disable_depth_test'],
                   text='Disable depth testing for transparent actors'),
                _I('render/avgnormaltreshold',
                   pf.cfg['render/avgnormaltreshold']),
                _I('_info_00_',
                   itemtype='info',
                   text=
                   'Changes to the options below will only become effective after restarting pyFormex!'
                   ),
                _I('draw/quadline',
                   text='Draw as quadratic lines',
                   itemtype='list',
                   check=True,
                   choices=elementTypes(1),
                   tooltip=
                   'Line elements checked here will be drawn as quadratic lines whenever possible.'
                   ),
                _I('draw/quadsurf',
                   text='Draw as quadratic surfaces',
                   itemtype='list',
                   check=True,
                   choices=elementTypes(2) + elementTypes(3),
                   tooltip=
                   'Surface and volume elements checked here will be drawn as quadratic surfaces whenever possible.'
                   ),
            ]),
            _T('Mouse', mouse_settings),
            _T('Plugins', plugin_items),
            _T('WebGL', webgl_settings),
            _T(
                'Environment',
                [
                    _G('Mail', mail_settings),
                    #                _G('Jobs',jobs_settings),
                ]),
        ],
        enablers=enablers,
        actions=[
            ('Close', close),
            ('Accept and Save', acceptAndSave),
            ('Accept', accept),
        ],
    )
    #dia.resize(800,400)
    dia.show()
Esempio n. 24
0
def canvasSettings():
    """Interactively change the canvas settings.

    Creates a dialog to change the canvasSettings of the current or any other
    viewport
    """

    dia = None

    def close():
        dia.close()


    def getVp(vp):
        """Return the vp corresponding with a vp choice string"""
        if vp == 'current':
            vp = pf.GUI.viewports.current
        elif vp == 'focus':
            vp = pf.canvas
        else:
            vp = pf.GUI.viewports.all[int(vp)]
        return vp


    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)

    def acceptAndSave():
        accept(save=True)

    def changeViewport(vp):
        if vp == 'current':
            vp = pf.GUI.viewports.current
        elif vp == 'focus':
            vp = pf.canvas
        else:
            vp = pf.GUI.viewports.all[int(vp)]
        dia.updateData(vp.settings)

    canv = pf.canvas
    vp = pf.GUI.viewports
    pf.debug("Focus: %s; Current: %s" % (canv,vp),pf.DEBUG.CANVAS)
    s = canv.settings

    dia = widgets.InputDialog(
        caption='Canvas Settings',
        store=canv.settings,
        items=[
            _I('viewport',choices=['focus','current']+[str(i) for i in range(len(pf.GUI.viewports.all))],onselect=changeViewport),
            _I('pointsize',),
            _I('linewidth',),
            _I('linestipple',),
            _I('fgcolor',itemtype='color'),
            _I('slcolor',itemtype='color'),
            _I('smooth'),
            _I('fill'),
            _I('lighting'),
            _I('culling'),
            _I('alphablend'),
            _I('transparency',min=0.0,max=1.0),
            _I('avgnormals',),
            ],
        enablers =[
            ('alphablend',('transparency')),
            ],
        actions=[
            ('Close',close),
            ('Apply and Save',acceptAndSave),
            ('Apply',accept),
            ],
        )
    #dia.resize(800,400)
    dia.show()
Esempio n. 25
0
 def autoSettings(keylist):
     return [_I(k, pf.cfg[k]) for k in keylist]
Esempio n. 26
0
 def autoSettings(keylist):
     return [_I(k,pf.cfg[k]) for k in keylist]