Exemple #1
0
 def create_loop(cls):
     loop = GLib.MainLoop()
     # See: https://dbus.freedesktop.org/doc/dbus-python/
     # dbus.mainloop.html?highlight=thread#dbus.mainloop.glib.threads_init
     threads_init()
     DBusGMainLoop(set_as_default=True)
     return loop
Exemple #2
0
	def __init__(self):
		threads_init()
		dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
		threads_init()
		bus = dbus.SessionBus()
		
		obj = bus.get_object("im.pidgin.purple.PurpleService",
		                     "/im/pidgin/purple/PurpleObject")
		#object used for send messages and more
		self.purple = dbus.Interface(obj,
		                             "im.pidgin.purple.PurpleInterface")
		
		#Signal for nudges
		bus.add_signal_receiver(self.got_attention,
					dbus_interface=
					"im.pidgin.purple.PurpleInterface",
					signal_name="GotAttention")
		#Signal for CoversationUpdates
		bus.add_signal_receiver(self.conversation_updated,
					dbus_interface=
					"im.pidgin.purple.PurpleInterface",
					signal_name="ConversationUpdated")
		#Signal for incomming messages
		bus.add_signal_receiver(self.recv_msg,
					dbus_interface=
					"im.pidgin.purple.PurpleInterface",
					signal_name="ReceivedImMsg")
Exemple #3
0
    def _setup_dbus_interfaces(self):
        from dbus.mainloop.glib import DBusGMainLoop
        self._mainloop = DBusGMainLoop(set_as_default=True)
        import dbus.mainloop.glib as gml
        gml.threads_init()

        self._bus = dbus.SystemBus(mainloop=self._mainloop)
        self._session_bus = dbus.SessionBus(mainloop=self._mainloop)
        self._proxy = self._bus.get_object('org.freedesktop.login1',
                                           '/org/freedesktop/login1')
        self._login1 = dbus.Interface(self._proxy,
                                      'org.freedesktop.login1.Manager')

        self._nsess_notiy = self._login1.connect_to_signal(
            "SessionNew",
            lambda sID, path: self._mod_session(add=True, path=path))
        self._rsess_notiy = self._login1.connect_to_signal(
            "SessionRemoved",
            lambda sID, path: self._mod_session(add=False, path=path))

        for session in self._login1.ListSessions():
            self._logger.info(
                "Neue Benutzersession gefunden {} auf {} in Pfad {}.".format(
                    session[2], session[3], session[4]))
            self._mod_session(add=True, path=session[4])

        if self._config.get("inactivity_ms", None) is not None:
            self._idle_monitor = IdleMonitor(
                self._config["inactivity_ms"],
                self._logger,
                self._pluginManager,
                self._session_bus,
                netName=autodisc.Topics.get_std_devInf().name
                if self._config.get("custom_name", None) is None else
                self._config.get("custom_name", None))
    def run ( self ):
        threads_init()
        self.need_to_quit = False
        self.path_to_watch = os.path.abspath (self.path_to_watch)
        print "Watching %s at %s" % (self.path_to_watch, time.asctime ())
        hDir = win32file.CreateFile(
            self.path_to_watch,
            win32con.GENERIC_READ,
            win32con.FILE_SHARE_READ|win32con.FILE_SHARE_WRITE,
            None,
            win32con.OPEN_EXISTING,
            win32con.FILE_FLAG_BACKUP_SEMANTICS,
            None
        )
        cnt = 0
        while not self.need_to_quit:
#            print "new watch\n"
            results = win32file.ReadDirectoryChangesW(
                hDir,
                1024,
                True,
                win32con.FILE_NOTIFY_CHANGE_FILE_NAME
                | win32con.FILE_NOTIFY_CHANGE_DIR_NAME
                | win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES
                | win32con.FILE_NOTIFY_CHANGE_SIZE
                | win32con.FILE_NOTIFY_CHANGE_LAST_WRITE
                | win32con.FILE_NOTIFY_CHANGE_SECURITY,
                None,
                None
            )
            if not self.need_to_quit:
                for action, file in results:
                    #full_filename = os.path.join (self.path_to_watch, file)
                    #print full_filename, ACTIONS.get (action, "Unknown")
                    self.callback(self.path_to_watch, file, ACTIONS.get (action, "Unknown"))
