class RelaySignal(QObject):
    relay_signal = Signal()

    def __init__(self):
        super(RelaySignal, self).__init__()

    def emit(self):
        self.relay_signal.emit()
class RelaySignalInt(QObject):
    relay_signal = Signal(int)

    def __init__(self):
        super(RelaySignalInt, self).__init__()

    def emit(self, row):
        self.relay_signal.emit(row)
class Foo(QObject):
    current_values_changed = Signal(str)
    current_duration_changed = Signal(float)
    _update_current_value_signal = Signal()
    _show_input_notification_signal = Signal()
    _hide_input_notification_signal = Signal()
    _show_scene_notification_signal = Signal()
    _hide_scene_notification_signal = Signal()
    _update_color_of_line_edit_signal = Signal()

    def __init__(self):
        super(Foo, self).__init__()
        self._action_set = None
        self._update_current_value_signal.connect(self._update_current_value)

        self._scene_notification = QDialog(main_window)
        ui_file = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                               '..', 'src', 'wrong_scene_dialog.ui')
        loadUi(ui_file, self._scene_notification)
        self._scene_notification_timer = QTimer(main_window)
        self._scene_notification_timer.setInterval(5000)
        self._scene_notification_timer.setSingleShot(True)
        self._scene_notification_timer.timeout.connect(
            self._hide_scene_notification)
        self._scene_notification.finished.connect(
            self._hide_scene_notification)

        self._input_notification = QDialog(main_window)
        ui_file = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                               '..', 'src', 'wrong_input_method_dialog.ui')
        loadUi(ui_file, self._input_notification)
        self._input_notification_timer = QTimer(main_window)
        self._input_notification_timer.setInterval(5000)
        self._input_notification_timer.setSingleShot(True)
        self._input_notification_timer.timeout.connect(
            self._hide_input_method_notification)
        self._input_notification.finished.connect(
            self._hide_input_method_notification)

        self._show_input_notification_signal.connect(
            self._show_input_notification)
        self._hide_input_notification_signal.connect(
            self._hide_input_method_notification)
        self._show_input_notification_signal.connect(
            self._show_scene_notification)
        self._hide_input_notification_signal.connect(
            self._hide_scene_notification)
        self._update_color_of_line_edit_signal.connect(
            self._update_color_of_line_edit)

    def _hide_scene_notification(self, result=None):
        self._scene_notification_timer.stop()
        self._scene_notification.hide()

    def _hide_input_method_notification(self, result=None):
        self._input_notification_timer.stop()
        self._input_notification.hide()

    # this method is call by ROS, all UI interaction is delayed via signals
    def update_current_value(self):
        global check_collisions
        global currently_in_collision

        if self._action_set is not None:
            self._action_set.stop()
        self._action_set = kontrol_subscriber.get_action_set()
        if self._action_set is not None:
            self.current_duration_changed.emit(self._action_set.get_duration())

        if not is_in_slider_mode():
            currently_in_collision = False
            self._show_input_notification_signal.emit()
            return
        if self._input_notification_timer.isActive():
            self._hide_input_notification_signal.emit()

        #print('update_current_value()')
        if not kontrol_subscriber.is_valid_action_set():
            self._show_scene_notification_signal.emit()
            return
        if self._scene_notification_timer.isActive():
            self._hide_scene_notification_signal.emit()

        joint_values = kontrol_subscriber.get_joint_values()
        if check_collisions:
            in_collision = collision_checker.is_in_collision(joint_values)
        else:
            in_collision = False

        collision_toggled = (currently_in_collision != in_collision)
        currently_in_collision = in_collision

        if collision_toggled:
            self._update_color_of_line_edit_signal.emit()

        self._update_current_value_signal.emit()

    def _show_input_notification(self):
        # open dialog which closes after some s_hide_scene_notification_hide_scene_notificationeconds or when confirmed manually
        self._input_notification.show()
        self._input_notification_timer.start()

    def _show_scene_notification(self):
        # open dialog which closes after some seconds or when confirmed manually
        self._scene_notification.show()
        self._scene_notification_timer.start()

    def _update_color_of_line_edit(self):
        global currently_in_collision
        palette = main_window.lineEdit.palette()
        if currently_in_collision:
            palette.setColor(QPalette.Text, QColor(255, 0, 0))
        else:
            palette.setColor(QPalette.Text, default_color)
        main_window.lineEdit.setPalette(palette)

    def _update_current_value(self):
        global currently_in_collision
        main_window.append_pushButton.setEnabled(not currently_in_collision)
        main_window.insert_before_pushButton.setEnabled(
            not currently_in_collision)

        value = self._action_set.to_string()
        self.current_values_changed.emit(value)
        for action in self._action_set._actions:
            action._duration = 0.1 if use_sim_time else 0.5
        self._action_set.execute()
