示例#1
0
def main(name):
  try:
    from python_qt_binding.QtGui import QApplication
  except:
    print >> sys.stderr, "please install 'python_qt_binding' package!!"
    sys.exit(-1)

  masteruri = init_cfg_path()
  parser = init_arg_parser()
  args = rospy.myargv(argv=sys.argv)
  parsed_args = parser.parse_args(args[1:])
  # Initialize Qt
  global app
  app = QApplication(sys.argv)

  # decide to show main or echo dialog
  global main_form
  if parsed_args.echo:
    main_form = init_echo_dialog(name, masteruri, parsed_args.echo[0], parsed_args.echo[1], parsed_args.hz)
  else:
    main_form = init_main_window(name, masteruri, parsed_args.file)

  # resize and show the qt window
  if not rospy.is_shutdown():
    os.chdir(PACKAGE_DIR) # change path to be able to the images of descriptions
    main_form.resize(1024, 720)
    screen_size = QApplication.desktop().availableGeometry()
    if main_form.size().width() >= screen_size.width() or main_form.size().height() >= screen_size.height()-24:
      main_form.showMaximized()
    else:
      main_form.show()
    exit_code = -1
    rospy.on_shutdown(finish)
    exit_code = app.exec_()
示例#2
0
def main():
    app = QApplication(sys.argv)
    
    test_g = MainWidget()
    test_g.show()
    
    return app.exec_()
示例#3
0
def main(name):
    '''
    Start the NodeManager or EchoDialog.
    :param name: the name propagated to the rospy.init_node()
    :type name: str
    '''
    try:
        from python_qt_binding.QtGui import QApplication
    except:
        try:
            from python_qt_binding.QtWidgets import QApplication
        except:
            print >> sys.stderr, "please install 'python_qt_binding' package!!"
            sys.exit(-1)

    init_settings()
    parser = init_arg_parser()
    args = rospy.myargv(argv=sys.argv)
    parsed_args = parser.parse_args(args[1:])
    if parsed_args.muri:
        masteruri = parsed_args.muri[0]
        hostname = NameResolution.get_ros_hostname(masteruri)
        os.environ['ROS_MASTER_URI'] = masteruri
        if hostname:
            os.environ['ROS_HOSTNAME'] = hostname
    masteruri = settings().masteruri()
    # Initialize Qt
    global _QAPP
    _QAPP = QApplication(sys.argv)

    # decide to show main or echo dialog
    global _MAIN_FORM
    try:
        if parsed_args.echo:
            _MAIN_FORM = init_echo_dialog(name, masteruri, parsed_args.echo[0],
                                          parsed_args.echo[1], parsed_args.hz,
                                          parsed_args.ssh)
        else:
            _MAIN_FORM = init_main_window(name, masteruri, parsed_args.file)
    except Exception as err:
        sys.exit("%s" % err)

    exit_code = 0
    # resize and show the qt window
    if not rospy.is_shutdown():
        # change path for access to the images of descriptions
        os.chdir(settings().PACKAGE_DIR)
#    _MAIN_FORM.resize(1024, 720)
        screen_size = QApplication.desktop().availableGeometry()
        if (_MAIN_FORM.size().width() >= screen_size.width() or
                _MAIN_FORM.size().height() >= screen_size.height() - 24):
            _MAIN_FORM.showMaximized()
        else:
            _MAIN_FORM.show()
        exit_code = -1
        rospy.on_shutdown(finish)
        exit_code = _QAPP.exec_()
    return exit_code
示例#4
0
def run(gui,debug=False):
    """
    @param gui: The gui to render and execute
    """
    
    if debug:
        str_traverse = StringTraverse()
        gui.traverse(str_traverse)
        
    rospy.init_node("guiname")
    code_traverse = pyqtTraverse()
    
    app = QApplication(sys.argv)
    
    gui.traverse(code_traverse)
    sys.exit(app.exec_())