Exemple #5
0
def loop_init():
    global _loop
    if not _loop:
        from dbus.mainloop.glib import DBusGMainLoop, threads_init
        threads_init()
        _loop = DBusGMainLoop(set_as_default=True)
    return _loop
Exemple #6
0
def loop_init():
    global _loop
    if not _loop:
        from dbus.mainloop.glib import DBusGMainLoop, threads_init
        threads_init()
        _loop = DBusGMainLoop(set_as_default=True)
    return _loop
Exemple #7
0
 def run(self):
     ###########
     #The following are required if threads are used in the services
     gtk.gdk.threads_init()
     from dbus.mainloop.glib import threads_init
     threads_init()
     #The above lines are required if threads are used in the services
     #################
     gtk.gdk.threads_enter()
     cnt = 0
     while True:
         item = self.pendingQ.get()
         print 'get item', item
         if item:
             self.pendingQ.task_done()
             break
         if True:#try:
             print 'calling subClassProcess'
             self.subClassProcess()
             #except:
             pass
         self.pendingQ.task_done()
         
         cnt = cnt + 1
         print cnt
     gtk.gdk.threads_leave()
     print 'returning'
Exemple #8
0
def init():
  load_version_libs()
  dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
  loop = glib.MainLoop()
  signal.signal(signal.SIGINT, lambda n, f: loop.quit())
  glib.threads_init()
  return loop
Exemple #9
0
def startServer(configfile,
                basedir,
                host,
                port,
                debug,
                allowRoot,
                logConf=None):
    signal(SIGTERM, lambda signum, stack_frame: sys.exit(1)
           )  #Redirects "nice" kill commands to SystemExit exception
    signal(SIGINT, lambda signum, stack_frame: sys.exit(1)
           )  #Redirects CTRL+C to SystemExit exception

    global astrobox

    astrobox = Server(configfile, basedir, host, port, debug, allowRoot,
                      logConf)

    try:
        from gi.repository import GObject
        from dbus.mainloop.glib import DBusGMainLoop, threads_init

        DBusGMainLoop(set_as_default=True)

        GObject.threads_init()
        threads_init()

    except ImportError:
        pass

    astrobox.run()
Exemple #10
0
def connect_to_session_bus():
    """
    Connect to the session bus properly.

    Returns a tuple (session_bus, loop) where loop is a GObject.MainLoop
    instance. The loop is there so that you can listen to signals.
    """
    # We'll need an event loop to observe signals. We will need the instance
    # later below so let's keep it. Note that we're not passing it directly
    # below as DBus needs specific API. The DBusGMainLoop class that we
    # instantiate and pass is going to work with this instance transparently.
    #
    # NOTE: DBus tutorial suggests that we should create the loop _before_
    # connecting to the bus.
    logger.debug("Setting up glib-based event loop")
    # Make sure gobject threads don't crash
    GObject.threads_init()
    threads_init()
    loop = GObject.MainLoop()
    # Let's get the system bus object.
    logger.debug("Connecting to DBus session bus")
    if os.getenv("DBUS_STARTER_ADDRESS"):
        session_bus = StarterBus(mainloop=DBusGMainLoop())
    else:
        session_bus = SessionBus(mainloop=DBusGMainLoop())
    return session_bus, loop
Exemple #11
0
def connect_to_session_bus():
    """
    Connect to the session bus properly.

    Returns a tuple (session_bus, loop) where loop is a GObject.MainLoop
    instance. The loop is there so that you can listen to signals.
    """
    # We'll need an event loop to observe signals. We will need the instance
    # later below so let's keep it. Note that we're not passing it directly
    # below as DBus needs specific API. The DBusGMainLoop class that we
    # instantiate and pass is going to work with this instance transparently.
    #
    # NOTE: DBus tutorial suggests that we should create the loop _before_
    # connecting to the bus.
    logger.debug("Setting up glib-based event loop")
    # Make sure gobject threads don't crash
    GObject.threads_init()
    threads_init()
    loop = GObject.MainLoop()
    # Let's get the system bus object.
    logger.debug("Connecting to DBus session bus")
    if os.getenv("DBUS_STARTER_ADDRESS"):
        session_bus = StarterBus(mainloop=DBusGMainLoop())
    else:
        session_bus = SessionBus(mainloop=DBusGMainLoop())
    return session_bus, loop
Exemple #12
0
def loop_init():
    global _loop_init_done
    if _loop_init_done:
        return
    from dbus.mainloop.glib import DBusGMainLoop, threads_init
    threads_init()
    DBusGMainLoop(set_as_default=True)
    _loop_init_done = True
