예제 #1
0
def main(argv):
    """A simple example of using the workbench."""

    # Create the GUI.
    gui = GUI()

    # Create the workbench.
    #
    # fixme: I wouldn't really want to specify the state location here.
    # Ideally this would be part of the GUI's as DOMs idea, and the state
    # location would be an attribute picked up from the DOM hierarchy. This
    # would also be the mechanism for doing 'confirm' etc... Let the request
    # bubble up the DOM until somebody handles it.
    workbench = ExampleWorkbench(state_location=gui.state_location)

    # Create the workbench window.
    window = workbench.create_window(position=(300, 300), size=(800, 600))
    window.open()

    # This will cause a TraitsUI editor to be created.
    window.edit(Person(name='fred', age=42, salary=50000))

    # This will cause a toolkit specific editor to be created.
    window.edit("This text is implemented by a toolkit specific widget.")

    # Start the GUI event loop.
    gui.start_event_loop()
예제 #2
0
def main():
    import optparse
    parser = optparse.OptionParser(usage="""\
%prog [options] [trace.txt|trace.txt.gz|trace.txt.lzma|trace.dat]

pytimechart - Fast graphical exploration and visualisation for linux kernel traces."""
                                   )
    parser.add_option("-p",
                      "--prof",
                      dest="prof",
                      action="store_true",
                      help="activate profiling",
                      default=False)
    (options, args) = parser.parse_args()

    # Create the GUI (this does NOT start the GUI event loop).
    gui = GUI()
    if len(args) == 0:
        args.append("dummy")
    for fn in args:
        if not open_file(fn):
            sys.exit(0)
    if options.prof:
        import cProfile
        dict = {"gui": gui}
        cProfile.runctx('gui.start_event_loop()', dict, dict, 'timechart.prof')
    else:
        gui.start_event_loop()
예제 #3
0
파일: example.py 프로젝트: fspaolo/code
def main(argv):
    """ A simple example of using the the application scripting framework in a
    workbench.
    """

    # Create the GUI.
    gui = GUI()

    # Create the workbench.
    workbench = ExampleScript(state_location=gui.state_location)

    window = workbench.create_window(position=(300, 300), size=(400, 300))
    window.open()

    # Create some objects to edit.
    # FIXME v3: The need to explicitly set the style to its default value is
    # due to a bug in the implementation of Scriptable.
    label = Label(text="Label", style='normal')
    label2 = Label(text="Label2", style='normal')

    # Edit the objects.
    window.edit(label)
    window.edit(label2)

    # Start the GUI event loop.
    gui.start_event_loop()

    return
예제 #4
0
파일: example.py 프로젝트: fspaolo/code
def main(argv):
    """A simple example of using the workbench."""

    # Create the GUI.
    gui = GUI()

    # Create the workbench.
    #
    # fixme: I wouldn't really want to specify the state location here.
    # Ideally this would be part of the GUI's as DOMs idea, and the state
    # location would be an attribute picked up from the DOM hierarchy. This
    # would also be the mechanism for doing 'confirm' etc... Let the request
    # bubble up the DOM until somebody handles it.
    workbench = ExampleWorkbench(state_location=gui.state_location)

    # Create the workbench window.
    window = workbench.create_window(position=(300, 300), size=(800, 600))
    window.open()

    # This will cause a TraitsUI editor to be created.
    window.edit(Person(name='fred', age=42, salary=50000))

    # This will cause a toolkit specific editor to be created.
    window.edit("This text is implemented by a toolkit specific widget.")

    # Start the GUI event loop.
    gui.start_event_loop()
예제 #5
0
    def wrapper(*args, **kw):
        """Wrapper function to run given function inside the GUI event
        loop.
        """
        global _gui, _stop_show
        tk = ETSConfig.toolkit

        if is_ui_running():
            # In this case we should not pop up the UI since we likely
            # don't want to stop the mainloop.
            return func(*args, **kw)
        else:
            g = GUI()
            if tk == "wx":
                # Create a dummy app so invoke later works on wx.
                a = ApplicationWindow(size=(1, 1))
                GUI.invoke_later(lambda: a.close())
                a.open()

            GUI.invoke_later(func, *args, **kw)
            _gui = g
            if stop:
                # Pop up the UI to stop the mainloop.
                _stop_show = StopShow()
            g.start_event_loop()
