def _connect_rocon_master(self): rocon_master_name = str( self.rocon_masters[self.cur_selected_rocon_master].name) rocon_master_uri = str( self.rocon_masters[self.cur_selected_rocon_master].uri) rocon_master_host_name = str( self.rocon_masters[self.cur_selected_rocon_master].host_name) rocon_master_index = str(self.cur_selected_rocon_master) self.rocon_masters[rocon_master_index].check() # Todo this use of flags is spanky if self.rocon_masters[rocon_master_index].flag == '0': QMessageBox.warning( self, 'Rocon Master Connection Error', "Could not find a rocon master at %s" % self.rocon_masters[rocon_master_index].uri, QMessageBox.Ok) return if self.rocon_masters[rocon_master_index].flag == '1': QMessageBox.warning( self, 'Rocon Master Communication Error', "Found a rocon master at %s but cannot communicate with it (are ROS_IP/ROS_MASTER_URI correctly configured locally and remotely?)" % self.rocon_masters[rocon_master_index].uri, QMessageBox.Ok) return self._widget_main.hide() arguments = ["", rocon_master_uri, rocon_master_host_name] os.execv(QMasterChooser.rocon_remocon_sub_script, arguments) console.logdebug("Spawning: %s with args %s" % (QMasterChooser.rocon_remocon_sub_script, arguments))
def click_btn_apply(self): if self.validate_checked(): quit_msg = "Are you sure you want to Apply this configuration?" reply = QMessageBox.question(self, 'Message', quit_msg, QMessageBox.Yes, QMessageBox.No) self.get_selected_robot_checked() if reply == QMessageBox.Yes: xml_info = XmlInfo() env_os = EnvOs() dialog_xml = DialogXml() deleted_general_items = xml_info.get_deleted_general_variable() #get deleted general items (deleted status = 1 in xml) variable_general_items = xml_info.get_general_variables() dialog_xml.get_deleted_variable_robot() deleted_robots_items=dialog_xml.get_deleted_variable_robot() variable_robot_items,active_robot=dialog_xml.get_general_variable_robot() deleted_robot=dialog_xml.get_deleted_robot() asociative_variable_robot = dialog_xml.get_asociative_robot_variable() env_os.unset_to_htbash(deleted_robots_items+deleted_robots_items) env_os.export_to_general_htbash(variable_general_items) env_os.export_to_robot_htbash(variable_robot_items,active_robot) dialog_xml.remove_asociative_robot_variable(asociative_variable_robot) for item in deleted_robot: dialog_xml.remove_robot_list_variable(item) for item in deleted_general_items: xml_info.remove_general_variable(item) env_os.include_htbash() self.lblmsg.setText("write file .htbash successfully") else: pass else: QMessageBox.information(self, 'Checked validate',"You only must select one active robot")
def click_btnSaveRos(self): if self.txtVariableRos.isEnabled(): if self.txtVariableRos.text().strip( ) != "" and self.txtValueRos.text().strip() != "": if not self.validate_item(self.txtVariableRos.text()): xml_info = XmlInfo() xml_info.add_variable_ros(self.txtVariableRos.text(), self.txtValueRos.text()) message_instance = None self._recursive_create_widget_items( self.env_ros_tree_widget, self.txtVariableRos.text(), self.txtValueRos.text(), message_instance) else: QMessageBox.information( self, 'Variable exists', self.txtVariableRos.text() + " exists in list") else: message_instance = None xml_info = XmlInfo() xml_info.modify_variable_ros(self.txtVariableRos.text(), self.txtValueRos.text()) self.env_ros_tree_widget.clear() self.refresh_env() self.btnSaveRos.setEnabled(False) self.btnRemoveRos.setEnabled(True) self.txtVariableRos.setText("") self.txtValueRos.setText("") self.txtVariableRos.setEnabled(False) self.txtValueRos.setEnabled(False) self.btnRemoveRos.setEnabled(False) self.btnNewRos.setEnabled(True)
def __init__(self, context): super(NodeManager, self).__init__(context) # Give QObjects reasonable names self.setObjectName('NodeManagerFKIE') # Process standalone plugin command-line arguments from argparse import ArgumentParser parser = ArgumentParser() # Add argument(s) to the parser. parser.add_argument("-q", "--quiet", action="store_true", dest="quiet", help="Put plugin in silent mode") args, unknowns = parser.parse_known_args(context.argv()) if not args.quiet: print 'arguments: ', args print 'unknowns: ', unknowns node_manager_fkie.init_settings() masteruri = node_manager_fkie.settings().masteruri() node_manager_fkie.init_globals(masteruri) # Create QWidget try: self._widget = MainWindow() # self._widget.read_view_history() except Exception, e: msgBox = QMessageBox() msgBox.setText(str(e)) msgBox.exec_() raise
def mergeTracks(self, unused=None): (track1Id, ok) = QInputDialog.getInteger( self.widget, "Merge two tracks", "Please enter the ID of the 1st person track you want to merge.") if not ok: return (track2Id, ok) = QInputDialog.getInteger( self.widget, "Merge two tracks", "Please enter the ID of the 2nd person track you want to merge.") if not ok: return if track1Id == track2Id: QMessageBox.critical(self.widget, "Merge two tracks", "Track IDs cannot be identical!") return if self.verifyTrackExists(track1Id) and self.verifyTrackExists( track2Id): self.editor.mergeTracks(track1Id, track2Id) self.updateTrackCount() QMessageBox.information( self.widget, "Merge two tracks", "Person tracks %d and %d have been merged!" % (track1Id, track2Id))
def _rightclick_menu(self, event): menu = QMenu() text_action = QAction(self.tr('View Text'), menu) menu.addAction(text_action) raw_action = QAction(self.tr('View Raw'), menu) menu.addAction(raw_action) action = menu.exec_(event.globalPos()) if action == raw_action or action == text_action: selected = self.messages_tree.selectedIndexes() selected_type = selected[1].data() if selected_type[-2:] == '[]': selected_type = selected_type[:-2] browsetext = None try: if self._mode == rosmsg.MODE_MSG: browsetext = rosmsg.get_msg_text(selected_type, action == raw_action) elif self._mode == rosmsg.MODE_SRV: browsetext = rosmsg.get_srv_text(selected_type, action == raw_action) else: raise except rosmsg.ROSMsgException, e: QMessageBox.warning( self, self.tr('Warning'), self. tr('The selected item component does not have text to view.' )) if browsetext is not None: self._browsers.append(TextBrowseDialog(browsetext)) self._browsers[-1].show()
def __init__(self, icon, title, text, detailed_text="", buttons=QMessageBox.Ok): QMessageBox.__init__(self, icon, title, text, buttons) if detailed_text: self.setDetailedText(detailed_text) horizontalSpacer = QSpacerItem(480, 0, QSizePolicy.Minimum, QSizePolicy.Expanding) layout = self.layout() layout.addItem(horizontalSpacer, layout.rowCount(), 0, 1, layout.columnCount()) if QMessageBox.Abort & buttons: self.setEscapeButton(QMessageBox.Abort) elif QMessageBox.Ignore & buttons: self.setEscapeButton(QMessageBox.Ignore) else: self.setEscapeButton(buttons) self.textEdit = textEdit = self.findChild(QTextEdit) if textEdit is not None: textEdit.setMinimumHeight(0) textEdit.setMaximumHeight(600) textEdit.setMinimumWidth(0) textEdit.setMaximumWidth(600) textEdit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.ignore_all_btn = QPushButton('Don\'t display again') self.addButton(self.ignore_all_btn, QMessageBox.HelpRole)
def _check_for_master(self): # check if master is available try: rospy.get_master().getSystemState() return except Exception: pass # spawn thread to detect when master becomes available self._wait_for_master_thread = threading.Thread( target=self._wait_for_master) self._wait_for_master_thread.start() self._wait_for_master_dialog = QMessageBox( QMessageBox.Question, self.tr('Waiting for ROS master'), self. tr("Could not find ROS master. Either start a 'roscore' or abort loading the plugin." ), QMessageBox.Abort) self._master_found_signal.connect(self._wait_for_master_dialog.done, Qt.QueuedConnection) button = self._wait_for_master_dialog.exec_() # check if master existence was not detected by background thread no_master = button != QMessageBox.Ok self._wait_for_master_dialog.deleteLater() self._wait_for_master_dialog = None if no_master: raise PluginLoadError( 'RosPyPluginProvider._init_node() could not find ROS master')
def on_servo_on(self): try: if self.start_command: Popen(['bash', '-c', self.start_command]) elif self.use_hrpsys_configurator: execHrpsysConfiguratorCommand("hcf.servoOn()") else: servo = rospy.ServiceProxy( "/RobotHardwareServiceROSBridge/servo", OpenHRP_RobotHardwareService_servo) power = rospy.ServiceProxy( "/RobotHardwareServiceROSBridge/power", OpenHRP_RobotHardwareService_power) actual = rospy.ServiceProxy( "/StateHolderServiceROSBridge/goActual", OpenHRP_StateHolderService_goActual) power(OpenHRP_RobotHardwareService_powerRequest("all", 0)) time.sleep(1) actual(OpenHRP_StateHolderService_goActualRequest()) time.sleep(2) servo(OpenHRP_RobotHardwareService_servoRequest("all", 0)) except Exception, e: mb = QMessageBox(QMessageBox.NoIcon, "Error", "Failed to servo on: %s" % (e), QMessageBox.Ok, self.parent()) mb.exec_()
def verifyTrackExists(self, trackId): if not trackId in self.database.getTrackIds(): QMessageBox.critical( self.widget, "Wrong track ID", "Person track with ID %d does not exist!" % trackId) return False return True
def on_save_motion_button_clicked(self): motion_name = str(self.motion_name_combo.currentText()) if len(motion_name) == 0: QMessageBox.warning(self, 'Error', 'No name given to save this motion.') return self._motion_data.save(motion_name, self.get_motion_from_timeline()) self.update_motion_name_combo()
def on_reset_motors(self): # if any of the breakers is not enabled ask if they'd like to enable them if (self._dashboard_message is not None and self._dashboard_message.power_board_state_valid): all_breakers_enabled = reduce(lambda x, y: x and y, [ state == PowerBoardState.STATE_ON for state in self._dashboard_message.power_board_state.circuit_state ]) if (not all_breakers_enabled): if (QMessageBox.question( self._breakers[0], self.tr('Enable Breakers?'), self. tr("Resetting the motors may not work because not all breakers are enabled. Enable all the breakers first?" ), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) == QMessageBox.Yes): [breaker.set_enable() for breaker in self._breakers] reset = rospy.ServiceProxy("pr2_etherCAT/reset_motors", std_srvs.srv.Empty) try: reset() except rospy.ServiceException, e: QMessageBox.critical( self._breakers[0], "Error", "Failed to reset the motors: service call failed with error: %s" % (e))
def on_power_on(self): try: power = rospy.ServiceProxy("/RobotHardwareServiceROSBridge/power", OpenHRP_RobotHardwareService_power) power(OpenHRP_RobotHardwareService_powerRequest("all", 0)) except Exception, e: mb = QMessageBox(QMessageBox.NoIcon, "Error", "Failed to power on: %s" % (e), QMessageBox.Ok, self.parent()) mb.exec_()
def _handle_remove_clicked(self): name = self.name_edit.text() if name in self.places_dict.keys(): self.places_dict.pop(name) for item in self._sceneItems[name].keys(): self._scene.removeItem(self._sceneItems[name][item]) else: QMessageBox.critical(self, "Error!", "Place does not exist.")
def on_power_off(self): try: power = rospy.ServiceProxy("/RobotHardwareServiceROSBridge/power", OpenHRP_RobotHardwareService_power ) power(OpenHRP_RobotHardwareService_powerRequest("all",1)) except Exception, e: mb = QMessageBox(QMessageBox.NoIcon, "Error", "Failed to power off: %s"%(e), QMessageBox.Ok, self.parent()) mb.exec_()
def enable_motorstop_cb(self): stop_srv = rospy.ServiceProxy("/emergency_stop", EmergencyStop) try: stop_srv() except rospy.ServiceException, e: QMessageBox.critical( self._drive, "Error", "Failed to emergency stop: service call failed with error: %s" % (e))
def reset_motorstop_cb(self): reset_srv = rospy.ServiceProxy("/reset_motorstop", ResetMotorStop) try: reset_srv() except rospy.ServiceException, e: QMessageBox.critical( self._drive, "Error", "Failed to halt the motors: service call failed with error: %s" % (e))
def on_move_button_clicked(self): position_name = str(self.move_name_combo.currentText()) if len(position_name) == 0: QMessageBox.warning(self, 'Error', 'No position selected to move to.') return appendix_name = str(self.move_appendix_combo.currentText()) target_positions = self._position_data[self.robot_config.groups[appendix_name].group_type][position_name] target_positions = self.robot_config.groups[appendix_name].adapt_to_side(target_positions) print '[Motion Editor] Moving %s to "%s": %s' % (appendix_name, position_name, target_positions) self._motion_publisher.move_to_position(appendix_name, target_positions)
def freerun_cb(self): self._freerun_state = not self._freerun_state freerun_srv = rospy.ServiceProxy("/enable_motors", EnableMotors) try: freerun_srv(not self._freerun_state) except rospy.ServiceException, e: QMessageBox.critical( self._drive, "Error", "Failed to enter freerun: service call failed with error: %s" % (e))
def on_halt_motors(self): halt = rospy.ServiceProxy( "{}/halt_motors".format(self._motor_namespace), std_srvs.srv.Empty) try: halt() except rospy.ServiceException as e: QMessageBox.critical( self._motors, "Error", "Failed to halt the motors: service call failed with error: %s" % (e))
def show_saved_map_message(self, rtn): (success, message) = rtn if success: QMessageBox.warning(self, 'SUCCESS', "SAVE!!!!", QMessageBox.Ok | QMessageBox.Ok) else: QMessageBox.warning(self, 'FAIL', "FAIURE CAPTURE[%s]" % str(message), QMessageBox.Ok | QMessageBox.Ok) self.setDisabled(False)
def on_halt_motors(self): halt = rospy.ServiceProxy("pr2_etherCAT/halt_motors", std_srvs.srv.Empty) try: halt() except rospy.ServiceException, e: QMessageBox.critical( self._motors, "Error", "Failed to halt the motors: service call failed with error: %s" % (e))
def on_delete_motion_button_clicked(self): motion_name = str(self.motion_name_combo.currentText()) if len(motion_name) == 0: QMessageBox.warning(self, 'Error', 'No motion selected to delete.') return if motion_name not in self._motion_data: QMessageBox.warning(self, 'Error', 'Motion "%s" not in motion list.' % motion_name) return self._motion_data.delete(motion_name) self.update_motion_name_combo()
def show(self): # append folder of 'qt_gui_cpp/lib' to module search path qt_gui_cpp_path = os.path.realpath(get_package_path("qt_gui_cpp")) sys.path.append(os.path.join(qt_gui_cpp_path, "lib")) sys.path.append(os.path.join(qt_gui_cpp_path, "src")) from qt_gui_cpp.cpp_binding_helper import qt_gui_cpp import rospkg _rospkg_version = getattr(rospkg, "__version__", "< 0.2.4") logo = os.path.join(self._qtgui_path, "resource", "ros_org_vertical.png") text = '<img src="%s" width="56" height="200" style="float: left;"/>' % logo text += '<h3 style="margin-top: 1px;">%s</h3>' % self.tr("rqt") text += "<p>%s %s</p>" % ( self.tr("rqt is a framework for graphical user interfaces."), self.tr("It is extensible with plugins which can be written in either Python or C++."), ) text += "<p>%s</p>" % ( self.tr( 'Please see the <a href="%s">Wiki</a> for more information on rqt and available plugins.' % "http://wiki.ros.org/rqt" ) ) text += "<p>%s: " % self.tr("Utilized libraries:") text += "Python %s, " % platform.python_version() text += "rospkg %s, " % _rospkg_version if QT_BINDING == "pyside": text += "PySide" elif QT_BINDING == "pyqt": text += "PyQt" text += " %s (%s), " % (QT_BINDING_VERSION, ", ".join(sorted(QT_BINDING_MODULES))) text += "Qt %s, " % qVersion() if qt_gui_cpp is not None: if QT_BINDING == "pyside": text += "%s" % (self.tr("%s C++ bindings available") % "Shiboken") elif QT_BINDING == "pyqt": text += "%s" % (self.tr("%s C++ bindings available") % "SIP") else: text += "%s" % self.tr("C++ bindings available") else: text += "%s" % self.tr("no C++ bindings found - no C++ plugins available") text += ".</p>" mb = QMessageBox(QMessageBox.NoIcon, self.tr("About rqt"), text, QMessageBox.Ok, self.parent()) mb.exec_()
class RosPyPluginProvider(CompositePluginProvider): _master_found_signal = Signal(int) def __init__(self): super(RosPyPluginProvider, self).__init__([RospkgPluginProvider('rqt_gui', 'rqt_gui_py::Plugin')]) self.setObjectName('RosPyPluginProvider') self._node_initialized = False self._wait_for_master_dialog = None self._wait_for_master_thread = None def load(self, plugin_id, plugin_context): self._check_for_master() self._init_node() return super(RosPyPluginProvider, self).load(plugin_id, plugin_context) def _check_for_master(self): # check if master is available try: rospy.get_master().getSystemState() return except Exception: pass # spawn thread to detect when master becomes available self._wait_for_master_thread = threading.Thread(target=self._wait_for_master) self._wait_for_master_thread.start() self._wait_for_master_dialog = QMessageBox(QMessageBox.Question, self.tr('Waiting for ROS master'), self.tr("Could not find ROS master. Either start a 'roscore' or abort loading the plugin."), QMessageBox.Abort) self._master_found_signal.connect(self._wait_for_master_dialog.done, Qt.QueuedConnection) button = self._wait_for_master_dialog.exec_() # check if master existence was not detected by background thread no_master = button != QMessageBox.Ok self._wait_for_master_dialog.deleteLater() self._wait_for_master_dialog = None if no_master: raise PluginLoadError('RosPyPluginProvider._init_node() could not find ROS master') def _wait_for_master(self): while True: time.sleep(0.1) if not self._wait_for_master_dialog: break try: rospy.get_master().getSystemState() except Exception: continue self._master_found_signal.emit(QMessageBox.Ok) break def _init_node(self): # initialize node once if not self._node_initialized: name = 'rqt_gui_py_node_%d' % os.getpid() qDebug('RosPyPluginProvider._init_node() initialize ROS node "%s"' % name) rospy.init_node(name, disable_signals=True) self._node_initialized = True
def on_delete_motion_button_clicked(self): motion_name = str(self.motion_name_combo.currentText()) if len(motion_name) == 0: QMessageBox.warning(self, 'Error', 'No motion selected to delete.') return if motion_name not in self._motion_data: QMessageBox.warning( self, 'Error', 'Motion "%s" not in motion list.' % motion_name) return self._motion_data.delete(motion_name) self.update_motion_name_combo()
def on_run_motion_button_clicked(self): motion_name = str(self.motion_name_combo.currentText()) if len(motion_name) == 0: QMessageBox.warning(self, 'Error', 'No motion selected to run.') return if motion_name not in self._motion_data: QMessageBox.warning(self, 'Error', 'Motion "%s" not in motion list.' % motion_name) return self._clear_playback_marker() self._motion_publisher.publish_motion(self._motion_data[motion_name], self.time_factor_spin.value()) print '[Motion Editor] Running motion:', motion_name
def _stop_interaction(self): console.logdebug("Interactions Chooser : stopping interaction %s " % str(self.cur_selected_interaction.name)) (result, message) = self.interactive_client.stop_interaction(self.cur_selected_interaction.hash) if result: if self.cur_selected_interaction.is_paired_type(): self._refresh_interactions_list() # make sure the highlight is disabled self._set_stop_interactions_button() #self.interactions_widget.stop_interactions_button.setDisabled(True) else: QMessageBox.warning(self, 'Stop Interaction Failed', "%s." % message.capitalize(), QMessageBox.Ok) console.logwarn("Interactions Chooser : stop interaction failed [%s]" % message)
def on_reconnect_clicked(self): if (self._dashboard_message is not None): reconnect = rospy.ServiceProxy("/reconnect", std_srvs.srv.Empty) try: reconnect() except rospy.ServiceException, e: QMessageBox.critical( self.ethercat, "Error", "Failed to reconnect the driver: service call failed with error: %s" % (e))
def _handle_get_clicked(self): name = self.name_edit.text() if (name in self.places_dict.keys()): self.x_spin.setValue(self.places_dict[name][0]) self.y_spin.setValue(self.places_dict[name][1]) theta = euler_from_quaternion( numpy.asarray(self.places_dict[name][3:7]))[2] self.theta_spin.setValue(degrees(theta)) else: QMessageBox.critical(self, "Error!", "This places has not been added.")
def on_download(self): try: hrpsys_save = rospy.ServiceProxy("/DataLoggerServiceROSBridge/save", OpenHRP_DataLoggerService_save ) name = "/tmp/rtclog-" + time.strftime("%Y%m%d%H%M%S") print "Writing log data to ",name hrpsys_save(OpenHRP_DataLoggerService_saveRequest(name)) print "Done writing",name except rospy.ServiceException, e: mb = QMessageBox(QMessageBox.NoIcon, "Error", "Failed to save rtcd log: service call failed with error: %s"%(e), QMessageBox.Ok, self.parent()) mb.exec_()
def _send_comand_cb(self): ''' Sends a mission command ''' msg = MissionCommand() msg.command = self._widget.comboBox_command.currentText() try: msg.variable = float(self._widget.lineEdit_parameter.text().encode("utf8")) except ValueError, e: rospy.logerr('MissionCommanderGUI:_send_command_cb: %s',e) QMessageBox.warning(self._widget, 'Error', 'Incorrect format of the parameter. A number is expected')
def show(self): # append folder of 'qt_gui_cpp/lib' to module search path qt_gui_cpp_path = os.path.realpath(get_package_path('qt_gui_cpp')) sys.path.append(os.path.join(qt_gui_cpp_path, 'lib')) sys.path.append(os.path.join(qt_gui_cpp_path, 'src')) from qt_gui_cpp.cpp_binding_helper import qt_gui_cpp _rospkg_version = None try: import rospkg _rospkg_version = getattr(rospkg, '__version__', '< 0.2.4') except ImportError: pass logo = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', '..', 'icons', 'ros_org_vertical.png')) text = '<img src="%s" width="56" height="200" style="float: left;"/>' % logo text += '<h3 style="margin-top: 1px;">%s</h3>' % self.tr('ROS GUI') text += '<p>%s %s</p>' % (self.tr('ROS GUI is a framework for graphical user interfaces.'), self.tr('It is extensible with plugins which can be written in either Python or C++.')) text += '<p>%s</p>' % (self.tr('Please see the <a href="%s">Wiki</a> for more information on ROS GUI and available plugins.' % 'http://www.ros.org/wiki/rqt')) text += '<p>%s: ' % self.tr('Utilized libraries:') text += 'Python %s, ' % platform.python_version() if _rospkg_version is not None: text += 'rospkg %s, ' % _rospkg_version else: text += '%s, ' % self.tr('rospkg not found - using roslib') if QT_BINDING == 'pyside': text += 'PySide' elif QT_BINDING == 'pyqt': text += 'PyQt' text += ' %s (%s), ' % (QT_BINDING_VERSION, ', '.join(sorted(QT_BINDING_MODULES))) text += 'Qt %s, ' % qVersion() if qt_gui_cpp is not None: if QT_BINDING == 'pyside': text += '%s' % (self.tr('%s C++ bindings available') % 'Shiboken') elif QT_BINDING == 'pyqt': text += '%s' % (self.tr('%s C++ bindings available') % 'SIP') else: text += '%s' % self.tr('C++ bindings available') else: text += '%s' % self.tr('no C++ bindings found - no C++ plugins available') text += '.</p>' QMessageBox.about(self.parent(), self.tr('About ROS GUI'), text)
def on_saveButton_clicked(self): ''' Saves the current document. This method is called if the C{save button} was clicked. ''' saved, errors, msg = self.tabWidget.currentWidget().save(True) if errors: QMessageBox.critical(self, "Error", msg) self.tabWidget.setTabIcon(self.tabWidget.currentIndex(), self._error_icon) self.tabWidget.setTabToolTip(self.tabWidget.currentIndex(), msg) elif saved: self.tabWidget.setTabIcon(self.tabWidget.currentIndex(), self._empty_icon) self.tabWidget.setTabToolTip(self.tabWidget.currentIndex(), '')
def save_map(self): if self._slam_widget_interface: self.setDisabled(True) map_name = str(self.map_name_txt.toPlainText()).lower().replace( ' ', '_') world_name = str( self.world_name_txt.toPlainText()).lower().replace(' ', '_') self.map_name_txt.setPlainText(map_name) self.world_name_txt.setPlainText(world_name) self._callback['save_map'](world=world_name, map_name=map_name) else: QMessageBox.warning(self, 'FAIL', "No map has created", QMessageBox.Ok | QMessageBox.Ok)
def on_delete_button_clicked(self): appendix_name = str(self.save_appendix_combo.currentText()) position_name = str(self.save_name_combo.currentText()) if len(position_name) == 0 or \ position_name not in self._position_data[self.robot_config.groups[appendix_name].group_type]: QMessageBox.warning(self, 'Error', 'Position "%s" not in position list.') return self._position_data[self.robot_config.groups[appendix_name].group_type].delete(position_name) self.position_list_updated.emit(self._position_data) self.on_save_appendix_combo_currentIndexChanged(appendix_name) if self.robot_config.groups[self.move_appendix_combo.currentText()].group_type \ == self.robot_config.groups[appendix_name].group_type: self.on_move_appendix_combo_currentIndexChanged(appendix_name)
def on_run_motion_button_clicked(self): motion_name = str(self.motion_name_combo.currentText()) if len(motion_name) == 0: QMessageBox.warning(self, 'Error', 'No motion selected to run.') return if motion_name not in self._motion_data: QMessageBox.warning( self, 'Error', 'Motion "%s" not in motion list.' % motion_name) return self._clear_playback_marker() self._motion_publisher.publish_motion(self._motion_data[motion_name], self.time_factor_spin.value()) print '[Motion Editor] Running motion:', motion_name
def paintEvent(self, event): QMessageBox.paintEvent(self, event) if self.textEdit is not None: if self.textEdit.isVisible(): if not self.ignore_all_btn.isVisible(): self.ignore_all_btn.setVisible(True) self.setSizeGripEnabled(True) self.setMaximumHeight(16777215) self.setMaximumWidth(16777215) elif not self.textEdit.isVisible(): if self.ignore_all_btn.isVisible(): self.ignore_all_btn.setVisible(False) self.setSizeGripEnabled(False)
def on_load_motion_button_clicked(self): motion_name = str(self.motion_name_combo.currentText()) if len(motion_name) == 0: QMessageBox.warning(self, 'Error', 'No motion selected to load.') return if motion_name not in self._motion_data: QMessageBox.warning(self, 'Error', 'Motion "%s" not in motion list.' % motion_name) return self.on_clear_motion_button_clicked() motion = self._motion_data[motion_name] for group_name, poses in motion.items(): for pose in poses: data = self.robot_config.groups[group_name].adapt_to_side(pose['positions']) self._timeline_widget.scene().add_clip(group_name, pose['name'], pose['starttime'], pose['duration'], data)
def _choose_new_perspective_name(self, show_cloning=True): # input dialog for new perspective name if self._create_perspective_dialog is None: ui_file = os.path.join(self._qtgui_path, 'resource', 'perspective_create.ui') self._create_perspective_dialog = loadUi(ui_file) # custom validator preventing forward slashs class CustomValidator(QValidator): def __init__(self, parent=None): super(CustomValidator, self).__init__(parent) def fixup(self, value): value = value.replace('/', '') def validate(self, value, pos): if value.find('/') != -1: pos = value.find('/') return (QValidator.Invalid, value, pos) if value == '': return (QValidator.Intermediate, value, pos) return (QValidator.Acceptable, value, pos) self._create_perspective_dialog.perspective_name_edit.setValidator( CustomValidator()) # set default values self._create_perspective_dialog.perspective_name_edit.setText('') self._create_perspective_dialog.clone_checkbox.setChecked(True) self._create_perspective_dialog.clone_checkbox.setVisible(show_cloning) # show dialog and wait for it's return value return_value = self._create_perspective_dialog.exec_() if return_value == self._create_perspective_dialog.Rejected: return name = str(self._create_perspective_dialog.perspective_name_edit.text( )).lstrip(self.HIDDEN_PREFIX) if name == '': QMessageBox.warning( self._menu_manager.menu, self.tr('Empty perspective name'), self.tr('The name of the perspective must be non-empty.')) return if name in self.perspectives: QMessageBox.warning( self._menu_manager.menu, self.tr('Duplicate perspective name'), self.tr('A perspective with the same name already exists.')) return return name
def _handle_add_clicked(self): name = self.name_edit.text() if len(name) != 0: # remove and re-draw it if name in self.places_dict.keys(): self.places_dict.pop(name) for item in self._sceneItems[name].keys(): self._scene.removeItem(self._sceneItems[name][item]) try: # storing the values in the dict x = self.x_spin.value() y = self.y_spin.value() theta = self.theta_spin.value() q = quaternion_from_euler(0.0, 0.0, theta) self.places_dict[str(name)] = [ x, y, 0.0, float(q[0]), float(q[1]), float(q[2]), float(q[3]) ] # drawing the items self._sceneItems[name] = {"text": QGraphicsTextItem()} self._sceneItems[name]["text"].setDefaultTextColor( QColor(0, 0, 255)) self._sceneItems[name]["text"].setFont(QFont("Times", 10)) self._sceneItems[name]["text"].setPlainText(name) scene_pos = self._gridToScene(x, y, q) x_c = scene_pos[0] - self._sceneItems[name][ "text"].boundingRect().width() / 2.0 self._sceneItems[name]["text"].setPos(x_c, scene_pos[1]) self._scene.addItem(self._sceneItems[name]["text"]) self._sceneItems[name]["rec"] = self._scene.addRect( QRectF((scene_pos[0] - 2), (scene_pos[1] - 2), 4, 4)) line = QLineF( scene_pos[0], scene_pos[1], (scene_pos[0] - self._mag * cos(radians(scene_pos[3]))), (scene_pos[1] + self._mag * sin(radians(scene_pos[3])))) self._sceneItems[name]["line"] = self._scene.addLine( line, pen=QPen(Qt.red, 2)) except ValueError: QMessageBox.critical(self, "Error!", "You must insert a valid value.") else: QMessageBox.critical( self, "Error!", "You have to insert a name and a valid position.")
class DialogService(QWidget): ''' Provides popup windows for information and error messages ''' #---------------------------------- # Initializer #-------------- def __init__(self, parent=None): super(DialogService, self).__init__(parent); # All-purpose error popup message: # Used by self.showErrorMsgByErrorCode(<errorCode>), # or self.showErrorMsg(<string>). Returns a # QErrorMessage without parent, but with QWindowFlags set # properly to be a dialog popup box: self.errorMsgPopup = QErrorMessage.qtHandler(); # Re-parent the popup, retaining the window flags set # by the qtHandler: self.errorMsgPopup.setParent(parent, self.errorMsgPopup.windowFlags()); #self.errorMsgPopup.setStyleSheet(SpeakEasyGUI.stylesheetAppBG); self.infoMsg = QMessageBox(parent=parent); #self.infoMsg.setStyleSheet(SpeakEasyGUI.stylesheetAppBG); #---------------------------------- # showErrorMsg #-------------- QErrorMessage def showErrorMsg(self,errMsg): ''' Given a string, pop up an error dialog on top of the application window. @param errMsg: The message @type errMsg: string ''' self.errorMsgPopup.showMessage(errMsg); #---------------------------------- # showInfoMsg #-------------- def showInfoMsg(self, text): ''' Display a message window with an OK button on top of the application window. @param text: text to display @type text: string ''' self.infoMsg.setText(text); self.infoMsg.exec_();
def on_servo_off(self): try: if self.stop_command: Popen(['bash', '-c', self.stop_command]) else: power = rospy.ServiceProxy("/RobotHardwareServiceROSBridge/power", OpenHRP_RobotHardwareService_power ) servo = rospy.ServiceProxy("/RobotHardwareServiceROSBridge/servo", OpenHRP_RobotHardwareService_servo ) servo(OpenHRP_RobotHardwareService_servoRequest("all", 1)) time.sleep(1) power(OpenHRP_RobotHardwareService_powerRequest("all",1)) except Exception, e: mb = QMessageBox(QMessageBox.NoIcon, "Error", "Failed to servo off: %s"%(e), QMessageBox.Ok, self.parent()) mb.exec_()
def on_close_tab(self, tab_index): ''' Signal handling to close single tabs. @param tab_index: tab index to close @type tab_index: C{int} ''' try: doremove = True w = self.tabWidget.widget(tab_index) if w.document().isModified(): name = self.__getTabName(w.filename) result = QMessageBox.question(self, "Unsaved Changes", '\n\n'.join(["Save the file before closing?", name]), QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel) if result == QMessageBox.Yes: self.tabWidget.currentWidget().save() elif result == QMessageBox.No: pass else: doremove = False if doremove: # remove the indexed files if w.filename in self.files: self.files.remove(w.filename) # close tab self.tabWidget.removeTab(tab_index) # close editor, if no tabs are open if not self.tabWidget.count(): self.close() except: import traceback rospy.logwarn("Error while close tab %s: %s", str(tab_index), traceback.format_exc(1))
def mouseReleaseEvent(self, event): ''' Opens the new editor, if the user clicked on the included file and sets the default cursor. ''' if event.modifiers() == Qt.ControlModifier or event.modifiers() == Qt.ShiftModifier: cursor = self.cursorForPosition(event.pos()) index = self.index(cursor.block().text()) if index > -1: startIndex = cursor.block().text().find('"', index) if startIndex > -1: endIndex = cursor.block().text().find('"', startIndex + 1) fileName = cursor.block().text()[startIndex + 1:endIndex] if len(fileName) > 0: try: qf = QFile(interpret_path(fileName)) if not qf.exists(): # create a new file, if it does not exists result = QMessageBox.question(self, "File not found", '\n\n'.join(["Create a new file?", qf.fileName()]), QMessageBox.Yes | QMessageBox.No) if result == QMessageBox.Yes: d = os.path.dirname(qf.fileName()) if not os.path.exists(d): os.makedirs(d) with open(qf.fileName(), 'w') as f: if qf.fileName().endswith('.launch'): f.write('<launch>\n\n</launch>') event.setAccepted(True) self.load_request_signal.emit(qf.fileName()) else: event.setAccepted(True) self.load_request_signal.emit(qf.fileName()) except Exception, e: WarningMessageBox(QMessageBox.Warning, "File not found %s" % fileName, str(e)).exec_()
def on_save_button_clicked(self): position_name = str(self.save_name_combo.currentText()) if len(position_name) == 0: QMessageBox.warning(self, 'Error', 'No name given to save this position.') return appendix_name = str(self.save_appendix_combo.currentText()) group = self.robot_config.groups[appendix_name] current_positions = self._motion_publisher.get_current_positions(group) current_positions = self.robot_config.groups[appendix_name].adapt_to_side(current_positions) print '[Motion Editor] Saving %s as "%s": %s' % (appendix_name, position_name, current_positions) self._position_data[self.robot_config.groups[appendix_name].group_type].save(position_name, current_positions) self.position_list_updated.emit(self._position_data) self.on_save_appendix_combo_currentIndexChanged(appendix_name) if self.robot_config.groups[self.move_appendix_combo.currentText()].group_type \ == self.robot_config.groups[appendix_name].group_type: self.on_move_appendix_combo_currentIndexChanged(appendix_name)
def closeEvent(self, event): ''' Test the open files for changes and save this if needed. ''' changed = [] # get the names of all changed files for i in range(self.tabWidget.count()): w = self.tabWidget.widget(i) if w.document().isModified(): changed.append(self.__getTabName(w.filename)) if changed: # ask the user for save changes if self.isHidden(): buttons = QMessageBox.Yes | QMessageBox.No else: buttons = QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel result = QMessageBox.question(self, "Unsaved Changes", '\n\n'.join(["Save the file before closing?", '\n'.join(changed)]), buttons) if result == QMessageBox.Yes: for i in range(self.tabWidget.count()): w = self.tabWidget.widget(i).save() event.accept() elif result == QMessageBox.No: event.accept() else: event.ignore() else: event.accept() if event.isAccepted(): self.storeSetting() self.finished_signal.emit(self.init_filenames)
def _reset_steering_encoder_cb(self): ''' Resets the steering encoder ''' msg = Empty() ret = QMessageBox.question(self._widget, "Reset Encoder", 'Are you sure of resetting the encoder?', QMessageBox.Ok, QMessageBox.Cancel) if ret == QMessageBox.Ok: try: self._reset_steering_encoder_service_client() except rospy.ROSInterruptException,e: rospy.logerr('MissionCommanderGUI:_reset_steering_encoder_cb: %s',e) QMessageBox.warning(self._widget, 'Error', 'Error sending the command') except rospy.ServiceException,e: rospy.logerr('MissionCommanderGUI:_reset_steering_encoder_cb: %s',e) QMessageBox.warning(self._widget, 'Error', 'Error sending the command')
def _rightclick_menu(self, event): """ :type event: QEvent """ # QTreeview.selectedIndexes() returns 0 when no node is selected. # This can happen when after booting no left-click has been made yet # (ie. looks like right-click doesn't count). These lines are the # workaround for that problem. selected = self._messages_tree.selectedIndexes() if len(selected) == 0: return menu = QMenu() text_action = QAction(self.tr('View Text'), menu) menu.addAction(text_action) raw_action = QAction(self.tr('View Raw'), menu) menu.addAction(raw_action) action = menu.exec_(event.globalPos()) if action == raw_action or action == text_action: rospy.logdebug('_rightclick_menu selected={}'.format(selected)) selected_type = selected[1].data() if selected_type[-2:] == '[]': selected_type = selected_type[:-2] browsetext = None try: if (self._mode == rosmsg.MODE_MSG or self._mode == rosaction.MODE_ACTION): browsetext = rosmsg.get_msg_text(selected_type, action == raw_action) elif self._mode == rosmsg.MODE_SRV: browsetext = rosmsg.get_srv_text(selected_type, action == raw_action) else: raise except rosmsg.ROSMsgException, e: QMessageBox.warning(self, self.tr('Warning'), self.tr('The selected item component ' + 'does not have text to view.')) if browsetext is not None: self._browsers.append(TextBrowseDialog(browsetext, self._rospack)) self._browsers[-1].show()
def _set_pantilt_cb(self): ''' Sends the setPanTilt command to the platform ''' msg = PlatformCommand() msg.command = 'setPanTilt' msg.variables = [self._widget.doubleSpinBox_set_pan.value(), self._widget.doubleSpinBox_set_tilt.value()] #msg.variables = [0.0, 0.0] #print self._widget.doubleSpinBox_set_pan.value() try: self._platform_command_service_client(msg) except rospy.ROSInterruptException,e: rospy.logerr('MissionCommanderGUI:_set_pantilt_cb: %s',e) QMessageBox.warning(self._widget, 'Error', 'Error sending the command')
def on_servo_off(self): try: if self.stop_command: Popen(["bash", "-c", self.stop_command]) elif self.use_hrpsys_configurator: execHrpsysConfiguratorCommand("hcf.servoOff()") else: power = rospy.ServiceProxy("/RobotHardwareServiceROSBridge/power", OpenHRP_RobotHardwareService_power) servo = rospy.ServiceProxy("/RobotHardwareServiceROSBridge/servo", OpenHRP_RobotHardwareService_servo) servo(OpenHRP_RobotHardwareService_servoRequest("all", 1)) time.sleep(1) power(OpenHRP_RobotHardwareService_powerRequest("all", 1)) except Exception, e: mb = QMessageBox( QMessageBox.NoIcon, "Error", "Failed to servo off: %s" % (e), QMessageBox.Ok, self.parent() ) mb.exec_()
def _stop_vehicle_cb(self): ''' Sends the stopcommand to the platform ''' msg = PlatformCommand() msg.command = 'cancel' ret = QMessageBox.question(self._widget, "Stop Vehicle", 'Do you want to stop the vehicle?', QMessageBox.Ok, QMessageBox.Cancel) if ret == QMessageBox.Ok: try: self._platform_command_service_client(msg) except rospy.ROSInterruptException,e: rospy.logerr('MissionCommanderGUI:_stop_vehicle_cb: %s',e) QMessageBox.warning(self._widget, 'Error', 'Error sending the command') except rospy.ServiceException,e: rospy.logerr('MissionCommanderGUI:_stop_vehicle_cb: %s',e) QMessageBox.warning(self._widget, 'Error', 'Error sending the command')
def on_servo_on(self): try: if self.start_command: Popen(['bash', '-c', self.start_command]) else: servo = rospy.ServiceProxy("/RobotHardwareServiceROSBridge/servo", OpenHRP_RobotHardwareService_servo ) power = rospy.ServiceProxy("/RobotHardwareServiceROSBridge/power", OpenHRP_RobotHardwareService_power ) actual = rospy.ServiceProxy("/StateHolderServiceROSBridge/goActual", OpenHRP_StateHolderService_goActual ) power(OpenHRP_RobotHardwareService_powerRequest("all",0)) time.sleep(1) actual(OpenHRP_StateHolderService_goActualRequest()) time.sleep(2) servo(OpenHRP_RobotHardwareService_servoRequest("all",0)) except Exception, e: mb = QMessageBox(QMessageBox.NoIcon, "Error", "Failed to servo on: %s"%(e), QMessageBox.Ok, self.parent()) mb.exec_()
def _initialize_platform_cb(self): ''' Initialize platform encoders ''' msg = Empty() ret = QMessageBox.question(self._widget, "Init platform", 'Are you sure of initializing?', QMessageBox.Ok, QMessageBox.Cancel) if ret == QMessageBox.Ok: try: self._initialize_platform_service_client() except rospy.ROSInterruptException,e: rospy.logerr('MissionCommanderGUI:_initialize_platform_cb: %s',e) QMessageBox.warning(self._widget, 'Error', 'Error sending the command') except rospy.ServiceException,e: rospy.logerr('MissionCommanderGUI:_initialize_platform_cb: %s',e) QMessageBox.warning(self._widget, 'Error', 'Error sending the command')
def focusInEvent(self, event): # check for file changes try: if self.filename and self.file_info: if self.file_info.lastModified() != QFileInfo(self.filename).lastModified(): self.file_info = QFileInfo(self.filename) result = QMessageBox.question(self, "File changed", "File was changed, reload?", QMessageBox.Yes | QMessageBox.No) if result == QMessageBox.Yes: f = QFile(self.filename) if f.open(QIODevice.ReadOnly | QIODevice.Text): self.setText(unicode(f.readAll(), "utf-8")) self.document().setModified(False) self.textChanged.emit() else: QMessageBox.critical(self, "Error", "Cannot open launch file%s" % self.filename) except: pass QTextEdit.focusInEvent(self, event)
def _fold_crane_cb(self): ''' Sends the foldCrane command to the platform ''' msg = PlatformCommand() msg.command = 'foldCrane' ret = QMessageBox.question(self._widget, "Fold Crane", 'Do you want to fold the crane?', QMessageBox.Ok, QMessageBox.Cancel) if ret == QMessageBox.Ok: try: self._platform_command_service_client(msg) except rospy.ROSInterruptException,e: rospy.logerr('MissionCommanderGUI:_fold_crane_cb: %s',e) QMessageBox.warning(self._widget, 'Error', 'Error sending the command') except rospy.ServiceException,e: rospy.logerr('MissionCommanderGUI:_fold_crane_cb: %s',e) QMessageBox.warning(self._widget, 'Error', 'Error sending the command')