Beispiel #1
0
 def run(self):
     print "Performing expensive calculation in %s..." % self.getName(),
     sleep(3)
     sd = self.data.scalar_data
     sd += numpy.sin(numpy.random.rand(*sd.shape) * 2.0 * numpy.pi)
     GUI.invoke_later(self.data.update)
     print "done."
Beispiel #2
0
    def select_selected(self, initialized):
        """ Force the tree editor to select the current engine selection,
            and eventually collapse other scenes.
        """
        # We need to explore the editors to find the one we are
        # interested in, and to switch its selection to None, and then 
        # back to what we are interested in.
        editors = self.info.ui._editors
        if editors is not None:
            for editor in editors:
                if editor.factory is self.info.object.tree_editor:
                    tree_editor = editor
                    break
            else:
                return
        else:
            return

        # We switch the selection to None, but we avoid
        # trait callback, to avoid changing the engine's
        # current_selection.
        tree_editor.set(selected=None, trait_change_notify=False)
        current_selection = self.info.object.engine.current_selection
        GUI.set_trait_later(tree_editor, 'selected', current_selection)

        # If we are selecting a scene, collapse the others
        if isinstance(current_selection, Scene) and \
                                    hasattr(tree_editor._tree, 'Collapse'):
            # The wx editor can collapse, dunno for the Qt
            for scene in self.info.object.engine.scenes:
                if scene is not current_selection:
                    tree_editor._tree.Collapse(
                                            tree_editor._get_object_nid(scene))
Beispiel #3
0
 def run(self):
     print "Performing expensive calculation in %s..." % self.getName(),
     sleep(3)
     sd = self.data.scalar_data
     sd += numpy.sin(numpy.random.rand(*sd.shape) * 2.0 * numpy.pi)
     GUI.invoke_later(self.data.update)
     print 'done.'
Beispiel #4
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()
Beispiel #5
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()
Beispiel #6
0
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
Beispiel #7
0
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
Beispiel #8
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()
Beispiel #9
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()
Beispiel #10
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()
Beispiel #11
0
 def _make_active(self, obj):
     """Make the object given, `obj`, the current selection of the
     engine."""
     engine = get_engine(obj)
     if engine is not None:
         # This is required when running mayavi in envisage.
         GUI.set_trait_later(engine, 'current_selection', obj)
     else:
         print "No engine"
Beispiel #12
0
    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
Beispiel #13
0
    def run(self):
        if ((not hasattr(self,'nonlinear_distortion_model')) or
            (self.nonlinear_distortion_model is None)):
            do_undistortion = False
        else:
            do_undistortion = True

        if do_undistortion:
            im,ll,ur = self.nonlinear_distortion_model.remove_distortion(
                self.image_data)
        else:
            im = self.image_data
            ll = 0,0
            ur = im.shape[:2][::-1]-np.array([1,1])

        ax = self.mplwidget.axes
        ax.images=[]
        ax.lines=[]
        kwargs = {}

        if self.display_transform == 'flip y':
            display_im = im
            kwargs['origin']='lower'
            kwargs['extent']=(ll[0],ur[0],ll[1],ur[1])
        elif self.display_transform == 'identity':
            display_im = im
            kwargs['extent']=(ll[0],ur[0],ur[1],ll[1])
        elif self.display_transform == 'rotate 180':
            display_im = np.rot90(np.rot90(im))
            kwargs['extent']=(ur[0],ll[0],ll[1],ur[1])#(ll[0],ur[0],ur[1],ll[1])
        elif self.display_transform == 'rotate 90':
            display_im = np.rot90(im)
            kwargs['extent']=(ll[1],ur[1],ll[0],ur[0])
        elif self.display_transform == 'rotate 270':
            display_im = np.rot90(np.rot90(np.rot90(im)))
            kwargs['extent']=(ur[1],ll[1],ur[0],ll[0])
        else:
            raise ValueError("unknown transform '%s'"%self.display_transform)

        ax.imshow(display_im,
                  aspect='equal',
                  cmap=cm.pink,
                  **kwargs)

        if hasattr(self,'lines'):
            if do_undistortion:
                func = self.nonlinear_distortion_model.undistort
            else:
                func = None
            draw_lines_on_ax(ax,self.lines,func=func,
                             display_transform=self.display_transform)

        GUI.invoke_later(self.mplwidget.figure.canvas.draw)