예제 #6
0
파일: example.py 프로젝트: sjl421/code-2
def main(argv):
    """ A simple example of using the the application scripting framework in a
    workbench.
    """

    # Create the GUI.
    gui = GUI()

    # Create the workbench.
    workbench = ExampleScript(state_location=gui.state_location)

    window = workbench.create_window(position=(300, 300), size=(400, 300))
    window.open()

    # Create some objects to edit.
    # FIXME v3: The need to explicitly set the style to its default value is
    # due to a bug in the implementation of Scriptable.
    label = Label(text="Label", style='normal')
    label2 = Label(text="Label2", style='normal')

    # Edit the objects.
    window.edit(label)
    window.edit(label2)

    # Start the GUI event loop.
    gui.start_event_loop()

    return
예제 #7
0
    def wrapper(*args, **kw):
        """Wrapper function to run given function inside the GUI event
        loop.
        """
        global _gui, _stop_show
        tk = ETSConfig.toolkit

        if is_ui_running():
            # In this case we should not pop up the UI since we likely
            # don't want to stop the mainloop.
            return func(*args, **kw)
        else:
            g = GUI()
            if tk == 'wx':
                # Create a dummy app so invoke later works on wx.
                a = ApplicationWindow(size=(1, 1))
                GUI.invoke_later(lambda: a.close())
                a.open()

            GUI.invoke_later(func, *args, **kw)
            _gui = g
            if stop:
                # Pop up the UI to stop the mainloop.
                _stop_show = StopShow()
            g.start_event_loop()
예제 #8
0
def main():
    # Create the GUI.
    gui = GUI()
    # Create and open an application window.
    window = IVTKWithCrustAndBrowser(size=(800, 600))
    window.open()
    # Start the GUI event loop!
    gui.start_event_loop()
예제 #9
0
파일: ivtk.py 프로젝트: sjl421/code-2
def main():
    # Create the GUI.
    gui = GUI()
    # Create and open an application window.
    window = IVTKWithCrustAndBrowser(size=(800, 600))
    window.open()
    # Start the GUI event loop!
    gui.start_event_loop()
예제 #10
0
파일: run.py 프로젝트: enthought/traitsgui
def main(argv):
    """ A simple example of using Tasks.
    """
    # Create the GUI (this does NOT start the GUI event loop).
    gui = GUI()

    # Create a Task and add it to a TaskWindow.
    task = ExampleTask()
    window = TaskWindow(size=(800, 600))
    window.add_task(task)

    # Show the window.
    window.open()

    # Start the GUI event loop.
    gui.start_event_loop()
예제 #11
0
def _test():
    import doctest, numpy
    from enthought.pyface.api import GUI, ApplicationWindow, ImageResource, SplashScreen
    #splash_screen = SplashScreen(image=ImageResource('splash'))
    splash_screen = SplashScreen()
    gui = GUI(splash_screen=splash_screen)
    #doctest.testmod()
    x = numpy.linspace(0, 100)
    y = numpy.linspace(0, 100) + numpy.random.randn(50)
    t = FitFunction(name='general.linear')
    data = FitData(x=x, y=y)
    #t = DataFitterPanel(data = data, category = 'general', function_name = 'linear')
    t = DataFitter(data=data, function=t)
    #t.fit()
    #t.plotter.savefig('test.png')
    gui.start_event_loop()
    t.configure_traits()
예제 #12
0
def main():
    gui = GUI()
    # Create and open an application window.
    window = ivtk.IVTKWithCrustAndBrowser(size=(800,600))
    window.open()
    f = Figure(window.scene)

    # Create an outline.
    o = Outline()
    f.add(o)

    # Create some pretty pictures.
    #test_lines(f)
    test_surf(f)

    window.scene.reset_zoom()
    
    # Start the GUI event loop!
    gui.start_event_loop()
