コード例 #1
0
ファイル: NH.py プロジェクト: regina-book/tfc-nacl
def dbus_receiver():
    """
    Start Qt loop that loads messages from Pidgin.

    :return: [no return value]
    """

    DBusQtMainLoop(set_as_default=True)
    bus = SessionBus()
    bus.add_signal_receiver(pidgin_to_rxm_queue,
                            dbus_interface="im.pidgin.purple.PurpleInterface",
                            signal_name="ReceivedImMsg")
コード例 #2
0
ファイル: vibra.py プロジェクト: proximate/proximate
class Vibra_Plugin(Plugin):
    def __init__(self):
        DBusGMainLoop(set_as_default=True)

        self.bus = SystemBus()
        self.sessionbus = SessionBus()
        try:
            self.mce = self.bus.get_object("com.nokia.mce", "/com/nokia/mce")
        except DBusException:
            warning("Nokia MCE not found. Vibra is disabled\n")
            return

        self.profiled = self.sessionbus.get_object("com.nokia.profiled", "/com/nokia/profiled")

        self.sessionbus.add_signal_receiver(
            self.profile_changed_handler,
            "profile_changed",
            "com.nokia.profiled",
            "com.nokia.profiled",
            "/com/nokia/profiled",
        )

        profile = self.profiled.get_profile(dbus_interface="com.nokia.profiled")
        self.get_vibra_enabled(profile)

        self.register_plugin(PLUGIN_TYPE_VIBRA)

    def ready(self):
        self.notification = get_plugin_by_type(PLUGIN_TYPE_NOTIFICATION)

        sendfile = get_plugin_by_type(PLUGIN_TYPE_SEND_FILE)
        sendfile.receive_cb.append(self.file_receive)

    def get_vibra_enabled(self, profile):
        self.enabled = (
            self.profiled.get_value(profile, "vibrating.alert.enabled", dbus_interface="com.nokia.profiled") == "On"
        )
        debug("Vibra enabled: %s\n" % self.enabled)

    def profile_changed_handler(self, foo, bar, profile, *args):
        self.get_vibra_enabled(profile)

    def vibrate(self):
        if self.enabled:
            self.mce.req_vibrator_pattern_activate("PatternChatAndEmail", dbus_interface="com.nokia.mce.request")

    def file_receive(self, cb, user, fname):
        self.vibrate()

    def user_appears(self, user):
        if user.get("friend"):
            self.vibrate()
コード例 #3
0
    def run_client(self):
        bus = SessionBus()
        obj = bus.get_object(CROSS_TEST_BUS_NAME, CROSS_TEST_PATH)
        self.obj = obj

        self.run_synchronous_tests(obj)

        # Signal tests
        logger.info("Binding signal handler for Triggered")
        # FIXME: doesn't seem to work when going via the Interface method
        # FIXME: should be possible to ask the proxy object for its
        # bus name
        bus.add_signal_receiver(self.triggered_cb, 'Triggered',
                                INTERFACE_SIGNAL_TESTS,
                                CROSS_TEST_BUS_NAME,
                                path_keyword='sender_path')
        logger.info("method/signal: Triggering signal")
        self.expected.add('%s.Trigger' % INTERFACE_TESTS)
        Interface(obj, INTERFACE_TESTS).Trigger(u'/Where/Ever', dbus.UInt64(42), reply_handler=self.trigger_returned_cb, error_handler=self.trigger_error_handler)
コード例 #4
0
    def run_client(self):
        bus = SessionBus()
        obj = bus.get_object(CROSS_TEST_BUS_NAME, CROSS_TEST_PATH)
        self.obj = obj

        self.run_synchronous_tests(obj)

        # Signal tests
        logger.info("Binding signal handler for Triggered")
        # FIXME: doesn't seem to work when going via the Interface method
        # FIXME: should be possible to ask the proxy object for its
        # bus name
        bus.add_signal_receiver(self.triggered_cb,
                                'Triggered',
                                INTERFACE_SIGNAL_TESTS,
                                CROSS_TEST_BUS_NAME,
                                path_keyword='sender_path')
        logger.info("method/signal: Triggering signal")
        self.expected.add('%s.Trigger' % INTERFACE_TESTS)
        Interface(obj, INTERFACE_TESTS).Trigger(
            '/Where/Ever',
            dbus.UInt64(42),
            reply_handler=self.trigger_returned_cb,
            error_handler=self.trigger_error_handler)
