Exemplo n.º 1
0
def main():
    os.chdir( os.path.dirname( os.path.realpath( __file__ )))

    #read the command line arguments or fetch the default values
    args=cli_args(sys.argv[2:])

    #generate the initial dataset
    #TODO collect the "name" of the sample dataset on the command line
    
    sample_dataset,sample_metadata,exec_script=preproc(args)
    
    g=CvuGUI(sample_dataset,sample_metadata,quiet=args['quiet'])
    sample_dataset.gui=g

    #Qt does not sys.exit in response to KeyboardInterrupt
    #we intercept KeyboardInterrupts in the interpreter, before even
    #reaching the Qt event loop and force them to call sys.exit
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    if exec_script is not None:
        from pyface.api import GUI
        gui=GUI()

        def run_script():
            gui.process_events()
            script(exec_script, cvu_gui=g, scriptdir=sys.argv[1])

        gui.invoke_later(run_script)

    g.configure_traits()
    def visualize(self):
        '''
        Start the visualisation of the simulation result.
        Set up Upgrade method and starts the main loop.
        Use only if the simulation result was set!
        '''
        # update the lookuptables and set them
        minL = []
        maxL = []
       
        for array in self.scalarSolution[self.solutionPosition][self.scalarPosition].itervalues(): 
            minL.append(array.min())
            maxL.append(array.max())
        self.SourceMin = min(minL)
        self.SourceMax = max(maxL)

        for actor in self.vizActors.itervalues():
            actor.module_manager.scalar_lut_manager.data_range = [self.SourceMin, self.SourceMax]
        #self.vizActors[0].module_manager.scalar_lut_manager.data_name = self.scalarNames[self.solutionPosition][self.scalarPosition]
        #self.vizActors[0].module_manager.scalar_lut_manager.show_scalar_bar = True

        timer = Timer(0.03, self.update)
        gui = GUI()
        gui.busy = True
        gui.start_event_loop()
Exemplo n.º 3
0
    def tracking_state_callback(self, sbp_msg, **metadata):
        t = time.time() - self.t_init
        self.time[0:-1] = self.time[1:]
        self.time[-1] = t
        # first we loop over all the SIDs / channel keys we have stored and set 0 in for CN0
        for key, cno_array in self.CN0_dict.items():
            # p
            if (cno_array == 0).all():
                self.CN0_dict.pop(key)
            else:
                new_arr = np.roll(cno_array, -1)
                new_arr[-1] = 0
                self.CN0_dict[key] = new_arr

        # If the whole array is 0 we remove it
        # for each satellite, we have a (code, prn, channel) keyed dict
        # for each SID, an array of size MAX PLOT with the history of CN0's stored
        # If there is no CN0 or not tracking for an epoch, 0 will be used
        # each array can be plotted against host_time, t
        for i, s in enumerate(sbp_msg.states):
            if code_is_gps(s.sid.code):
                sat = s.sid.sat
            elif code_is_glo(s.sid.code):
                sat = s.fcn - GLO_FCN_OFFSET
                self.glo_slot_dict[sat] = s.sid.sat

            key = (s.sid.code, sat, i)
            if s.cn0 != 0:
                self.CN0_dict[key][-1] = s.cn0 / 4.0

        GUI.invoke_later(self.update_plot)
Exemplo n.º 4
0
 def run(self):
     cams, new_cams = register_image(self.vsfm_interface, self.imfn, 
                                     match_specified_fn = self.match_specified_fn,
                                     max_sleep_seconds = self.max_sleep_seconds)
     GUI.invoke_later(mayaviu.plot_cameras, new_cams)
     self.cams = cams
     self.new_cams = new_cams
Exemplo n.º 5
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.'
Exemplo n.º 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
Exemplo n.º 7
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()
Exemplo n.º 8
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.trait_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))
Exemplo n.º 9
0
  def _baseline_callback_ned(self, sbp_msg, **metadata):
    # Updating an ArrayPlotData isn't thread safe (see chaco issue #9), so
    # actually perform the update in the UI thread.
    if self.running:
      #GUI.invoke_later(self.baseline_callback, sbp_msg)

      soln = MsgBaselineNED(sbp_msg)
      GUI.invoke_later(self.baseline_callback, soln)

      cnt = self.cnt % 4
      fake_sbp_msg = copy.copy(soln)
      if cnt == 3:
        fake_sbp_msg.e = 217371
        fake_sbp_msg.n = 100837 - (cnt+1) * 10e3
      else:
        fake_sbp_msg.e = 217371 + cnt * 20e3
        fake_sbp_msg.n = 100837 - cnt * 20e3
      fake_sbp_msg.sender = 100 + cnt
      fake_sbp_msg.flags = cnt
      soln = fake_sbp_msg
      self.cnt += 1
      GUI.invoke_later(self.baseline_callback, soln)

    # _threshold_satisfied()函数计算需要优化
    # 或者保持数据发送频率小于2(/s)
    time.sleep(0.5)