def call_signal(callback):
    '''add dbus signal'''
    DBusGMainLoop(set_as_default=True)
    threads_init()  #Fix bug
    bus = dbus.SystemBus()
    bus.add_signal_receiver(callback,
                            dbus_interface=DBUS_IFACE,
                            signal_name='changed')
Exemple #14
0
def loop_init():
    global _loop_init_done
    if _loop_init_done:
        return
    from dbus.mainloop.glib import DBusGMainLoop, threads_init
    threads_init()
    DBusGMainLoop(set_as_default=True)
    _loop_init_done = True
Exemple #15
0
def run():
    loop = MainLoop()
    bus = SystemBus(mainloop=dglib.DBusGMainLoop())
    dglib.threads_init()

    bat_object = bus.get_object(
        'org.freedesktop.UPower',
        '/org/freedesktop/UPower/devices/battery_BAT1')
    bat = Interface(bat_object, 'org.freedesktop.DBus.Properties')

    lemonbar = Feeder(i3, bat, bus, bar, display_title)
    lemonbar.render_all()

    pulse = Pulse('event-printer')
    pulse.event_mask_set('sink', 'server')
    pulse.event_callback_set(lemonbar.on_volume_event)
    pulse_thread = Thread(target=pulse.event_listen, args=[0])
    pulse_thread.daemon = True
    pulse_thread.start()

    bat_object.connect_to_signal(
        "PropertiesChanged",
        lemonbar.on_battery_event,
        dbus_interface='org.freedesktop.DBus.Properties')
    bat_thread = Thread(target=loop.run)
    bat_thread.daemon = True
    bat_thread.start()

    sched = BackgroundScheduler(daemon=True)
    sched.add_job(lemonbar.on_timedate_event, 'cron', second=0)
    sched.start()

    def shutdown(caller, e):
        bar.stop_bar(wbak, bar_pid)
        print(e.change)
        exit(0)

    def reload_bar(caller, data):
        global bar_pid
        bar.stop_bar(wbak, bar_pid)
        #print("reloading...")
        bar_pid = bar.start_bar()
        lemonbar.set_outputs()
        lemonbar.render_all(caller=caller, e=data)

    i3.on('workspace::urgent', lemonbar.on_workspace_event)
    i3.on('workspace::empty', lemonbar.on_workspace_event)
    if display_title:
        i3.on('window::title', lemonbar.on_window_title_change)
        i3.on('window::close', lemonbar.on_window_close)
        i3.on('window::focus', lemonbar.on_window_title_change)
        i3.on('workspace::focus', lemonbar.on_workspace_focus)
    else:
        i3.on('workspace::focus', lemonbar.on_workspace_event)
    i3.on('mode', lemonbar.on_binding_mode_change)
    i3.on('output', reload_bar)
    i3.on('shutdown', shutdown)
    i3.main()
Exemple #16
0
def main():
    logging.getLogger().setLevel(LOG_LEVEL)
    glib.threads_init()

    service_thread = ServiceThread('Television', 2015)
    logging.info('Starting service thread.')
    service_thread.start()

    waitForComplete([service_thread])
Exemple #17
0
def main():
    logging.getLogger().setLevel(LOG_LEVEL)
    glib.threads_init()

    service_thread = ServiceThread('Television', 2015)
    logging.info('Starting service thread.')
    service_thread.start()

    waitForComplete([service_thread])
Exemple #18
0
	def __init__(self):
		super(DebianNetworkManager, self).__init__()
		self._nm = NetworkManager
		self._eventListener = NetworkManagerEvents(self)

		threads_init()
		self._eventListener.start()
		logger.info('NetworkManagerEvents is listening for signals')

		if not self.settings.getBoolean(['wifi', 'hotspotOnlyOffline']):
			self.startHotspot()
Exemple #19
0
def _dbus_init():
    try:
        from dbus.mainloop.glib import DBusGMainLoop, threads_init
    except ImportError:
        try:
            import dbus.glib
        except ImportError:
            return
    else:
        threads_init()
        DBusGMainLoop(set_as_default=True)