def main(name, anonymous=False):
  masteruri = init_cfg_path()

  args = rospy.myargv(argv=sys.argv)
  # decide to show main or echo dialog
  if len(args) >= 4 and args[1] == '-t':
    name = ''.join([name, '_echo'])
    anonymous = True

  try:
    from python_qt_binding.QtGui import QApplication
  except:
    print >> sys.stderr, "please install 'python-pyside' package!!"
    sys.exit(-1)
  rospy.init_node(name, anonymous=anonymous, log_level=rospy.DEBUG)
  setTerminalName(rospy.get_name())
  setProcessName(rospy.get_name())

  # Initialize Qt
  global app
  app = QApplication(sys.argv)

  # decide to show main or echo dialog
  import main_window, echo_dialog
  global main_form
  if len(args) >= 4 and args[1] == '-t':
    show_hz_only = (len(args) > 4 and args[4] == '--hz')
    main_form = echo_dialog.EchoDialog(args[2], args[3], show_hz_only, masteruri)
  else:
    local_master = init_globals(masteruri)

    #start the gui
    main_form = main_window.MainWindow(args, not local_master)

  if not rospy.is_shutdown():
    os.chdir(PACKAGE_DIR) # change path to be able to the images of descriptions
    main_form.show()
    exit_code = -1
    rospy.on_shutdown(finish)
    exit_code = app.exec_()
    def __init__(self, qTextPanel):
        self.textPanel = qTextPanel;
    
    def setText(self, theStr):
        self.textPanel.clear();
        self.textPanel.setText(theStr);
    
    def getText(self):
        # Get text field text as plain text, and convert
        # unicode to ascii, ignoring errors:
        #return self.toPlainText().encode('ascii', 'ignore');
        return self.textPanel.toPlainText().encode('utf-8');
    
    def textCursor(self):
        return self.textPanel.textCursor();

    def getCursorPos(self):
        return self.textCursor().position;

    def isEmpty(self):
        return len(self.textPanel.toPlainText()) == 0;
          
if __name__ == '__main__':
    
    app = QApplication(sys.argv);
    ui = MarkupManagementUI();
    ui.show();
    app.exec_();
    sys.exit();
        
        
                )
            except:
                print (
                    "Will attempt to start SpeakEasy in ROS mode. If fail, switch to local mode. Possibly a few seconds delay..."
                )
            speakeasyController = SpeakEasyController(scriptDir, unix_sig_notify_read_socket=rsock, stand_alone=None)
    else:
        try:
            rospy.loginfo(
                "Will attempt to start SpeakEasy in ROS mode. If fail, switch to local mode. Possibly a few seconds delay..."
            )
        except:
            print (
                "Will attempt to start SpeakEasy in ROS mode. If fail, switch to local mode. Possibly a few seconds delay..."
            )
        speakeasyController = SpeakEasyController(scriptDir, unix_sig_notify_read_socket=rsock, stand_alone=None)

    # Attach Unix signals USR1/USR2 to the sigusr1_2_handler().
    # (These signals are separate from the Qt signals!):
    signal.signal(signal.SIGUSR1, sigusr1_2_handler)
    signal.signal(signal.SIGUSR2, sigusr1_2_handler)
    # Unix signals are delivered to Qt only when Qt
    # leaves its event loop. Force that to happen
    # every half second:
    timer = QTimer()
    timer.start(500)
    timer.timeout.connect(lambda: None)

    # Enter Qt application main loop
    sys.exit(app.exec_())
a2 = QAction('add v', tb)
a2.do = add_vertical
a2.triggered.connect(a2.do)
tb.addAction(a2)

def save(self):
    global mw, settings
    settings.setValue('state', mw.saveState())
    print('saved')

def restore(self):
    global mw, settings
    if settings.contains('state'):
        restored = mw.restoreState(settings.value('state'))
        if restored:
            print('restored')
        else:
            print('restore failed')

a3 = QAction('save', tb)
a3.do = save
a3.triggered.connect(a3.do)
tb.addAction(a3)