class JointObserver(QObject):
    current_values_changed = Signal(str)
    _update_current_value_signal = Signal()

    def __init__(self):
        super(JointObserver, self).__init__()
        self.action_set = None
        self._latest_joint_state = None
        self._update_current_value_signal.connect(self._update_current_value)
        self._subscriber = None
        self._trajectory_locks = []
        self._trajectory_locks.append(
            TrajectoryLock('head_traj_controller_loose', [.08, .08]))
        self._trajectory_locks.append(
            TrajectoryLock('l_arm_controller_loose',
                           [.02, .02, .02, .02, .02, .06, .06]))
        self._trajectory_locks.append(
            TrajectoryLock('r_arm_controller_loose',
                           [.02, .02, .02, .02, .02, .06, .06]))

    def start(self):
        print 'JointObserver.start()'
        if self._subscriber is not None:
            self._subscriber.unregister()
        self._subscriber = rospy.Subscriber('/joint_states', JointState,
                                            self._receive_joint_states)
        for trajectory_lock in self._trajectory_locks:
            trajectory_lock.start()

    def stop(self):
        print 'JointObserver.stop()'
        if self._subscriber is not None:
            self._subscriber.unregister()
            self._subscriber = None
        for trajectory_lock in self._trajectory_locks:
            trajectory_lock.stop()

    def _receive_joint_states(self, joint_state_msg):
        self._latest_joint_state = joint_state_msg
        self._update_current_value_signal.emit()

    def _update_current_value(self):
        self.action_set = ActionSet()
        self.action_set.add_action(Pr2MoveHeadAction())
        self.action_set.add_action(Pr2MoveLeftArmAction())
        self.action_set.add_action(Pr2MoveRightArmAction())

        labels = self.action_set.get_labels()

        for label in labels:
            value = self._latest_joint_state.position[
                self._latest_joint_state.name.index(label)]
            value *= 180.0 / math.pi
            try:
                self.action_set.update_value(label, value)
            except KeyError, e:
                print 'JointObserver._update_current_value() label "%s" not found' % label
                pass

        value = self.action_set.to_string()
        self.current_values_changed.emit(value)