Exemplo n.º 10
0
 def tracking_state_callback(self, sbp_msg, **metadata):
   t = time.time() - self.t_init
   self.time[0:-1] = self.time[1:]
   self.time[-1] = t
   # first we loop over all the SIDs / channel keys we have stored and set 0 in for CN0
   for key, cno_array in self.CN0_dict.items():
     # p
     if (cno_array==0).all():
       self.CN0_dict.pop(key)
     else:
       self.CN0_dict[key][0:-1] = cno_array[1:]
       self.CN0_dict[key][-1] = 0
     # If the whole array is 0 we remove it
   # for each satellite, we have a (code, prn, channel) keyed dict
   # for each SID, an array of size MAX PLOT with the history of CN0's stored
   # If there is no CN0 or not tracking for an epoch, 0 will be used
   # each array can be plotted against host_time, t
   for i,s in enumerate(sbp_msg.states):
     prn = s.sid.sat
     if code_is_gps(s.sid.code):
       prn += 1
     key = (s.sid.code, prn, i)
     if s.state != 0:
       if len(self.CN0_dict.get(key, [])) == 0:
         self.CN0_dict[key] = np.zeros(NUM_POINTS)
       self.CN0_dict[key][-1] = s.cn0
   GUI.invoke_later(self.update_plot)
Exemplo n.º 11
0
  def manage_multi_firmware_update(self):
    # Set up progress dialog and transfer file to Piksi using SBP FileIO
    progress_dialog = PulsableProgressDialog(len(self.stm_fw.blob))
    progress_dialog.title = "Transferring image file"
    GUI.invoke_later(progress_dialog.open)
    self._write("Transferring image file...")
    try:
      FileIO(self.link).write("upgrade.image_set.bin", self.stm_fw.blob,
                              progress_cb=progress_dialog.progress)
    except Exception as e:
      self._write("Failed to transfer image file to Piksi: %s\n" % e)
      progress_dialog.close()
      return
    try:
      progress_dialog.close()
    except AttributeError:
      pass

    # Setup up pulsed progress dialog and commit to flash
    progress_dialog = PulsableProgressDialog(100, True)
    progress_dialog.title = "Committing to flash"
    GUI.invoke_later(progress_dialog.open)
    self._write("Committing file to flash...")
    def log_cb(msg, **kwargs): self._write(msg.text)
    self.link.add_callback(log_cb, SBP_MSG_LOG)
    code = shell_command(self.link, "upgrade_tool upgrade.image_set.bin", 240)
    self.link.remove_callback(log_cb, SBP_MSG_LOG)
    progress_dialog.close()

    if code != 0:
      self._write('Failed to perform upgrade (code = %d)' % code)
      return
    self._write('Resetting Piksi...')
    self.link(MsgReset(flags=0))
Exemplo n.º 12
0
 def manage_nap_firmware_update(self, check_version=False):
   # Flash NAP if out of date.
   try:
     local_nap_version = parse_version(
         self.settings['system_info']['nap_version'].value)
     remote_nap_version = parse_version(self.newest_nap_vers)
     nap_out_of_date = local_nap_version != remote_nap_version
   except KeyError:
     nap_out_of_date = True
   if nap_out_of_date or check_version==False:
     text = "Updating NAP"
     self._write(text)
     self.create_flash("M25")
     nap_n_ops = self.pk_flash.ihx_n_ops(self.nap_fw.ihx)
     progress_dialog = PulsableProgressDialog(nap_n_ops, True)
     progress_dialog.title = text
     GUI.invoke_later(progress_dialog.open)
     self.pk_flash.write_ihx(self.nap_fw.ihx, self.stream, mod_print=0x40, \
                             elapsed_ops_cb = progress_dialog.progress)
     self.stop_flash()
     self._write("")
     progress_dialog.close()
     return True
   else:
     text = "NAP is already to latest version, not updating!"
     self._write(text)
     self._write("")
     return False
    def process(self):
        for job in self.jobs:
            job.percent_complete = min(
                job.percent_complete + random.randint(0, 3), 100)

        if any(job.percent_complete < 100 for job in self.jobs):
            GUI.invoke_after(100, self.process)