コード例 #5
0
class SSTrigger:
    def __init__(self):
        DBusGMainLoop(set_as_default=True)
        self.mem='ActiveChanged'
        self.dest='org.gnome.ScreenSaver'
        self.bus=SessionBus()
        self.loop=MainLoop()
        self.bus.add_signal_receiver(self.catch,self.mem,self.dest)

    def catch(self,ssOn):
        conn = mdb.connect('localhost', 'root','mysql_password', 'working_time');
        cursor = conn.cursor()
        now = datetime.datetime.now()

        if ssOn == 1: #Screensaver turned on
            sql = "UPDATE working_time SET end='%s' WHERE date='%s' AND end='0:0'"\
                    %(now.strftime("%H:%M"),now.strftime("%Y-%m-%d"))
            #logging.info(" sql=%s "%sql)
            logging.info("end=%s" % str(now.strftime("%H:%M")))
            res = cursor.execute(sql)
            if conn.affected_rows() != 1:
                cursor.execute("SELECT * from working_time")
                if cursor.rowcount != 1: # ignore error if it is a very first record in database
                    logging.error("ERROR!!! It should be only one (the last) record with end=0:0")

        else: #Screensaver turned off
            sql = "INSERT INTO working_time (date, start, end) VALUES('%s','%s','%s')"\
                    %(now.strftime("%Y-%m-%d"),now.strftime("%H:%M"),"0:0")
            #logging.info(" sql=%s "%sql)
            res=cursor.execute(sql)
            logging.info("start=%s "%now.strftime("%H:%M"))
            os.system("xmessage -nearmouse 'If you were out then start: log_working_time.py break'")

        conn.commit()	
        cursor.close()
        conn.close()
コード例 #6
0
class _ISkypeAPI(_ISkypeAPIBase):
    def __init__(self, handler, opts):
        _ISkypeAPIBase.__init__(self, opts)
        self.RegisterHandler(handler)
        self.skype_in = self.skype_out = self.dbus_name_owner_watch = None
        self.bus = opts.pop('Bus', None)
        try:
            mainloop = opts.pop('MainLoop')
            if self.bus is not None:
                raise TypeError(
                    'Bus and MainLoop cannot be used at the same time!')
        except KeyError:
            if self.bus is None:
                import dbus.mainloop.glib
                import gobject
                gobject.threads_init()
                dbus.mainloop.glib.threads_init()
                mainloop = dbus.mainloop.glib.DBusGMainLoop()
                self.mainloop = gobject.MainLoop()
        if self.bus is None:
            from dbus import SessionBus
            self.bus = SessionBus(private=True, mainloop=mainloop)
        if opts:
            raise TypeError('Unexpected parameter(s): %s' %
                            ', '.join(opts.keys()))

    def run(self):
        self.DebugPrint('thread started')
        if hasattr(self, 'mainloop'):
            self.mainloop.run()
        self.DebugPrint('thread finished')

    def Close(self):
        if hasattr(self, 'mainloop'):
            self.mainloop.quit()
        self.skype_in = self.skype_out = None
        if self.dbus_name_owner_watch is not None:
            self.bus.remove_signal_receiver(self.dbus_name_owner_watch)
        self.dbus_name_owner_watch = None
        self.DebugPrint('closed')

    def SetFriendlyName(self, FriendlyName):
        self.FriendlyName = FriendlyName
        if self.skype_out:
            self.SendCommand(ICommand(-1, 'NAME %s' % FriendlyName))

    def StartWatcher(self):
        self.dbus_name_owner_watch = self.bus.add_signal_receiver(
            self.dbus_name_owner_changed,
            'NameOwnerChanged',
            'org.freedesktop.DBus',
            'org.freedesktop.DBus',
            '/org/freedesktop/DBus',
            arg0='com.Skype.API')

    def __Attach_ftimeout(self):
        self.wait = False

    def Attach(self, Timeout=30000, Wait=True):
        try:
            if not self.isAlive():
                self.StartWatcher()
                self.start()
        except AssertionError:
            pass
        try:
            self.wait = True
            t = threading.Timer(Timeout / 1000.0, self.__Attach_ftimeout)
            if Wait:
                t.start()
            while self.wait:
                if not Wait:
                    self.wait = False
                try:
                    if not self.skype_out:
                        self.skype_out = self.bus.get_object(
                            'com.Skype.API', '/com/Skype')
                    if not self.skype_in:
                        self.skype_in = _SkypeNotifyCallback(
                            self.bus, self.notify)
                except dbus.DBusException:
                    if not Wait:
                        break
                    time.sleep(1.0)
                else:
                    break
            else:
                raise ISkypeAPIError('Skype attach timeout')
        finally:
            t.cancel()
        c = ICommand(-1, 'NAME %s' % self.FriendlyName, '', True, Timeout)
        if self.skype_out:
            self.SendCommand(c)
        if c.Reply != 'OK':
            self.skype_out = None
            self.SetAttachmentStatus(apiAttachRefused)
            return
        self.SendCommand(ICommand(-1, 'PROTOCOL %s' % self.Protocol))
        self.SetAttachmentStatus(apiAttachSuccess)

    def IsRunning(self):
        try:
            self.bus.get_object('com.Skype.API', '/com/Skype')
            return True
        except dbus.DBusException:
            return False

    def Start(self, Minimized=False, Nosplash=False):
        # options are not supported as of Skype 1.4 Beta for Linux
        if not self.IsRunning():
            import os
            if os.fork() == 0:  # we're child
                os.setsid()
                os.execlp('skype')

    def Shutdown(self):
        import os
        from signal import SIGINT
        fh = os.popen('ps -o %p --no-heading -C skype')
        pid = fh.readline().strip()
        fh.close()
        if pid:
            os.kill(int(pid), SIGINT)
            self.skype_in = self.skype_out = None

    def SendCommand(self, Command):
        if not self.skype_out:
            self.Attach(Command.Timeout)
        self.CommandsStackPush(Command)
        self.CallHandler('send', Command)
        com = u'#%d %s' % (Command.Id, Command.Command)
        self.DebugPrint('->', repr(com))
        if Command.Blocking:
            Command._event = event = threading.Event()
        else:
            Command._timer = timer = threading.Timer(Command.Timeout / 1000.0,
                                                     self.CommandsStackPop,
                                                     (Command.Id, ))
        try:
            result = self.skype_out.Invoke(com)
        except dbus.DBusException, err:
            raise ISkypeAPIError(str(err))
        if result.startswith(u'#%d ' % Command.Id):
            self.notify(result)
        if Command.Blocking:
            event.wait(Command.Timeout / 1000.0)
            if not event.isSet():
                raise ISkypeAPIError('Skype command timeout')
        else:
            timer.start()