예제 #13
0
def main():
    gui = GUI()
    # Create and open an application window.
    window = ivtk.IVTKWithCrustAndBrowser(size=(800, 600))
    window.open()
    f = Figure(window.scene)

    # Create an outline.
    o = Outline()
    f.add(o)

    # Create some pretty pictures.
    #test_lines(f)
    test_surf(f)

    window.scene.reset_zoom()

    # Start the GUI event loop!
    gui.start_event_loop()
예제 #14
0
def main(argv):
    """ A simple example of using the the undo framework in a workbench. """

    # Create the GUI.
    gui = GUI()

    # Create the workbench.
    workbench = ApplicationWorkbench(state_location=gui.state_location)

    window = workbench.create_window(position=(300, 300), size=(400, 300))
    window.open()

    # fixme: This is a little silly...
    window.edit(workbench.app.project.active_experiment)

    # Start the GUI event loop.
    gui.start_event_loop()

    return
예제 #15
0
def main(argv):
    """ A simple example of using the workbench. """

    # Create the GUI (this does NOT start the GUI event loop).
    gui = GUI()

    # Create some objects to edit.
    fred = Person(name='fred', age=42)
    wilma = Person(name='wilma', age=35)

    # Create the workbench.
    #
    # fixme: I wouldn't really want to specify the state location here.
    # Ideally this would be part of the GUI's as DOMs idea, and the state
    # location would be an attribute picked up from the DOM hierarchy. This
    # would also be the mechanism for doing 'confirm' etc... Let the request
    # bubble up the DOM until somebody handles it.
    workbench = ExampleWorkbench(state_location=gui.state_location)

    # Create some workbench windows.
    x = 300
    y = 300
    for i in range(2):
        window = workbench.create_window(position=(x, y), size=(800, 600))
        window.open()

        # Edit the objects if they weren't restored from a previous session.
        if window.get_editor_by_id('fred') is None:
            window.edit(fred)

        if window.get_editor_by_id('wilma') is None:
            window.edit(wilma)

        # Cascade the windows.
        x += 100
        y += 100

    # Start the GUI event loop.
    gui.start_event_loop()

    return
예제 #16
0
def main():
    usage = '%prog IMAGE_FILE [IMAGE_FILE] [...]'
    parser = OptionParser(usage)
    (options, args) = parser.parse_args()

    if len(args)<1:
        # Currently at least one IMAGE_FILE is required because the
        # add_image button is broken.
        parser.print_help()
        return

    gui = GUI()
    window = MainWindow()

    window.size = (700, 400)
    window.open()

    for filename in args:
        window.add_filename( filename )

    gui.start_event_loop()
예제 #17
0
파일: run.py 프로젝트: enthought/traitsgui
def main(argv):
    """ A simple example of using the workbench. """

    # Create the GUI (this does NOT start the GUI event loop).
    gui = GUI()

    # Create some objects to edit.
    fred = Person(name='fred', age=42)
    wilma = Person(name='wilma', age=35)

    # Create the workbench.
    #
    # fixme: I wouldn't really want to specify the state location here.
    # Ideally this would be part of the GUI's as DOMs idea, and the state
    # location would be an attribute picked up from the DOM hierarchy. This
    # would also be the mechanism for doing 'confirm' etc... Let the request
    # bubble up the DOM until somebody handles it.
    workbench = ExampleWorkbench(state_location=gui.state_location)

    # Create some workbench windows.
    x = 300; y = 300
    for i in range(2):
        window = workbench.create_window(position=(x, y), size=(800, 600))
        window.open()

        # Edit the objects if they weren't restored from a previous session.
        if window.get_editor_by_id('fred') is None:
            window.edit(fred)

        if window.get_editor_by_id('wilma') is None:
            window.edit(wilma)

        # Cascade the windows.
        x += 100; y += 100

    # Start the GUI event loop.
    gui.start_event_loop()

    return