class HipViewerPlugin(QObject):

    _deferred_fit_in_view = Signal()

    def __init__(self, context):
        super(HipViewerPlugin, self).__init__(context)
        self.setObjectName('HipViewer')

        self._current_dotcode = None

        self._widget = QWidget()

        ui_file = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                               'hip_viewer.ui')
        loadUi(ui_file, self._widget,
               {'InteractiveGraphicsView': InteractiveGraphicsView})
        self._widget.setObjectName('HipViewerUi')
        if context.serial_number() > 1:
            self._widget.setWindowTitle(self._widget.windowTitle() +
                                        (' (%d)' % context.serial_number()))

        self._scene = QGraphicsScene()
        self._widget.graphics_view.setScene(self._scene)

        self._widget.graph_type_combo_box.insertItem(0, self.tr('infinite'),
                                                     -1)
        self._widget.graph_type_combo_box.insertItem(1, self.tr('1'), 2)
        self._widget.graph_type_combo_box.insertItem(2, self.tr('2'), 3)
        self._widget.graph_type_combo_box.insertItem(3, self.tr('3'), 4)
        self._widget.graph_type_combo_box.insertItem(4, self.tr('4'), 5)
        self._widget.graph_type_combo_box.setCurrentIndex(0)

        self._widget.refresh_graph_push_button.setIcon(
            QIcon.fromTheme('view-refresh'))

        self._widget.highlight_connections_check_box.toggled.connect(
            self._redraw_graph_view)
        self._widget.auto_fit_graph_check_box.toggled.connect(
            self._redraw_graph_view)
        self._widget.fit_in_view_push_button.setIcon(
            QIcon.fromTheme('zoom-original'))
        self._widget.fit_in_view_push_button.pressed.connect(self._fit_in_view)

        self._widget.load_dot_push_button.setIcon(
            QIcon.fromTheme('document-open'))
        self._widget.load_dot_push_button.pressed.connect(self._load_dot)
        self._widget.save_dot_push_button.setIcon(
            QIcon.fromTheme('document-save-as'))
        self._widget.save_dot_push_button.pressed.connect(self._save_dot)
        self._widget.save_as_svg_push_button.setIcon(
            QIcon.fromTheme('document-save-as'))
        self._widget.save_as_svg_push_button.pressed.connect(self._save_svg)
        self._widget.save_as_image_push_button.setIcon(
            QIcon.fromTheme('image'))
        self._widget.save_as_image_push_button.pressed.connect(
            self._save_image)

        self._deferred_fit_in_view.connect(self._fit_in_view,
                                           Qt.QueuedConnection)
        self._deferred_fit_in_view.emit()

        context.add_widget(self._widget)

        self.connect(self, SIGNAL('update_planning_graph'),
                     self.update_planning_graph_synchronous)

        # start the planner in a separate thread
        planning_node = HipViewerNode(ex_callback=self.update_planning_graph)
        planning_node.start()

    def save_settings(self, global_settings, perspective_settings):
        perspective_settings.set_value(
            'graph_type_combo_box_index',
            self._widget.graph_type_combo_box.currentIndex())
        perspective_settings.set_value('filter_line_edit_text',
                                       self._widget.filter_line_edit.text())
        perspective_settings.set_value(
            'quiet_check_box_state', self._widget.quiet_check_box.isChecked())
        perspective_settings.set_value(
            'auto_fit_graph_check_box_state',
            self._widget.auto_fit_graph_check_box.isChecked())
        perspective_settings.set_value(
            'highlight_connections_check_box_state',
            self._widget.highlight_connections_check_box.isChecked())

    def restore_settings(self, global_settings, perspective_settings):
        self._widget.graph_type_combo_box.setCurrentIndex(
            int(perspective_settings.value('graph_type_combo_box_index', 0)))
        self._widget.filter_line_edit.setText(
            perspective_settings.value('filter_line_edit_text', ''))
        self._widget.quiet_check_box.setChecked(
            perspective_settings.value('quiet_check_box_state', True) in
            [True, 'true'])
        self._widget.auto_fit_graph_check_box.setChecked(
            perspective_settings.value('auto_fit_graph_check_box_state', True)
            in [True, 'true'])
        self._widget.highlight_connections_check_box.setChecked(
            perspective_settings.value('highlight_connections_check_box_state',
                                       True) in [True, 'true'])

    def update_planning_graph(self, op, htree):
        self.emit(SIGNAL('update_planning_graph'), op, htree)

    def update_planning_graph_synchronous(self, op, htree):
        graph = hip.dot_from_plan_tree(htree)
        graph.layout('dot')
        self._update_graph_view(graph)

    def _update_graph_view(self, graph):
        self._graph = graph
        self._redraw_graph_view()

    def _generate_tool_tip(self, url):
        if url is not None and ':' in url:
            item_type, item_path = url.split(':', 1)
            if item_type == 'node':
                tool_tip = 'Node:\n  %s' % (item_path)
                service_names = rosservice.get_service_list(node=item_path)
                if service_names:
                    tool_tip += '\nServices:'
                    for service_name in service_names:
                        try:
                            service_type = rosservice.get_service_type(
                                service_name)
                            tool_tip += '\n  %s [%s]' % (service_name,
                                                         service_type)
                        except rosservice.ROSServiceIOException, e:
                            tool_tip += '\n  %s' % (e)
                return tool_tip
            elif item_type == 'topic':
                topic_type, topic_name, _ = rostopic.get_topic_type(item_path)
                return 'Topic:\n  %s\nType:\n  %s' % (topic_name, topic_type)
        return url