コード例 #7
0
class Server(SingleTestsImpl, TestsImpl, SignalTestsImpl):
    def triggered_by_client(self, parameter1, parameter2, sender, sender_path):
        # Called when the client emits TestSignals.Trigger from any object.
        logger.info('signal/callback: Triggered by client (%s:%s): (%r,%r)',
                    sender, sender_path, parameter1, parameter2)
        tested_things.add(INTERFACE_SIGNAL_TESTS + '.Trigger')
        dbus.Interface(dbus.SessionBus().get_object(sender, sender_path),
                       INTERFACE_CALLBACK_TESTS).Response(
                           parameter1, parameter2)
        logger.info('signal/callback: Sent Response')


if __name__ == '__main__':
    bus = SessionBus()
    bus_name = BusName(CROSS_TEST_BUS_NAME, bus=bus)
    loop = gobject.MainLoop()
    obj = Server(bus_name, CROSS_TEST_PATH, loop.quit)
    objects[CROSS_TEST_PATH] = obj
    bus.add_signal_receiver(obj.triggered_by_client,
                            signal_name='Trigger',
                            dbus_interface=INTERFACE_SIGNAL_TESTS,
                            named_service=None,
                            path=None,
                            sender_keyword='sender',
                            path_keyword='sender_path',
                            utf8_strings=True)

    logger.info("running...")
    loop.run()
    logger.info("main loop exited.")
コード例 #8
0
class Server(SingleTestsImpl, TestsImpl, SignalTestsImpl):

    def triggered_by_client(self, parameter1, parameter2, sender, sender_path):
        # Called when the client emits TestSignals.Trigger from any object.
        logger.info('signal/callback: Triggered by client (%s:%s): (%r,%r)', sender, sender_path, parameter1, parameter2)
        tested_things.add(INTERFACE_SIGNAL_TESTS + '.Trigger')
        dbus.Interface(dbus.SessionBus().get_object(sender, sender_path),
                       INTERFACE_CALLBACK_TESTS).Response(parameter1, parameter2)
        logger.info('signal/callback: Sent Response')