예제 #18
0
def main():
    import optparse
    parser = optparse.OptionParser(usage="""\
%prog [options] [trace.txt|trace.txt.gz|trace.txt.lzma|trace.dat]

pytimechart - Fast graphical exploration and visualisation for linux kernel traces.""")
    parser.add_option("-p", "--prof", dest="prof", action="store_true",
                      help="activate profiling",
                      default=False)
    (options, args) = parser.parse_args()

    # Create the GUI (this does NOT start the GUI event loop).
    gui = GUI()
    if len(args) == 0:
        args.append("dummy")
    for fn in args:
        if not open_file(fn):
            sys.exit(0)
    if options.prof:
        import cProfile
        dict = {"gui":gui}
        cProfile.runctx('gui.start_event_loop()',dict,dict,'timechart.prof')
    else:
        gui.start_event_loop()
예제 #19
0
def main(argv):
    """ A simple example of using the the undo framework in a workbench. """

    # Create the GUI.
    gui = GUI()

    # Create the workbench.
    workbench = ExampleUndo(state_location=gui.state_location)

    window = workbench.create_window(position=(300, 300), size=(400, 300))
    window.open()

    # Create some objects to edit.
    label = Label(text="Label")
    label2 = Label(text="Label2")

    # Edit the objects.
    window.edit(label)
    window.edit(label2)

    # Start the GUI event loop.
    gui.start_event_loop()

    return
예제 #20
0
def main():
    try:
        from enthought.etsconfig.api import ETSConfig
        from enthought.pyface.api import GUI
    except:
        print >>sys.stderr, "did you install python-chaco?"
        print >>sys.stderr, "maybe you did install chaco>=4, then you will need to install the package etsproxy"
        print >>sys.stderr, "sudo easy_install etsproxy"
        raise

    # select the toolkit we want to use
    # WX is more stable for now
    #ETSConfig.toolkit = 'qt4'
    ETSConfig.toolkit = 'wx'

    # workaround bad bg color in ubuntu, with Ambiance theme
    # wxgtk (or traitsGUI, I dont know) looks like using the menu's bgcolor 
    # for all custom widgets bg colors. :-(

    if ETSConfig.toolkit == 'wx':
        import wx, os
        if "gtk2" in wx.PlatformInfo:
            from gtk import rc_parse, MenuBar
            m = MenuBar()
            if m.rc_get_style().bg[0].red_float < 0.5: # only customize dark bg
                rc_parse(os.path.join(os.path.dirname(__file__),"images/gtkrc"))
            m.destroy()

    # workaround bug in kiva's font manager that fails to find a correct default font on linux
    if os.name=="posix":
        import warnings
        def devnull(*args):
            pass
        warnings.showwarning = devnull
        from  enthought.kiva.fonttools.font_manager import fontManager, FontProperties
        try:
            font = FontProperties()
            font.set_name("DejaVu Sans")
            fontManager.defaultFont = fontManager.findfont(font)
            fontManager.warnings = None
        except: # this code will throw exception on ETS4, which has actually fixed fontmanager
            pass

    from window import open_file



    import optparse
    parser = optparse.OptionParser(usage="""\
%prog [options] [trace.txt|trace.txt.gz|trace.txt.lzma|trace.dat]

pytimechart - Fast graphical exploration and visualisation for linux kernel traces.""")
    parser.add_option("-l", "--log", dest="loglevel", action="store",
                      help="change log level",
                      default=False)
    parser.add_option("-p", "--prof", dest="prof", action="store_true",
                      help="activate profiling",
                      default=False)
    (options, args) = parser.parse_args()

    if options.loglevel:
        numeric_level = getattr(logging, options.loglevel.upper(), None)
        logging.basicConfig(format='%(levelname)s:%(asctime)s:%(message)s',level=numeric_level)
    else:
        logging.basicConfig(format='%(levelname)s:%(asctime)s:%(message)s',level=logging.ERROR)
    # Create the GUI (this does NOT start the GUI event loop).
    gui = GUI()
    if len(args) == 0:
        args.append("dummy")
    for fn in args:
        if not open_file(fn):
            sys.exit(0)
    if options.prof:
        import cProfile
        dict = {"gui":gui}
        cProfile.runctx('gui.start_event_loop()',dict,dict,'timechart.prof')
    else:
        gui.start_event_loop()
예제 #21
0
import sys
from enthought.etsconfig.api import ETSConfig
# select the toolkit we want to use
# WX is more stable for now
#ETSConfig.toolkit = 'qt4'
ETSConfig.toolkit = 'wx'