Beispiel #14
0
 def close_scene(self, scene):
     """Given a VTK scene instance, this method closes it.
     """
     active_window = self.window 
     s = scene.scene
     for editor in active_window.editors[:]:
         if isinstance(editor, scene_editor.SceneEditor):
             if id(editor.scene) == id(s):
                 editor.close()
                 break
     # Flush the UI.
     GUI.process_events()
Beispiel #15
0
 def new_scene(self):
     """Creates a new TVTK scene, sets its size to that prescribed
     and returns the scene.
     """
     script = self.script
     # Create a new VTK scene.
     script.new_scene()
     # Set its background.
     if self.standalone:
         GUI.process_events()
     s = script.engine.current_scene
     s.scene.background = (0.5, 0.5, 0.5)
     return s
Beispiel #16
0
 def _loaded_changed(self, value):
     if value:
         n = self.dname
         if ' [Active]' not in n:
             self.dname = "%s [Loaded]" % n
             
         if not self.window is None:
             #from enthought.pyface.timer.api import do_later
             from enthought.pyface.api import GUI
             GUI.invoke_later(self.window.status_bar_manager.set, message = '')
         
     else:
         self.dname = self.dname.replace(' [Loaded]', '')
Beispiel #17
0
 def _active_changed(self , value):
     if value:
         n = self.name
         if ' [Active]' not in n:
             self.name = "%s [Active]" % n
             
         # XXX: do refactor with threaded loading of surfaces
         # and default spring force layout for graph rendering!
         # see also TraitsUI Demos: Multi thread demo
         
         # load the surface containers data
         # make a deep copy of the already loaded surface containers
         import copy
         self.surfaces = copy.deepcopy(self.surfaces_loaded)
         for surfcont in self.surfaces:
             surfcont.load_surface_container()
         
         if self.rendermanager is None:
             self._create_datasourcemanager()
             self._create_renderer()
             # if there are no surfaces, initialize
             # network rendering, but only if dn_positions are given
             if len(self.surfaces) == 0:
                 logger.debug('No surfaces found. Try to render graph view with dn_position information.')
                 self.rendermanager.datasourcemanager._compute_3DLayout(-1, -1)
                 self.rendermanager.visualize_graph()
             else:
                 logger.debug('SurfaceContainer found. Try to render 3D View using %s.' % self.surfaces[0].name)
                 if len(self.surfaces[0].surfaces) == 0:
                     logger.debug('Rendering not possible because SurfaceContainer contains no surfaces.')
                 else:
                     logger.debug('Using first surface for rendering.')
                     self.surfaces[0].surfaces[0]._layout_3DView()
         
         if not self._parentcfile._workbenchwin is None:
             #from enthought.pyface.timer.api import do_later
             from enthought.pyface.api import GUI
             GUI.invoke_later(self._parentcfile._workbenchwin.status_bar_manager.set, message = '')
         
     else:
         self.name = self.name.replace(' [Active]', '')
         logger.debug('Close RenderManager scenes')
         self.rendermanager.close_scenes()
         logger.debug('All scenes closed.')
         # FIXME: what is happening in the following?
         # e.g. for instances. e.g. reset traits?
         # XXX: this is somehow not correct. do i need to use del
         # or remove/reset traits?
         self.rendermanager = None
         self.datasourcemanager = None
         self.surfaces = []
Beispiel #18
0
    def new_scene(self, name=None, **kwargs):
        """ Creates a new VTK scene window.

            For the time being the extra kwargs are ignored with the
            envisage engine.
        """
        action = NewScene(window=self.window)
        editor = action.perform(None)
        if name is not None:
            editor.name = name
        
        # Flush the UI.
        GUI.process_events()
        return self.scenes[-1]
Beispiel #19
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()
Beispiel #20
0
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()
Beispiel #21
0
def compare_image_raw(renwin, img_fname, threshold=10, allow_resize=True):
    """Compares renwin's (a tvtk.RenderWindow) contents with the image
    file whose name is given in the second argument.  If the image
    file does not exist the image is generated and stored.  If not the
    image in the render window is compared to that of the figure.
    This function also handles multiple images and finds the best
    matching image.  If `allow_resize` is True then the images are
    rescaled if they are not of the same size.
    """
    # If this is not done the window may not be parented correctly.
    GUI.process_events()
    
    w2if = tvtk.WindowToImageFilter(read_front_buffer=False, input=renwin)
    w2if.update()
    return compare_image_with_saved_image(w2if.output, img_fname,
                                          threshold, allow_resize)