if __name__ == '__main__':
    bus = SessionBus()
    bus_name = BusName(CROSS_TEST_BUS_NAME, bus=bus)
    loop = gobject.MainLoop()
    obj = Server(bus_name, CROSS_TEST_PATH, loop.quit)
    objects[CROSS_TEST_PATH] = obj
    bus.add_signal_receiver(obj.triggered_by_client,
                            signal_name='Trigger',
                            dbus_interface=INTERFACE_SIGNAL_TESTS,
                            named_service=None,
                            path=None,
                            sender_keyword='sender',
                            path_keyword='sender_path',
                            utf8_strings=True)

    logger.info("running...")
    loop.run()
    logger.info("main loop exited.")
コード例 #9
0
ファイル: posix_dbus.py プロジェクト: brianhlin/htcondor
class _ISkypeAPI(_ISkypeAPIBase):
    def __init__(self, handler, opts):
        _ISkypeAPIBase.__init__(self, opts)
        self.RegisterHandler(handler)
        self.skype_in = self.skype_out = self.dbus_name_owner_watch = None
        self.bus = opts.pop('Bus', None)
        try:
            mainloop = opts.pop('MainLoop')
            if self.bus is not None:
                raise TypeError('Bus and MainLoop cannot be used at the same time!')
        except KeyError:
            if self.bus is None:
                import dbus.mainloop.glib
                import gobject
                gobject.threads_init()
                dbus.mainloop.glib.threads_init()
                mainloop = dbus.mainloop.glib.DBusGMainLoop()
                self.mainloop = gobject.MainLoop()
        if self.bus is None:
            from dbus import SessionBus
            self.bus = SessionBus(private=True, mainloop=mainloop)
        if opts:
            raise TypeError('Unexpected parameter(s): %s' % ', '.join(opts.keys()))

    def run(self):
        self.DebugPrint('thread started')
        if hasattr(self, 'mainloop'):
            self.mainloop.run()
        self.DebugPrint('thread finished')

    def Close(self):
        if hasattr(self, 'mainloop'):
            self.mainloop.quit()
        self.skype_in = self.skype_out = None
        if self.dbus_name_owner_watch is not None:
            self.bus.remove_signal_receiver(self.dbus_name_owner_watch)
        self.dbus_name_owner_watch = None
        self.DebugPrint('closed')

    def SetFriendlyName(self, FriendlyName):
        self.FriendlyName = FriendlyName
        if self.skype_out:
            self.SendCommand(ICommand(-1, 'NAME %s' % FriendlyName))

    def StartWatcher(self):
        self.dbus_name_owner_watch = self.bus.add_signal_receiver(self.dbus_name_owner_changed,
            'NameOwnerChanged',
            'org.freedesktop.DBus',
            'org.freedesktop.DBus',
            '/org/freedesktop/DBus',
            arg0='com.Skype.API')

    def __Attach_ftimeout(self):
        self.wait = False

    def Attach(self, Timeout=30000, Wait=True):
        try:
            if not self.isAlive():
                self.StartWatcher()
                self.start()
        except AssertionError:
            pass
        try:
            self.wait = True
            t = threading.Timer(Timeout / 1000.0, self.__Attach_ftimeout)
            if Wait:
                t.start()
            while self.wait:
                if not Wait:
                    self.wait = False
                try:
                    if not self.skype_out:
                        self.skype_out = self.bus.get_object('com.Skype.API', '/com/Skype')
                    if not self.skype_in:
                        self.skype_in = _SkypeNotifyCallback(self.bus, self.notify)
                except dbus.DBusException:
                    if not Wait:
                        break
                    time.sleep(1.0)
                else:
                    break
            else:
                raise ISkypeAPIError('Skype attach timeout')
        finally:
            t.cancel()
        c = ICommand(-1, 'NAME %s' % self.FriendlyName, '', True, Timeout)
        if self.skype_out:
            self.SendCommand(c)
        if c.Reply != 'OK':
            self.skype_out = None
            self.SetAttachmentStatus(apiAttachRefused)
            return
        self.SendCommand(ICommand(-1, 'PROTOCOL %s' % self.Protocol))
        self.SetAttachmentStatus(apiAttachSuccess)

    def IsRunning(self):
        try:
            self.bus.get_object('com.Skype.API', '/com/Skype')
            return True
        except dbus.DBusException:
            return False

    def Start(self, Minimized=False, Nosplash=False):
        # options are not supported as of Skype 1.4 Beta for Linux
        if not self.IsRunning():
            import os
            if os.fork() == 0: # we're child
                os.setsid()
                os.execlp('skype')

    def Shutdown(self):
        import os
        from signal import SIGINT
        fh = os.popen('ps -o %p --no-heading -C skype')
        pid = fh.readline().strip()
        fh.close()
        if pid:
            os.kill(int(pid), SIGINT)
            self.skype_in = self.skype_out = None

    def SendCommand(self, Command):
        if not self.skype_out:
            self.Attach(Command.Timeout)
        self.CommandsStackPush(Command)
        self.CallHandler('send', Command)
        com = u'#%d %s' % (Command.Id, Command.Command)
        self.DebugPrint('->', repr(com))
        if Command.Blocking:
            Command._event = event = threading.Event()
        else:
            Command._timer = timer = threading.Timer(Command.Timeout / 1000.0, self.CommandsStackPop, (Command.Id,))
        try:
            result = self.skype_out.Invoke(com)
        except dbus.DBusException, err:
            raise ISkypeAPIError(str(err))
        if result.startswith(u'#%d ' % Command.Id):
            self.notify(result)
        if Command.Blocking:
            event.wait(Command.Timeout / 1000.0)
            if not event.isSet():
                raise ISkypeAPIError('Skype command timeout')
        else:
            timer.start()
