Пример #1
0
def run():
    items = [
        widgets.simpleInputItem(n,
                                globals()[n])
        for n in ['r0', 'r1', 'h', 't', 'nr', 'nt']
    ] + [
        widgets.simpleInputItem(
            'diag', diag, itemtype='radio', choices=['', 'u', 'd'])
    ]
    dialog = widgets.InputDialog(items)

    while not dialog.result() == widgets.TIMEOUT:
        res = dialog.getResults()
        if not res:
            break

        globals().update(res)
        F = cone(r0, r1, h, t, nr, nt, diag)
        G = cone1(r0, r1, h, t, nr, nt,
                  diag).swapAxes(1, 2).trl(0, 2 * max(r0, r1))
        G.setProp(1)
        H = F + G
        clear()
        smoothwire()
        draw(H)
        return
Пример #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
Пример #3
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()
Пример #4
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.FileDialog(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():
        from pyformex.gui import appMenu
        appMenu.reloadMenu(mode=mode)

    data = [list(c) for c in 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
Пример #5
0
    def createDialog():
        matnames = pf.GUI.materials.keys()
        mat = vp.material
        print("createDialog: %s" % vp.settings.lighting)

        #light0 = {'enabled':True,'ambient':0.0,'diffuse':0.6,'specular':0.4,'position':(1., 1., 2., 0.)}
        light_items = []
        for i in range(4):
            name = 'light%s' % i
            light = pf.cfg['light/%s'%name]
            items = _T(name, [
                _I("enabled", text="Enabled", value=light['enabled']),
                _I("ambient", text="Ambient", value=light['ambient'], itemtype='color', func=changeLight),
                _I("diffuse", text="Diffuse", value=light['diffuse'], itemtype='color', func=changeLight),
                _I("specular", text="Specular", value=light['specular'], itemtype='color', func=changeLight),
                _I("position", text="Position", value=light['position'][:3], itemtype='point'),
                ])
            light_items.append(items)

        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, itemtype='slider', min=0, max=100, scale=0.01, func=set_render_value, text='Global Ambient Lighting'),

            _G('light', text='Lights', items=light_items),
            _I('render/material', vp.material.name, text='Material', choices=matnames, onselect=updateLightParams),
            _G('material', text='Material Parameters', 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']
                ]),
            ]

        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
Пример #6
0
def openDialog():
    """Create and display the dialog"""
    global dialog, explanation, Illusion, Explain
    data_items = [
        _I('Illusion', Illusion, choices=method.keys()),
        _I('Explain', Explain, text='Show explanation'),
    ]

    dialog = widgets.InputDialog(data_items,
                                 caption='Optical illusions',
                                 actions=[('Done', close), ('Next', next),
                                          ('Explain', explain),
                                          ('Show', show)],
                                 default='Show')
    dialog.timeout = timeOut
    dialog.show()
Пример #7
0
def askItems(items, timeout=None, **kargs):
    """Ask the value of some items to the user.

    Create an interactive widget to let the user set the value of some items.
    The items are specified as a list of dictionaries. Each dictionary
    contains the input arguments for a widgets.InputItem. It is often
    convenient to use one of the _I, _G, ot _T functions to create these
    dictionaries. These will respectively create the input for a
    simpleInputItem, a groupInputItem or a tabInputItem.

    For convenience, simple items can also be specified as a tuple.
    A tuple (key,value) will be transformed to a dict
    {'key':key, 'value':value}.

    See the widgets.InputDialog class for complete description of the
    available input items.

    A timeout (in seconds) can be specified to have the input dialog
    interrupted automatically and return the default values.

    The remaining arguments are keyword arguments that are passed to the
    widgets.InputDialog.getResult method.

    Returns a dictionary with the results: for each input item there is a
    (key,value) pair. Returns an empty dictionary if the dialog was canceled.
    Sets the dialog timeout and accepted status in global variables.
    """
    global _dialog_widget, _dialog_result

    w = widgets.InputDialog(items, **kargs)

    _dialog_widget = w
    _dialog_result = None
    res = w.getResults(timeout)
    _dialog_widget = None
    _dialog_result = w.result()
    return res