Exemplo n.º 14
0
def test_coreg_gui():
    """Test CoregFrame."""
    _check_ci()
    home_dir = _TempDir()
    os.environ['_MNE_GUI_TESTING_MODE'] = 'true'
    os.environ['_MNE_FAKE_HOME_DIR'] = home_dir
    try:
        assert_raises(ValueError, mne.gui.coregistration, subject='Elvis',
                      subjects_dir=subjects_dir)

        from pyface.api import GUI
        gui = GUI()

        # avoid modal dialog if SUBJECTS_DIR is set to a directory that
        # does not contain valid subjects
        ui, frame = mne.gui.coregistration(subjects_dir='')

        frame.model.mri.subjects_dir = subjects_dir
        frame.model.mri.subject = 'sample'

        assert_false(frame.model.mri.fid_ok)
        frame.model.mri.lpa = [[-0.06, 0, 0]]
        frame.model.mri.nasion = [[0, 0.05, 0]]
        frame.model.mri.rpa = [[0.08, 0, 0]]
        assert_true(frame.model.mri.fid_ok)
        frame.raw_src.file = raw_path

        # grow hair (high-res head has no norms)
        assert_true(frame.model.mri.use_high_res_head)
        frame.model.mri.use_high_res_head = False
        frame.model.grow_hair = 40.

        # scale
        frame.coreg_panel.n_scale_params = 3
        frame.coreg_panel.scale_x_inc = True
        assert_equal(frame.model.scale_x, 1.01)
        frame.coreg_panel.scale_y_dec = True
        assert_equal(frame.model.scale_y, 0.99)

        # reset parameters
        frame.coreg_panel.reset_params = True
        assert_equal(frame.model.grow_hair, 0)
        assert_false(frame.model.mri.use_high_res_head)

        # configuration persistence
        assert_true(frame.model.prepare_bem_model)
        frame.model.prepare_bem_model = False
        frame.save_config(home_dir)
        ui.dispose()
        gui.process_events()

        ui, frame = mne.gui.coregistration(subjects_dir=subjects_dir)
        assert_false(frame.model.prepare_bem_model)
        assert_false(frame.model.mri.use_high_res_head)
        ui.dispose()
        gui.process_events()
    finally:
        del os.environ['_MNE_GUI_TESTING_MODE']
        del os.environ['_MNE_FAKE_HOME_DIR']
Exemplo n.º 15
0
    def _append_log(self, msg, endline="\n"):
        def toappend():
            if self._progress_started:
                self._progress_logs += msg + endline
            else:
                self._logs += msg + endline

        GUI.invoke_later(toappend)  # to be thread safe when logs are displayed in gui
Exemplo n.º 16
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()
Exemplo n.º 17
0
 def _wrap_update():
     update_funcs = self._update_funcs.copy()
     self._update_funcs.clear()
     for update in update_funcs.values():
         update_func, args = update
         update_func(*args)
     if self._update_funcs:
         GUI.invoke_later(_wrap_update)
Exemplo n.º 18
0
def close():
    """Close the scene."""
    f = mlab.gcf()
    e = mlab.get_engine()
    e.window.workbench.prompt_on_exit = False
    e.window.close()
    mlab.options.backend = 'auto'
    # Hack: on Linux the splash screen does not go away so we force it.
    GUI.invoke_after(500, e.window.workbench.application.gui.stop_event_loop)
Exemplo n.º 19
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"
Exemplo n.º 20
0
 def set_view(self, s):
     """Sets the view correctly."""
     #s.scene.reset_zoom()
     s.scene.z_plus_view()
     c = s.scene.camera
     c.azimuth(30)
     c.elevation(30)
     s.render()
     GUI.process_events()
Exemplo n.º 21
0
def lock_orientation(obj, name, old, new):
##    print 'locking o'
    if orientation_flag[obj]:
        orientation_flag[obj] = False
        return
    def icb():
        orientation_flag[obj] = True
        obj.orientation = np.array(old)
    GUI.invoke_later(icb)
Exemplo n.º 22
0
 def run(self):
     step = 0
     while (self.running):
         self.interface.datamodel.Update()
         step += 1
         if step>=self.interface.steps:
             step=0
             GUI.invoke_later(self.interface.callback)
     GUI.invoke_later(self.interface.redraw_scene)