from enthought.pyface.api import GUI
from timechart.window import open_file


prof=0
if __name__ == '__main__':
    # Create the GUI (this does NOT start the GUI event loop).
    gui = GUI()
    if len(sys.argv)>1:
        fn = sys.argv[1]
    else:
        fn = None
    if open_file(fn):
        if prof:
            import cProfile
            cProfile.run('gui.start_event_loop()','timechart.prof')
        else:
            gui.start_event_loop()

import timechart.py2exe_wximports

##### EOF #####################################################################

예제 #22
0
def show(func=None, stop=False):
    """ Start interacting with the figure.
    
    By default, this function simply creates a GUI and starts its
    event loop if needed.
    
    If it is used as a decorator, then it may be used to decorate a
    function which requires a UI.   If the GUI event loop is already
    running it simply runs the function.  If not the event loop is
    started and function is run in the toolkit's event loop.  The choice
    of UI is via `ETSConfig.toolkit`.  

    If the argument stop is set to True then it pops up a UI where the
    user can stop the event loop.  Subsequent calls to `show` will
    restart the event loop.

    **Parameters**

      :stop:  A boolean which specifies if a UI dialog is displayed which
              allows the event loop to be stopped.

    **Examples**

    Here is a simple example demonstrating the use of show::

      >>> from enthought.mayavi import mlab
      >>> mlab.test_contour3d()
      >>> mlab.show()

    You can stop interaction via a simple pop up UI like so::

      >>> mlab.test_contour3d()
      >>> mlab.show(stop=True)

    The decorator can be used like so::

      >>> @mlab.show
      ... def do():
      ...    mlab.test_contour3d()
      ...
      >>> do()
    
    The decorator can also be passed the stop argument::

      >>> @mlab.show(stop=True)
      ... def do():
      ...    mlab.test_contour3d()
      ...
      >>> do()

    """
    global _gui, _stop_show
    if func is None:
        if not is_ui_running():
            g = GUI()
            _gui = g
            if stop:
                _stop_show = StopShow()
            g.start_event_loop()
        return

    def wrapper(*args, **kw):
        """Wrapper function to run given function inside the GUI event
        loop.
        """
        global _gui, _stop_show
        tk = ETSConfig.toolkit

        if is_ui_running():
            # In this case we should not pop up the UI since we likely
            # don't want to stop the mainloop.
            return func(*args, **kw)
        else:
            g = GUI()
            if tk == "wx":
                # Create a dummy app so invoke later works on wx.
                a = ApplicationWindow(size=(1, 1))
                GUI.invoke_later(lambda: a.close())
                a.open()

            GUI.invoke_later(func, *args, **kw)
            _gui = g
            if stop:
                # Pop up the UI to stop the mainloop.
                _stop_show = StopShow()
            g.start_event_loop()

    return wrapper