Beispiel #22
0
def viewer(browser=True, instantiate_gui=False):
    """Creates an IVTK instance, opens the window and returns the
    embedded scene inside it.  This is useful from an IPython/vanilla
    Python shell.  It returns the viewer window instance.

    Parameters
    ----------

    - browser : `bool` (default, True)
    
      If True, creates an IVTK scene with an embedded PipelineBrowser.
      If False, does not create it.

    - instantiate_gui : `bool` (default: False)

      If True, create an instance of GUI().  This is useful when this
      function is invoked from within an IPython shell.  OTOH, if this
      is called from within a wxPython app (or with ipython -wthread)
      you don't want to start another GUI instance.
    """
    if instantiate_gui:
        gui = GUI()
    if browser:
        v = IVTKWithBrowser(size=(600, 600))
    else:
        v = IVTK(size=(600, 600))
    v.open()
    return v
Beispiel #23
0
    def _on_tree_end_label_edit(self, event):
        """ Called when the user has finished editing am item's label. """

        wxid = event.GetItem()

        # The item data is a tuple.  The first element indicates whether or not
        # we have already populated the item with its children.  The second
        # element is the actual item data.
        populated, node = self.control.GetPyData(wxid)

        # Give the model a chance to veto the edit.
        label = event.GetLabel()

        # Making sure the new label is not an empty string

        if label is not None and len(label) > 0 and \
            self.model.can_set_text(node, label):

            def end_label_edit():
                """ Called to complete the label edit. """

                # Set the node's text.
                self.model.set_text(node, label)

                # If a label edit callback was specified (in the call to
                # 'edit_label'), then call it).
                if self._label_edit_callback is not None:
                    self._label_edit_callback(self, node, label)

                return

            # We use a deffered call here, because a name change can trigger
            # the structure of a node to change, and hence the actual tree
            # nodes might get moved/deleted before the label edit operation has
            # completed.  When this happens wx gets very confused!  By using
            # 'invoke_later' we allow the label edit to complete.
            GUI.invoke_later(end_label_edit)

        else:
            event.Veto()

            # If a label edit callback was specified (in the call to
            # 'edit_label'), then call it).
            if self._label_edit_callback is not None:
                self._label_edit_callback(self, node, label)

        return
Beispiel #24
0
    def _on_tree_end_label_edit(self, event):
        """ Called when the user has finished editing am item's label. """

        wxid = event.GetItem()

        # The item data is a tuple.  The first element indicates whether or not
        # we have already populated the item with its children.  The second
        # element is the actual item data.
        populated, node = self.control.GetPyData(wxid)

        # Give the model a chance to veto the edit.
        label = event.GetLabel()

        # Making sure the new label is not an empty string

        if label is not None and len(label) > 0 and \
            self.model.can_set_text(node, label):
            def end_label_edit():
                """ Called to complete the label edit. """

                # Set the node's text.
                self.model.set_text(node, label)

                # If a label edit callback was specified (in the call to
                # 'edit_label'), then call it).
                if self._label_edit_callback is not None:
                    self._label_edit_callback(self, node, label)

                return

            # We use a deffered call here, because a name change can trigger
            # the structure of a node to change, and hence the actual tree
            # nodes might get moved/deleted before the label edit operation has
            # completed.  When this happens wx gets very confused!  By using
            # 'invoke_later' we allow the label edit to complete.
            GUI.invoke_later(end_label_edit)

        else:
            event.Veto()

            # If a label edit callback was specified (in the call to
            # 'edit_label'), then call it).
            if self._label_edit_callback is not None:
                self._label_edit_callback(self, node, label)

        return
Beispiel #25
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()
Beispiel #26
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()
Beispiel #27
0
    def _anytrait_changed(self, name, old, new):
        if name[:4] == "var_":
            name = name[4:]
            if (not self._no_block_update) and (self.block is not None):
                if isinstance(old, ArangeGenerator):
                    old.on_trait_change(self._array_changed, "array", remove=True)
                if isinstance(new, ArangeGenerator):
                    new.on_trait_change(self._array_changed, "array")
                    new = new.array
                self.context[name] = new
                self._needs_update = True
                # print "Adding update func"
                def update_func():
                    if self._needs_update:
                        self._blocks[name].execute(self.context)
                        self._needs_update = False

                GUI.invoke_after(10, update_func)