Exemplo n.º 23
0
def lock_scale(obj, name, old, new):
##    print 'locking s'
    if scale_flag[obj]:
        scale_flag[obj] = False
        return
##    if np.all(new==1): return
    def icb():
        scale_flag[obj] = True
        obj.scale = np.array(old)
    GUI.invoke_later(icb)
Exemplo n.º 24
0
    def close(self):
        """ Close the dialog. """

        self._closing = True

        # We don't call our superclass' 'close' method immediately as there
        # may be one final call to '_pulse_and_reschedule' already on the
        # event queue. This makes sure that we call 'close' *after* that final
        # update.
        GUI.invoke_after(self.delay, super(PulseProgressDialog, self).close)
Exemplo n.º 25
0
  def _run(self):
    GUI.invoke_later(self.edit_traits, self.view)
    while not self.handler_executed:
      sleep(0.1)

    if self.execute_callback:
      GUI.invoke_later(self.callback)

    if not self.closed:
      self.close = 1
Exemplo n.º 26
0
def main():
    # Create the GUI.
    gui = GUI()

    # Create and open the main window.
    window = MainWindow()
    window.open()

    # Start the GUI event loop!
    gui.start_event_loop()
Exemplo n.º 27
0
def lock_position(obj, name, old, new):
##    print 'locking p'
    if position_flag[obj]:
        position_flag[obj] = False
        return
##    if np.all(new==0): return
    def icb():
        position_flag[obj] = True
        """crash seems to originate here? lost as to why"""
        obj.position = np.array(old)
##        obj.position = 0,0,0
    GUI.invoke_later(icb)
Exemplo n.º 28
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()
Exemplo n.º 29
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
Exemplo n.º 30
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 pyface.timer.api import do_later
             from pyface.api import GUI
             GUI.invoke_later(self.window.status_bar_manager.set, message = '')
         
     else:
         self.dname = self.dname.replace(' [Loaded]', '')
Exemplo n.º 31
0
    def spectrum_analyzer_state_callback(self, sbp_msg, **metadata):
        '''
        Params
        ======
        sbp_msg: sbp.msg.SBP object

        Updates the view's data for use in self.update_plot
        '''
        self.fftmonitor.capture_fft(sbp_msg, **metadata)
        channel = int(self.which_plot[-1:])
        if self.fftmonitor.num_ffts(channel) > 0:
            most_recent_fft = self.fftmonitor.get_ffts(channel).pop()
            self.fftmonitor.clear_ffts()
            self.most_recent_complete_data['frequencies'] = most_recent_fft[
                'frequencies']
            self.most_recent_complete_data['amplitudes'] = most_recent_fft[
                'amplitudes']
            GUI.invoke_later(self.update_plot)
Exemplo n.º 32
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.
    task1 = ExampleTask()
    task2 = SecondTask()
    window = TaskWindow(size=(800, 600))
    window.add_task(task1)
    window.add_task(task2)

    # Show the window.
    window.open()

    # Start the GUI event loop.
    gui.start_event_loop()
Exemplo n.º 33
0
 def force_draw(self):
     r"""
     Method for forcing the current figure to render. This is useful for
     the widgets animation.
     """
     from pyface.api import GUI
     _gui = GUI()
     orig_val = _gui.busy
     _gui.set_busy(busy=True)
     _gui.set_busy(busy=orig_val)
     _gui.process_events()
Exemplo n.º 34
0
 def manage_stm_firmware_update(self):
     # Erase all of STM's flash (other than bootloader) if box is checked.
     if self.erase_stm:
         text = "Erasing STM"
         self._write(text)
         self.create_flash("STM")
         sectors_to_erase = set(range(self.pk_flash.n_sectors)).difference(
             set(self.pk_flash.restricted_sectors))
         progress_dialog = PulsableProgressDialog(len(sectors_to_erase),
                                                  False)
         progress_dialog.title = text
         GUI.invoke_later(progress_dialog.open)
         erase_count = 0
         for s in sorted(sectors_to_erase):
             progress_dialog.progress(erase_count)
             self._write('Erasing %s sector %d' %
                         (self.pk_flash.flash_type, s))
             self.pk_flash.erase_sector(s)
             erase_count += 1
         self.stop_flash()
         self._write("")
         try:
             progress_dialog.close()
         except AttributeError:
             pass
     # Flash STM.
     text = "Updating STM"
     self._write(text)
     self.create_flash("STM")
     stm_n_ops = self.pk_flash.ihx_n_ops(self.stm_fw.ihx, \
                                         erase = not self.erase_stm)
     progress_dialog = PulsableProgressDialog(stm_n_ops, True)
     progress_dialog.title = text
     GUI.invoke_later(progress_dialog.open)
     # Don't erase sectors if we've already done so above.
     self.pk_flash.write_ihx(self.stm_fw.ihx, self.stream, mod_print=0x40, \
                             elapsed_ops_cb = progress_dialog.progress, \
                             erase = not self.erase_stm)
     self.stop_flash()
     self._write("")
     try:
         progress_dialog.close()
     except AttributeError:
         pass