コード例 #10
0
class Py3status:
    """ """

    # available configuration parameters
    button_next = None
    button_next_player = None
    button_prev_player = None
    button_previous = None
    button_stop = None
    button_switch_to_top_player = None
    button_toggle = 1
    cache_timeout = 0.5
    format = "[{artist} - ][{title}] {previous} {toggle} {next}"
    format_none = "no player running"
    icon_next = "\u25b9"
    icon_pause = "\u25eb"
    icon_play = "\u25b7"
    icon_previous = "\u25c3"
    icon_stop = "\u25a1"
    max_width = None
    player_hide_non_canplay = []
    player_priority = []
    state_pause = "\u25eb"
    state_play = "\u25b7"
    state_stop = "\u25a1"

    def post_config_hook(self):
        if self.py3.is_gevent():
            raise Exception(STRING_GEVENT)
        self._name_owner_change_match = None
        self._kill = False
        self._mpris_players: dict[Player] = {}
        self._identity_cache = {}
        self._identity_index = {}
        self._priority_cache = {}
        self._player: [Player, None] = None
        self._tries = 0
        self._empty_response = {
            "album": None,
            "artist": None,
            "length": None,
            "title": None,
            "nowplaying": None,
            "time": None,
            "state": None,
            "player": None,
            # for debugging ;p
            "full_name": None,
        }

        self._states = {
            "pause": {
                "action": "Pause",
                "clickable": "CanPause",
                "icon": self.icon_pause,
                "inactive": [STATE.Stopped, STATE.Paused],
            },
            "play": {
                "action": "Play",
                "clickable": "CanPlay",
                "icon": self.icon_play,
                "inactive": [STATE.Playing],
            },
            "stop": {
                "action": "Stop",
                "clickable": "CanControl",
                "icon": self.icon_stop,
                "inactive": [STATE.Stopped],
            },
            "next": {
                "action": "Next",
                "clickable": "CanGoNext",
                "icon": self.icon_next,
            },
            "previous": {
                "action": "Previous",
                "clickable": "CanGoPrevious",
                "icon": self.icon_previous,
            },
            "toggle": {
                "action": "PlayPause",
                "clickable": "CanPause",
                # Not used, but it will be set dynamically with player state map.
                "icon": None,
            },
        }

        self._state_icon_color_map = {
            STATE.Playing: {
                "state_icon": self.state_play,
                "color": self.py3.COLOR_PLAYING or self.py3.COLOR_GOOD,
                "toggle_icon": self.state_pause,
                "cached_until": self.cache_timeout,
            },
            STATE.Paused: {
                "state_icon": self.state_pause,
                "color": self.py3.COLOR_PAUSED or self.py3.COLOR_DEGRADED,
                "toggle_icon": self.state_play,
                "cached_until": self.py3.CACHE_FOREVER,
            },
            STATE.Stopped: {
                "state_icon": self.state_stop,
                "color": self.py3.COLOR_STOPPED or self.py3.COLOR_BAD,
                "toggle_icon": self.state_play,
                "cached_until": self.py3.CACHE_FOREVER,
            },
        }

        self._color_active = self.py3.COLOR_CONTROL_ACTIVE or self.py3.COLOR_GOOD
        self._color_inactive = self.py3.COLOR_CONTROL_INACTIVE or self.py3.COLOR_BAD

        self._format_contains_metadata = False
        self._metadata_keys = ["album", "artist", "title", "nowplaying", "length"]
        for key in self._metadata_keys:
            if self.py3.format_contains(self.format, key):
                self._format_contains_metadata = True
                break

        self._format_contains_control_buttons = False
        self._used_can_properties = []
        for key, value in self._states.items():
            if self.py3.format_contains(self.format, key):
                self._format_contains_control_buttons = True
                self._used_can_properties.append(value["clickable"])

        if (
            len(self.player_hide_non_canplay)
            and "CanPlay" not in self._used_can_properties
        ):
            self._used_can_properties.append("CanPlay")

        self._format_contains_time = self.py3.format_contains(self.format, "time")
        self._button_cache_flush = None
        if 2 not in [
            self.button_next,
            self.button_next_player,
            self.button_prev_player,
            self.button_previous,
            self.button_stop,
            self.button_switch_to_top_player,
            self.button_toggle,
        ]:
            self._button_cache_flush = 2

        if self.player_priority:
            try:
                self._random_player_priority = self.player_priority.index("*")
            except ValueError:
                self._random_player_priority = False
        else:
            self._random_player_priority = 0

        # start last
        self._dbus_loop = DBusGMainLoop()
        self._dbus = SessionBus(mainloop=self._dbus_loop)
        self._start_listener()

    def _start_loop(self):
        self._loop = GLib.MainLoop()
        GLib.timeout_add(1000, self._timeout)
        try:
            self._loop.run()
        except KeyboardInterrupt:
            # This branch is only needed for the test mode
            self._kill = True

    @staticmethod
    def _is_mediaplayer_interface(player_id):
        return player_id.startswith(Interfaces.MEDIA_PLAYER)

    def _dbus_name_owner_changed(self, name, old_owner, new_owner):
        if not self._is_mediaplayer_interface(name):
            return
        if new_owner:
            self._add_player(name)
        if old_owner:
            self._remove_player(name)
        self._set_player()

    def _set_player(self, update=True):
        """
        Sort the current players into priority order and set self._player
        Players are ordered by working state, then by preference supplied by
        user and finally by instance if a player has more than one running.
        """
        players = []
        for name, player in self._mpris_players.items():
            player_priority_tuple = player.priority_tuple
            if player_priority_tuple:
                players.append(player_priority_tuple)

        new_top_player_id = None
        if players:
            new_top_player_id = sorted(players)[0][3]

        self._set_data_entry_point_by_name_key(new_top_player_id, update)

    def _player_on_change(self, interface_name, data, invalidated_properties, sender):
        """
        Monitor a player and update its status.
        """
        pass

    def _add_player(self, player_id):
        """
        Add player to mpris_players
        """
        player_id_parts_list = player_id.split(".")
        name_from_id = player_id_parts_list[3]

        identity = self._identity_cache.get(name_from_id)
        if not identity:
            dMediaPlayer = dMediaPlayer2(dbus_interface_info={"dbus_uri": player_id})
            identity = str(dMediaPlayer.Identity)
            self._identity_cache[name_from_id] = identity

        if self.player_priority:
            # Expected value: numeric / False, None is cache miss.
            priority = self._priority_cache.get(name_from_id, None)
            if priority is None:
                for i, _player in enumerate(self.player_priority):
                    if _player == name_from_id or _player == identity:
                        priority = i
                        break

                if priority is None:
                    priority = self._random_player_priority
                self._priority_cache[identity] = priority

            if not isinstance(priority, int):
                return

        else:
            priority = 0

        identity_index = self._identity_index.get(identity, 0)
        if identity_index:
            self._identity_index[identity] += 1
        else:
            self._identity_index[identity] = 1

        name_with_instance = ".".join(player_id_parts_list[3:])

        player = Player(
            self,
            player_id=player_id,
            name_from_id=name_from_id,
            name_with_instance=name_with_instance,
            name_priority=priority,
            identity=identity,
            identity_index=identity_index,
        )

        self._mpris_players[player_id] = player

    def _remove_player(self, player_id):
        """
        Remove player from mpris_players
        """
        if self._mpris_players.get(player_id):
            del self._mpris_players[player_id]

    def _get_players(self):
        for player in get_players_uri():
            try:
                # str(player) helps avoid to use dbus.Str(*) as dict key
                self._add_player(str(player))
            except DBusException:
                continue

        self._set_player()

    def _start_listener(self):
        self._get_players()

        self._name_owner_change_match = self._dbus.add_signal_receiver(
            handler_function=self._dbus_name_owner_changed,
            dbus_interface="org.freedesktop.DBus",
            signal_name="NameOwnerChanged",
        )

        # Start listening things after initiating players.
        t = Thread(target=self._start_loop)
        t.daemon = True
        t.start()

    def _timeout(self):
        if self._kill:
            self._loop.quit()
            sys.exit(0)

    def _set_data_entry_point_by_name_key(self, new_active_player_key, update=True):
        if self._player is None or new_active_player_key != self._player.id:
            self._player = self._mpris_players.get(new_active_player_key, None)
            if self._player:
                self._player.prepare_output()

        if update:
            self.py3.update()

    def kill(self):
        self._kill = True
        if self._name_owner_change_match:
            self.parent._dbus._clean_up_signal_match(self._name_owner_change_match)

    def mpris(self):
        """
        Get the current output format and return it.
        """
        if self._kill:
            raise KeyboardInterrupt

        current_player = self._player
        cached_until = self.py3.CACHE_FOREVER
        color = self.py3.COLOR_BAD

        if current_player:
            current_player_id = str(current_player.id)
            current_state_map = current_player.state_map
            data = current_player.data

            if current_player_id == self._player.id:
                if self._format_contains_time:
                    cached_until = self.py3.time_in(
                        seconds=current_state_map.get("cached_until"), sync_to=0
                    )

                placeholders = {"state": current_state_map["state_icon"]}
                color = current_state_map["color"]
                composite = self.py3.safe_format(
                    self.format,
                    dict(self._empty_response, **placeholders, **data),
                    max_width=self.max_width,
                )
            else:
                # The player changed during our processing
                # This is usually due to something like a player being killed
                # whilst we are checking its details
                # Retry but limit the number of attempts
                self._tries += 1
                if self._tries < 3:
                    return self.mpris()

                # Max retries hit we need to output something
                return {
                    # Can't decide what is good time to restart 3 retry cycle
                    "cached_until": self.py3.time_in(10),
                    "color": self.py3.COLOR_BAD,
                    "composite": [
                        {
                            "full_text": "Something went wrong",
                            "color": self.py3.COLOR_BAD,
                        }
                    ],
                }

        else:
            composite = [{"full_text": self.format_none, "color": color}]

        # we are outputting so reset tries
        self._tries = 0

        response = {
            "cached_until": cached_until,
            "color": color,
            "composite": composite,
        }
        return response

    def on_click(self, event):
        """
        Handles click events
        """
        index = event["index"]
        button = event["button"]

        if not self._player:
            return

        if button == self._button_cache_flush:
            self._player.metadata = None
            self._player.state = None

        elif index not in self._states:
            if button == self.button_toggle:
                return self._player.send_mpris_action("toggle")
            elif button == self.button_stop:
                return self._player.send_mpris_action("stop")
            elif button == self.button_next:
                return self._player.send_mpris_action("next")
            elif button == self.button_previous:
                return self._player.send_mpris_action("previous")
            elif button == self.button_switch_to_top_player:
                return self._set_player(update=False)

            elif button == self.button_prev_player or button == self.button_next_player:
                switchable_players = []
                order_asc = button == self.button_next_player
                current_player_index = False
                for key, player in self._mpris_players.items():
                    if player.state == self._player.state and not player.hide:
                        if not current_player_index:
                            if player.id == self._player.id:
                                current_player_index = len(switchable_players)
                                if order_asc:
                                    continue

                        switchable_players.append(key)
                        if current_player_index:
                            if order_asc:
                                break
                            else:
                                if current_player_index != 0:
                                    break

                if len(switchable_players):
                    try:
                        if order_asc:
                            next_index = current_player_index % len(switchable_players)
                        else:
                            next_index = (current_player_index - 1) % len(
                                switchable_players
                            )

                        self._set_data_entry_point_by_name_key(
                            switchable_players[next_index], update=False
                        )

                    except KeyError:
                        pass

            else:
                return

        elif button == 1:
            self._player.send_mpris_action(index)