Пример #8
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.
    """
    from pyformex.opengl import canvas
    from pyformex import plugins
    from pyformex import sendmail
    from pyformex.elements import elementTypes

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

    gui_console_options = { 'b':'Message board only','c':'Console only', 'bc':'Message board and Console' }

    def close():
        dia.close()

    def accept(save=False):
        dia.acceptData()
        res = dia.results
        res['_save_'] = save
        ok_plugins = utils.subDict(res, '_plugins/')
        res['gui/console'] = utils.inverseDict(gui_console_options)[res['gui/console']]
        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'] = 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 = ['any', 'PySide', 'PyQt4']
    bindings_current = pf.cfg['gui/bindings']

    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'], itemtype='radio', 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
        ]

    # Make sure splash image exists
    cur = pf.cfg['gui/splash']
    if not os.path.exists(cur):
        pf.cfg['gui/splash'] = cur = pf.refcfg['gui/splash']
    splashviewer = widgets.ImageView(cur, maxheight=200)

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

    scripts = [
        pf.cfg['webgl/script'],
#        "https:///fewgl-0.2.js",
#        "file://"+os.path.join(pf.cfg['datadir'],'fewgl.js'),
        ]
    if pf.installtype == 'G':
        fewgl_dir = os.path.join(pf.parentdir, "fewgl")
        if os.path.exists(fewgl_dir):
            scripts += [ "file://"+os.path.join(fewgl_dir,f) for f in ['fewgl.js','fewgl_debug.js'] ]
    scripts.append('custom')
    guiscripts = [
        pf.cfg['webgl/guiscript'],
        #        "https://net.feops.com/public/webgl/xtk_xdat.gui.js",
#        "file://"+os.path.join(pf.cfg['datadir'],'xtk_xdat.js'),
        ]
    guiscripts.append('custom')
    webgl_settings = [
        _I('webgl/script', pf.cfg['webgl/script'], text='WebGL base script', choices=scripts),
        _I('_webgl_script', '', text='URL for local WebGL base script', itemtype='filename', filter='js', exist=True),
        _I('webgl/guiscript', pf.cfg['webgl/guiscript'], text='GUI base script', choices=guiscripts),
        _I('_webgl_guiscript', '', text='URL for local GUI base script'),
        _I('webgl/autogui', pf.cfg['webgl/autogui'], text='Always add a standard GUI'),
        _I('webgl/devel', pf.cfg['webgl/devel'], text='Use the pyFormex source WebGL script'),
        _I('webgl/devpath', pf.cfg['webgl/devpath'], text='Path to the pyFormex source WebGL script'),
        ]
    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/interpreter',interpreter_current,choices=interpreter_choices,tooltip="The Python interpreter to use for the message board"),
                _I('gui/splash', text='Splash image', itemtype='filename', filter='img', exist=True, preview=splashviewer),
                splashviewer,
                ]),
            _T('GUI', [
                _G('Appearance', appearance),
                _G('Components', toolbars+actionbuttons+[
                    _I('gui/console', gui_console_options[pf.cfg['gui/console']], itemtype='hradio', choices=gui_console_options.values(), text="Board"),
                    _I('gui/redirect', pf.cfg['gui/redirect']),
                    _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']),
                    _I('gui/easter_egg', pf.cfg['gui/easter_egg']),
                    ],
                 ),
                ]),
            _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()
Пример #9
0
def setBgColor():
    """Interactively set the viewport background colors."""
    global bgcolor_dialog
    from pyformex.opengl.sanitize import saneColorArray
    from numpy import resize
    from pyformex.opengl import colors
    import os
    bgmodes = pf.canvas.settings.bgcolor_modes
    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 changeColor(field):
        bgcolor_dialog.acceptData()
        res = bgcolor_dialog.results
        if res:
            setBackground(**res)

    bgcolor_dialog = widgets.InputDialog(
        [
            _I('mode', mode, choices=bgmodes),
            _I('color1',
               color[0],
               itemtype='color',
               func=changeColor,
               text='Background color 1 (Bottom Left)'),
            _I('color2',
               color[1],
               itemtype='color',
               func=changeColor,
               text='Background color 2 (Bottom Right)'),
            _I('color3',
               color[2],
               itemtype='color',
               func=changeColor,
               text='Background color 3 (Top Right)'),
            _I('color4',
               color[3],
               itemtype='color',
               func=changeColor,
               text='Background color 4 (Top Left'),
            _I('showimage', showimage, text='Show background image'),
            _I('image',
               cur,
               text='Background image',
               itemtype='filename',
               filter='img',
               exist=True,
               preview=viewer),
            viewer,
            _I('_save_', False, text='Save as default'),
        ],
        caption='Config Dialog',
        enablers=[
            ('mode', 'vertical', 'color4'),
            ('mode', 'horizontal', 'color2'),
            ('mode', 'full', 'color2', 'color3', 'color4'),
            ('showimage', True, 'image'),
            #('mode', 'solid', '_save_'),
        ])
    res = bgcolor_dialog.getResults()
    if res:
        setBackground(**res)
Пример #10
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
            del res['canvas/viewport']
            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()