Exemplo n.º 35
0
def _take_3d_screenshot(figure, mode='rgb', filename=None):
    from mayavi import mlab
    from mne.viz.backends.renderer import MNE_3D_BACKEND_TESTING
    if MNE_3D_BACKEND_TESTING:
        ndim = 3 if mode == 'rgb' else 4
        if figure.scene is None:
            figure_size = (600, 600)
        else:
            figure_size = figure.scene._renwin.size
        return np.zeros(tuple(figure_size) + (ndim,), np.uint8)
    else:
        from pyface.api import GUI
        gui = GUI()
        gui.process_events()
        with warnings.catch_warnings(record=True):  # traits
            img = mlab.screenshot(figure, mode=mode)
        if isinstance(filename, str):
            _save_figure(img, filename)
        return img
Exemplo n.º 36
0
    def manage_multi_firmware_update(self):
        # Set up progress dialog and transfer file to Piksi using SBP FileIO
        progress_dialog = PulsableProgressDialog(len(self.stm_fw.blob))
        progress_dialog.title = "Transferring image file"
        GUI.invoke_later(progress_dialog.open)
        self._write("Transferring image file...")
        try:
            FileIO(self.link).write("upgrade.image_set.bin",
                                    self.stm_fw.blob,
                                    progress_cb=progress_dialog.progress)
        except Exception as e:
            self._write("Failed to transfer image file to Piksi: %s\n" % e)
            progress_dialog.close()
            return
        try:
            progress_dialog.close()
        except AttributeError:
            pass

        # Setup up pulsed progress dialog and commit to flash
        progress_dialog = PulsableProgressDialog(100, True)
        progress_dialog.title = "Committing to flash"
        GUI.invoke_later(progress_dialog.open)
        self._write("Committing file to flash...")

        def log_cb(msg, **kwargs):
            self._write(msg.text)

        self.link.add_callback(log_cb, SBP_MSG_LOG)
        code = shell_command(self.link,
                             "upgrade_tool upgrade.image_set.bin",
                             600,
                             progress_cb=progress_dialog.progress)
        self.link.remove_callback(log_cb, SBP_MSG_LOG)
        progress_dialog.close()

        if code != 0:
            self._write('Failed to perform upgrade (code = %d)' % code)
            if code == -255:
                self._write('Shell command timed out.  Please try again.')
            return
        self._write('Resetting Piksi...')
        self.link(MsgReset(flags=0))
    def test7(self):
        s = tvtk.STLReader(file_name="E:/mesh.stl")  # 调用stl文件
        m = tvtk.PolyDataMapper(input_connection=s.output_port)
        a = tvtk.Actor(mapper=m)

        # win=ivtk.IVTKWithCrust()
        # win=ivtk.IVTK()
        win = ivtk.IVTKWithCrustAndBrowser()
        win.open()
        win.scene.add_actor(a)
        win.scene.isometric_view()

        dialog = win.control.centralWidget().widget(0).widget(0)
        from pyface.qt import QtCore
        dialog.setWindowFlags(QtCore.Qt.WindowFlags(0x00000000))
        dialog.show()

        gui = GUI()
        gui.start_event_loop()
Exemplo n.º 38
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
Exemplo n.º 39
0
 def settings_display_setup(self, do_read_finished=True):
     self.settings_list = []
     sections = sorted(self.settings.keys())
     for sec in sections:
         this_section = []
         for name, setting in sorted(self.settings[sec].iteritems(),
                                     key=lambda (n, s): s.ordering):
             if not setting.expert or (self.expert and setting.expert):
                 this_section.append(setting)
         if this_section:
             self.settings_list.append(SectionHeading(sec))
             self.settings_list += this_section
     # call read_finished_functions as needed
     if do_read_finished:
         for cb in self.read_finished_functions:
             if self.gui_mode:
                 GUI.invoke_later(cb)
             else:
                 cb()