Beispiel #28
0
    def _on_editor_closed(self, editor):
        """ Dynamic trait change handler. """

        index = self.editors.index(editor)
        del self.editors[index]
        if editor is self.active_editor:
            if len(self.editors) > 0:
                index = min(index, len(self.editors) - 1)
                # If the user closed the editor manually then this method is
                # being called from a toolkit-specific event handler. Because
                # of that we have to make sure that we don't change the focus
                # from within this method directly hence we activate the editor
                # later in the GUI thread.
                GUI.invoke_later(self.activate_editor, self.editors[index])

            else:
                self.active_editor = None

        return
Beispiel #29
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()
Beispiel #30
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
Beispiel #31
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()
Beispiel #32
0
def show_actors(actors, shell=False):
    gui = GUI()
    if shell:
        window = ivtk.IVTKWithCrustAndBrowser(size=(800, 600))
    else:
        window = ivtk.IVTKWithBrowser(size=(600, 400))
    window.open()
    for a in actors:
        window.scene.add_actor(a)
    window.scene.background = (1, 1, 1)
    return window, gui
Beispiel #33
0
    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
Beispiel #34
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
Beispiel #35
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()
Beispiel #36
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
Beispiel #37
0
    def normal_right_down(self, event):
        """ Right click will bring up a dialog to edit the
            prefix/suffix of the selected variables.
        """
        field = self._get_underlying_box_field(event.x, event.y)
        if field:
            selected_fields = self.input_selected_fields + self.output_selected_fields
            if field in selected_fields:
                for group in self.menu.groups:
                    for action_item in group.items:
                        action = action_item.action
                        action.container = self.component
                        action.selected_fields = selected_fields
                menu = self.menu.create_menu(event.window.control)

                if len(event._pos_stack) > 0:
                    real_x, real_y = event._pos_stack[0]
                else:
                    real_x, real_y = event.x, event.y
                from enthought.pyface.api import GUI
                GUI.invoke_later(menu.show, real_x - 10, event.window._flip_y(real_y))
                self.component.request_redraw()
        event.handled = True
 def run(self):
     im = self.image
     X, Y = indices(im.shape)
     x = sum(X*im)/sum(im)
     y = sum(Y*im)/sum(im)
     width = sqrt(abs(sum(((X-x)**2+(Y-y)**2)*im)/sum(im))) 
     GUI.invoke_later(setattr, self.results, 'x', x)
     GUI.invoke_later(setattr, self.results, 'y', y)
     GUI.invoke_later(setattr, self.results, 'width', width)
Beispiel #39
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()
Beispiel #40
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
Beispiel #41
0
def visual_test(jpos, jfreedom, loads, elements, E, r, p, max_stress=3e+8):
    displacements, strains, stresses, mass, status, times = analyse_truss(jpos, jfreedom, loads, elements, E, r, p)
    jpos_d = jpos + displacements*100
    print status
    print times
    print 'displacements: ', displacements
    print 'strains: ', strains
    print 'stresses: ', stresses
    #strains_abs = N.abs(strains)

    from enthought.tvtk.api import tvtk
    from enthought.tvtk.tools import ivtk
    from enthought.pyface.api import GUI
    v = ivtk.viewer(False, False)
    v.scene.z_plus_view()

    pd = tvtk.PolyData()
    pts = jpos[elements].reshape((-1,2))
    pd.points = N.column_stack((pts[:,0], pts[:,1], N.zeros(len(pts))))
    pd.lines = N.r_[:len(elements)*2].reshape((-1,2))
    pd.cell_data.scalars = -strains
    pd.point_data.scalars = N.column_stack((r, r)).ravel()
    #tubes = tvtk.TubeFilter(input=pd, radius=N.sqrt(element_A.max() / N.pi), number_of_sides=16)
    tubes = tvtk.TubeFilter(input=pd, number_of_sides=16, vary_radius='vary_radius_by_absolute_scalar', capping=True)
    #tubes = tvtk.RibbonFilter(input=pd, use_default_normal=True, vary_width=True)
    b = tvtk.Actor(mapper=tvtk.PolyDataMapper(input=tubes.output, scalar_range=(-N.abs(strains).max(), N.abs(strains).max()), scalar_mode='use_cell_data'))
    b.mapper.lookup_table.hue_range = (0, 0.66)
    v.scene.add_actor(b)

    pd1 = tvtk.PolyData()
    pd1.points = N.column_stack((jpos_d[:,0], jpos_d[:,1], N.zeros(len(jpos))))
    pd1.lines = elements
    tubes1 = tvtk.TubeFilter(input=pd1, radius=0.01, number_of_sides=16)
    a = tvtk.Actor(mapper=tvtk.PolyDataMapper(input=tubes1.output))
    a.property.opacity = 0.3
    v.scene.add_actor(a)

    print "strain: ", strains.min(), strains.max()

    v.scene.reset_zoom()
    GUI().start_event_loop()