예제 #23
0
class Figure:
    def __init__(self, gui='tvtk'):
        self.actors = []
        self.gui = None
        self.renderer = None
        self.items = []
        if gui == 'tvtk':
            self._create_tvtk_window()
        else:
            self._create_ivtk_window()
        self.renderer.background = (1,1,1)
    def _create_tvtk_window(self, size=(500,500)):
        # create a renderer
        self.renderer = tvtk.Renderer()
        # create a render window and hand it the renderer
        self.render_window = tvtk.RenderWindow(size=size)
        self.render_window.add_renderer(self.renderer)
        # create interactor and hand it the render window
        # This handles mouse interaction with window.
        self.interactor = tvtk.RenderWindowInteractor(render_window=self.render_window)
        self.gui = None

    def _create_ivtk_window(self, size=(800,800)):
        from enthought.tvtk.tools import ivtk
        from enthought.pyface.api import GUI

        # Create a GUI instance.
        self.gui = GUI()
        window = ivtk.IVTKWithCrustAndBrowser(size=size)  # Size is optional.
        # Open the window.
        window.open()
        self.renderer = window.scene
        self.render_window = window


    def show_mesh(self, m, **args):
        it = FigureItem(self)
        it.build_from_mesh(m, **args)
        self.actors += it.vtk_actors()
        self.items.append(it)

    def show_mesh_fem(self, mf, **args):
        it = FigureItem(self)
        it.build_from_mesh(mf.linked_mesh(), **args)
        if 'deformation' in args:
            it.deformation_from_mf(args.get('deformation_mf',mf),
                                   args['deformation'],
                                   args.get('deformation_scale','10%'));
        if 'data' in args:
            it.set_scalar_data(args.get('data'),
                               args.get('scalar_label', 'data'));
        it.set_scalar_bar(args.get('scalar_bar', False))

        if 'vdata' in args:
            it.set_vector_data(args.get('vdata'))
            
        self.actors += it.vtk_actors()
        self.items.append(it)

        it.set_colormap(args.get('colormap','earth'));

    def show_slice(self, sl, **args):
        it = FigureItem(self)
        it.build_from_slice(sl, **args)
        
        if 'data' in args:
            it.set_scalar_data(args.get('data'),
                               args.get('scalar_label', 'data'));

        it.set_scalar_bar(args.get('scalar_bar', False))

        if 'vdata' in args:
            it.set_vector_data(args.get('vdata'))
                               
        self.actors += it.vtk_actors()
        self.items.append(it)

        it.set_colormap(args.get('colormap','chouette'));

    def scalar_range(self, *args):
        if len(self.items):
            if len(args)==0:
                return self.items[-1].scalar_range()
            else:
                for i in self.items:
                    i.scalar_range(*args)
        else:
            raise Exception("plot something before changing its scalar range!")

##    def scalar_bar(self):
##        if len(self.items):
##            self.items[-1].set_scalar_bar(True)

    def set_colormap(self, c):
        if (len(self.items)):
            self.items[-1].set_colormap(c)
    def show(self, mf, **args):
        if isinstance(mf, getfem.MeshFem):
            self.show_mesh_fem(mf, **args)
        elif isinstance(mf, getfem.Mesh):
            self.show_mesh(mf, **args)
        elif isinstance(mf, getfem.Slice):
            self.show_slice(mf, **args)
        else:
            raise TypeError("argument must be a drawable getfem object")
    def loop(self):
        for a in self.actors:
            self.renderer.add_actor(a)
        if self.gui:
            self.renderer.reset_zoom()
            self.gui.start_event_loop()
        else:
            self.interactor.start()

    def export_picture(self, filename):
        w2if = tvtk.WindowToImageFilter()
        w2if.magnification = 2
        w2if.input = self.render_window
        ex = tvtk.PNGWriter()
        ex.file_name = filename
        ex.input = w2if.output
        ex.write()
예제 #24
0
    # notifies others that the engine is ready.
    e.start()

    # Do this if you need to see the MayaVi tree view UI.
    ev = EngineView(engine=e)
    ui = ev.edit_traits()

    # Create a new scene.
    scene = e.new_scene()
    # Now create a new scene just for kicks.
    scene1 = e.new_scene()

    # Now setup a normal MayaVi pipeline.
    src = VTKXMLFileReader()
    src.initialize(join(get_data_dir(abspath(__file__)), 'fire_ug.vtu'))
    e.add_source(src)
    e.add_module(Outline())
    e.add_module(ScalarCutPlane())
    e.add_module(Streamline())
    return e, ui


if __name__ == '__main__':
    # When main returns the ui to go out of scope and be gc'd causing the view
    # to disappear with qt4.
    e, ui = main()
    # Create a GUI instance and start the event loop.  We do this here so that
    # main can be run from IPython -wthread if needed.
    gui = GUI()
    gui.start_event_loop()