Пример #6
0
class PosesDataModel(QAbstractTableModel):

    actions_changed = Signal()
    duration_modified = Signal()

    _mime_type = 'application/x-slider-action'

    def __init__(self, editable=False):
        super(PosesDataModel, self).__init__()
        self._action_sequence = ActionSequence()
        self._editable = editable
        self._joint_columns = {}

        action = DefaultAction()
        self._add_joint(1, action, 'head_pan_joint', 'Hd Turn')
        self._add_joint(2, action, 'head_tilt_joint', 'Hd Nod')
        self._add_joint(3, action, 'torso_lift_joint', 'Torso', 2)
        self._add_joint(4, action, 'l_shoulder_pan_joint', 'Lp1')
        self._add_joint(5, action, 'l_shoulder_lift_joint', 'Ll2')
        self._add_joint(6, action, 'l_upper_arm_roll_joint', 'Lu3')
        self._add_joint(7, action, 'l_elbow_flex_joint', 'Le4')
        self._add_joint(8, action, 'l_forearm_roll_joint', 'Lf5')
        self._add_joint(9, action, 'l_wrist_flex_joint', 'Lw6')
        self._add_joint(10, action, 'l_wrist_roll_joint', 'Lr7')
        self._add_joint(11, action, 'l_gripper', 'LGrip', 3)
        self._add_joint(12, action, 'r_shoulder_pan_joint', 'Rp1')
        self._add_joint(13, action, 'r_shoulder_lift_joint', 'Rl2')
        self._add_joint(14, action, 'r_upper_arm_roll_joint', 'Ru3')
        self._add_joint(15, action, 'r_elbow_flex_joint', 'Re4')
        self._add_joint(16, action, 'r_forearm_roll_joint', 'Rf5')
        self._add_joint(17, action, 'r_wrist_flex_joint', 'Rw6')
        self._add_joint(18, action, 'r_wrist_roll_joint', 'Rr7')
        self._add_joint(19, action, 'r_gripper', 'RGrip', 3)

        # keep reference to delegates to prevent being garbaged
        self._delegates = []

    def _add_joint(self, column, action, label, header, precision=None):
        info = copy(action.get_joint_info(label))
        info['header'] = header
        info['decimals'] = precision
        self._joint_columns[column] = info

    def set_editable(self, editable):
        if self._editable != editable:
            self._editable = editable
            self.reset()

    def add_action(self, action, index=None):
        self._add_action(action, index)
        self.actions_changed.emit()
        self.duration_modified.emit()

    def _add_action(self, action, index=None):
        model_index = QModelIndex()
        if index is None or index == len(self._action_sequence.actions()):
            rows = len(self._action_sequence.actions())
            index = None
        else:
            assert (index >= 0
                    and index < len(self._action_sequence.actions()))
            rows = index

        # insert at model-index of parent-item
        self.beginInsertRows(model_index, rows, rows)
        self._action_sequence.add_action(action, index)
        self.endInsertRows()

    def move_action(self, source_index, destination_index):
        assert (source_index >= 0
                and source_index < len(self._action_sequence.actions()))
        assert (destination_index >= 0
                and destination_index <= len(self._action_sequence.actions()))
        action = self._action_sequence.actions()[source_index]
        self._remove_action(source_index)
        if destination_index > source_index:
            destination_index -= 1
        self._add_action(action, destination_index)
        self.actions_changed.emit()

    def remove_action(self, index):
        self._remove_action(index)
        self.actions_changed.emit()
        self.duration_modified.emit()

    def _remove_action(self, index):
        assert (index >= 0 and index < len(self._action_sequence.actions()))
        # delete at model-index of parent-item
        model_index = QModelIndex()
        self.beginRemoveRows(model_index, index, index)
        self._action_sequence.remove_action(index)
        self.endRemoveRows()

    def remove_all_actions(self):
        index = QModelIndex()
        rows = len(self._action_sequence.actions())
        self.beginRemoveRows(index, 0, rows - 1)
        self._action_sequence.remove_all_actions()
        self.endRemoveRows()
        self.actions_changed.emit()
        self.duration_modified.emit()

    def action_sequence(self):
        return self._action_sequence

    def rowCount(self, parent=None):
        return len(self._action_sequence.actions())

    def columnCount(self, parent=None):
        if self._editable:
            return 1 + len(self._joint_columns)
        else:
            return 1 + 1

    def data(self, index, role=None):
        if role is None:
            role = Qt.DisplayRole
        if index.row() >= 0 and index.row() < len(
                self._action_sequence.actions()):
            if role == Qt.DisplayRole:
                if index.column() == 0:
                    return '%.1f' % self._action_sequence.actions()[
                        index.row()].get_duration()
                elif not self._editable and index.column() == 1:
                    return self._action_sequence.actions()[
                        index.row()].to_string()
                elif self._editable and index.column(
                ) in self._joint_columns.keys():
                    joint_info = self._joint_columns[index.column()]
                    try:
                        value = self._action_sequence.actions()[
                            index.row()].get_value(joint_info['label'])
                        if joint_info['decimals'] is not None:
                            value = round(value, joint_info['decimals'])
                        else:
                            value = int(round(value))
                        return value
                    except:
                        return ''
            if role == Qt.EditRole:
                if index.column() == 0:
                    return self._action_sequence.actions()[
                        index.row()].get_duration()
                elif self._editable and index.column(
                ) in self._joint_columns.keys():
                    joint_info = self._joint_columns[index.column()]
                    try:
                        value = self._action_sequence.actions()[
                            index.row()].get_value(joint_info['label'])
                        if joint_info['decimals'] is not None:
                            value = round(value, joint_info['decimals'])
                        else:
                            value = int(round(value))
                        return value
                    except:
                        return ''
        return None

    def setData(self, index, value, role):
        if role == Qt.EditRole:
            if index.column() == 0:
                value = float(value)
                self._action_sequence.actions()[index.row()].set_duration(
                    value)
                self.duration_modified.emit()
                return True
            elif self._editable:
                value = float(value)
                try:
                    self._action_sequence.actions()[index.row()].update_value(
                        self._joint_columns[index.column()]['label'], value)
                except:
                    return False
                return True
        return super(PosesDataModel, self).setData(index, value, role)

    def flags(self, index):
        f = super(PosesDataModel, self).flags(index)
        if index.isValid():
            if index.column() == 0:
                f |= Qt.ItemIsEditable
            elif self._editable and index.column() in self._joint_columns.keys(
            ):
                try:
                    # only cell which have real values can be edited
                    self._action_sequence.actions()[index.row()].get_value(
                        self._joint_columns[index.column()]['label'])
                    f |= Qt.ItemIsEditable
                except:
                    pass
            f |= Qt.ItemIsDragEnabled
        f |= Qt.ItemIsDropEnabled
        return f

    def headerData(self, section, orientation, role=None):
        if role is None:
            role = Qt.DisplayRole
        if role == Qt.DisplayRole:
            if orientation == Qt.Horizontal:
                if section == 0:
                    return 'Time'
                elif not self._editable and section == 1:
                    return 'Joints'
                elif self._editable and section in self._joint_columns.keys():
                    return self._joint_columns[section]['header']
            elif orientation == Qt.Vertical:
                return 'Pose %d' % (section + 1)
        return None

    def supportedDropActions(self):
        return Qt.CopyAction | Qt.MoveAction

    def mimeTypes(self):
        return [self._mime_type]

    def mimeData(self, indexes):
        #print 'mimeData()'
        row = None
        for index in indexes:
            if index.isValid():
                if row is None:
                    row = index.row()
                if row != index.row():
                    row = None
                    break

        mimeData = QMimeData()
        if row is not None:
            mimeData.setData(self._mime_type, QByteArray.number(row))
        return mimeData

    def dropMimeData(self, data, action, row, column, parent):
        #print 'dropMimeData()'
        if action == Qt.MoveAction:
            before_row = None
            if row != -1:
                before_row = row
            elif parent.isValid():
                before_row = parent.row()
            else:
                before_row = self.rowCount()
            if data.hasFormat(self._mime_type):
                byte_array = data.data(self._mime_type)
                source_row, is_int = byte_array.toInt()
                if is_int and before_row != source_row + 1:
                    #print 'dropMimeData()', source_row, '->', before_row
                    self.move_action(source_row, before_row)
                    return True
        return super(PosesDataModel,
                     self).dropMimeData(data, action, row, column, parent)

    def add_delegates(self, table_view):
        for i in self._joint_columns.keys():
            joint_info = self._joint_columns[i]
            if joint_info['decimals'] is not None:
                delegate = DoubleSpinBoxDelegate()
                delegate.setDecimals(joint_info['decimals'])
            else:
                delegate = IntegerSpinBoxDelegate()
            delegate.setMinimum(joint_info['min'])
            delegate.setMaximum(joint_info['max'])
            delegate.setSingleStep(joint_info['single_step'])
            table_view.setItemDelegateForColumn(i, delegate)
            self._delegates.append(delegate)
Пример #7
0
# future division is important to divide integers and get as
# a result precise floating numbers (instead of truncated int)
# import compatibility functions and utilities
import sys
from time import time

from QtCore import QObject, Signal, SIGNAL

import hyperspy.external.progressbar
from tqdm import tqdm

from hyperspyui.exceptions import ProcessCanceled

# Create signal object which will handle all events
signaler = QObject()
signaler.created = Signal(object)
signaler.progress = Signal((object, int), (object, int, str))
signaler.finished = Signal(int)
signaler.cancel = Signal(int)
# This is necessary as it bugs out if not (it's a daisy chained event)


def _on_cancel(pid):
    signaler.emit(SIGNAL('cancel(int)'), pid)
signaler.on_cancel = _on_cancel

# Hook function


def _wrap(*args, **kwargs):
    """