Exemplo n.º 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 = 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
Exemplo n.º 41
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()
Exemplo n.º 42
0
def require_gui(func):
    """ Decorator for tests that require a non-null GUI toolkit.
    """
    # Defer GUI import side-effect.
    # The toolkit is not resolved until we import pyface.api
    from pyface.api import GUI
    try:
        GUI()
    except NotImplementedError:
        return unittest.skip("No GUI available.")(func)
    return func
Exemplo n.º 43
0
    def progress(self, count):
        """
        Update progress of progress bar. If pulsing initially, wait until count
        is at least 12 before changing to discrete progress bar.

        Parameters
        ----------
        count : int
          Current value of progress.
        """
        # Provide user feedback initially via pulse for slow sector erases.
        if self.pulsed:
            if count > 12:
                self.max = 100
                GUI.invoke_later(self.update,
                                 int(100 * float(count) / self.passed_max))
        else:
            self.max = 100
            GUI.invoke_later(self.update,
                             int(100 * float(count) / self.passed_max))
Exemplo n.º 44
0
    def schedule_update(self, ident, update_func, *args):
        '''Schedule a GUI update'''
        def _wrap_update():
            self._lock.acquire()
            update_funcs = self._update_funcs.copy()
            self._update_funcs.clear()
            self._lock.release()
            for update in update_funcs.values():
                update_func, args = update
                update_func(*args)
            if self._update_funcs:
                GUI.invoke_later(_wrap_update)

        self._lock.acquire()
        if self._update_funcs:
            self._update_funcs[ident] = (update_func, args)
        else:
            self._update_funcs[ident] = (update_func, args)
            GUI.invoke_later(_wrap_update)
        self._lock.release()
Exemplo n.º 45
0
    def test_event_processed_prior_to_resolving_location(self):
        # Test GUI events are processed prior to resolving location
        gui = GUI()
        model = NumberHasTraits()
        gui.set_trait_later(model, "number", 2)

        def solver(wrapper, location):
            return model.number

        wrapper = example_ui_wrapper(
            registries=[
                StubRegistry(
                    solver=solver,
                    supported_locator_classes=[float],
                )
            ],
        )

        new_wrapper = wrapper.locate(4.567)
        self.assertEqual(new_wrapper._target, 2)
Exemplo n.º 46
0
    def run(self):
        while True:
            frame = self.queue.get()  # blocks until a frame is available
            if self.abort_flag:
                break
            if self.queue.qsize() > 2:
                continue  # drop frame if there is a backlog

            # Do any transformations on the frame
            for plugin in self.controller.transform_plugins:
                frame = plugin.process_frame(frame)

            # Display the frame on screen
            GUI.set_trait_later(self.controller.screen, 'data', frame)

            # Send the frame to the analysis components
            for plugin in self.controller.display_plugins:
                plugin.process_frame(frame)

            time.sleep(1.0 / self.update_frequency)
Exemplo n.º 47
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
    def create_control(self, parent):
        """ Creates the toolkit-specific control that represents the view. """

        self.shell = IPythonWidget(parent,
                                   banner='\n'.join(self._banner),
                                   interp=self.interpreter)

        # Namespace contributions.
        for bindings in self._bindings:
            for name, value in bindings.items():
                self.bind(name, value)

        for command in self._commands:
            try:
                self.execute_command(command)
            except Exception as e:
                logger.exception(
                    "The command '%s' supplied to the Ipython shell "
                    "plugin has raised an exception:\n%s" %
                    (command, traceback.format_exc()))

        # Register the view as a service.
        self.window.application.register_service(IPythonShell, self)

        ns_view = self.window.application.get_service(INamespaceView)
        if ns_view is not None:
            self.on_trait_change(ns_view._on_names_changed, 'names')

        def try_set_focus():
            try:
                self.shell.control.SetFocus()
            except:
                # The window may not have been created yet.
                pass

        def set_focus():
            self.window.application.gui.invoke_later(try_set_focus)

        GUI.invoke_later(set_focus)

        return self.shell.control
Exemplo n.º 49
0
 def test_tree_editor_with_nested_ui(self):
     tree_editor = TreeEditor(
         nodes=[
             TreeNode(
                 node_for=[Bogus],
                 auto_open=True,
                 children="bogus_list",
                 label="bogus",
                 view=View(Item("name")),
             ),
         ],
         hide_root=True,
     )
     bogus_list = [Bogus()]
     object_view = BogusTreeView(bogus=Bogus(bogus_list=bogus_list))
     view = View(Item("bogus", id="tree", editor=tree_editor))
     with reraise_exceptions(), \
             create_ui(object_view, dict(view=view)) as ui:
         editor = ui.info.tree
         editor.selected = bogus_list[0]
         GUI.process_events()