예제 #25
0
def main():
    try:
        from enthought.etsconfig.api import ETSConfig
        from enthought.pyface.api import GUI
    except:
        print >> sys.stderr, "did you install python-chaco?"
        print >> sys.stderr, "maybe you did install chaco>=4, then you will need to install the package etsproxy"
        print >> sys.stderr, "sudo easy_install etsproxy"
        raise

    # select the toolkit we want to use
    # WX is more stable for now
    #ETSConfig.toolkit = 'qt4'
    ETSConfig.toolkit = 'wx'

    # workaround bad bg color in ubuntu, with Ambiance theme
    # wxgtk (or traitsGUI, I dont know) looks like using the menu's bgcolor
    # for all custom widgets bg colors. :-(

    if ETSConfig.toolkit == 'wx':
        import wx, os
        if "gtk2" in wx.PlatformInfo:
            from gtk import rc_parse, MenuBar
            m = MenuBar()
            if m.rc_get_style(
            ).bg[0].red_float < 0.5:  # only customize dark bg
                rc_parse(
                    os.path.join(os.path.dirname(__file__), "images/gtkrc"))
            m.destroy()

    # workaround bug in kiva's font manager that fails to find a correct default font on linux
    if os.name == "posix":
        import warnings

        def devnull(*args):
            pass

        warnings.showwarning = devnull
        from enthought.kiva.fonttools.font_manager import fontManager, FontProperties
        try:
            font = FontProperties()
            font.set_name("DejaVu Sans")
            fontManager.defaultFont = fontManager.findfont(font)
            fontManager.warnings = None
        except:  # this code will throw exception on ETS4, which has actually fixed fontmanager
            pass

    from window import open_file

    import optparse
    parser = optparse.OptionParser(usage="""\
%prog [options] [trace.txt|trace.txt.gz|trace.txt.lzma|trace.dat]

pytimechart - Fast graphical exploration and visualisation for linux kernel traces."""
                                   )
    parser.add_option("-p",
                      "--prof",
                      dest="prof",
                      action="store_true",
                      help="activate profiling",
                      default=False)
    (options, args) = parser.parse_args()

    # Create the GUI (this does NOT start the GUI event loop).
    gui = GUI()
    if len(args) == 0:
        args.append("dummy")
    for fn in args:
        if not open_file(fn):
            sys.exit(0)
    if options.prof:
        import cProfile
        dict = {"gui": gui}
        cProfile.runctx('gui.start_event_loop()', dict, dict, 'timechart.prof')
    else:
        gui.start_event_loop()
예제 #26
0
class Figure:
    def __init__(self, gui='tvtk'):
        self.actors = []
        self.gui = None
        self.renderer = None
        self.items = []
        if gui == 'tvtk':
            self._create_tvtk_window()
        else:
            self._create_ivtk_window()
        self.renderer.background = (1, 1, 1)

    def _create_tvtk_window(self, size=(500, 500)):
        # create a renderer
        self.renderer = tvtk.Renderer()
        # create a render window and hand it the renderer
        self.render_window = tvtk.RenderWindow(size=size)
        self.render_window.add_renderer(self.renderer)
        # create interactor and hand it the render window
        # This handles mouse interaction with window.
        self.interactor = tvtk.RenderWindowInteractor(
            render_window=self.render_window)
        self.gui = None

    def _create_ivtk_window(self, size=(800, 800)):
        from enthought.tvtk.tools import ivtk
        from enthought.pyface.api import GUI

        # Create a GUI instance.
        self.gui = GUI()
        window = ivtk.IVTKWithCrustAndBrowser(size=size)  # Size is optional.
        # Open the window.
        window.open()
        self.renderer = window.scene
        self.render_window = window

    def show_mesh(self, m, **args):
        it = FigureItem(self)
        it.build_from_mesh(m, **args)
        self.actors += it.vtk_actors()
        self.items.append(it)

    def show_mesh_fem(self, mf, **args):
        it = FigureItem(self)
        it.build_from_mesh(mf.linked_mesh(), **args)
        if 'deformation' in args:
            it.deformation_from_mf(args.get('deformation_mf', mf),
                                   args['deformation'],
                                   args.get('deformation_scale', '10%'))
        if 'data' in args:
            it.set_scalar_data(args.get('data'),
                               args.get('scalar_label', 'data'))
        it.set_scalar_bar(args.get('scalar_bar', False))

        if 'vdata' in args:
            it.set_vector_data(args.get('vdata'))

        self.actors += it.vtk_actors()
        self.items.append(it)

        it.set_colormap(args.get('colormap', 'earth'))

    def show_slice(self, sl, **args):
        it = FigureItem(self)
        it.build_from_slice(sl, **args)

        if 'data' in args:
            it.set_scalar_data(args.get('data'),
                               args.get('scalar_label', 'data'))

        it.set_scalar_bar(args.get('scalar_bar', False))

        if 'vdata' in args:
            it.set_vector_data(args.get('vdata'))

        self.actors += it.vtk_actors()
        self.items.append(it)

        it.set_colormap(args.get('colormap', 'chouette'))

    def scalar_range(self, *args):
        if len(self.items):
            if len(args) == 0:
                return self.items[-1].scalar_range()
            else:
                for i in self.items:
                    i.scalar_range(*args)
        else:
            raise Exception("plot something before changing its scalar range!")