Beispiel #42
0
 def update(self):
     for prim in self.primitives:
         prim.update()
     GUI.invoke_later(self.scene.render)
Beispiel #43
0
from enthought.traits import *
from enthought.pyface.api import GUI
from enthought.traits.api import HasTraits, Int, Button
from enthought.traits.ui.api import View, Item, ButtonEditor


class Counter(HasTraits):
    value = Int()
    add_one = Button()

    def _add_one_fired(self):
        self.value += 1

    view = View('value', Item('add_one', show_label=False))


Counter().edit_traits()
GUI().start_event_loop()
#Counter().configure_traits()
Beispiel #44
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()
Beispiel #45
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()
Beispiel #46
0
 def update_table_editor(self, object, name, old, new):
     if isinstance(object, ListItem):
         self.tabular_editor.adapter.columns[object.column_number] = \
                             (new, object.column_number)
         GUI.set_trait_later(self.info.ui, 'updated', True)
Beispiel #47
0
 def object_update_changed(self, info):
     if info.initialized:
         def run():
             info.object.fig.canvas.draw()
         GUI.invoke_later(run) 
Beispiel #48
0
 def object_update_changed(self, info):
     if info.initialized:
         info.object.ax.mouse_init() 
         GUI.invoke_later(info.object.fig.canvas.draw) 
Beispiel #49
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()
Beispiel #50
0
 def update(self):
   for prim in self.primitives:
     prim.update()
   GUI.invoke_later(self.scene.render)
Beispiel #51
0
 def _busy_changed(self, val):
     GUI.set_busy(val)