Exemplo n.º 50
0
  def tracking_state_callback(self, data):
    n_channels = len(data) / TRACKING_STATE_BYTES_PER_CHANNEL

    if n_channels != self.n_channels:
      # Update number of channels
      self.n_channels = n_channels
      self.states = [TrackingState(0, 0, 0) for _ in range(n_channels)]
      for pl in self.plot.plots.iterkeys():
        self.plot.delplot(pl.name)
      self.plots = []
      for n in range(n_channels):
        self.plot_data.set_data('ch'+str(n), [0.0])
        pl = self.plot.plot(('t', 'ch'+str(n)), type='line', color='auto', name='ch'+str(n))
        self.plots.append(pl)
      print 'Number of tracking channels changed to', n_channels

    fmt = '<' + n_channels * 'BBf'
    state_data = struct.unpack(fmt, data)
    for n, s in enumerate(self.states):
      s.update(*state_data[3*n:3*(n+1)])
    GUI.invoke_later(self.update_plot)
Exemplo n.º 51
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)
Exemplo n.º 52
0
    def step10(self):
        theoretical  = np.genfromtxt(f"{TestDataPath}/PyMieScattQscaCoreShellMedium.csv", delimiter=',')

        Diameter     = np.geomspace(10e-9, 500e-9, 400)
        scatSet      = CoreShellSet(CoreDiameter = Diameter, ShellDiameter = 600e-9, CoreIndex = 1.4, ShellIndex=1.5, nMedium = 1.2)
        sourceSet    = SourceSet(Wavelength = 600e-9, Polarization = [None], Amplitude = 1)
        ExpSet       = Setup(ScattererSet = scatSet, SourceSet = sourceSet, DetectorSet  = None)
        Data         = ExpSet.Get(Measure.Qsca).Data.squeeze()

        GUI.invoke_after(PLOTTIME, Close)
        plt.figure()
        plt.plot(Diameter, Data,'C1-', linewidth=3, label='PyMieSim' )

        plt.plot( Diameter, theoretical,'k--', linewidth=1, label='PyMieScatt')

        plt.xlabel(r'Diameter [\mu m]'); plt.ylabel('Scattering efficiency [CoreShell + nMedium]')
        plt.grid(); plt.legend(); plt.tight_layout()
        plt.show()

        if not np.all(np.isclose(Data,theoretical, 1e-9)):
            raise
Exemplo n.º 53
0
    def demo_main(cls, **traits):
        """ Create the demo application and start the mainloop, if needed

        This should be called with appropriate arguments which will be passed
        to the class' constructor.

        """
        # get the Pyface GUI
        gui = GUI()

        # create the application's main window
        window = cls(**traits)
        window.open()

        # start the application
        # if there isn't already a running mainloop, this will block
        gui.start_event_loop()

        # if there is already a running mainloop (eg. in an IPython session),
        # return a reference to the window so that our caller can hold on to it
        return window
Exemplo n.º 54
0
    def test_locate_event_processed_optional(self):
        # Allow event processing to be switched off.
        gui = GUI()
        side_effect = mock.Mock()
        gui.invoke_later(side_effect)
        self.addCleanup(process_cascade_events)

        def solver(wrapper, location):
            return 1

        wrapper = example_ui_wrapper(
            registries=[StubRegistry(solver=solver)],
            auto_process_events=False,
        )

        # With auto_process_events set to False, events are not automatically
        # processed.
        new_wrapper = wrapper.locate(None)

        self.assertEqual(side_effect.call_count, 0)
        self.assertFalse(new_wrapper._auto_process_events)
Exemplo n.º 55
0
def run_mlab_examples():
    from mayavi import mlab
    from mayavi.tools.animator import Animator

    ############################################################
    # run all the "test_foobar" functions in the mlab module.
    for name, func in getmembers(mlab):
        if not callable(func) or not name[:4] in ('test', 'Test'):
            continue

        if sys.platform == 'win32' and name == 'test_mesh_mask_custom_colors':
            # fixme: This test does not seem to work on win32, disabling for now.
            continue

        mlab.clf()
        GUI.process_events()
        obj = func()

        if isinstance(obj, Animator):
            obj.delay = 10
            # Close the animation window.
            obj.close()
            while is_timer_running(obj.timer):
                GUI.process_events()
                sleep(0.05)

        # Mayavi has become too fast: the operator cannot see if the
        # Test function was succesful.
        GUI.process_events()
        sleep(0.1)
