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 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.'
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)
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))
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)
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()
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 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
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)
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)
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
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)
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)
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
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)
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)
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]', '')
def settings_read_by_index_callback(self, data): if not data: self.settings_list = [] sections = sorted(self.settings.keys()) for sec in sections: self.settings_list.append(SectionHeading(sec)) for name, setting in sorted(self.settings[sec].iteritems(), key=lambda (n, s): s.ordering): self.settings_list.append(setting) for cb in self.read_finished_functions: if self.gui_mode: GUI.invoke_later(cb) else: cb() return section, setting, value, format_type = data[2:].split('\0')[:4] self.ordering_counter += 1 if format_type == '': format_type = None else: setting_type, setting_format = format_type.split(':') if not self.settings.has_key(section): self.settings[section] = {} if format_type is None: # Plain old setting, no format information self.settings[section][setting] = Setting(setting, section, value, ordering=self.ordering_counter, settings=self ) else: if setting_type == 'enum': enum_values = setting_format.split(',') self.settings[section][setting] = EnumSetting(setting, section, value, ordering=self.ordering_counter, values=enum_values, settings=self ) else: # Unknown type, just treat is as a string self.settings[section][setting] = Setting(setting, section, value, settings=self ) self.enumindex += 1 self.link.send_message(ids.SETTINGS_READ_BY_INDEX, u16_to_str(self.enumindex))
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 ''' # Need to figure out which user_msg_tag means it's an FFT message # for now assume that all SBP_MSG_USER_DATA is relevant fft = MsgSpecan(sbp_msg) frequencies = self.get_frequencies(fft.freq_ref, fft.freq_step, len(fft.amplitude_value)) amplitudes = self.get_amplitudes( fft.amplitude_ref, fft.amplitude_value, fft.amplitude_unit) tag = fft.channel_tag if (tag == 1 and self.which_plot != "Channel 1"): return if (tag == 2 and self.which_plot != "Channel 2"): return if (tag == 3 and self.which_plot != "Channel 3"): return if (tag == 4 and self.which_plot != "Channel 4"): return timestamp = GpsTime(fft.t.wn, fft.t.tow) if len(self.incomplete_data[timestamp]['frequencies']) + len( frequencies) == NUM_POINTS: self.most_recent_complete_data['frequencies'] = np.append( self.incomplete_data[timestamp]['frequencies'], frequencies, axis=0) self.most_recent_complete_data['amplitudes'] = np.append( self.incomplete_data[timestamp]['amplitudes'], amplitudes, axis=0) self.incomplete_data.pop(timestamp) if timestamp is None or timestamp > self.most_recent: self.most_recent = timestamp GUI.invoke_later(self.update_plot) else: self.incomplete_data[timestamp]['frequencies'] = np.append( self.incomplete_data[timestamp]['frequencies'], frequencies, axis=0) self.incomplete_data[timestamp]['amplitudes'] = np.append( self.incomplete_data[timestamp]['amplitudes'], amplitudes, axis=0)
def schedule_update(self, ident, update_func, *args): '''Schedule a GUI update''' 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) if not self._update_funcs: self._update_funcs[ident] = (update_func, args) GUI.invoke_later(_wrap_update) else: self._update_funcs[ident] = (update_func, args)
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
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
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
def test_create_ui_respect_auto_process_events_flag(self): tester = UITester(auto_process_events=False) order = Order() view = View(Item("_")) side_effect = mock.Mock() gui = GUI() gui.invoke_later(side_effect) # Make sure all pending events are processed at the end of the test. self.addCleanup(process_cascade_events) with tester.create_ui(order, dict(view=view)) as ui: pass # dispose is called. self.assertIsNone(ui.control) # But the GUI events are not processed. self.assertEqual(side_effect.call_count, 0)
def settings_read_by_index_callback(self, data): if not data: self.settings_list = [] sections = sorted(self.settings.keys()) for sec in sections: self.settings_list.append(SectionHeading(sec)) for name, setting in sorted(self.settings[sec].iteritems(), key=lambda (n, s): s.ordering): self.settings_list.append(setting) for cb in self.read_finished_functions: GUI.invoke_later(cb) return section, setting, value, format_type = data[2:].split('\0')[:4] self.ordering_counter += 1 if format_type == '': format_type = None else: setting_type, setting_format = format_type.split(':') if not self.settings.has_key(section): self.settings[section] = {} if format_type is None: # Plain old setting, no format information self.settings[section][setting] = Setting(setting, section, value, link=self.link, ordering=self.ordering_counter ) else: if setting_type == 'enum': enum_values = setting_format.split(',') self.settings[section][setting] = EnumSetting(setting, section, value, link=self.link, ordering=self.ordering_counter, values=enum_values) else: # Unknown type, just treat is as a string self.settings[section][setting] = Setting(setting, section, value, link=self.link) self.enumindex += 1 self.link.send_message(ids.SETTINGS_READ_BY_INDEX, u16_to_str(self.enumindex))
def settings_display_setup(self): 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 (self.hide_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 for cb in self.read_finished_functions: if self.gui_mode: GUI.invoke_later(cb) else: cb()
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)
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))
def main(): #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 if exec_script is not None: from pyface.api import GUI gui=GUI() gui.invoke_later(lambda:script(exec_script,scriptdir=sys.argv[1])) g.configure_traits()
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) 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 k.update(s.state, prn, s.cn0) GUI.invoke_later(self.update_plot)
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 _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
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(iter(list(self.settings[sec].items())), key=lambda n_s: n_s[1].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()
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)
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
def tracking_state_callback(self, sbp_msg, **metadata): channel_size = TRACKING_STATE_BYTES_PER_CHANNEL if sbp_msg.msg_type is SBP_MSG_TRACKING_STATE else TRACKING_STATE_BYTES_PER_CHANNEL_DEP_A n_channels = len(sbp_msg.payload) / channel_size 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 {0}'.format(n_channels) fmt = '<' + n_channels * ('BIf' if sbp_msg.msg_type is SBP_MSG_TRACKING_STATE else 'BBf') state_data = struct.unpack(fmt, sbp_msg.payload) for n, s in enumerate(self.states): s.update(*state_data[3*n:3*(n+1)]) GUI.invoke_later(self.update_plot)
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)
def open_in_gui_thread(self, timeout_secs=5): """ Open dialog in gui thread and wait to return until open up to timeout_sec seconds The superclass open method sets the _start_time variable which is used as a signal for whether open has occured. Parameters ---------- timeouts_secs : int Number of seconds to wait for widget to initialize. Returns ---------- True if widget was opened (i.e _start_time var exists) False if otherwise """ GUI.invoke_later(self.open) counter = 0 while(getattr(self, '_start_time', -1) == -1 and counter < timeout_secs * 2): sleep(0.5) counter += 1 return getattr(self, '_start_time', -1) != -1
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)
def setup(self): try: mlab.figure(bgcolor=(.34, .34, .34), figure=self.scene.mayavi_scene) except Exception as e: print str(e) return self.surfs_gen() self.nodes_gen() from pyface.api import GUI gui = GUI() gui.invoke_later(self.zaxis_view) #If only the parcellation is loaded, the adj will be supplied later if self.ds.adj is not None: self.supply_adj() #if adj exists (on init) we are the last thing to initialize, #so we should call display_all at the end. if not, we delegate #that responsibility to somewhere where it makes more modular sense self.ds.display_all()
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 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 _result_consumer(self, delayed_result): """ The delayed result consumer. """ GUI.invoke_later(self._close_progress_dialog) try: result = delayed_result.get() GUI.invoke_later(self.on_success, result) except Exception, exc: GUI.invoke_later(self.on_failure, exc)
def solution_draw(self): if self.running: GUI.invoke_later(self._solution_draw)
def manage_firmware_updates(self): """ Update Piksi firmware. Erase entire STM flash (other than bootloader) if so directed. Flash NAP only if new firmware is available. """ self.updating = True self._write('') # 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("") progress_dialog.close() # 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("") progress_dialog.close() # 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: 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() # Must tell Piksi to jump to application after updating firmware. self.link.send(SBP_MSG_BOOTLOADER_JUMP_TO_APP, '\x00') self._write("Firmware updates finished.") self._write("") self.updating = False
class ModalDialogTester(object): """ Test helper for code that open a traits ui or QDialog window. Usage ----- :: # Common usage calling a `function` that will open a dialog and then # accept the dialog info. tester = ModalDialogTester(function) tester.open_and_run(when_opened=lambda x: x.close(accept=True)) self.assertEqual(tester.result, <expected>) # Even if the dialog was not opened upon calling `function`, # `result` is assigned and the test may not fail. # To test if the dialog was once opened: self.assertTrue(tester.dialog_was_opened) .. note:: - Proper operation assumes that at all times the dialog is a modal window. - Errors and failures during the when_opened call do not register with the unittest testcases because they take place on a deferred call in the event loop. It is advised that the `capture_error` context manager is used from the GuiTestAssistant when necessary. """ def __init__(self, function): #: The command to call that will cause a dialog to open. self.function = function self._assigned = False self._result = Undefined self._qt_app = QtGui.QApplication.instance() self._gui = GUI() self._event_loop_error = [] self._helper = EventLoopHelper(qt_app=self._qt_app, gui=self._gui) self._dialog_widget = None self.dialog_was_opened = False @property def result(self): """ The return value of the provided function. """ return self._result @result.setter def result(self, value): """ Setter methods for the result attribute. """ self._assigned = True self._result = value def open_and_run(self, when_opened, *args, **kwargs): """ Execute the function to open the dialog and run ``when_opened``. Parameters ---------- when_opened : callable A callable to be called when the dialog has been created and opened. The callable with be called with the tester instance as argument. *args, **kwargs : Additional arguments to be passed to the `function` attribute of the tester. Raises ------ AssertionError if an assertion error was captured during the deferred calls that open and close the dialog. RuntimeError if a result value has not been assigned within 15 seconds after calling `self.function` Any other exception that was captured during the deferred calls that open and close the dialog. .. note:: This method is synchronous """ condition_timer = QtCore.QTimer() def handler(): """ Run the when_opened as soon as the dialog has opened. """ if self.dialog_opened(): self._gui.invoke_later(when_opened, self) self.dialog_was_opened = True else: condition_timer.start() # Setup and start the timer to fire the handler every 100 msec. condition_timer.setInterval(100) condition_timer.setSingleShot(True) condition_timer.timeout.connect(handler) condition_timer.start() self._assigned = False try: # open the dialog on a deferred call. self._gui.invoke_later(self.open, *args, **kwargs) # wait in the event loop until timeout or a return value assigned. self._helper.event_loop_until_condition( condition=self.value_assigned, timeout=15) finally: condition_timer.stop() condition_timer.timeout.disconnect(handler) self._helper.event_loop() self.assert_no_errors_collected() def open_and_wait(self, when_opened, *args, **kwargs): """ Execute the function to open the dialog and wait to be closed. Parameters ---------- when_opened : callable A callable to be called when the dialog has been created and opened. The callable with be called with the tester instance as argument. *args, **kwargs : Additional arguments to be passed to the `function` attribute of the tester. Raises ------ AssertionError if an assertion error was captured during the deferred calls that open and close the dialog. RuntimeError if the dialog has not been closed within 15 seconds after calling `self.function`. Any other exception that was captured during the deferred calls that open and close the dialog. .. note:: This method is synchronous """ condition_timer = QtCore.QTimer() def handler(): """ Run the when_opened as soon as the dialog has opened. """ if self.dialog_opened(): self._dialog_widget = self.get_dialog_widget() self._gui.invoke_later(when_opened, self) self.dialog_was_opened = True else: condition_timer.start() def condition(): if self._dialog_widget is None: return False else: value = (self.get_dialog_widget() != self._dialog_widget) if value: # process any pending events so that we have a clean # event loop before we exit. self._helper.event_loop() return value # Setup and start the timer to signal the handler every 100 msec. condition_timer.setInterval(100) condition_timer.setSingleShot(True) condition_timer.timeout.connect(handler) condition_timer.start() self._assigned = False try: # open the dialog on a deferred call. self._gui.invoke_later(self.open, *args, **kwargs) # wait in the event loop until timeout or a return value assigned. self._helper.event_loop_until_condition( condition=condition, timeout=15) finally: condition_timer.stop() condition_timer.timeout.disconnect(handler) self._dialog_widget = None self._helper.event_loop() self.assert_no_errors_collected() def open(self, *args, **kwargs): """ Execute the function that will cause a dialog to be opened. Parameters ---------- *args, **kwargs : Arguments to be passed to the `function` attribute of the tester. .. note:: This method is synchronous """ with self.capture_error(): self.result = self.function(*args, **kwargs) def close(self, accept=False): """ Close the dialog by accepting or rejecting. """ with self.capture_error(): widget = self.get_dialog_widget() if accept: self._gui.invoke_later(widget.accept) else: self._gui.invoke_later(widget.reject) @contextlib.contextmanager def capture_error(self): """ Capture exceptions, to be used while running inside an event loop. When errors and failures take place through an invoke later command they might not be caught by the unittest machinery. This context manager when used inside a deferred call, will capture the fact that an error has occurred and the user can later use the `check for errors` command which will raise an error or failure if necessary. """ try: yield except Exception: self._event_loop_error.append( (sys.exc_info()[0], traceback.format_exc()) ) def assert_no_errors_collected(self): """ Assert that the tester has not collected any errors. """ if len(self._event_loop_error) > 0: msg = 'The following error(s) were detected:\n\n{0}' tracebacks = [] for type_, message in self._event_loop_error: if isinstance(type_, AssertionError): msg = 'The following failure(s) were detected:\n\n{0}' tracebacks.append(message) raise type_(msg.format('\n\n'.join(tracebacks))) def click_widget(self, text, type_=QtGui.QPushButton): """ Execute click on the widget of `type_` with `text`. This strips '&' chars from the string, since usage varies from platform to platform. """ control = self.get_dialog_widget() def test(widget): # XXX asking for widget.text() causes occasional segfaults on Linux # and pyqt (both 4 and 5). Not sure why this is happening. # See issue #282 return widget.text().replace('&', '') == text widget = find_qt_widget( control, type_, test=test ) if widget is None: # this will only occur if there is some problem with the test raise RuntimeError("Could not find matching child widget.") widget.click() def click_button(self, button_id): text = BUTTON_TEXT[button_id] self.click_widget(text) def value_assigned(self): """ A value was assigned to the result attribute. """ result = self._assigned if result: # process any pending events so that we have a clean # even loop before we exit. self._helper.event_loop() return result def dialog_opened(self): """ Check that the dialog has opened. """ dialog = self.get_dialog_widget() if dialog is None: return False if hasattr(dialog, '_ui'): # This is a traitsui dialog, we need one more check. ui = dialog._ui return ui.info.initialized else: # This is a simple QDialog. return dialog.isVisible() def get_dialog_widget(self): """ Get a reference to the active modal QDialog widget. """ # It might make sense to also check for active window and active popup # window if this Tester is used for non-modal windows. return self._qt_app.activeModalWidget() def has_widget(self, text=None, type_=QtGui.QPushButton): """ Return true if there is a widget of `type_` with `text`. """ if text is None: test = None else: test = lambda qwidget: qwidget.text() == text return self.find_qt_widget(type_=type_, test=test) is not None def find_qt_widget(self, type_=QtGui.QPushButton, test=None): """ Return the widget of `type_` for which `test` returns true. """ if test is None: test = lambda x: True window = self.get_dialog_widget() return find_qt_widget(window, type_, test=test)
def finish_read(self): for cb in self.read_finished_functions: if self.gui_mode: GUI.invoke_later(cb) else: cb()
def finish_read(self): for cb in self.read_finished_functions: GUI.invoke_later(cb)
def register_temporal_sequence(vsfm_interface, nvm_model_fn, model, model_image_dir, image_files, radius = 2, max_sleep_seconds = 15): cams = [] new_cams = [] near_cams = [] sequence = [] def reset_model(): print "clearing workspace & reloading model" vsfm_interface.restart() vsfm_interface.sfm_clear_workspace() vsfm_interface.sfm_load_nview_match(nvm_model_fn) seq_positions = numpy.nan * numpy.ones((len(image_files), 3), dtype = numpy.float64) query_cam = None mlab.show() colors1 = numpy.linspace(0, 1, len(image_files)) colors2 = numpy.tile(numpy.linspace(0, 1, len(image_files)/2), 2) colors3 = numpy.tile(numpy.linspace(0, 1, len(image_files)/4), 4) while colors2.shape[0] < colors1.shape[0]: colors2 = numpy.hstack((colors2, 0)) while colors3.shape[0] < colors1.shape[0]: colors3 = numpy.hstack((colors3, 0)) colors = numpy.vstack((colors1, colors2, colors3)).T for (im_idx, imfn) in enumerate(image_files): imdir, imbasename, ext = util.fileparts(imfn) failed = False if len(near_cams) == 0: try: cams, new_cams = register_image(vsfm_interface, imfn, max_sleep_seconds = max_sleep_seconds) except VSFMCrashedError: reset_model() else: mfn = write_specified_match_file(imfn, near_cams, model_image_dir) try: cams, new_cams = register_image(vsfm_interface, imfn, match_specified_fn = mfn, max_sleep_seconds = max_sleep_seconds) except VSFMCrashedError: reset_model() if len(new_cams) == 0: print "OH NO, Didn't localize!!!" failed = True if len(near_cams) > 0: print "trying more image matching" for r in [radius * 2, radius * 4, radius * 1e100]: near_cams_2 = model.lookup_nearby_cameras(query_cam, radius = r) mfn = write_specified_match_file(imfn, near_cams_2, model_image_dir) try: cams, new_cams = register_image(vsfm_interface, imfn, match_specified_fn = mfn, rerun_sift = True, max_sleep_seconds = max_sleep_seconds) except VSFMCrashedError: reset_model() if len(new_cams) == 0: print "Matching with radius failed: {}".format(r) else: print "Matching success!" failed = False break else: print "already matched against all cams, localization will not work" if failed: reset_model() sequence.append(None) continue else: print "\nLocalized new cam! {}".format(new_cams[0].camera_position) GUI.invoke_later(mayaviu.plot_cameras, new_cams, color = tuple(colors[im_idx, :])) # os.kill(os.getpid(), signal.SIGUSR1) query_cam = new_cams[0] near_cams = model.lookup_nearby_cameras(query_cam, radius = radius) sequence.append(new_cams[0]) if new_cams[0] is not None: seq_positions[im_idx, :] = new_cams[0].camera_position # vsfm_interface.sfm_delete_selected_camera() vsfm_interface.sfm_delete_selected_camera() numpy.savez_compressed("cams_localized.npz", seq_positions) return sequence
def baseline_callback(self, sbp_msg, **metadata): soln = MsgBaselineNEDDepA(sbp_msg) table = [] soln.n = soln.n * 1e-3 soln.e = soln.e * 1e-3 soln.d = soln.d * 1e-3 soln.h_accuracy = soln.h_accuracy * 1e-3 soln.v_accuracy = soln.v_accuracy * 1e-3 dist = np.sqrt(soln.n**2 + soln.e**2 + soln.d**2) tow = soln.tow * 1e-3 if self.nsec is not None: tow += self.nsec * 1e-9 ((tloc, secloc), (tgps, secgps)) = log_time_strings(self.week, tow) if self.utc_time is not None: ((tutc, secutc)) = datetime_2_str(self.utc_time) if self.directory_name_b == '': filepath = time.strftime("baseline_log_%Y%m%d-%H%M%S.csv") else: filepath = os.path.join( self.directory_name_b, time.strftime("baseline_log_%Y%m%d-%H%M%S.csv")) if not self.logging_b: self.log_file = None if self.logging_b: if self.log_file is None: self.log_file = sopen(filepath, 'w') self.log_file.write( 'pc_time,gps_time,tow(sec),north(meters),east(meters),down(meters),h_accuracy(meters),v_accuracy(meters),' 'distance(meters),num_sats,flags,num_hypothesis\n') log_str_gps = '' if tgps != '' and secgps != 0: log_str_gps = "{0}:{1:06.6f}".format(tgps, float(secgps)) self.log_file.write( '%s,%s,%.3f,%.4f,%.4f,%.4f,%.4f,%.4f,%.4f,%d,%d,%d\n' % ("{0}:{1:06.6f}".format(tloc, float(secloc)), log_str_gps, tow, soln.n, soln.e, soln.d, soln.h_accuracy, soln.v_accuracy, dist, soln.n_sats, soln.flags, self.num_hyps)) self.log_file.flush() self.last_mode = get_mode(soln) if self.last_mode < 1: table.append(('GPS Week', EMPTY_STR)) table.append(('GPS TOW', EMPTY_STR)) table.append(('GPS Time', EMPTY_STR)) table.append(('UTC Time', EMPTY_STR)) table.append(('UTC Src', EMPTY_STR)) table.append(('N', EMPTY_STR)) table.append(('E', EMPTY_STR)) table.append(('D', EMPTY_STR)) table.append(('Horiz Acc', EMPTY_STR)) table.append(('Vert Acc', EMPTY_STR)) table.append(('Dist.', EMPTY_STR)) table.append(('Sats Used', EMPTY_STR)) table.append(('Flags', EMPTY_STR)) table.append(('Mode', EMPTY_STR)) table.append(('Heading', EMPTY_STR)) table.append(('Corr. Age [s]', EMPTY_STR)) else: self.last_btime_update = time.time() if self.week is not None: table.append(('GPS Week', str(self.week))) table.append(('GPS TOW', "{:.3f}".format(tow))) if self.week is not None: table.append(('GPS Time', "{0}:{1:06.3f}".format( tgps, float(secgps)))) if self.utc_time is not None: table.append(('UTC Time', "{0}:{1:06.3f}".format( tutc, float(secutc)))) table.append(('UTC Src', self.utc_source)) table.append(('N', soln.n)) table.append(('E', soln.e)) table.append(('D', soln.d)) table.append(('Horiz Acc', soln.h_accuracy)) table.append(('Vert Acc', soln.v_accuracy)) table.append(('Dist.', "{0:.3f}".format(dist))) table.append(('Sats Used', soln.n_sats)) table.append(('Flags', '0x%02x' % soln.flags)) table.append(('Mode', mode_dict[self.last_mode])) if self.heading is not None: table.append(('Heading', self.heading)) if self.age_corrections is not None: table.append(('Corr. Age [s]', self.age_corrections)) else: table.append(('Corr. Age [s]', EMPTY_STR)) self.table = table if self.last_mode != 0: self.last_soln = soln mode_string = mode_string_dict[self.last_mode] if mode_string not in self.pending_draw_modes: # if we don't already have a pending upate for that mode self.pending_draw_modes.append(mode_string) self.list_lock.acquire() self._update_sln_data_by_mode(soln, mode_string) self.list_lock.release() else: self.list_lock.acquire() self._append_empty_sln_data(soln) self.list_lock.release() if time.time() - self.last_plot_update_time > GUI_UPDATE_PERIOD: GUI.invoke_later(self._solution_draw)
def _pos_llh_callback(self, data): # 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.pos_llh_callback, data)
def run(self): # print 'STARTING THREAD' GUI.invoke_later(self.vs.update_pipeline, self.vot)
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)
def _on_names_changed(self, new): """ Dynamic trait change handler. """ if not self._refresh_tree_nodes_timer.IsRunning(): GUI.invoke_later(self._refresh_tree_nodes_timer.Start)