a4 = QAction('restore', tb)
a4.do = restore
a4.triggered.connect(a4.do)
tb.addAction(a4)

app.exec_()
        label.setPalette(palette)
        label.setFont(QFont('sans', 13))
        self.track_label_layout.addWidget(label)


if __name__ == '__main__':
    import sys
    from python_qt_binding.QtGui import QApplication
    app = QApplication(sys.argv)
    widget = TimelineWidget()
    for track_name in ['l_leg', 'l_arm', 'torso', 'r_arm', 'r_leg', 'neck', 'pelvis']:
        track_type = track_name[2:] if track_name[1] == '_' else track_name
        widget.add_track(track_name, track_type)
        widget._timeline_view.scene().add_clip(track_name, '%s_1' % track_name, 1.0, 1.0, {})
        widget._timeline_view.scene().add_clip(track_name, '%s_2' % track_name, 3.0, 1.0, {})
        widget._timeline_view.scene().add_clip(track_name, '%s_3' % track_name, 5.0, 1.5, {})

    time = 0.0
    interval = 0.03
    marker = widget._timeline_view.scene().add_marker(time)
    from python_qt_binding.QtCore import QTimer
    def move_marker():
        global time, interval
        time += interval
        if time < 10.0:
            marker.set_time(time)
            QTimer.singleShot(int(interval * 1000), move_marker)

    widget.show()
    app.exec_()
示例#10
0
def main(name):
    '''
    Start the NodeManager or EchoDialog.

    :param str name: the name propagated to the :meth:`rospy.init_node`
    '''
    try:
        from python_qt_binding.QtGui import QApplication
    except Exception:
        try:
            from python_qt_binding.QtWidgets import QApplication
        except Exception:
            sys.stderr.write("please install 'python_qt_binding' package!!")
            sys.exit(-1)
    init_settings()
    global __version__
    global __date__
    __version__, __date__ = detect_version(PKG_NAME)
    parser = init_arg_parser()
    args = rospy.myargv(argv=sys.argv)
    parsed_args = parser.parse_args(args[1:])
    if parsed_args.muri:
        masteruri = parsed_args.muri[0]
        hostname = nmdhost.get_ros_hostname(masteruri)
        os.environ['ROS_MASTER_URI'] = masteruri
        if hostname:
            os.environ['ROS_HOSTNAME'] = hostname
    masteruri = settings().masteruri()
    # Initialize Qt
    global _QAPP
    _QAPP = QApplication(sys.argv)

    # decide to show main or echo dialog
    global _MAIN_FORM
    try:
        if parsed_args.echo:
            _MAIN_FORM = init_echo_dialog(name, masteruri, parsed_args.echo[0],
                                          parsed_args.echo[1], parsed_args.hz,
                                          parsed_args.ssh)
        else:
            _MAIN_FORM = init_main_window(name, masteruri, parsed_args.file, parsed_args.port)
        thread = threading.Thread(target=rospy.spin)
        thread.daemon = True
        thread.start()
        rospy.on_shutdown(finish)
    except Exception as err:
        import traceback
        print(traceback.format_exc())
        sys.exit("%s" % err)

    exit_code = 0
    # resize and show the qt window
    if not rospy.is_shutdown():
        # change path for access to the images of descriptions
        os.chdir(settings().PACKAGE_DIR)
#    _MAIN_FORM.resize(1024, 720)
        screen_size = QApplication.desktop().availableGeometry()
        if (_MAIN_FORM.size().width() >= screen_size.width() or
                _MAIN_FORM.size().height() >= screen_size.height() - 24):
            _MAIN_FORM.showMaximized()
        else:
            _MAIN_FORM.show()
        exit_code = -1
        try:
            exit_code = _QAPP.exec_()
            if nmd() is not None:
                nmd().stop()
        except Exception:
            if not rospy.is_shutdown():
                import traceback
                print(traceback.format_exc())
    return exit_code
    def set_xlim(self, limits):
        self.setAxisScale(Qwt.QwtPlot.xBottom, limits[0], limits[1])
        self._x_limits = limits

    def set_ylim(self, limits):
        self.setAxisScale(Qwt.QwtPlot.yLeft, limits[0], limits[1])
        self._y_limits = limits

    def get_xlim(self):
        return self._x_limits

    def get_ylim(self):
        return self._y_limits