Beispiel #52
0
    def run(self):
        logger.debug("Start Threaded Parsing of Connectome File ...")
        import time
        tic = time.time()
        
        # given the full path to meta.xml, create lxml tree and
        # under the precondition of having a certain file version and generator
        # one can assume some content of the .cff file
        # loop over the networks, for each network, the surfaces etc.
        # in the form of all the attributes (name, srce filename, description etc.)
        # are given to the created Network instance methods to complete
        from lxml import etree
        tree = etree.fromstring(self.metaxmlcontent)   
        nsprefix = "{%s}" % tree.nsmap[None]
        
        t = 0
        for child in tree.iterchildren():
            if child.tag == (nsprefix+'viewer-network'):
                t = t + 1

        if t != self.data.metadata.nr_of_networks:
            logger.error('The number of networks of networks in meta.xml is not correct!')
            logger.error('Loading ' + str(t) + ' network(s).')


        # find all the networks
        for child in tree.iterchildren():
            if child.tag == (nsprefix+'viewer-network'):

                # load network as string from zip
                # create temporary StringIO
                logger.info('-----------------------------------------')
                logger.info('Now loading ' + child.attrib['src'])
                logger.info('-----------------------------------------')
                
                if child.attrib.has_key('src'):
                    (tmpstring, pickled_graph, local_fname) = self.process_pickle(childnode = child)
                
                tmp_network = Network(name = child.attrib['name'],
                                    src = tmpstring,
                                    pickled_graph = pickled_graph,
                                    directed = child.attrib['directed'],
                                    hierarchical = child.attrib['hierarchical'],
                                    hypergraph = child.attrib['hypergraph'])

                # store pickled version in connectome file
                if not tmpstring is None and pickled_graph is None:
                    self.save_pickle_in_cfile(local_fname, networkref = tmp_network)

                
                # iterate over children
                for mchildren in child.iterchildren():
                    
                    # handling of the metadata
                    # -------------------------
                    if mchildren.tag == (nsprefix+'network-metadata'):
                        tmp_network.metadata = self.process_metadata(metadata_node = mchildren, nsprefix = nsprefix)
                        
                        
                    # handling of the surfaces
                    # ------------------------
                    if mchildren.tag == (nsprefix+'network-surface'):
                    
                        # load into surface
                        attr = mchildren.attrib
    
                        if attr.has_key('src'):
                            # create surface container
                            tmpsurfacecontainer = self.process_surface(surface_node = mchildren, nsprefix = nsprefix)
                            # and add it to the network
                            tmp_network.add_surface_container(tmpsurfacecontainer)

                        # adding a template atlas if stated in the meta.xml
                        if attr.has_key('addatlas'):
                            # create surface container for atlas
                            tmpsurfacecontainer = self.process_atlas(surface_node = mchildren, nsprefix = nsprefix)
                            # and add it to the network
                            tmp_network.add_surface_container(tmpsurfacecontainer)
                            
                        
                    # handling of the volumes
                    # -----------------------
                    elif mchildren.tag == (nsprefix+'network-volume'):
                        
                        # get the description, is there an easier way with lxml?
                        for desc in mchildren.iterchildren():
                            if desc.tag == (nsprefix+'description'):
                                mydescr = desc.text
                      
                        attr = mchildren.attrib
                        
                        if attr.has_key('src') and attr.has_key('name'):
                          
                            if not attr.has_key('segmentation'):
                                segm = False
                            else:
                                segm = bool(attr['segmentation'])
                          
                            # create an instance of the Volume class with it
                            tmpvolume = Volume(volumename = attr['name'], \
                                                 networkref = tmp_network, \
                                                 src = attr['src'], \
                                                 description = mydescr, \
                                                 segmentation = segm)
                            
                            # add this instance to the list of its network
                            tmp_network.add_volume(tmpvolume)
                            logger.info('Added volume ' + tmpvolume.volumename + \
                                        ' to ' + tmp_network.networkname)

                            
                    # handling of the trackfiles
                    # --------------------------
                    elif mchildren.tag == (nsprefix+'network-track'):
                        
                        # get the description, is there an easier way with lxml?
                        for desc in mchildren.iterchildren():
                            if desc.tag == (nsprefix+'description'):
                              mydescr = desc.text
                      
                        attr = mchildren.attrib
                    
                        if attr.has_key('src') and attr.has_key('name'):
                            tmptrack = Trackfile(trkname = attr['name'], tmpfname = attr['src'], \
                                                 description = mydescr, networkref = tmp_network)
                            
                            # add this instance to the list of its trackfiles
                            tmp_network.add_trackfile(tmptrack)
                            logger.info('Added trackfile ' + tmptrack.trkname + \
                                        ' to ' + tmp_network.networkname)

                # setting the correct parent cfile
                tmp_network._parentcfile = self.data
                
                # add the created network object to this cfile
                self.data.networks.append(tmp_network)

        toc = time.time()
        logger.info('Loading Connectome File DONE. (Time: %s)' % str(toc-tic))
        logger.info('-----------------------------------------')
        
        # setting data loaded flag
        self.data._data_loaded = True
        
        # with do_later, we the change in the statusbar is done in the gui main thread
        if not self.data._workbenchwin is None:
            #from enthought.pyface.timer.api import do_later
            #do_later(self.data._workbenchwin.status_bar_manager.set, message = '')
            # TEST
            from enthought.pyface.api import GUI
            GUI.invoke_later(self.data._workbenchwin.status_bar_manager.set, message = '')
Beispiel #53
0
    ###########################################################################

    #### Trait event handlers #################################################

    def _on_name_changed(self, new):
        """ Called when the name has been changed. """

        self.complete = len(new.strip()) > 0

        return


# Application entry point.
if __name__ == '__main__':
    # Create the GUI (this does NOT start the GUI event loop).
    gui = GUI()

    wizard = ChainedWizard(
        parent=None,
        title='Chained wizard root',
        pages=[
            SimpleWizardPage(
                id='foo',
                color='red',
                heading="The Red Page",
                subheading="The default color on this page is red.")
        ])

    next_wizard = Wizard(
        parent=None,
        title='Chained wizard child.',