Example #1
0
class Main:

        def __init__(self):

		self.GetPath()

# get FSO Usage proxy/iface up to request GPS
		self.systembus=systembus = SystemBus(mainloop=e_dbus.DBusEcoreMainLoop())
		self.usage_proxy = self.systembus.get_object('org.freesmartphone.ousaged', '/org/freesmartphone/Usage')
		self.usage_iface = Interface(self.usage_proxy, 'org.freesmartphone.Usage')

# Request GPS from FSO (which then powers on the GPS chip)
		self.usage_iface.RequestResource("GPS")

#get gypsy proxy/iface up
		self.ogpsd_proxy = self.systembus.get_object('org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
		self.course_iface = Interface(self.ogpsd_proxy, 'org.freedesktop.Gypsy.Course')
		self.pos_iface = Interface(self.ogpsd_proxy, 'org.freedesktop.Gypsy.Position')

# call self.UpdatePosition() when a dbus signal "PositionChanged" comes along the system bus
		self.pos_iface.connect_to_signal("PositionChanged", self.UpdatePosition)


	def UpdatePosition(self, fields, timestamp, lat, lon, alt):

# get UTC time from gypsy timestamp
		string = str(datetime.datetime.utcfromtimestamp(timestamp))
		date, time = string.split()
		utctime = "%sT%sZ" % (date, time)

# write data to file
		s ="%s,%s,%s,%s\n" % (lat, lon, alt, utctime)
		with open(self.trackfile,'a') as file:
			file.write(s)

#debugging output:
		print s


	def Parser(self):

# parse command line options
		self.parser=OptionParser("usage foo bar")
		self.parser.add_option("-f", "--file", "-o", "-l", action = "store", dest = "trackfile")
		(self.options, self.args) = self.parser.parse_args()


	def GetPath(self):
		trackpath = '.'
		suffix = 'track'
		self.Parser()

# raises an Exception if the path doesn't exist! :)
		path, rubbish, suffix = self.trackfile.options.rpartition("/")

		if not os.path.exists(path):
			raise Exception("path does not exist!")

# sets trackfile path and filename		
		self.trackfile = "%s/%s-%s" % (trackpath, time.strftime(), suffix)
Example #2
0
    def _connect_to_udisks2(self, bus):
        """
        Setup the initial connection to UDisks2

        This step can fail if UDisks2 is not available and cannot be
        service-activated.
        """
        # Access the /org/freedesktop/UDisks2 object sitting on the
        # org.freedesktop.UDisks2 bus name. This will trigger the necessary
        # activation if udisksd is not running for any reason
        logging.debug("Accessing main UDisks2 object")
        self._udisks2_obj = bus.get_object("org.freedesktop.UDisks2",
                                           "/org/freedesktop/UDisks2")
        # Now extract the standard ObjectManager interface so that we can
        # observe and iterate the collection of objects that UDisks2 provides.
        logging.debug("Accessing ObjectManager interface on UDisks2 object")
        self._udisks2_obj_manager = Interface(self._udisks2_obj,
                                              OBJECT_MANAGER_INTERFACE)
        # Connect to the PropertiesChanged signal. Here unlike before we want
        # to listen to all signals, regardless of who was sending them in the
        # first place.
        logging.debug("Setting up DBus signal handler for PropertiesChanged")
        bus.add_signal_receiver(
            self._on_properties_changed,
            signal_name="PropertiesChanged",
            dbus_interface=PROPERTIES_IFACE,
            # Use the sender_keyword keyword argument to indicate that we wish
            # to know the sender of each signal. For consistency with other
            # signals we choose to use the 'object_path' keyword argument.
            sender_keyword='sender')
Example #3
0
    def pathfactory(self, name):
        """
        Allocate a new channel from the MUXer.

        Overridden for internal purposes.
        """
        logger.info("Requesting new channel from '%s'", self._muxercommand)

        if self._muxercommand == "gsm0710muxd":
            if self._muxeriface is None:
                muxer = self._bus.get_object("org.pyneo.muxer",
                                             "/org/pyneo/Muxer")
                self._muxeriface = Interface(muxer,
                                             "org.freesmartphone.GSM.MUX")
            return str(self._muxeriface.AllocChannel(name))

        elif self._muxercommand == "fso-abyss":
            if self._muxeriface is None:
                muxer = self._bus.get_object("org.freesmartphone.omuxerd",
                                             "/org/freesmartphone/GSM/Muxer")
                self._muxeriface = Interface(muxer,
                                             "org.freesmartphone.GSM.MUX")
                # power on modem
                if not self._modemOn():
                    self._muxeriface = None
                    return ""  # FIXME: emit error?
                if not self._muxeriface.HasAutoSession():
                    # abyss needs an open session before we can allocate channels
                    self._muxeriface.OpenSession(True, 98, "serial",
                                                 DEVICE_CALYPSO_PATH, 115200)
            pts, vc = self._muxeriface.AllocChannel(name,
                                                    self._channelmap[name])
            return str(pts)
    def initialize(self, conf_reader, msgQlist, product):
        """initialize configuration reader and internal msg queues."""
        # Initialize ScheduledMonitorThread and InternalMsgQ
        super(ServiceMonitor, self).initialize(conf_reader)

        # Initialize internal message queues for this module
        super(ServiceMonitor, self).initialize_msgQ(msgQlist)

        self.iem = Iem()
        self.iem.check_exsisting_fault_iems()
        self.KAFKA = self.iem.EVENT_CODE["KAFKA_ACTIVE"][1]

        # Integrate into the main dbus loop to catch events
        DBusGMainLoop(set_as_default=True)

        # Initialize SystemBus and get Manager Interface
        self._bus = SystemBus()
        systemd = self._bus.get_object("org.freedesktop.systemd1",
                                       "/org/freedesktop/systemd1")
        self._manager = Interface(
            systemd, dbus_interface='org.freedesktop.systemd1.Manager')

        self.remove_disabled_services()

        return True
Example #5
0
def set_dns_systemd_resolved(lease):
    # NOTE: if systemd-resolved is not already running, we might not want to
    # run it in case there's specific system configuration for other resolvers
    ipr = IPRoute()
    index = ipr.link_lookup(ifname=lease.interface)[0]
    # Construct the argument to pass to DBUS.
    # the equivalent argument for:
    # busctl call org.freedesktop.resolve1 /org/freedesktop/resolve1 \
    # org.freedesktop.resolve1.Manager SetLinkDNS 'ia(iay)' 2 1 2 4 1 2 3 4
    # is SetLinkDNS(2, [(2, [8, 8, 8, 8])]_
    iay = [(2, [int(b) for b in ns.split('.')])
           for ns in lease.name_server.split()]
    #        if '.' in ns
    #        else (10, [ord(x) for x in
    #            socket.inet_pton(socket.AF_INET6, ns)])
    bus = SystemBus()
    resolved = bus.get_object('org.freedesktop.resolve1',
                              '/org/freedesktop/resolve1')
    manager = Interface(resolved,
                        dbus_interface='org.freedesktop.resolve1.Manager')
    try:
        manager.SetLinkDNS(index, iay)
        return True
    except DBusException as e:
        logger.error(e)
        return False
Example #6
0
    def _get_rhythmbox_player(self):
        # Para controlar el reproductor, usaremos la interfaz estándar que
        # define FreeDestkop.org, es decir MPRIS

        # Información de D-Bus para Rhythmbox usando interfaz estándar MPRIS
        rhythmbox_bus_name = 'org.mpris.MediaPlayer2.rhythmbox'
        rhythmbox_object_path = '/org/mpris/MediaPlayer2'
        rhythmbox_dbus_interface_player = 'org.mpris.MediaPlayer2.Player'
        rhythmbox_dbus_interface_playlists = 'org.mpris.MediaPlayer2.Playlists'

        # Se obtiene el objeto remoto de Rhythmbox desde el bus de sesión
        rhythmbox_object = self._session_bus.get_object(
            rhythmbox_bus_name, rhythmbox_object_path)

        # Se obtiene la interfaz Player del objeto remoto del reproductor
        rhythmbox_player = Interface(rhythmbox_object,
                                     rhythmbox_dbus_interface_player)

        # Se obtiene la interfaz Playerlists del objeto remoto del reproductor
        rhythmbox_playlists = Interface(rhythmbox_object,
                                        rhythmbox_dbus_interface_playlists)

        # Se necesita obtener la cantidad de listas de reproducción contenidas
        # en el reproductor. Eso lo devuelve la propiedad "PlaylistCount"
        playlists_properties = Interface(rhythmbox_object,
                                         'org.freedesktop.DBus.Properties')
        pl_count = playlists_properties.Get(rhythmbox_dbus_interface_playlists,
                                            'PlaylistCount')

        return rhythmbox_player, rhythmbox_playlists, pl_count
Example #7
0
    def __init__(self):
        bus = SystemBus()
        systemd = bus.get_object('org.freedesktop.systemd1',
                                 '/org/freedesktop/systemd1')

        self.manager = Interface(systemd, 'org.freedesktop.systemd1.Manager')
        self.supported_operations = ['stop', 'start', 'restart']
 def __init__(self, unit):
     """
     Initialize Service.
     """
     self.unit = unit
     self.properties_iface = Interface(self.unit,
                                       dbus_interface=PROPERTIES_IFACE)
     self.name = str(self.properties_iface.Get(UNIT_IFACE, 'Id'))
     self.state = "N/A"
     self.substate = "N/A"
     self.pid = "N/A"
     self.previous_state = "N/A"
     self.previous_substate = "N/A"
     self.previous_pid = "N/A"
     self.nonactive_enter_timestamp = time.time()
     self.active_enter_timestamp = time.time()
     self.nonactive_threshold = int(
         Conf.get(SSPL_CONF,
                  f"{ServiceMonitor.name().upper()}>threshold_inactive_time",
                  '60'))
     self.active_threshold = int(Conf.get(SSPL_CONF,
                  f"{ServiceMonitor.name().upper()}>threshold_active_time",
                  '30'))
     self.properties_changed_signal = None
     self._service_state = ActiveState
     self._unit_state = None
Example #9
0
    def setup(self, parent):
        from dbus import Interface, SessionBus

        self.iface = Interface(
            SessionBus().get_object("org.xfce.Xfconf", "/org/xfce/Xfconf"),
            "org.xfce.Xfconf",
        )
Example #10
0
	def show_paused(self):
		# Debug info
		if self.debug == True:
			print "Show paused..."
	
		# Get Spotify tray icon coordinates
		coords = self.get_tray_coords()
	
		# Configure notification hints
		if coords['x'] > 0:
			hints = { 'x': coords['x'], 'y': coords['y'] }
		else:
			hints = {}
	
		# Get interface for call notification daemon
		proxy = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
		interface = Interface(proxy, dbus_interface='org.freedesktop.Notifications')
	
		# Closes active notification
		if self.nid != False:
			if self.debug == True:
				print "Closing existing notification..."
			
			interface.CloseNotification(self.nid)
	
		# Shows notification
		self.nid = interface.Notify('Spotify', 0, '/usr/share/pixmaps/spotify.png', 'Spotify', self.translate('playback_paused'), [], hints, self.timeout)
    def _load(self):
        conn = Connection(
            self._application_context.options.embed_plugin_address)
        proxy = conn.get_object(None, self._dbus_object_path)
        self._remote_container = Interface(
            proxy, 'org.ros.qt_gui.PluginHandlerContainer')
        self._remote_container.connect_to_signal('shutdown_plugin',
                                                 self._shutdown_plugin)
        self._remote_container.connect_to_signal(
            'save_settings', self._save_settings_from_remote)
        self._remote_container.connect_to_signal(
            'restore_settings', self._restore_settings_from_remote)
        self._remote_container.connect_to_signal('trigger_configuration',
                                                 self._trigger_configuration)
        self._remote_container.connect_to_signal(
            'toolbar_orientation_changed', self._toolbar_orientation_changed)

        proxy = conn.get_object(None, self._dbus_object_path + '/plugin')
        self._remote_plugin_settings = Interface(proxy,
                                                 'org.ros.qt_gui.Settings')
        proxy = conn.get_object(None, self._dbus_object_path + '/instance')
        self._remote_instance_settings = Interface(proxy,
                                                   'org.ros.qt_gui.Settings')

        super(PluginHandlerXEmbedClient, self)._load()
Example #12
0
	def mpris(self):
		from dbus import Interface
		player = self.NPCommand.get_text()
		dbus_mpris_service = u'org.mpris.MediaPlayer2.'
		dbus_mpris_player_service = u'org.mpris.MediaPlayer2.Player'
		dbus_mpris_path = u'/org/mpris/MediaPlayer2'
		dbus_property = u'org.freedesktop.DBus.Properties'
		if not player:
			names = self.bus.list_names()
			players = []
			for name in names:
				if name.startswith(dbus_mpris_service):
					players.append(name[len(dbus_mpris_service):])
			if not players:
				self.frame.logMessage(_("Could not find a suitable MPRIS player."))
				return None
			player = players[0]
			if len(players) > 1:
				self.frame.logMessage(_("Found multiple MPRIS players: %(players)s. Using: %(player)s") % {'players': players, 'player': player})
			else:
				self.frame.logMessage(_("Auto-detected MPRIS player: %s.") % player)
		try:
			player_obj          = self.bus.get_object(dbus_mpris_service + player, dbus_mpris_path)
			player_property_obj = Interface(player_obj, dbus_interface=dbus_property)
			metadata            = player_property_obj.Get(dbus_mpris_player_service, "Metadata")
		except Exception, exception:
			self.frame.logMessage(_("Something went wrong while querying %(player)s: %(exception)s") % {'player': player, 'exception': exception})
			return None
	def show_playing(self, track = False, interactive = True):
		# Debug info
		if self.debug == True and interactive == True:
			print "Show track data interactively..."
		elif self.debug == True:
			print "Show track data..."
	
		# Define actions in notification
		if interactive == True:
			actions = [ '2', self.translate('action_next') ]
		else:
			actions = []
	
		# If track not specified in parameter, read from D-Bus
		if not track:
			track = self.get_metadata()
	
		# If there's a song playing
		if track:
			# Get Spotify tray icon coordinates
			coords = self.get_tray_coords()
	
			# Configure notification hints
			if coords['x'] > 0:
				hints = { 'x': coords['x'], 'y': coords['y'] }
			else:
				hints = {}
	
			# Generate notification content
			text = self.translate('detail_by') + ' <i>' + self.get_info(track, 'artist')
			text = text + '</i> ' + self.translate('detail_album') + ' <i>' + self.get_info(track, 'album') + '</i>'
			text = text.replace('&', '&amp;')
	
			# Get interface for call notification daemon
			proxy = self.bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
			interface = Interface(proxy, dbus_interface='org.freedesktop.Notifications')
	
			# Closes active notification
			if self.nid != False:
				if self.debug == True:
					print "Closing existing notification..."
				
				interface.CloseNotification(self.nid)
	
			# Shows notification
			self.nid = interface.Notify('Spotify', 0, self.get_cover(), self.get_info(track, 'title'), text, actions, hints, self.timeout)
	
			# Connects to actions signals
			if self.nid > 0:
				if interactive == True:
					interface.connect_to_signal('ActionInvoked', self.action_listener)
	
				interface.connect_to_signal('NotificationClosed', self.action_dismisser)
				gobject.threads_init()
				gobject.timeout_add(self.timeout * 10, self.action_listener)
	
		return self.nid
Example #14
0
def _get_bus_connections_pid(bus, connection_name):
    """Returns the pid for the connection **connection_name** on **bus**

    :raises: **DBusException** if connection_name is invalid etc.

    """
    bus_obj = bus.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus')
    bus_iface = Interface(bus_obj, 'org.freedesktop.DBus')
    return bus_iface.GetConnectionUnixProcessID(connection_name)
Example #15
0
    def __init__(self, dbus_object, interface):
        """
        Initialize a proxy object with standard DBus property interface.

        :param dbus.proxies.ProxyObject dbus_object: accessed object
        :param str interface: accessed interface name
        """
        self.__proxy = Interface(
            dbus_object, dbus_interface='org.freedesktop.DBus.Properties')
        self.__interface = interface
Example #16
0
 def __init__(self):
     self.services = []
     self.systemd = bus.get_object('org.freedesktop.systemd1',
                                   '/org/freedesktop/systemd1')
     self.manager = Interface(
         self.systemd, dbus_interface='org.freedesktop.systemd1.Manager')
     self.manager.connect_to_signal('UnitNew', self.load)
     self.manager.connect_to_signal('UnitRemoved', self.load)
     self.manager.connect_to_signal('UnitFilesChanged', self.load)
     self.load()
Example #17
0
File: osd.py Project: xuhui/clay
    def __init__(self):
        self._last_id = 0

        if IS_INIT:
            self.bus = SessionBus()
            self.notifcations = self.bus.get_object(
                "org.freedesktop.Notifications",
                "/org/freedesktop/Notifications")
            self.notify_interface = Interface(self.notifcations,
                                              "org.freedesktop.Notifications")
Example #18
0
	def close_notification(self):
		# Get interface for call notification daemon
		proxy = self.bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
		interface = Interface(proxy, dbus_interface='org.freedesktop.Notifications')

		# Closes active notification
		if self.nid != False:
			if self.debug == True:
				print "Closing existing notification..."
			
			interface.CloseNotification(self.nid)		
Example #19
0
class Snapper(dnf.Plugin):
    name = 'snapper'

    def __init__(self, base, cli):
        self.base = base
        self.description = " ".join(sys.argv)
        self._pre_snap_created = False
        self._snapper = None
        self._pre_snap_number = None

    def pre_transaction(self):
        if not self.base.transaction:
            return

        try:
            bus = SystemBus()
            self._snapper = Interface(bus.get_object('org.opensuse.Snapper',
                                                     '/org/opensuse/Snapper'),
                                      dbus_interface='org.opensuse.Snapper')
        except DBusException as e:
            logger.critical("snapper: " + _("connect to snapperd failed: %s"),
                            e)
            return

        try:
            logger.debug("snapper: " + _("creating pre_snapshot"))
            self._pre_snap_number = self._snapper.CreatePreSnapshot(
                "root", self.description, "number", {})
            self._pre_snap_created = True
            logger.debug("snapper: " + _("created pre_snapshot %d"),
                         self._pre_snap_number)
        except DBusException as e:
            logger.critical(
                "snapper: " + _("creating pre_snapshot failed: %s"), e)

    def transaction(self):
        if not self.base.transaction:
            return

        if not self._pre_snap_created:
            logger.debug("snapper: " + _(
                "skipping post_snapshot because creation of pre_snapshot failed"
            ))
            return

        try:
            logger.debug("snapper: " + _("creating post_snapshot"))
            snap_post_number = self._snapper.CreatePostSnapshot(
                "root", self._pre_snap_number, self.description, "number", {})
            logger.debug("snapper: " + _("created post_snapshot %d"),
                         snap_post_number)
        except DBusException as e:
            logger.critical(
                "snapper: " + _("creating post_snapshot failed: %s"), e)
Example #20
0
def simdi_kapat(istek):
    bus = SystemBus()
    dbus_k = bus.get_object('org.freedesktop.ConsoleKit',
                            '/org/freedesktop/ConsoleKit/Manager')
    dbus_kapat = Interface(dbus_k, 'org.freedesktop.ConsoleKit.Manager')

    if istek == 'Stop':
        print("\033[1;41mBilgisayarınız kapatılıyor...\033[0m")
        dbus_kapat.Stop()
    else:
        print("\033[1;41mBilgisayarınız yeniden başlatılıyor...\033[0m")
        dbus_kapat.Restart()
Example #21
0
def main():
    print(
        "starting to monitor your spotify tracks, make sure you start the spotify client before you run this program"
    )
    while True:
        try:
            session_bus = SessionBus()

            bus_data = ("org.mpris.MediaPlayer2.spotify",
                        "/org/mpris/MediaPlayer2")
            spotify_bus = session_bus.get_object(*bus_data)

            interface = Interface(spotify_bus,
                                  "org.freedesktop.DBus.Properties")

            metadata = interface.Get("org.mpris.MediaPlayer2.Player",
                                     "Metadata")
            status = str(
                interface.Get("org.mpris.MediaPlayer2.Player",
                              "PlaybackStatus"))
            is_playing = False

            if status == "Playing":
                is_playing = True

            data = {"artist": None, "song": None, "album": None}

            artist_data = metadata.get("xesam:albumArtist")

            artist = str(next(iter(artist_data)))
            song_name = str(metadata.get("xesam:title"))
            album = str(metadata.get("xesam:album"))

            thread = Thread(target=handle_track,
                            args=(
                                song_name,
                                album,
                                artist,
                                is_playing,
                                prev_track,
                            ))
            thread.start()

            # if is_playing:
            #     print('{} - {}'.format(song_name, artist))

            sleep(1)
        except Exception as e:
            print("exception occurred")
            print(e)
            sleep(1)

    print('exiting? wtf?')
Example #22
0
def restart_daemon():
    cmd = f"systemctl restart chain-maind"
    print("### Restart service ###")
    sysbus = SystemBus()
    systemd1 = sysbus.get_object('org.freedesktop.systemd1',
                                 '/org/freedesktop/systemd1')
    manager = Interface(systemd1,
                        dbus_interface='org.freedesktop.systemd1.Manager')
    if is_service_active('chain-maind.service'):
        manager.StopUnit('chain-maind.service', 'replace')
    #job = manager.RestartUnit('chain-maind.service', 'fail')
    time.sleep(2)
    manager.StartUnit('chain-maind.service', 'replace')
Example #23
0
    def initialize(self, conf_reader, msgQlist, product):
        """initialize configuration reader and internal msg queues."""
        # Initialize ScheduledMonitorThread and InternalMsgQ
        super(ServiceMonitor, self).initialize(conf_reader)

        # Initialize internal message queues for this module
        super(ServiceMonitor, self).initialize_msgQ(msgQlist)

        self.iem = Iem()
        self.iem.check_exsisting_fault_iems()
        self.KAFKA = self.iem.EVENT_CODE["KAFKA_ACTIVE"][1]

        # Integrate into the main dbus loop to catch events
        DBusGMainLoop(set_as_default=True)

        # Initialize SystemBus and get Manager Interface
        self._bus = SystemBus()
        systemd = self._bus.get_object("org.freedesktop.systemd1",
                                       "/org/freedesktop/systemd1")
        self._manager = Interface(
            systemd, dbus_interface='org.freedesktop.systemd1.Manager')

        self._node_id = Conf.get(GLOBAL_CONF, NODE_ID_KEY, 'SN01')

        cache_dir_path = os.path.join(DATA_PATH, self.CACHE_DIR_NAME)
        self.SERVICE_MONITOR_DATA_PATH = os.path.join(
            cache_dir_path, f'SERVICE_MONITOR_DATA_{self._node_id}')
        # Get the stored previous service info
        self.persistent_service_data = {}
        if os.path.isfile(self.SERVICE_MONITOR_DATA_PATH):
            self.persistent_service_data = \
                store.get(self.SERVICE_MONITOR_DATA_PATH)
        if self.persistent_service_data:
            self.not_active_services = \
                self.persistent_service_data['not_active_services']
            self.failed_services = \
                self.persistent_service_data['failed_services']
            self.service_status = \
                self.persistent_service_data['service_status']
        else:
            self.persistent_service_data = {
                'not_active_services': self.not_active_services,
                'failed_services': self.failed_services,
                'service_status': self.service_status
            }
            store.put(self.persistent_service_data,
                      self.SERVICE_MONITOR_DATA_PATH)

        self.remove_disabled_services()

        return True
    def __init__(self):
        super(SystemdLogin, self).__init__()

        # Use d-bus to communicate with systemd
        #  Described at: http://www.freedesktop.org/wiki/Software/systemd/logind/

        # Obtain an instance of d-bus to communicate with systemd
        self._bus = SystemBus()

        # Obtain a manager interface to d-bus for communications with login1
        logind = self._bus.get_object('org.freedesktop.login1',
                                      '/org/freedesktop/login1')
        self._manager = Interface(
            logind, dbus_interface='org.freedesktop.login1.Manager')
	def getActiveState(self, name) :
		unit = DBusInterface(
			self._bus.get_object(
				'org.freedesktop.systemd1',
				str(self._systemd_manager.LoadUnit(name + '.service'))
			),
			'org.freedesktop.systemd1.Unit'
		)
		active_state = unit.Get(
			'org.freedesktop.systemd1.Unit',
			'ActiveState',
			dbus_interface='org.freedesktop.DBus.Properties'
		)
		return active_state
Example #26
0
def systemd_resolved_status():
    bus = SystemBus()
    systemd = bus.get_object('org.freedesktop.systemd1',
                             '/org/freedesktop/systemd1')
    manager = Interface(systemd,
                        dbus_interface='org.freedesktop.systemd1.Manager')
    unit = manager.LoadUnit('sytemd-resolved.service')
    proxy = bus.get_object('org.freedesktop.systemd1', str(unit))
    r = proxy.Get('org.freedesktop.systemd1.Unit',
                  'ActiveState',
                  dbus_interface='org.freedesktop.DBus.Properties')
    if str(r) == 'active':
        return True
    return False
Example #27
0
	def rhythmbox(self):
		from dbus import Interface
		
		if self.bus is None:
			self.frame.logMessage(_("ERROR: DBus not available:")+" "+"Rhythmbox"+ " "+ _("cannot be contacted"))
			return None
		try:
			proxyobj = self.bus.get_object("org.gnome.Rhythmbox", "/org/gnome/Rhythmbox/Shell")
			rbshell = Interface(proxyobj, "org.gnome.Rhythmbox.Shell")
			proxyobj = self.bus.get_object('org.gnome.Rhythmbox', '/org/gnome/Rhythmbox/Player')
			rbplayer = Interface(proxyobj, 'org.gnome.Rhythmbox.Player')
		except Exception, error:
			self.frame.logMessage(_("ERROR while accessing the %(program)s DBus interface: %(error)s") % {"program": "Rhythmbox", "error": error })
			return None
Example #28
0
def handleQuery(query):
    results = []
    if query.isTriggered:
        try:
            if not SessionBus().name_has_owner(BUS):
                warning("Seems like %s is not running" % __bin__)
                return []

            obj = SessionBus().get_object(bus_name=BUS, object_path=OBJ)
            iface = Interface(obj, dbus_interface=IFACE)

            if query.string.strip():
                for note in iface.SearchNotes(query.string.lower(), False):
                    results.append(
                        Item(
                            id="%s%s" % (__prettyname__, note),
                            icon=iconPath,
                            text=iface.GetNoteTitle(note),
                            subtext="%s%s" %
                            ("".join([
                                "#%s " % re.search('.+:.+:(.+)', s).group(1)
                                for s in iface.GetTagsForNote(note)
                            ]),
                             datetime.fromtimestamp(
                                 iface.GetNoteChangeDate(note)).strftime(
                                     "Note from %c")),
                            completion=query.rawString,
                            actions=[
                                FuncAction(
                                    "Open note",
                                    lambda note=note: iface.DisplayNote(note)),
                                FuncAction(
                                    "Delete note",
                                    lambda note=note: iface.DeleteNote(note))
                            ]))
            else:

                def createAndShowNote():
                    note = iface.CreateNote()
                    iface.DisplayNote(note)

                results.append(
                    Item(id="%s-create" % __prettyname__,
                         icon=iconPath,
                         text=__prettyname__,
                         subtext="%s notes" % __prettyname__,
                         completion=query.rawString,
                         actions=[
                             FuncAction("Open %s" % __prettyname__,
                                        lambda: iface.DisplaySearch()),
                             FuncAction("Create a new note", createAndShowNote)
                         ]))
        except DBusException as e:
            critical(str(e))
    return results
Example #29
0
class systemdBus(object):
    def __init__(self, user=False):
        self.bus = SessionBus() if user else SystemBus()
        systemd = self.bus.get_object(SYSTEMD_BUSNAME, SYSTEMD_PATH)
        self.manager = Interface(systemd,
                                 dbus_interface=SYSTEMD_MANAGER_INTERFACE)

    def get_unit_active_state(self, unit):
        unit = self.manager.LoadUnit(unit)
        unit_object = self.bus.get_object(SYSTEMD_BUSNAME, unit)
        unit_properties = Interface(unit_object, DBUS_INTERFACE)
        return unit_properties.Get(SYSTEMD_UNIT_INTERFACE, 'ActiveState')

    def get_unit_load_state(self, unit):
        unit = self.manager.LoadUnit(unit)
        unit_object = self.bus.get_object(SYSTEMD_BUSNAME, unit)
        unit_properties = Interface(unit_object, DBUS_INTERFACE)
        return unit_properties.Get(SYSTEMD_UNIT_INTERFACE, 'LoadState')

    def get_unit_uptime(self, unit):
        unit = self.manager.LoadUnit(unit)
        unit_object = self.bus.get_object(SYSTEMD_BUSNAME, unit)
        unit_properties = Interface(unit_object, DBUS_INTERFACE)
        return unit_properties.Get(SYSTEMD_UNIT_INTERFACE,
                                   'ActiveEnterTimestamp')

    def start_unit(self, unit):
        try:
            self.manager.StartUnit(unit, 'replace')
            return True
        except exceptions.DBusException:
            return False

    def stop_unit(self, unit):
        try:
            self.manager.StopUnit(unit, 'replace')
            return True
        except exceptions.DBusException:
            return False

    def restart_unit(self, unit):
        try:
            self.manager.RestartUnit(unit, 'replace')
            return True
        except exceptions.DBusException:
            return False

    def reload_unit(self, unit):
        try:
            self.manager.ReloadUnit(unit, 'replace')
            return True
        except exceptions.DBusException:
            return False

    def reload_or_restart_unit(self, unit):
        try:
            self.manager.ReloadOrRestartUnit(unit, 'replace')
            return True
        except exceptions.DBusException:
            return False
Example #30
0
    def __init__(self, bus):
        def player_message_cb(bus, message):
            if gst.MESSAGE_EOS == message.type:
                self.__player.set_state(gst.STATE_NULL)
                return True

            if gst.MESSAGE_ERROR == message.type:
                print message.structure and message.structure.to_string() or ''
                self.__player.set_state(gst.STATE_NULL)
                return True

            if gst.MESSAGE_STATE_CHANGED == message.type:
                if message.src == self.__player:
                    self.StateChanged(*self.GetState())
                    self.__favorites.set_state(*self.GetState())

                return True

            if gst.MESSAGE_TAG == message.type:
                valid_types = float, int, str, unicode

                tags = [(k, v) for k, v in dict(message.structure).items()
                        if isinstance(v, valid_types)]

                self.StreamTagsChanged(dict(tags))

                return True

            return True

        self.__data_stage = 0
        self.__player = Player()
        self.__player.get_bus().add_watch(player_message_cb)
        self.__httplib = Http(cache=get_cache_filename())
        self.__favorites = Favorites()
        self.__stations = list()
        self.__stream_tags = dict()

        proxy = SessionBus().get_object('org.freedesktop.Notifications',
                                        '/org/freedesktop/Notifications')
        self.__notifications = Interface(proxy,
                                         'org.freedesktop.Notifications')
        self.__notify_id = 0

        name = BusName(Service.name, bus)
        super(Service, self).__init__(bus, '/', name)
        self.__loop = MainLoop(None, True)

        Thread(target=self.__load).start()
    def __init__(self):
        super(SystemdService, self).__init__()

        # Use d-bus to communicate with systemd
        #  Described at: http://www.freedesktop.org/wiki/Software/systemd/dbus/

        # Obtain an instance of d-bus to communicate with systemd
        self._bus = SystemBus()

        # Obtain a manager interface to d-bus for communications with systemd
        systemd = self._bus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
        self._manager = Interface(systemd, dbus_interface='org.freedesktop.systemd1.Manager')

        # Subscribe to signal changes
        self._manager.Subscribe()
Example #32
0
 def assert_method_matches(self, interface, check_fn, check_arg, member,
                           *args):
     if_obj = Interface(self.obj, interface)
     method = getattr(if_obj, member)
     try:
         real_ret = method(*args)
     except Exception as e:
         self.fail_id += 1
         print("%s.%s fail %d" % (interface, member, self.fail_id))
         s = ("report %d: %s.%s%r: raised %r \"%s\"" %
              (self.fail_id, interface, member, args, e, e))
         print(s)
         logger.error(s)
         __import__('traceback').print_exc()
         return
     try:
         check_fn(real_ret, check_arg)
     except Exception as e:
         self.fail_id += 1
         print("%s.%s fail %d" % (interface, member, self.fail_id))
         s = ("report %d: %s.%s%r: %s" %
              (self.fail_id, interface, member, args, e))
         print(s)
         logger.error(s)
         return
     print("%s.%s pass" % (interface, member))
Example #33
0
    def _connect_to_udisks2(self, bus):
        """
        Setup the initial connection to UDisks2

        This step can fail if UDisks2 is not available and cannot be
        service-activated.
        """
        # Access the /org/freedesktop/UDisks2 object sitting on the
        # org.freedesktop.UDisks2 bus name. This will trigger the necessary
        # activation if udisksd is not running for any reason
        logging.debug("Accessing main UDisks2 object")
        self._udisks2_obj = bus.get_object(
            "org.freedesktop.UDisks2", "/org/freedesktop/UDisks2")
        # Now extract the standard ObjectManager interface so that we can
        # observe and iterate the collection of objects that UDisks2 provides.
        logging.debug("Accessing ObjectManager interface on UDisks2 object")
        self._udisks2_obj_manager = Interface(
            self._udisks2_obj, OBJECT_MANAGER_INTERFACE)
        # Connect to the PropertiesChanged signal. Here unlike before we want
        # to listen to all signals, regardless of who was sending them in the
        # first place.
        logging.debug("Setting up DBus signal handler for PropertiesChanged")
        bus.add_signal_receiver(
            self._on_properties_changed,
            signal_name="PropertiesChanged",
            dbus_interface=PROPERTIES_IFACE,
            # Use the sender_keyword keyword argument to indicate that we wish
            # to know the sender of each signal. For consistency with other
            # signals we choose to use the 'object_path' keyword argument.
            sender_keyword='sender')
Example #34
0
        def InitDbusStuff(self):

# get FSO Usage proxy/iface up to request GPS
		self.systembus=systembus = SystemBus(mainloop=e_dbus.DBusEcoreMainLoop())
		self.usage_proxy = self.systembus.get_object('org.freesmartphone.ousaged', '/org/freesmartphone/Usage')
		self.usage_iface = Interface(self.usage_proxy, 'org.freesmartphone.Usage')

# request GPS from FSO (which then powers on the GPS chip)
		self.usage_iface.RequestResource("GPS")

# get gypsy proxy/iface up
		self.ogpsd_proxy = self.systembus.get_object('org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
		self.course_iface = Interface(self.ogpsd_proxy, 'org.freedesktop.Gypsy.Course')
		self.pos_iface = Interface(self.ogpsd_proxy, 'org.freedesktop.Gypsy.Position')

		self.terminator=""
    def _load(self):
        conn = Connection(self._application_context.options.embed_plugin_address)
        proxy = conn.get_object(None, self._dbus_object_path)
        self._remote_container = Interface(proxy, 'org.ros.qt_gui.PluginHandlerContainer')
        self._remote_container.connect_to_signal('shutdown_plugin', self._shutdown_plugin)
        self._remote_container.connect_to_signal('save_settings', self._save_settings_from_remote)
        self._remote_container.connect_to_signal('restore_settings', self._restore_settings_from_remote)
        self._remote_container.connect_to_signal('trigger_configuration', self._trigger_configuration)
        self._remote_container.connect_to_signal('toolbar_orientation_changed', self._toolbar_orientation_changed)

        proxy = conn.get_object(None, self._dbus_object_path + '/plugin')
        self._remote_plugin_settings = Interface(proxy, 'org.ros.qt_gui.Settings')
        proxy = conn.get_object(None, self._dbus_object_path + '/instance')
        self._remote_instance_settings = Interface(proxy, 'org.ros.qt_gui.Settings')

        super(PluginHandlerXEmbedClient, self)._load()
Example #36
0
    def _connect_to_udisks2(self, bus):
        """
        Setup the initial connection to UDisks2

        This step can fail if UDisks2 is not available and cannot be
        service-activated.
        """
        # Access the /org/freedesktop/UDisks2 object sitting on the
        # org.freedesktop.UDisks2 bus name. This will trigger the necessary
        # activation if udisksd is not running for any reason
        logging.debug("Accessing main UDisks2 object")
        self._udisks2_obj = bus.get_object(
            "org.freedesktop.UDisks2", "/org/freedesktop/UDisks2")
        # Now extract the standard ObjectManager interface so that we can
        # observe and iterate the collection of objects that UDisks2 provides.
        logging.debug("Accessing ObjectManager interface on UDisks2 object")
        self._udisks2_obj_manager = Interface(
            self._udisks2_obj, OBJECT_MANAGER_INTERFACE)
Example #37
0
        def __init__(self):

		self.GetPath()

# get FSO Usage proxy/iface up to request GPS
		self.systembus=systembus = SystemBus(mainloop=e_dbus.DBusEcoreMainLoop())
		self.usage_proxy = self.systembus.get_object('org.freesmartphone.ousaged', '/org/freesmartphone/Usage')
		self.usage_iface = Interface(self.usage_proxy, 'org.freesmartphone.Usage')

# Request GPS from FSO (which then powers on the GPS chip)
		self.usage_iface.RequestResource("GPS")

#get gypsy proxy/iface up
		self.ogpsd_proxy = self.systembus.get_object('org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
		self.course_iface = Interface(self.ogpsd_proxy, 'org.freedesktop.Gypsy.Course')
		self.pos_iface = Interface(self.ogpsd_proxy, 'org.freedesktop.Gypsy.Position')

# call self.UpdatePosition() when a dbus signal "PositionChanged" comes along the system bus
		self.pos_iface.connect_to_signal("PositionChanged", self.UpdatePosition)
Example #38
0
class TrackClient:

	def __init__(self, username='******', passwordhash='', host='localhost', port='49152'):
                self.InitSocket(host, port)
                self.InitDbusStuff()
                self.InitUserHash(username, passwordhash)

        def InitSocket(self, host, port):

# Set the socket parameters
# e.g.	        host = "localhost"
# e.g.	        port = 49152
        	self.__addr = (str(host),int(port))

# Create socket
                self.__UDPSock = socket(AF_INET,SOCK_DGRAM)

# Debug message:
                print "UDP Socket for %s at port %s created" % (host, port)


        def TransmitUDP(self, data):
                if data:
                        self.__UDPSock.sendto(data,self.__addr)

# Debug message:
                        print "UDP stream %s sent" % (data)

        def CloseSocket(self):
                self.__UDPSock.close()

# Debug message:
#               print "UDP Socket closed"


        def InitDbusStuff(self):

# get FSO Usage proxy/iface up to request GPS
		self.systembus=systembus = SystemBus(mainloop=e_dbus.DBusEcoreMainLoop())
		self.usage_proxy = self.systembus.get_object('org.freesmartphone.ousaged', '/org/freesmartphone/Usage')
		self.usage_iface = Interface(self.usage_proxy, 'org.freesmartphone.Usage')

# request GPS from FSO (which then powers on the GPS chip)
		self.usage_iface.RequestResource("GPS")

# get gypsy proxy/iface up
		self.ogpsd_proxy = self.systembus.get_object('org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
		self.course_iface = Interface(self.ogpsd_proxy, 'org.freedesktop.Gypsy.Course')
		self.pos_iface = Interface(self.ogpsd_proxy, 'org.freedesktop.Gypsy.Position')

		self.terminator=""

        def UpdateData(self, fields, timestamp, lat, lon, alt):
# get UTC time from gypsy timestamp
		string = str(datetime.datetime.utcfromtimestamp(timestamp))

		date, time = string.split()
		utctime = "%sT%sZ" % (date, time)

# prepare data for sending
	        UDPData = "%s,%s,%s,%s" % (lat, lon, alt, utctime)
                self.SendData(self.__username, self.__pwhash, 'TRANSMIT', UDPData)

# Debug message:
#                print "Updated Data"

        def InitUserHash(self, username, pwhash):

# set username and password globally in the class
                self.__username = username
                self.__pwhash = pwhash

        def SendData(self, username, pwhash, action, data=""):

# put together and send data to TransmitUDP()
                senddata = "%s;%s;%s;%s" % (username, pwhash, action, data)
                self.TransmitUDP(senddata)


	def StartTrack(self):
		self.SendData(self.__username, self.__pwhash, action="START")

# call self.UpdatePosition() when a dbus signal "PositionChanged" comes along the system bus
# if an event handler has already been set, delete it!
                try:
                        if self.terminator:
                                self.terminator.delete()
                except:
                        pass
                self.terminator = self.pos_iface.connect_to_signal("PositionChanged", self.UpdateData)


        def StopTrack(self):
                self.SendData(self.__username, self.__pwhash, action="STOP")

# remove connect_to_signal event
		self.terminator.remove()
Example #39
0
    def __init__(self):
        super(Client, self).__init__()

        self.__stations = dict()
        self.__channels = dict()
        self.__stream_tags = dict()

        self.__current_channel = None
        self.__is_playing = False

        def register_channel(station, channel):
            if station:
                station.channels.append(channel)

            for stream in channel.streams:
                self.__channels[stream.uri] = channel

            self.__channels[channel.uri] = channel

        def station_added_cb(station):
            id, title, uri, channels = station
            station = Station(id, title, uri)

            for channel in channels:
                channel = self.decode_channel(station, *channel)
                register_channel(station, channel)

            self.__stations[station.id] = station
            self.emit('station-added', station)

        def channel_added_cb(station_id, channel):
            station = self.find_station(station_id)
            channel = self.decode_channel(station, *channel)
            register_channel(station, channel)
            self.emit('channel-added', channel)

        def state_changed_cb(playing, stream_uri):
            self.__stream_tags = self.__service.GetStreamTags()
            self.__current_channel = self.__channels.get(stream_uri)
            self.__is_playing = playing
            self.emit('state-changed')

        def stream_tags_changed_cb(tags):
            self.__stream_tags.update(tags)
            self.emit('stream-tags-changed')

        def name_owner_cb(new_owner):
            if not new_owner:
                # FIXME
                from gtk import main_quit
                main_quit()

        self.__bus = SessionBus()
        proxy = self.__bus.get_object(Service.name, '/')
        self.__bus.watch_name_owner(Service.name, name_owner_cb)
        self.__service = Interface(proxy, Service.interface)
        self.__service.connect_to_signal('StationAdded',      station_added_cb)
        self.__service.connect_to_signal('ChannelAdded',      channel_added_cb)
        self.__service.connect_to_signal('StateChanged',      state_changed_cb)
        self.__service.connect_to_signal('StreamTagsChanged', stream_tags_changed_cb)

        for station in self.__service.GetStations():
            station_added_cb(station)

        state_changed_cb(*self.__service.GetState())
Example #40
0
class UDisks2Observer:
    """
    Class for observing ongoing changes in UDisks2
    """

    def __init__(self):
        """
        Create a UDisks2 model.

        The model must be connected to a bus before it is first used, see
        connect()
        """
        # Proxy to the UDisks2 object
        self._udisks2_obj = None
        # Proxy to the ObjectManager interface exposed by UDisks2 object
        self._udisks2_obj_manager = None

    @Signal.define
    def on_initial_objects(self, managed_objects):
        """
        Signal fired when the initial list of objects becomes available
        """

    @Signal.define
    def on_interfaces_added(self, object_path, interfaces_and_properties):
        """
        Signal fired when one or more interfaces gets added to a specific
        object.
        """

    @Signal.define
    def on_interfaces_removed(self, object_path, interfaces):
        """
        Signal fired when one or more interface gets removed from a specific
        object
        """

    @Signal.define
    def on_properties_changed(self, interface_name, changed_properties,
                              invalidated_properties, sender=None):
        """
        Signal fired when one or more property changes value or becomes
        invalidated.
        """

    def connect_to_bus(self, bus):
        """
        Establish initial connection to UDisks2 on the specified DBus bus.

        This will also load the initial set of objects from UDisks2 and thus
        fire the on_initial_objects() signal from the model. Please call this
        method only after connecting that signal if you want to observe that
        event.
        """
        # Once everything is ready connect to udisks2
        self._connect_to_udisks2(bus)
        # And read all the initial objects and setup
        # change event handlers
        self._get_initial_objects()

    def _connect_to_udisks2(self, bus):
        """
        Setup the initial connection to UDisks2

        This step can fail if UDisks2 is not available and cannot be
        service-activated.
        """
        # Access the /org/freedesktop/UDisks2 object sitting on the
        # org.freedesktop.UDisks2 bus name. This will trigger the necessary
        # activation if udisksd is not running for any reason
        logging.debug("Accessing main UDisks2 object")
        self._udisks2_obj = bus.get_object(
            "org.freedesktop.UDisks2", "/org/freedesktop/UDisks2")
        # Now extract the standard ObjectManager interface so that we can
        # observe and iterate the collection of objects that UDisks2 provides.
        logging.debug("Accessing ObjectManager interface on UDisks2 object")
        self._udisks2_obj_manager = Interface(
            self._udisks2_obj, OBJECT_MANAGER_INTERFACE)
        # Connect to the PropertiesChanged signal. Here unlike before we want
        # to listen to all signals, regardless of who was sending them in the
        # first place.
        logging.debug("Setting up DBus signal handler for PropertiesChanged")
        bus.add_signal_receiver(
            self._on_properties_changed,
            signal_name="PropertiesChanged",
            dbus_interface=PROPERTIES_IFACE,
            # Use the sender_keyword keyword argument to indicate that we wish
            # to know the sender of each signal. For consistency with other
            # signals we choose to use the 'object_path' keyword argument.
            sender_keyword='sender')

    def _get_initial_objects(self):
        """
        Get the initial collection of objects.

        Needs to be called before the first signals from DBus are observed.
        Requires a working connection to UDisks2.
        """
        # Having this interface we can now peek at the existing objects.
        # We can use the standard method GetManagedObjects() to do that
        logging.debug("Accessing GetManagedObjects() on UDisks2 object")
        managed_objects = self._udisks2_obj_manager.GetManagedObjects()
        managed_objects = drop_dbus_type(managed_objects)
        # Fire the public signal for getting initial objects
        self.on_initial_objects(managed_objects)
        # Connect our internal handles to the DBus signal handlers
        logging.debug("Setting up DBus signal handler for InterfacesAdded")
        self._udisks2_obj_manager.connect_to_signal(
            "InterfacesAdded", self._on_interfaces_added)
        logging.debug("Setting up DBus signal handler for InterfacesRemoved")
        self._udisks2_obj_manager.connect_to_signal(
            "InterfacesRemoved", self._on_interfaces_removed)

    def _on_interfaces_added(self, object_path, interfaces_and_properties):
        """
        Internal callback that is called by DBus

        This function is responsible for firing the public signal
        """
        # Convert from dbus types
        object_path = drop_dbus_type(object_path)
        interfaces_and_properties = drop_dbus_type(interfaces_and_properties)
        # Log what's going on
        logging.debug("The object %r has gained the following interfaces and "
                      "properties: %r", object_path, interfaces_and_properties)
        # Call the signal handler
        self.on_interfaces_added(object_path, interfaces_and_properties)

    def _on_interfaces_removed(self, object_path, interfaces):
        """
        Internal callback that is called by DBus

        This function is responsible for firing the public signal
        """
        # Convert from dbus types
        object_path = drop_dbus_type(object_path)
        interfaces = drop_dbus_type(interfaces)
        # Log what's going on
        logging.debug("The object %r has lost the following interfaces: %r",
                      object_path, interfaces)
        # Call the signal handler
        self.on_interfaces_removed(object_path, interfaces)

    def _on_properties_changed(self, interface_name, changed_properties,
                               invalidated_properties, sender=None):
        """
        Internal callback that is called by DBus

        This function is responsible for firing the public signal
        """
        # Convert from dbus types
        interface_name = drop_dbus_type(interface_name)
        changed_properties = drop_dbus_type(changed_properties)
        invalidated_properties = drop_dbus_type(invalidated_properties)
        sender = drop_dbus_type(sender)
        # Log what's going on
        logging.debug("Some object with the interface %r has changed "
                      "properties: %r and invalidated properties %r "
                      "(sender: %s)",
                      interface_name, changed_properties,
                      invalidated_properties, sender)
        # Call the signal handler
        self.on_properties_changed(interface_name, changed_properties,
                                   invalidated_properties, sender)
Example #41
0
class UDisks2Observer(object):
    """
    Class for observing ongoing changes in UDisks2
    """

    def __init__(self):
        """
        Create a UDisks2 model.

        The model must be connected to a bus before it is first used, see
        connect()
        """
        # Proxy to the UDisks2 object
        self._udisks2_obj = None
        # Proxy to the ObjectManager interface exposed by UDisks2 object
        self._udisks2_obj_manager = None

    @Signal.define
    def on_initial_objects(self, managed_objects):
        """
        Signal fired when the initial list of objects becomes available
        """

    @Signal.define
    def on_interfaces_added(self, object_path, interfaces_and_properties):
        """
        Signal fired when one or more interfaces gets added to a specific
        object.
        """

    @Signal.define
    def on_interfaces_removed(self, object_path, interfaces):
        """
        Signal fired when one or more interface gets removed from a specific
        object
        """

    def connect_to_bus(self, bus):
        """
        Establish initial connection to UDisks2 on the specified DBus bus.

        This will also load the initial set of objects from UDisks2 and thus
        fire the on_initial_objects() signal from the model. Please call this
        method only after connecting that signal if you want to observe that
        event.
        """
        # Once everything is ready connect to udisks2
        self._connect_to_udisks2(bus)
        # And read all the initial objects and setup
        # change event handlers
        self._get_initial_objects()

    def _connect_to_udisks2(self, bus):
        """
        Setup the initial connection to UDisks2

        This step can fail if UDisks2 is not available and cannot be
        service-activated.
        """
        # Access the /org/freedesktop/UDisks2 object sitting on the
        # org.freedesktop.UDisks2 bus name. This will trigger the necessary
        # activation if udisksd is not running for any reason
        logging.debug("Accessing main UDisks2 object")
        self._udisks2_obj = bus.get_object(
            "org.freedesktop.UDisks2", "/org/freedesktop/UDisks2")
        # Now extract the standard ObjectManager interface so that we can
        # observe and iterate the collection of objects that UDisks2 provides.
        logging.debug("Accessing ObjectManager interface on UDisks2 object")
        self._udisks2_obj_manager = Interface(
            self._udisks2_obj, OBJECT_MANAGER_INTERFACE)

    def _get_initial_objects(self):
        """
        Get the initial collection of objects.

        Needs to be called before the first signals from DBus are observed.
        Requires a working connection to UDisks2.
        """
        # Having this interface we can now peek at the existing objects.
        # We can use the standard method GetManagedObjects() to do that
        logging.debug("Accessing GetManagedObjects() on UDisks2 object")
        managed_objects = self._udisks2_obj_manager.GetManagedObjects()
        # Fire the public signal for getting initial objects
        self.on_initial_objects(managed_objects)
        # Connect our internal handles to the DBus signal handlers
        logging.debug("Setting up DBus signal handler for InterfacesAdded")
        self._udisks2_obj_manager.connect_to_signal(
            "InterfacesAdded", self._on_interfaces_added)
        logging.debug("Setting up DBus signal handler for InterfacesRemoved")
        self._udisks2_obj_manager.connect_to_signal(
            "InterfacesRemoved", self._on_interfaces_removed)

    def _on_interfaces_added(self, object_path, interfaces_and_properties):
        """
        Internal callback that is called by DBus

        This function is responsible for firing the public signal
        """
        # Log what's going on
        logging.debug("The object %r has gained the following interfaces and"
                      " properties: %r", object_path,
                      interfaces_and_properties)
        # Call the signal handler
        self.on_interfaces_added(object_path, interfaces_and_properties)

    def _on_interfaces_removed(self, object_path, interfaces):
        """
        Internal callback that is called by DBus

        This function is responsible for firing the public signal
        """
        # Log what's going on
        logging.debug("The object %r has lost the following interfaces: %r",
                      object_path,  interfaces)
        # Call the signal handler
        self.on_interfaces_removed(object_path, interfaces)
Example #42
0
    def main(self, argv=None, standalone=None, plugin_argument_provider=None, plugin_manager_settings_prefix=''):
        if argv is None:
            argv = sys.argv

        # extract --args and everything behind manually since argparse can not handle that
        arguments = argv[1:]

        # extract plugin specific args when not being invoked in standalone mode programmatically
        if not standalone:
            plugin_args = []
            if '--args' in arguments:
                index = arguments.index('--args')
                plugin_args = arguments[index + 1:]
                arguments = arguments[0:index + 1]

        parser = ArgumentParser(os.path.basename(Main.main_filename), add_help=False)
        self.add_arguments(parser, standalone=bool(standalone), plugin_argument_provider=plugin_argument_provider)
        self._options = parser.parse_args(arguments)

        if standalone:
            # rerun parsing to separate common arguments from plugin specific arguments
            parser = ArgumentParser(os.path.basename(Main.main_filename), add_help=False)
            self.add_arguments(parser, standalone=bool(standalone))
            self._options, plugin_args = parser.parse_known_args(arguments)
        self._options.plugin_args = plugin_args

        # set default values for options not available in standalone mode
        if standalone:
            self._options.freeze_layout = False
            self._options.lock_perspective = False
            self._options.multi_process = False
            self._options.perspective = None
            self._options.perspective_file = None
            self._options.standalone_plugin = standalone
            self._options.list_perspectives = False
            self._options.list_plugins = False
            self._options.command_pid = None
            self._options.command_start_plugin = None
            self._options.command_switch_perspective = None
            self._options.embed_plugin = None
            self._options.embed_plugin_serial = None
            self._options.embed_plugin_address = None

        # check option dependencies
        try:
            if self._options.plugin_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')

            if self._options.freeze_layout and not self._options.lock_perspective:
                raise RuntimeError('Option --freeze_layout can only be used together with the --lock_perspective 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')

            perspective_options = (self._options.perspective, self._options.perspective_file)
            perspective_options_set = [opt for opt in perspective_options if opt is not None]
            if len(perspective_options_set) > 1:
                raise RuntimeError('Only one --perspective-* option can be used at a time')

            if self._options.perspective_file is not None and not os.path.isfile(self._options.perspective_file):
                raise RuntimeError('Option --perspective-file must reference existing file')

        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

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

        if self._dbus_available:
            from dbus import DBusException, Interface, SessionBus

        # 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.plugin_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, QIcon, QMenuBar

        from .about_handler import AboutHandler
        from .composite_plugin_provider import CompositePluginProvider
        from .container_manager import ContainerManager
        from .help_provider import HelpProvider
        from .icon_loader import get_icon
        from .main_window import MainWindow
        from .minimized_dock_widgets_toolbar import MinimizedDockWidgetsToolbar
        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 = self.create_application(argv)

        self._check_icon_theme_compliance()

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

            main_window = MainWindow()
            if self._options.on_top:
                main_window.setWindowFlags(Qt.WindowStaysOnTopHint)

            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()
            if 'darwin' in platform.platform().lower():
                menu_bar.setNativeMenuBar(True)
            else:
                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)

            main_window = None
            menu_bar = None

        self._add_plugin_providers()

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

        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 main_window 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:
            container_manager = ContainerManager(main_window, plugin_manager)
            plugin_manager.set_main_window(main_window, menu_bar, container_manager)

            if not self._options.freeze_layout:
                minimized_dock_widgets_toolbar = MinimizedDockWidgetsToolbar(container_manager, main_window)
                main_window.addToolBar(Qt.BottomToolBarArea, minimized_dock_widgets_toolbar)
                plugin_manager.set_minimized_dock_widgets_toolbar(minimized_dock_widgets_toolbar)

        if menu_bar is not None:
            perspective_menu = menu_bar.addMenu(menu_bar.tr('P&erspectives'))
            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(context.qtgui_path, 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()

        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 plugin:
                perspective_manager.set_perspective(plugin, hide_and_without_plugin_changes=True)
            elif self._options.perspective_file:
                perspective_manager.import_perspective_from_file(self._options.perspective_file, perspective_manager.HIDDEN_PREFIX + '__cli_perspective_from_file')
            else:
                perspective_manager.set_perspective(self._options.perspective)

        # load specific plugin
        if plugin:
            plugin_manager.load_plugin(plugin, plugin_serial, self._options.plugin_args)
            running = plugin_manager.is_plugin_running(plugin, plugin_serial)
            if not running:
                return 1
            if self._options.standalone_plugin:
                # use icon of standalone plugin (if available) for application
                plugin_descriptor = plugin_manager.get_plugin_descriptor(plugin)
                action_attributes = plugin_descriptor.action_attributes()
                if 'icon' in action_attributes and action_attributes['icon'] is not None:
                    base_path = plugin_descriptor.attributes().get('plugin_path')
                    try:
                        icon = get_icon(action_attributes['icon'], action_attributes.get('icontype', None), base_path)
                    except UserWarning:
                        pass
                    else:
                        app.setWindowIcon(icon)

        if main_window is not None:
            main_window.show()
            if sys.platform == 'darwin':
                main_window.raise_()

        return app.exec_()
class PluginHandlerXEmbedClient(PluginHandlerDirect):

    """
    Client part of the `PluginHandlerXEmbed`.
    It utilizes the `PluginHandlerDBusService` of the `PluginHandlerXEmbedContainer` through a peer-to-peer DBus connection.
    """

    def __init__(self, parent, main_window, instance_id, application_context, container_manager, argv, dbus_object_path):
        super(PluginHandlerXEmbedClient, self).__init__(parent, main_window, instance_id, application_context, container_manager, argv)
        self.setObjectName('PluginHandlerXEmbedClient')
        self._dbus_object_path = dbus_object_path
        self._remote_container = None
        self._remote_plugin_settings = None
        self._remote_instance_settings = None
        # mapping of added widgets to their embed widget and WindowChangedSignaler
        self._embed_widgets = {}

    def _load(self):
        conn = Connection(self._application_context.options.embed_plugin_address)
        proxy = conn.get_object(None, self._dbus_object_path)
        self._remote_container = Interface(proxy, 'org.ros.qt_gui.PluginHandlerContainer')
        self._remote_container.connect_to_signal('shutdown_plugin', self._shutdown_plugin)
        self._remote_container.connect_to_signal('save_settings', self._save_settings_from_remote)
        self._remote_container.connect_to_signal('restore_settings', self._restore_settings_from_remote)
        self._remote_container.connect_to_signal('trigger_configuration', self._trigger_configuration)
        self._remote_container.connect_to_signal('toolbar_orientation_changed', self._toolbar_orientation_changed)

        proxy = conn.get_object(None, self._dbus_object_path + '/plugin')
        self._remote_plugin_settings = Interface(proxy, 'org.ros.qt_gui.Settings')
        proxy = conn.get_object(None, self._dbus_object_path + '/instance')
        self._remote_instance_settings = Interface(proxy, 'org.ros.qt_gui.Settings')

        super(PluginHandlerXEmbedClient, self)._load()

    def _emit_load_completed(self, exception=None):
        # signal failed loading before emitting signal, as it might not be possible afterwards
        if exception is not None:
            self._remote_container.load_completed(False, False)
        super(PluginHandlerXEmbedClient, self)._emit_load_completed(exception)
        # signal successful loading after emitting signal, for better message order
        if exception is None:
            self._remote_container.load_completed(True, self._plugin_has_configuration)

    def shutdown_plugin(self, callback):
        # this method should never be called for embedded clients
        assert(False)

    def emit_shutdown_plugin_completed(self):
        self._remote_container.shutdown_plugin_completed()

    def save_settings(self, plugin_settings, instance_settings, callback=None):
        # this method should never be called for embedded clients
        assert(False)

    def _save_settings_from_remote(self):
        qDebug('PluginHandlerXEmbedClient._save_settings_from_remote()')
        try:
            plugin_settings = Settings(self._remote_plugin_settings, '')
            instance_settings = Settings(self._remote_instance_settings, '')
            self._save_settings(plugin_settings, instance_settings)
        except Exception:
            qCritical('PluginHandlerXEmbedClient._save_settings_from_remote() plugin "%s" raised an exception:\n%s' % (str(self._instance_id), traceback.format_exc()))
            self.emit_save_settings_completed()

    def emit_save_settings_completed(self):
        self._remote_container.save_settings_completed()

    def restore_settings(self, plugin_settings, instance_settings, callback=None):
        # this method should never be called for embedded clients
        assert(False)

    def _restore_settings_from_remote(self):
        qDebug('PluginHandlerXEmbedClient._restore_settings_from_remote()')
        try:
            plugin_settings = Settings(self._remote_plugin_settings, '')
            instance_settings = Settings(self._remote_instance_settings, '')
            self._restore_settings(plugin_settings, instance_settings)
        except Exception:
            qCritical('PluginHandlerXEmbedClient._restore_settings_from_remote() plugin "%s" raised an exception:\n%s' % (str(self._instance_id), traceback.format_exc()))
            self.emit_restore_settings_completed()

    def emit_restore_settings_completed(self):
        self._remote_container.restore_settings_completed()

    # pointer to QWidget must be used for PySide to work (at least with 1.0.1)
    @Slot('QWidget*')
    def add_widget(self, widget):
        if widget in self._embed_widgets:
            qWarning('PluginHandlerXEmbedClient.add_widget() widget "%s" already added' % widget.objectName())
            return
        embed_widget = QX11EmbedWidget()
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(widget)
        embed_widget.setLayout(layout)

        # close embed widget when container is closed
        # TODO necessary?
        #embed_widget.containerClosed.connect(embed_widget.close)

        embed_container_window_id = self._remote_container.embed_widget(os.getpid(), widget.objectName())
        embed_widget.embedInto(embed_container_window_id)

        signaler = WindowChangedSignaler(widget, widget)
        signaler.window_icon_changed_signal.connect(self._on_embed_widget_icon_changed)
        signaler.window_title_changed_signal.connect(self._on_embed_widget_title_changed)
        self._embed_widgets[widget] = embed_widget, signaler
        # trigger to update initial window icon and title
        signaler.window_icon_changed_signal.emit(widget)
        signaler.window_title_changed_signal.emit(widget)

        embed_widget.show()

    def _on_embed_widget_icon_changed(self, widget):
        # serialize icon base64-encoded string
        ba = QByteArray()
        s = QDataStream(ba, QIODevice.WriteOnly)
        s << widget.windowIcon()
        icon_str = str(ba.toBase64())
        self._remote_container.update_embedded_widget_icon(widget.objectName(), icon_str)

    def _on_embed_widget_title_changed(self, widget):
        self._remote_container.update_embedded_widget_title(widget.objectName(), widget.windowTitle())

    # pointer to QWidget must be used for PySide to work (at least with 1.0.1)
    @Slot('QWidget*')
    def remove_widget(self, widget):
        embed_widget, signaler = self._embed_widgets[widget]
        del self._embed_widgets[widget]
        signaler.window_icon_changed_signal.disconnect(self._on_embed_widget_icon_changed)
        signaler.window_title_changed_signal.disconnect(self._on_embed_widget_title_changed)
        self._remote_container.unembed_widget(widget.objectName())
        # do not delete the widget, only the embed widget
        widget.setParent(None)
        embed_widget.deleteLater()
        # triggering close after last widget and toolbar is closed is handled by the container

    # pointer to QToolBar must be used for PySide to work (at least with 1.0.1)
    @Slot('QToolBar*')
    def add_toolbar(self, toolbar):
        if toolbar in self._embed_widgets:
            qWarning('PluginHandlerXEmbedClient.add_toolbar() toolbar "%s" already added' % toolbar.objectName())
            return
        embed_widget = QX11EmbedWidget()
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(toolbar)
        embed_widget.setLayout(layout)

        # close embed widget when container is closed
        # TODO necessary?
        #embed_widget.containerClosed.connect(embed_widget.close)
        def foo():
            print('embed_widget.containerClosed')
        embed_widget.containerClosed.connect(foo)

        embed_container_window_id = self._remote_container.embed_toolbar(os.getpid(), toolbar.objectName())
        embed_widget.embedInto(embed_container_window_id)

        self._embed_widgets[toolbar] = embed_widget, None

        embed_widget.show()

    def _toolbar_orientation_changed(self, win_id, is_horizontal):
        for toolbar, (embed_widget, _) in self._embed_widgets.items():
            if embed_widget.containerWinId() == win_id:
                toolbar.setOrientation(Qt.Horizontal if is_horizontal else Qt.Vertical)
                break

    # pointer to QToolBar must be used for PySide to work (at least with 1.0.1)
    @Slot('QToolBar*')
    def remove_toolbar(self, toolbar):
        embed_widget, _ = self._embed_widgets[toolbar]
        del self._embed_widgets[toolbar]
        self._remote_container.unembed_widget(toolbar.objectName())
        # do not delete the toolbar, only the embed widget
        toolbar.setParent(None)
        embed_widget.deleteLater()
        # triggering close after last widget and toolbar is closed is handled by the container

    def _emit_close_plugin(self):
        self._remote_container.close_plugin()
Example #44
0
class Client(GObject):
    (STATE_INITIALIZED,
     STATE_STATIONS_LOADED,
     STATE_CHANNELS_LOADED) = range(3)

    __gtype_name__ = 'WebRadioClient'

    __gsignals__ = {
        'station-added':       (SIGNAL_RUN_LAST, TYPE_NONE, (object,)),
        'channel-added':       (SIGNAL_RUN_LAST, TYPE_NONE, (object,)),
        'state-changed':       (SIGNAL_RUN_LAST, TYPE_NONE, ()),
        'stream-tags-changed': (SIGNAL_RUN_LAST, TYPE_NONE, ()),
    }

    @staticmethod
    def decode_stream(uri, title, length):
        return Stream(uri, title, length)

    @classmethod
    def decode_channel(cls, station, uri, tags, streams):
        streams = [cls.decode_stream(*s) for s in streams]
        return Channel(station, uri, tags, streams)

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

        self.__stations = dict()
        self.__channels = dict()
        self.__stream_tags = dict()

        self.__current_channel = None
        self.__is_playing = False

        def register_channel(station, channel):
            if station:
                station.channels.append(channel)

            for stream in channel.streams:
                self.__channels[stream.uri] = channel

            self.__channels[channel.uri] = channel

        def station_added_cb(station):
            id, title, uri, channels = station
            station = Station(id, title, uri)

            for channel in channels:
                channel = self.decode_channel(station, *channel)
                register_channel(station, channel)

            self.__stations[station.id] = station
            self.emit('station-added', station)

        def channel_added_cb(station_id, channel):
            station = self.find_station(station_id)
            channel = self.decode_channel(station, *channel)
            register_channel(station, channel)
            self.emit('channel-added', channel)

        def state_changed_cb(playing, stream_uri):
            self.__stream_tags = self.__service.GetStreamTags()
            self.__current_channel = self.__channels.get(stream_uri)
            self.__is_playing = playing
            self.emit('state-changed')

        def stream_tags_changed_cb(tags):
            self.__stream_tags.update(tags)
            self.emit('stream-tags-changed')

        def name_owner_cb(new_owner):
            if not new_owner:
                # FIXME
                from gtk import main_quit
                main_quit()

        self.__bus = SessionBus()
        proxy = self.__bus.get_object(Service.name, '/')
        self.__bus.watch_name_owner(Service.name, name_owner_cb)
        self.__service = Interface(proxy, Service.interface)
        self.__service.connect_to_signal('StationAdded',      station_added_cb)
        self.__service.connect_to_signal('ChannelAdded',      channel_added_cb)
        self.__service.connect_to_signal('StateChanged',      state_changed_cb)
        self.__service.connect_to_signal('StreamTagsChanged', stream_tags_changed_cb)

        for station in self.__service.GetStations():
            station_added_cb(station)

        state_changed_cb(*self.__service.GetState())

    def wait(self, stage=STATE_CHANNELS_LOADED):
        loop = MainLoop(None, True)

        def data_ready_cb(new_stage):
            if new_stage >= stage:
                loop.quit()

        self.__service.connect_to_signal('DataReady', data_ready_cb)

        if self.__service.GetDataStage() >= stage:
            loop.quit()

        progress_id = 0

        if loop.is_running():
            if sys.stdout.isatty():
                progress = ['-\r', '\\\r', '|\r', '/\r']

                def progress_cb():
                    c = progress.pop(0)
                    sys.stdout.write(c)
                    sys.stdout.flush()
                    progress.append(c)
                    return True

                progress_id = timeout_add(250, progress_cb)
                sys.stdout.write('  loading...\r')

            loop.run()

        if progress_id:
            source_remove(progress_id)
            sys.stdout.write('\r\033[K')
            sys.stdout.flush()

    def find_channels(self, query=[]):
        result = list()

        for station_id, channel in self.__service.Find(query):
            station = self.__stations.get(station_id)
            channel = self.decode_channel(station, *channel)
            result.append(channel)

        return result

    def find_station(self, id):
        return self.__stations.get(id)
    def get_stations(self):
        return self.__stations.values()

    def get_tags(self):
        return self.__service.GetTags()

    def play(self, channel):
        self.__service.Play(channel.streams[0].uri)

    def pause(self):
        self.__service.Pause()

    def resume(self):
        self.__service.Resume()

    def quit(self):
        self.__service.Quit()

    def get_equalizer_profiles(self):
        return self.__service.ListEqualizerProfiles()
    def __get_equalizer_profile(self):
        return self.__service.GetEqualizerProfile()
    def __set_equalizer_profile(self, value):
        self.__service.SetEqualizerProfile(value)

    is_playing = property(fget=lambda self: self.__is_playing)
    current_channel = property(fget=lambda self: self.__current_channel)
    stream_tags = property(fget=lambda self: self.__stream_tags)
    equalizer_profile = property(fget=__get_equalizer_profile, fset=__set_equalizer_profile)