if __name__ == '__main__':
    from python_qt_binding.QtGui import QApplication

    app = QApplication(sys.argv)
    plot = QwtDataPlot()
    plot.resize(700, 500)
    plot.show()
    plot.add_curve(0, '(x/500)^2')
    plot.add_curve(1, 'sin(x / 20) * 500')
    for i in range(plot._num_value_saved):
        plot.update_value(0, (i / 500.0) * (i / 5.0))
        plot.update_value(1, math.sin(i / 20.0) * 500)

    sys.exit(app.exec_())
示例#12
0
        # instance_settings.set_value(k, v)
        pass

    def restore_settings(self, plugin_settings, instance_settings):
        # TODO restore intrinsic configuration, usually using:
        # v = instance_settings.value(k)
        pass

    # def trigger_configuration(self):
    # Comment in to signal that the plugin has a way to configure
    # This will enable a setting button (gear icon) in each dock widget title bar
    # Usually used to open a modal configuration dialog


if __name__ == '__main__':

    NODE_NAME = 'easy_handeye_mover'

    rospy.init_node(NODE_NAME)
    while rospy.get_time() == 0.0:
        pass

    qapp = QApplication(sys.argv)
    lmg = CalibrationMovementsGUI()
    lmg.show()
    sys.exit(qapp.exec_())
    # TODO: alternative workflow for automatic calibration:
    # generate poses around current pose, each rotating by angle_delta in each direction
    # generate a plan to each pose and back
    # if all movements are possible, perform them in a row (at low speed)