Exemple #20
0
 def __init__(self, logger=logging, diskClass=object):
     """
     Le constructeur.
     @param logger un objet permettant de journaliser les messages ; 
     par défaut il se confond avec le module logging
     @param diskClass la classe à utiliser pour créer des instances de disques
     """
     self.install_thread = None
     self.logger=logger
     ## self.targets est un dictionnaire des disques détectés
     ## les clés sont les paths et les contenus des instances de diskClass
     self.diskClass=diskClass
     self.targets = {}
     ## self.modified signifie une modification récente, à prendre en compte
     ## par une application au niveau utilisateur
     self.modified=False
     DBusGMainLoop(set_as_default=True)
     threads_init()
     self.bus = dbus.SystemBus()
     self.udisks = UDisks.Client.new_sync(None)
     self.manager = self.udisks.get_object_manager()
     self.cbHooks = {
         'object-added':      {
             'profile': ['man', 'obj'],
             'hooks'  : []
             },
         'object-removed':      {
             'profile': ['man', 'obj'],
             'hooks'  : []
             },
         'interface-added':      {
             'profile': ['man', 'obj'],
             'hooks'  : []
             },
         'interface-removed':      {
             'profile': ['man', 'obj'],
             'hooks'  : []
             },
         'interface-proxy-properties-changed':      {
             'profile': ['man', 'obj', 'interface'],
             'hooks'  : []
             },
     }
     # mise en place des fonctions de rappel à utiliser pour tout changement
     self.addHook('object-added',
                  lambda man, obj: self._udisks_obj_added(obj))
     self.addHook('object-removed',
                  lambda man, obj: self._udisks_obj_removed(obj))
     self.addHook('interface-added',
                  lambda man, obj, iface: self._device_changed(obj))
     self.addHook('interface-removed',
                  lambda man, obj, iface: self._device_changed(obj))
     self.addHook('interface-proxy-properties-changed',
                  lambda man, obj, iface, props, invalid: self._device_changed(obj))
Exemple #21
0
def startAppRunnerService(target = None):
    from dbus.mainloop.glib import threads_init
    threads_init()
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    session_bus = dbus.SessionBus()
    name = dbus.service.BusName("com.wwjufsdatabase.appStarterService", session_bus)
    object = appStarter(session_bus, '/appStarter')
    object.setTarget(target)
    mainloop = gobject.MainLoop()
    mainloop.run()