Exemplo n.º 56
0
    def test_error_from_gui_captured_and_raise(self):
        def raise_error_1():
            raise ZeroDivisionError()

        def raise_error_2():
            raise IndexError()

        # without the context manager:
        #   - with Qt5, the test run will be aborted prematurely.
        #   - with Qt4, the traceback is printed and the test passes.
        #   - with Wx, the traceback is printed and the test passes.
        # With the context manager, the exception is always reraised.
        gui = GUI()
        with self.assertRaises(RuntimeError) as exception_context, \
                self.assertLogs("traitsui") as watcher:
            with reraise_exceptions():
                gui.invoke_later(raise_error_1)
                gui.invoke_later(raise_error_2)
                gui.process_events()

        error_msg = str(exception_context.exception)
        self.assertIn("ZeroDivisionError", error_msg)
        self.assertIn("IndexError", error_msg)
        log_content1, log_content2 = watcher.output
        self.assertIn("ZeroDivisionError", log_content1)
        self.assertIn("IndexError", log_content2)
Exemplo n.º 57
0
    def test_dispose_inner_ui(self):
        obj = DummyObject()
        view = View(
            Group(
                Item(
                    "number",
                    editor=BasicEditorFactory(klass=EditorWithCustomWidget),
                ), ), )
        ui = obj.edit_traits(view=view)
        editor, = ui.get_editors("number")

        gui = GUI()
        with ensure_destroyed(ui):
            # This represents an event handler that causes a nested UI to be
            # disposed.
            gui.invoke_later(editor.dispose_inner_ui)

            # Allowing GUI to process the disposal requests is crucial.
            # This requirement should be satisfied in production setting
            # where the dispose method is part of an event handler.
            # Not doing so before disposing the main UI would be a programming
            # error in tests settings.
            with reraise_exceptions():
                process_cascade_events()

            gui.invoke_later(close_control, ui.control)
            with reraise_exceptions():
                process_cascade_events()

            self.assertIsNone(ui.control)
Exemplo n.º 58
0
class SimpleApplication(HasStrictTraits):
    """
    Simple application that attempts to set a trait at start time,
    and immediately exits in response to that trait.
    """
    # The GUI instance underlying this app.
    gui = Instance(IGUI)

    # Event fired after the event loop starts.
    application_running = Event

    def __init__(self):
        super(HasStrictTraits, self).__init__()
        self.gui = GUI()

    def start(self):
        """
        Start the application.
        """
        # This shouldn't be executed until after the event loop is running.
        self.gui.set_trait_later(self, 'application_running', True)
        self.gui.start_event_loop()

    def stop(self):
        self.gui.stop_event_loop()
Exemplo n.º 59
0
 def tracking_state_callback(self, sbp_msg, **metadata):
   n_channels = len(sbp_msg.states)
   if n_channels != self.n_channels:
     # Update number of channels
     self.n_channels = n_channels
     self.states = [TrackingState(0, 0, 0, 0) for _ in range(n_channels)]
     for pl in self.plot.plots.iterkeys():
       self.plot.delplot(pl.name)
     self.plots = []
     for n in range(n_channels):
       self.plot_data.set_data('ch' + str(n), [0.0])
       pl = self.plot.plot(('t', 'ch' + str(n)), type='line', color='auto',
                           name='ch' + str(n))
       self.plots.append(pl)
     print 'Number of tracking channels changed to {0}'.format(n_channels)
   for n, k in enumerate(self.states):
     s = sbp_msg.states[n]
     prn = s.sid.sat
     if (s.sid.code == 0 or s.sid.code == 1):
       prn += 1
     k.update(s.state, prn, s.cn0, s.sid.code)
   GUI.invoke_later(self.update_plot)
Exemplo n.º 60
0
    def test_event_processed(self):
        # Test GUI events are processed such that the trait is changed.
        gui = GUI()
        model = NumberHasTraits()

        def handler(wrapper, action):
            gui.set_trait_later(model, "number", 2)

        wrapper = example_ui_wrapper(
            registries=[StubRegistry(handler=handler)], )

        with self.assertTraitChanges(model, "number"):
            wrapper.perform(None)