示例#13
0
    def main(self, argv=None, standalone=None):
        # check if DBus is available
        try:
            import dbus
            del dbus
            self._dbus_available = True
        except ImportError:
            pass

        if argv is None:
            argv = sys.argv

        # extract --args and everything behind manually since argparse can not handle that
        arguments = argv[1:]
        args = []
        if '--args' in arguments:
            index = arguments.index('--args')
            args = arguments[index + 1:]
            arguments = arguments[0:index + 1]

        if standalone:
            arguments += ['-s', standalone]

        parser = ArgumentParser('usage: %prog [options]')
        self._add_arguments(parser)
        self._options = parser.parse_args(arguments)
        self._options.args = args

        # check option dependencies
        try:
            if self._options.args and not self._options.standalone_plugin and not self._options.command_start_plugin and not self._options.embed_plugin:
                raise RuntimeError(
                    'Option --args can only be used together with either --standalone, --command-start-plugin or --embed-plugin option'
                )

            list_options = (self._options.list_perspectives,
                            self._options.list_plugins)
            list_options_set = [
                opt for opt in list_options if opt is not False
            ]
            if len(list_options_set) > 1:
                raise RuntimeError(
                    'Only one --list-* option can be used at a time')

            command_options = (self._options.command_start_plugin,
                               self._options.command_switch_perspective)
            command_options_set = [
                opt for opt in command_options if opt is not None
            ]
            if len(command_options_set) > 0 and not self._dbus_available:
                raise RuntimeError(
                    'Without DBus support the --command-* options are not available'
                )
            if len(command_options_set) > 1:
                raise RuntimeError(
                    'Only one --command-* option can be used at a time (except --command-pid which is optional)'
                )
            if len(command_options_set
                   ) == 0 and self._options.command_pid is not None:
                raise RuntimeError(
                    'Option --command_pid can only be used together with an other --command-* option'
                )

            embed_options = (self._options.embed_plugin,
                             self._options.embed_plugin_serial,
                             self._options.embed_plugin_address)
            embed_options_set = [
                opt for opt in embed_options if opt is not None
            ]
            if len(command_options_set) > 0 and not self._dbus_available:
                raise RuntimeError(
                    'Without DBus support the --embed-* options are not available'
                )
            if len(embed_options_set) > 0 and len(embed_options_set) < len(
                    embed_options):
                raise RuntimeError(
                    'Missing option(s) - all \'--embed-*\' options must be set'
                )

            if len(embed_options_set) > 0 and self._options.clear_config:
                raise RuntimeError(
                    'Option --clear-config can only be used without any --embed-* option'
                )

            groups = (list_options_set, command_options_set, embed_options_set)
            groups_set = [opt for opt in groups if len(opt) > 0]
            if len(groups_set) > 1:
                raise RuntimeError(
                    'Options from different groups (--list, --command, --embed) can not be used together'
                )

        except RuntimeError as e:
            print(str(e))
            #parser.parse_args(['--help'])
            # calling --help will exit
            return 1

        # set implicit option dependencies
        if self._options.standalone_plugin is not None:
            self._options.lock_perspective = True

        # use qt/glib mainloop integration to get dbus mainloop working
        if self._dbus_available:
            from dbus.mainloop.glib import DBusGMainLoop
            from dbus import DBusException, Interface, SessionBus
            DBusGMainLoop(set_as_default=True)

        # create application context containing various relevant information
        from .application_context import ApplicationContext
        context = ApplicationContext()
        context.options = self._options

        # non-special applications provide various dbus interfaces
        if self._dbus_available:
            context.provide_app_dbus_interfaces = len(groups_set) == 0
            context.dbus_base_bus_name = 'org.ros.qt_gui'
            if context.provide_app_dbus_interfaces:
                context.dbus_unique_bus_name = context.dbus_base_bus_name + '.pid%d' % os.getpid(
                )

                # provide pid of application via dbus
                from .application_dbus_interface import ApplicationDBusInterface
                _dbus_server = ApplicationDBusInterface(
                    context.dbus_base_bus_name)

        # determine host bus name, either based on pid given on command line or via dbus application interface if any other instance is available
        if len(command_options_set) > 0 or len(embed_options_set) > 0:
            host_pid = None
            if self._options.command_pid is not None:
                host_pid = self._options.command_pid
            else:
                try:
                    remote_object = SessionBus().get_object(
                        context.dbus_base_bus_name, '/Application')
                except DBusException:
                    pass
                else:
                    remote_interface = Interface(
                        remote_object,
                        context.dbus_base_bus_name + '.Application')
                    host_pid = remote_interface.get_pid()
            if host_pid is not None:
                context.dbus_host_bus_name = context.dbus_base_bus_name + '.pid%d' % host_pid

        # execute command on host application instance
        if len(command_options_set) > 0:
            if self._options.command_start_plugin is not None:
                try:
                    remote_object = SessionBus().get_object(
                        context.dbus_host_bus_name, '/PluginManager')
                except DBusException:
                    (rc,
                     msg) = (1,
                             'unable to communicate with GUI instance "%s"' %
                             context.dbus_host_bus_name)
                else:
                    remote_interface = Interface(
                        remote_object,
                        context.dbus_base_bus_name + '.PluginManager')
                    (rc, msg) = remote_interface.start_plugin(
                        self._options.command_start_plugin,
                        ' '.join(self._options.args))
                if rc == 0:
                    print('qt_gui_main() started plugin "%s" in GUI "%s"' %
                          (msg, context.dbus_host_bus_name))
                else:
                    print(
                        'qt_gui_main() could not start plugin "%s" in GUI "%s": %s'
                        % (self._options.command_start_plugin,
                           context.dbus_host_bus_name, msg))
                return rc
            elif self._options.command_switch_perspective is not None:
                remote_object = SessionBus().get_object(
                    context.dbus_host_bus_name, '/PerspectiveManager')
                remote_interface = Interface(
                    remote_object,
                    context.dbus_base_bus_name + '.PerspectiveManager')
                remote_interface.switch_perspective(
                    self._options.command_switch_perspective)
                print(
                    'qt_gui_main() switched to perspective "%s" in GUI "%s"' %
                    (self._options.command_switch_perspective,
                     context.dbus_host_bus_name))
                return 0
            raise RuntimeError('Unknown command not handled')

        # choose selected or default qt binding
        setattr(sys, 'SELECT_QT_BINDING', self._options.qt_binding)
        from python_qt_binding import QT_BINDING

        from python_qt_binding.QtCore import qDebug, qInstallMsgHandler, QSettings, Qt, QtCriticalMsg, QtDebugMsg, QtFatalMsg, QTimer, QtWarningMsg
        from python_qt_binding.QtGui import QAction, QApplication, QIcon, QMenuBar

        from .about_handler import AboutHandler
        from .composite_plugin_provider import CompositePluginProvider
        from .help_provider import HelpProvider
        from .main_window import MainWindow
        from .perspective_manager import PerspectiveManager
        from .plugin_manager import PluginManager

        def message_handler(type_, msg):
            colored_output = 'TERM' in os.environ and 'ANSI_COLORS_DISABLED' not in os.environ
            cyan_color = '\033[36m' if colored_output else ''
            red_color = '\033[31m' if colored_output else ''
            reset_color = '\033[0m' if colored_output else ''
            if type_ == QtDebugMsg and self._options.verbose:
                print(msg, file=sys.stderr)
            elif type_ == QtWarningMsg:
                print(cyan_color + msg + reset_color, file=sys.stderr)
            elif type_ == QtCriticalMsg:
                print(red_color + msg + reset_color, file=sys.stderr)
            elif type_ == QtFatalMsg:
                print(red_color + msg + reset_color, file=sys.stderr)
                sys.exit(1)

        qInstallMsgHandler(message_handler)

        app = QApplication(argv)
        app.setAttribute(Qt.AA_DontShowIconsInMenus, False)

        self.__check_icon_theme_compliance()

        if len(embed_options_set) == 0:
            settings = QSettings(QSettings.IniFormat, QSettings.UserScope,
                                 'ros.org', self._settings_filename)
            if self._options.clear_config:
                settings.clear()

            main_window = MainWindow()
            main_window.setDockNestingEnabled(True)
            main_window.statusBar()

            def sigint_handler(*args):
                qDebug('\nsigint_handler()')
                main_window.close()

            signal.signal(signal.SIGINT, sigint_handler)
            # the timer enables triggering the sigint_handler
            timer = QTimer()
            timer.start(500)
            timer.timeout.connect(lambda: None)

            # create own menu bar to share one menu bar on Mac
            menu_bar = QMenuBar()
            menu_bar.setNativeMenuBar(False)
            if not self._options.lock_perspective:
                main_window.setMenuBar(menu_bar)

            file_menu = menu_bar.addMenu(menu_bar.tr('File'))
            action = QAction(file_menu.tr('Quit'), file_menu)
            action.setIcon(QIcon.fromTheme('application-exit'))
            action.triggered.connect(main_window.close)
            file_menu.addAction(action)

        else:
            app.setQuitOnLastWindowClosed(False)

            settings = None
            main_window = None
            menu_bar = None

        self._add_plugin_providers()

        # setup plugin manager
        plugin_provider = CompositePluginProvider(self.plugin_providers)
        plugin_manager = PluginManager(plugin_provider, context)

        if self._options.list_plugins:
            # output available plugins
            print('\n'.join(sorted(plugin_manager.get_plugins().values())))
            return 0

        help_provider = HelpProvider()
        plugin_manager.plugin_help_signal.connect(
            help_provider.plugin_help_request)

        # setup perspective manager
        if settings is not None:
            perspective_manager = PerspectiveManager(settings, context)

            if self._options.list_perspectives:
                # output available perspectives
                print('\n'.join(sorted(perspective_manager.perspectives)))
                return 0
        else:
            perspective_manager = None

        if main_window is not None:
            plugin_manager.set_main_window(main_window, menu_bar)

        if settings is not None and menu_bar is not None:
            perspective_menu = menu_bar.addMenu(menu_bar.tr('Perspectives'))
            perspective_manager.set_menu(perspective_menu)

        # connect various signals and slots
        if perspective_manager is not None and main_window is not None:
            # signal changed perspective to update window title
            perspective_manager.perspective_changed_signal.connect(
                main_window.perspective_changed)
            # signal new settings due to changed perspective
            perspective_manager.save_settings_signal.connect(
                main_window.save_settings)
            perspective_manager.restore_settings_signal.connect(
                main_window.restore_settings)
            perspective_manager.restore_settings_without_plugin_changes_signal.connect(
                main_window.restore_settings)

        if perspective_manager is not None and plugin_manager is not None:
            perspective_manager.save_settings_signal.connect(
                plugin_manager.save_settings)
            plugin_manager.save_settings_completed_signal.connect(
                perspective_manager.save_settings_completed)
            perspective_manager.restore_settings_signal.connect(
                plugin_manager.restore_settings)
            perspective_manager.restore_settings_without_plugin_changes_signal.connect(
                plugin_manager.restore_settings_without_plugins)

        if plugin_manager is not None and main_window is not None:
            # signal before changing plugins to save window state
            plugin_manager.plugins_about_to_change_signal.connect(
                main_window.save_setup)
            # signal changed plugins to restore window state
            plugin_manager.plugins_changed_signal.connect(
                main_window.restore_state)
            # signal save settings to store plugin setup on close
            main_window.save_settings_before_close_signal.connect(
                plugin_manager.close_application)
            # signal save and shutdown called for all plugins, trigger closing main window again
            plugin_manager.close_application_signal.connect(
                main_window.close, type=Qt.QueuedConnection)

        if main_window is not None and menu_bar is not None:
            about_handler = AboutHandler(main_window)
            help_menu = menu_bar.addMenu(menu_bar.tr('Help'))
            action = QAction(file_menu.tr('About'), help_menu)
            action.setIcon(QIcon.fromTheme('help-about'))
            action.triggered.connect(about_handler.show)
            help_menu.addAction(action)

        # set initial size - only used without saved configuration
        if main_window is not None:
            main_window.resize(600, 450)
            main_window.move(100, 100)

        # ensure that qt_gui/src is in sys.path
        src_path = os.path.realpath(
            os.path.join(os.path.dirname(__file__), '..'))
        if src_path not in sys.path:
            sys.path.append(src_path)

        # load specific plugin
        plugin = None
        plugin_serial = None
        if self._options.embed_plugin is not None:
            plugin = self._options.embed_plugin
            plugin_serial = self._options.embed_plugin_serial
        elif self._options.standalone_plugin is not None:
            plugin = self._options.standalone_plugin
            plugin_serial = 0
        if plugin is not None:
            plugins = plugin_manager.find_plugins_by_name(plugin)
            if len(plugins) == 0:
                print('qt_gui_main() found no plugin matching "%s"' % plugin)
                return 1
            elif len(plugins) > 1:
                print(
                    'qt_gui_main() found multiple plugins matching "%s"\n%s' %
                    (plugin, '\n'.join(plugins.values())))
                return 1
            plugin = plugins.keys()[0]

        qDebug('QtBindingHelper using %s' % QT_BINDING)

        plugin_manager.discover()

        self._caching_hook()

        if self._options.reload_import:
            qDebug(
                'ReloadImporter() automatically reload all subsequent imports')
            from .reload_importer import ReloadImporter
            _reload_importer = ReloadImporter()
            self._add_reload_paths(_reload_importer)
            _reload_importer.enable()

        # switch perspective
        if perspective_manager is not None:
            if not plugin:
                perspective_manager.set_perspective(self._options.perspective)
            else:
                perspective_manager.set_perspective(
                    plugin, hide_and_without_plugin_changes=True)

        # load specific plugin
        if plugin:
            plugin_manager.load_plugin(plugin, plugin_serial,
                                       self._options.args)

        if main_window is not None:
            main_window.show()

        return app.exec_()