Exemple #22
0
    def init_dbus_ifaces(self):
        try:
            LOG.info("InstallBackend init_dbus_ifaces (" + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f") + ")")
            DBusGMainLoop(set_as_default=True)
            threads_init()
            bus = dbus.SystemBus()
        except Exception as e:
            if (Globals.DEBUG_DEBUG_SWITCH):
                print("could not initiate dbus")
            LOG.error("dbus exception:%s" % str(e))
            #self.init_models_ready.emit("fail","初始化失败!")
            self.init_models_ready.emit("fail", _("Initialization failed"))
            return False

        try:
            LOG.info("InstallBackend init_dbus_ifaces call blocking (%s)" % datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
            bus.call_blocking(UBUNTUKYLIN_SERVICE_PATH, '/', UBUNTUKYLIN_INTERFACE_PATH, 'wakeup', None, (), timeout=5)
        except dbus.DBusException as e:
            LOG.error("InstallBackend DBusConnection call blocking exception: %s" % str(e))
            return False

        try:
            LOG.info("InstallBackend init_dbus_ifaces bus.get_object (%s)" % datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
            obj = bus.get_object(UBUNTUKYLIN_SERVICE_PATH, '/')
            LOG.info("InstallBackend init_dbus_ifaces dbus.Interface (%s)" % datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
            self.iface = dbus.Interface(obj, dbus_interface=UBUNTUKYLIN_INTERFACE_PATH)
            LOG.info("InstallBackend init_dbus_ifaces finished (%s)" % datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))

            # lixiang: Repeated starts dbus service may cause 25 seconds stuck because of bus.get_object or connect_to_signal
            #if self.iface is not None:
            #    LOG.info("InstallBackend start to connect signal named software_apt_signal (%s)" % datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
            #    self.iface.connect_to_signal("software_apt_signal",self._on_software_apt_signal, dbus_interface=UBUNTUKYLIN_INTERFACE_PATH)
            #    LOG.info("InstallBackend start to connect signal named software_fetch_signal (%s)" % datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
            #    self.iface.connect_to_signal("software_fetch_signal",self._on_software_fetch_signal, dbus_interface=UBUNTUKYLIN_INTERFACE_PATH)
            #    LOG.info("InstallBackend start to connect signal named software_auth_signal (%s)" % datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
            #    self.iface.connect_to_signal("software_auth_signal",self._on_software_auth_signal, dbus_interface=UBUNTUKYLIN_INTERFACE_PATH)
            #    LOG.info("InstallBackend connect signals finished (%s)" % datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
            #else:
            #    LOG.info("InstallBackend dbus interface in none (%s)" % datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
        except dbus.DBusException as e:
#            bus_name = dbus.service.BusName('com.ubuntukylin.softwarecenter', bus)
#            self.dbusControler = SoftwarecenterDbusController(self, bus_name)
#           self.init_models_ready.emit("fail","初始化失败!")
            self.init_models_ready.emit("fail",_("Initialization failed"))
            LOG.error("InstallBackend DBusConnection exception: %s" % str(e))
            if(Globals.DEBUG_SWITCH):
                print("dbus.DBusException error: ",str(e))
            return False

        # lixiang: QTimer no response ???
        GObject.timeout_add(2000, self.slotTimeout)

        return True
Exemple #23
0
 def __init__(self, sessionBus, objectPath, appConfigDictInst = None):
     dbus.service.Object.__init__(self, sessionBus, objectPath)
     self.appConfigDictInst = appConfigDictInst
     self.pendingQ = Queue.Queue()
     self.t = None
     ###########
     #The following are required if threads are used in the services
     gtk.gdk.threads_init()
     from dbus.mainloop.glib import threads_init
     threads_init()
     #The above lines are required if threads are used in the services
     #################
     gtk.gdk.threads_enter()
Exemple #24
0
def _dbus_init():
    try:
        from dbus.mainloop.glib import DBusGMainLoop, threads_init
    except ImportError:
        try:
            import dbus.glib
        except ImportError:
            return
    else:
        import gobject
        gobject.threads_init()
        threads_init()
        DBusGMainLoop(set_as_default=True)
Exemple #25
0
def startAppRunnerService(target = None):
    ########################
    #Start dbus deamon first
    ########################
    dbusAppName = "dbus-daemon.exe"
    dbusAppPath = fileTools.findFileInProduct(dbusAppName)
    processObj = None
    if not (dbusAppPath is None):
        print 'launching dbus daemon'
        processObj = subprocess.Popen([dbusAppPath, "--config-file=session.conf"],
                                        creationflags = CREATE_NO_WINDOW)
    ########################
    threads_init()
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
    session_bus = dbus.SessionBus()
    name = dbus.service.BusName("com.wwjufsdatabase.appStarterService", session_bus)
    mainloop = gobject.MainLoop()
    
    ############################
    #Start app starter service
    ############################
    #Set message target so start app message can be sent to the GTK desktop application. And the GTK desktop
    #application will start the real application and add entry to task bar icon menu.
    object = appStarter(session_bus, '/appStarter')
    object.setTarget(target)
    #Set the mainloop obj so app starter service provides 
    object.setLoop(mainloop)
    
    ############################
    #Start task manager service
    ############################
    taskManagerObj = taskManager.taskManagerService(session_bus, '/taskManager')    
    #Only appStarter need to take control on stop the bus message loop
    #taskManagerObj.setLoop(mainloop)
    
    ############################
    #Start task manager service
    ############################
    #dirMon = dirMonitorService.dirMonitorService(session_bus, '/dirMonitor')

    ############################
    #Start main message loop for DBus services
    ############################
    mainloop.run()
    '''
    if not (processObj is None):
        print 'processing:', processObj.pid, int(processObj._handle)
        processManager.killChildProcessTree(processObj.pid)
        win32api.TerminateProcess(int(processObj._handle), -1)
    '''
    print 'quitting mainloop.run()'
Exemple #26
0
def _init_dbus():
    """Setup dbus mainloop integration. Call before using dbus"""

    try:
        from dbus.mainloop.glib import DBusGMainLoop, threads_init
    except ImportError:
        try:
            import dbus.glib
            dbus.glib
        except ImportError:
            return
    else:
        threads_init()
        DBusGMainLoop(set_as_default=True)
Exemple #27
0
def _init_dbus():
    """Setup dbus mainloop integration. Call before using dbus"""

    try:
        from dbus.mainloop.glib import DBusGMainLoop, threads_init
    except ImportError:
        try:
            import dbus.glib
            dbus.glib
        except ImportError:
            return
    else:
        threads_init()
        DBusGMainLoop(set_as_default=True)
Exemple #28
0
def test():
    import signal
    from dbus.mainloop.glib import DBusGMainLoop, threads_init
    DBusGMainLoop(set_as_default=True)
    threads_init()
    app = QApplication([])
    app.setApplicationName('Testing SNI Interface')
    signal.signal(signal.SIGINT, signal.SIG_DFL)  # quit on Ctrl-C
    tray_icon = factory().create_indicator()
    tray_icon.setToolTip('A test tooltip')
    tray_icon.setIcon(QIcon(I('debug.png')))
    m = QMenu()
    m.addAction('Quit this application', app.quit)
    tray_icon.setContextMenu(m)
    app.exec_()
def _browser():
    import dbus
    import gobject
    from dbus.mainloop.glib import threads_init, DBusGMainLoop

    gobject.threads_init()
    threads_init()
    DBusGMainLoop(set_as_default=True)

    bus = dbus.SystemBus()
    server = dbus.Interface(bus.get_object(_DBUS_NAME, '/'),
                            'org.freedesktop.Avahi.Server')

    def ItemNew_cb(interface, protocol, name, stype, domain, flags):
        if flags & _LOOKUP_RESULT_LOCAL:
            return
        _logger.debug('Got new workstation: %s', name)
        server.ResolveService(interface,
                              protocol,
                              name,
                              stype,
                              domain,
                              _PROTO_UNSPEC,
                              0,
                              reply_handler=ResolveService_cb,
                              error_handler=error_handler_cb)

    def ResolveService_cb(interface, protocol, name, type_, domain, host,
                          aprotocol, address, port, txt, flags):
        _logger.debug('Got new address: %s', address)
        pipe.feedback('resolve', address=str(address))

    def ItemRemove_cb(interface, protocol, name, type_, domain, *args):
        _logger.debug('Got removed workstation: %s', name)

    def error_handler_cb(error, *args):
        _logger.warning('ResolveService failed: %s', error)

    browser = dbus.Interface(
        bus.get_object(
            _DBUS_NAME,
            server.ServiceBrowserNew(_IF_UNSPEC, _PROTO_UNSPEC,
                                     '_workstation._tcp', 'local', 0)),
        _DBUS_INTERFACE_SERVICE_BROWSER)
    browser.connect_to_signal('ItemNew', ItemNew_cb)
    browser.connect_to_signal('ItemRemove', ItemRemove_cb)

    gobject.MainLoop().run()
Exemple #30
0
def create_device(device_file_path,
                  device_removed_listener,
                  configured_backend='org.freedesktop.UDisks'):

    DBusGMainLoop(set_as_default=True)
    mainloop = gobject.MainLoop()
    system_bus = dbus.SystemBus()
    backend_init = {
        'org.freedesktop.UDisks': 'backend_org_freedesktop_UDisks',
        'org.freedesktop.UDisks2': 'backend_org_freedesktop_Udisks2'
    }
    gobject.threads_init()  #@UndefinedVariable
    threads_init()
    backend = eval(backend_init[configured_backend])(system_bus,
                                                     device_file_path)
    return Device(device_removed_listener, mainloop, system_bus, backend)
Exemple #31
0
    def __init__(self, allow_system_internal=False, bus=None):
        Backend.__init__(self)
        self.handles = []
        self.allow_system_internal = allow_system_internal
        logging.debug('UDisks2Backend')
        DBusGMainLoop(set_as_default=True)
        threads_init()
        if bus:
            self.bus = bus
        else:
            self.bus = dbus.SystemBus()

        self.udisks = UDisks.Client.new_sync(None)

        self.helper = self.bus.get_object('com.ubuntu.USBCreator',
                                          '/com/ubuntu/USBCreator')
        self.helper = dbus.Interface(self.helper, 'com.ubuntu.USBCreator')
        self.helper.connect_to_signal('Progress', self.got_progress)
        self.no_options = GLib.Variant('a{sv}', {})
Exemple #32
0
def _init_dbus():
    """Setup dbus mainloop integration. Call before using dbus"""

    # To make GDBus fail early and we don't have to wait for a timeout
    if is_osx() or is_windows():
        os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "something-invalid"
        os.environ["DBUS_SESSION_BUS_ADDRESS"] = "something-invalid"

    try:
        from dbus.mainloop.glib import DBusGMainLoop, threads_init
    except ImportError:
        try:
            import dbus.glib
            dbus.glib
        except ImportError:
            return
    else:
        threads_init()
        DBusGMainLoop(set_as_default=True)
Exemple #33
0
    def __init__(self, allow_system_internal=False, bus=None, show_all=False):
        Backend.__init__(self)
        self.mounted_source = ''
        self.formatting = []
        self.handles = []
        self.show_all = show_all
        self.allow_system_internal = allow_system_internal
        logging.debug('UDisks2Backend')
        DBusGMainLoop(set_as_default=True)
        threads_init()
        if bus:
            self.bus = bus
        else:
            self.bus = dbus.SystemBus()

        self.udisks = UDisks.Client.new_sync(None)

        self.helper = self.bus.get_object('com.ubuntu.USBCreator',
                                          '/com/ubuntu/USBCreator')
        self.helper = dbus.Interface(self.helper, 'com.ubuntu.USBCreator')
Exemple #34
0
def startServer(configfile, basedir, host, port, debug, allowRoot, logConf = None):
	signal(SIGTERM, lambda signum, stack_frame: sys.exit(1)) #Redirects "nice" kill commands to SystemExit exception
	signal(SIGINT, lambda signum, stack_frame: sys.exit(1)) #Redirects CTRL+C to SystemExit exception

	global astrobox

	astrobox = Server(configfile, basedir, host, port, debug, allowRoot, logConf)
	
	try:
		from gi.repository import GObject
		from dbus.mainloop.glib import DBusGMainLoop, threads_init

		DBusGMainLoop(set_as_default=True)

		GObject.threads_init()
		threads_init()

	except ImportError:
		pass

	astrobox.run()	
def _get_pk():
    global _pk, _pk_max_resolve, _pk_max_install

    if _pk is not None:
        if _pk is False:
            return None
        else:
            return _pk

    gobject.threads_init()
    threads_init()
    DBusGMainLoop(set_as_default=True)
    try:
        bus = dbus.SystemBus()
        pk_object = bus.get_object('org.freedesktop.PackageKit',
                '/org/freedesktop/PackageKit', False)
        _pk = dbus.Interface(pk_object, 'org.freedesktop.PackageKit')
        _logger.info('PackageKit dbus service found')
    except Exception, error:
        _pk = False
        _logger.info('PackageKit dbus service not found: %s', error)
        return None
Exemple #36
0
    def run(self):
        self.loop.run()

    def shutdown(self):
        self.loop.quit()


thread_gml = GlibThread()
_mainloop = None

from dbus.mainloop.glib import DBusGMainLoop

_mainloop = DBusGMainLoop(set_as_default=True)
import dbus.mainloop.glib as gml

gml.threads_init()

_bus = dbus.SystemBus(mainloop=_mainloop)
_session_bus = dbus.SessionBus(mainloop=_mainloop)


def printer(*args, **kwargs):
    print("Signal begin:")
    for arg in args:
        print("Next argument through *argv :", arg)
    for key, value in kwargs.items():
        print("%s == %s" % (key, value))
    print("==== SIGNAL END =====")


_session_bus.add_signal_receiver(printer)
Exemple #37
0
def get_dbus_spotify():
    import dbus
    import gobject
    import threading
    from dbus.mainloop.glib import threads_init, DBusGMainLoop

    gobject.threads_init()
    threads_init()

    class DbusSpotify:
        def __init__(self):
            loop = DBusGMainLoop(set_as_default=True)
            
            bus  = dbus.SessionBus()
            obj  = bus.get_object('org.mpris.MediaPlayer2.spotify', '/')

            self.iface = dbus.Interface(obj,
                                        'org.freedesktop.MediaPlayer2')
    
            service = bus.get_object('com.spotify.qt',
                                     '/org/mpris/MediaPlayer2')
        
            service.connect_to_signal('TrackChange',
                                      self.properties_changed)

            service.connect_to_signal('PropertiesChanged',
                                      self.properties_changed)
            
            self.notify_queue = None

        def properties_changed(self, *data):
            if self.notify_queue is not None:
                self.notify_queue.put_nowait('update')
    
        def play(self):
            self.iface.PlayPause()

        def next(self):
            self.iface.Next()

        def prev(self):
            self.iface.Previous()

        def current_track(self):
            info = self.iface.GetMetadata()
            artwork = info['mpris:artUrl'].replace('/thumb/', '/300/')

            artist = info.pop('xesam:artist')
            all_keys = [ unicode(x) for x in info.keys() ]

            full_info = {
                'xesam:artist': ', '.join([ unicode(x) for x in artist ]),
            }
            for x in all_keys:
                full_info[x] = unicode(info[x])

            url = info['xesam:url']
            url = url.replace('spotify:track:', 'http://open.spotify.com/track/')

            return json.dumps({
                'artist':    unicode(full_info['xesam:artist']),
                'album':     unicode(info['xesam:album']),
                'title':     unicode(info['xesam:title']),
                'art_url':   artwork,
                'trackid':   info['mpris:trackid'],
                'url':       url,
                'full_info': full_info,
            })
    
    return DbusSpotify()
Exemple #38
0
def call_signal(callback):
    '''add dbus signal'''
    DBusGMainLoop(set_as_default=True)
    threads_init() #Fix bug
    bus = dbus.SystemBus()
    bus.add_signal_receiver(callback, dbus_interface=DBUS_IFACE, signal_name='changed')
Exemple #39
0
def setup_for_cli_run():
    import signal
    from dbus.mainloop.glib import DBusGMainLoop, threads_init
    threads_init()
    DBusGMainLoop(set_as_default=True)
    signal.signal(signal.SIGINT, signal.SIG_DFL)  # quit on Ctrl-C
Exemple #40
0
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import dbus.mainloop.glib
import glib
import gobject
import gtk
import subprocess
import threading
from gettext import gettext as _
from debug import *

# Initialise threading for D-Bus.  This is needed as long as it is
# used from two separate threads.  We only do this in a few places
# now, but in particular the troubleshooter does this (bug #662047).
glib.threads_init()
dbus.mainloop.glib.threads_init()


class OperationCanceled(RuntimeError):
    pass


class Timed:
    def run(self):
        pass

    def cancel(self):
        return False

Exemple #41
0
def init_dbus():
    from calibre.constants import islinux, isbsd
    if islinux or isbsd:
        from dbus.mainloop.glib import DBusGMainLoop, threads_init
        threads_init()
        DBusGMainLoop(set_as_default=True)
Exemple #42
0
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

from __future__ import print_function

# Imports
try:
    import ConfigParser
except ImportError:
    import configparser as ConfigParser
from dbus.mainloop.glib import threads_init
threads_init()

from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GObject
from gi.repository import AppIndicator3 as AppIndicator
from gi.repository import Notify
import os
import sys
import select
import threading
import platform
import re
import glob
import hashlib
Exemple #43
0
    def new_bot(self, type, id, args):
        print "launching new bot %i..." % id
        running_bots[id] = BOT_MAP[type](*args)
        running_bots[id].start()

    @dbus.service.method('com.excid3.bothost')
    def delete_bot(self, id):
        print "deleting %i" % id
        running_bots[id].stop()


if __name__ == "__main__":
    # Initialize gtk threading
    gobject.threads_init()
    glib.DBusGMainLoop(set_as_default=True)
    glib.threads_init()

    # Connect to the database
    engine = create_engine('sqlite:///' + DATABASE)
    Session = sessionmaker()
    Session.configure(bind=engine)
    session = Session()

    # Create the bots
    print "starting bots"
    for bot in session.query(Bot).all():
        running_bots[bot.id] = BOT_MAP[bot.type](bot.server, bot.port,
                                                 bot.nick, bot.channels)
        running_bots[bot.id].start()

    # Setup the dbus service
Exemple #44
0
def init_dbus():
    from calibre.constants import islinux, isbsd
    if islinux or isbsd:
        from dbus.mainloop.glib import DBusGMainLoop, threads_init
        threads_init()
        DBusGMainLoop(set_as_default=True)
import argparse
import pprint
pp = pprint.PrettyPrinter(indent=4)

import gi
gi.require_version('Gst', '1.0')
from gi.repository import GObject
from gi.repository import Gst
from gi.repository import GLib
from gi.repository import Gio
import threading

GObject.threads_init()
Gst.init(None)
threads_init()
DBusGMainLoop(set_as_default=True)

print '********************************************************'
print 'GObject: '
pp.pprint(GObject.pygobject_version)
print ''
print 'Gst: '
pp.pprint(Gst.version_string())
print '********************************************************'

Gst.debug_set_active(True)
Gst.debug_set_default_threshold(3)

import StringIO
import os