コード例 #11
0
from dbus import SessionBus, Interface
import gobject
from dbus.mainloop.glib import DBusGMainLoop


def handler(*args, **kwargs):
    if 'RemoteVolumeMonitor' in kwargs[
            'dbus_interface'] and 'VolumeAdded' in kwargs['DriveChanged']:
        print "-" * 30
        print kwargs
        print args
        lproperties = []
        lproperties = args
        for prop in lproperties:
            print prop


DBusGMainLoop(set_as_default=True)
bus = SessionBus()

bus.add_signal_receiver(handler_function=handler,
                        interface_keyword="dbus_interface",
                        member_keyword="DriveChanged",
                        dbus_interface="org.gtk.Private.RemoteVolumeMonitor")

# Start Loop
loop = gobject.MainLoop()
loop.run()
コード例 #12
0
ファイル: proxy.py プロジェクト: ow2-proactive/agent-common
class SSTrigger:
	
    # FORMAT MESSAGE : [START/STOP] [X] [Y]

    MAIN_DIR = "/usr/bin/ProActiveScreenSaver"

    start = 'START'
    stop = 'STOP'

    #log path of proxy
    config_file = 'log/proxy.txt'

    #named pipe path
    pipe_path = "/tmp/ss.pipe"

    #Initialize dbus
    def __init__(self):
        DBusGMainLoop(set_as_default=True)
        self.mem='ActiveChanged'
        self.dest='org.gnome.ScreenSaver'
        self.bus=SessionBus()
        self.loop=MainLoop()
        self.bus.add_signal_receiver(self.catch,self.mem,self.dest)

    # log method
    def writeLOG(self, txt):
    	f = open( self.MAIN_DIR + "/" + self.config_file ,'a')
        f.write( txt )
        f.close()

    # receive signal and write message on dbus
    def catch(self,ssOn):
        
        screen = commands.getoutput("xrandr | grep \* | tr -s ' ' | cut -d' ' -f2")
        screen_res = screen.split('x')
    
        #Screensize	
        length = screen_res[0]
        width = screen_res[1]
        
        if ssOn == 1: #Screensaver turned on

            data = self.start + " " + length + " " + width
            
            pipe = open(self.pipe_path, 'w')
	    
            pipe.write(data)		
            pipe.close()

            self.writeLOG(time.ctime() + "proxy has send : " + data + "\n")
            print "proxy has send : " + data

        else: #Screensaver turned off
 	    
            data = self.stop + " " + length + " " + width
            
            pipe = open(self.pipe_path, 'w')
	    
            pipe.write(data)		
            pipe.close()

            self.writeLOG(time.ctime() + "proxy has send : " + data + "\n")
            print "proxy has send : " + data
コード例 #13
0
        tested_things.add(INTERFACE_SIGNAL_TESTS + ".Trigger")
        dbus.Interface(dbus.SessionBus().get_object(sender, sender_path), INTERFACE_CALLBACK_TESTS).Response(
            parameter1, parameter2
        )
        logger.info("signal/callback: Sent Response")


if __name__ == "__main__":
    bus = SessionBus()
    bus_name = BusName(CROSS_TEST_BUS_NAME, bus=bus)
    loop = gobject.MainLoop()
    obj = Server(bus_name, CROSS_TEST_PATH, loop.quit)
    objects[CROSS_TEST_PATH] = obj
    kwargs = {}
    if is_py2:
        kwargs["utf8_strings"] = True
    bus.add_signal_receiver(
        obj.triggered_by_client,
        signal_name="Trigger",
        dbus_interface=INTERFACE_SIGNAL_TESTS,
        named_service=None,
        path=None,
        sender_keyword="sender",
        path_keyword="sender_path",
        **kwargs
    )

    logger.info("running...")
    loop.run()
    logger.info("main loop exited.")