##    def scalar_bar(self):
##        if len(self.items):
##            self.items[-1].set_scalar_bar(True)

    def set_colormap(self, c):
        if (len(self.items)):
            self.items[-1].set_colormap(c)

    def show(self, mf, **args):
        if isinstance(mf, getfem.MeshFem):
            self.show_mesh_fem(mf, **args)
        elif isinstance(mf, getfem.Mesh):
            self.show_mesh(mf, **args)
        elif isinstance(mf, getfem.Slice):
            self.show_slice(mf, **args)
        else:
            raise TypeError("argument must be a drawable getfem object")

    def loop(self):
        for a in self.actors:
            self.renderer.add_actor(a)
        if self.gui:
            self.renderer.reset_zoom()
            self.gui.start_event_loop()
        else:
            self.interactor.start()

    def export_picture(self, filename):
        w2if = tvtk.WindowToImageFilter()
        w2if.magnification = 2
        w2if.input = self.render_window
        ex = tvtk.PNGWriter()
        ex.file_name = filename
        ex.input = w2if.output
        ex.write()
예제 #27
0
def show(func=None, stop=False):
    """ Start interacting with the figure.
    
    By default, this function simply creates a GUI and starts its
    event loop if needed.
    
    If it is used as a decorator, then it may be used to decorate a
    function which requires a UI.   If the GUI event loop is already
    running it simply runs the function.  If not the event loop is
    started and function is run in the toolkit's event loop.  The choice
    of UI is via `ETSConfig.toolkit`.  

    If the argument stop is set to True then it pops up a UI where the
    user can stop the event loop.  Subsequent calls to `show` will
    restart the event loop.

    **Parameters**

      :stop:  A boolean which specifies if a UI dialog is displayed which
              allows the event loop to be stopped.

    **Examples**

    Here is a simple example demonstrating the use of show::

      >>> from enthought.mayavi import mlab
      >>> mlab.test_contour3d()
      >>> mlab.show()

    You can stop interaction via a simple pop up UI like so::

      >>> mlab.test_contour3d()
      >>> mlab.show(stop=True)

    The decorator can be used like so::

      >>> @mlab.show
      ... def do():
      ...    mlab.test_contour3d()
      ...
      >>> do()
    
    The decorator can also be passed the stop argument::

      >>> @mlab.show(stop=True)
      ... def do():
      ...    mlab.test_contour3d()
      ...
      >>> do()

    """
    global _gui, _stop_show
    if func is None:
        if not is_ui_running():
            g = GUI()
            _gui = g
            if stop:
                _stop_show = StopShow()
            g.start_event_loop()
        return

    def wrapper(*args, **kw):
        """Wrapper function to run given function inside the GUI event
        loop.
        """
        global _gui, _stop_show
        tk = ETSConfig.toolkit

        if is_ui_running():
            # In this case we should not pop up the UI since we likely
            # don't want to stop the mainloop.
            return func(*args, **kw)
        else:
            g = GUI()
            if tk == 'wx':
                # Create a dummy app so invoke later works on wx.
                a = ApplicationWindow(size=(1, 1))
                GUI.invoke_later(lambda: a.close())
                a.open()

            GUI.invoke_later(func, *args, **kw)
            _gui = g
            if stop:
                # Pop up the UI to stop the mainloop.
                _stop_show = StopShow()
            g.start_event_loop()

    return wrapper