示例#14
0
def main():
    global logger
    global item
    global rpc_client
    global linphone_wrap
    global config


    args = sys.argv[1:]
    parser = mk_parser()
    options = parser.parse_args(args)
    setup_logging(options.log_config)
    logger = logging.getLogger(__name__)

    import mhlinphone_wrapper
    from linphone import linphone
    from wrappers import common
    from lp_rpc_server import lp_rpc_server
    from lp_config import LPConfig

    from python_qt_binding.QtGui import QApplication
    from python_qt_binding.QtGui import QWidget
    from python_qt_binding.QtGui import QDesktopWidget
    
    app = QApplication(sys.argv)
    preview_widget=QWidget()
    view_widget=QWidget()

    for w in [preview_widget,view_widget]:
        w.setBaseSize(300,300)
        w.show()
        wid = w.winId()
        print("WID %s %s" % (hex(wid), int(wid)))

    screen = QDesktopWidget()
    preview_widget.move(screen.width() - preview_widget.width(), 0)
    view_widget.move(screen.width() - view_widget.width(), screen.height() - view_widget.height())

    config=None
    if options.config_file:
        config = LPConfig(options.config_file)

    linphone_wrap = mhlinphone_wrapper.MHLinphoneWrapper(rc_config_file=options.linphonerc,
        config=config)
    linphone_wrap.init()

    if options.xmlrpcsrv:
        rpc_funcs = lp_rpc_server.MHLPFuncs(linphone_wrap,
            quit_func=quit_app, show_func=show)

        addr, port = (options.xmlrpcsrv + ':8000').split(':')[:2]
        rpc_server = lp_rpc_server.LPRpcServer(linphone_wrap, addr, int(port),
            rpc_funcs)
        rpc_server.start_in_thread()
    else:
        rpc_server = None

    if options.auto_answer:
        linphone_wrap.register_callback(linphone_wrap.EVT.INCOMING,
            auto_answer)

    linphone_wrap.set_vvideo(int(view_widget.winId()))
    linphone_wrap.set_pvideo(int(preview_widget.winId()))

    linphone_wrap.register_callback(linphone_wrap.EVT.RMT_PREVIEW_SNAPSHOT, unzip_test)

    addr = linphone_wrap.config.get('test.address')
    port = linphone_wrap.config.get('test.port')
    rpc_client = xmlrpclib.ServerProxy('http://'+addr+':'+str(port)+'/MH_LP')


    def dirfind(str, *objs):
        ret = []
        if not objs:
            objs = dir(linphone)
        for obj in objs:
            ret.extend([ (obj, v) for v in dir(obj) if str in v.lower() ])
        return ret


    def start(fname): #open file under win
        os.system('cmd /c start ' + fname)

    if options.cli:
        from mh_cli import CLI
        namespace = dict(
            dirfind=dirfind,
            start=start,
            linphone=linphone,
            os=os,
            app=app,
            preview_widget=preview_widget,
            view_widget=view_widget,
            mhlinphone_wrapper=mhlinphone_wrapper,
            lin=linphone_wrap,
            args=args,
            options=options,
            logger=logger,
            rpc_server=rpc_server,
            rpc_client=rpc_client,
            remote_sip_addr=linphone_wrap.config.get('test.remote_sip_addr'),
            local_sip_addr=linphone_wrap.config.get('local_sip_addr'),
            item=item,
            sce= Scenarios,
            auto_ans= auto_answer,
        )
        cli = CLI(options, namespace=namespace)
        cli.run_as_thread(daemon=False)

    exitcode = app.exec_()
    sys.exit(exitcode)