Python gobject.MainLoop() Examples

The following are 20 code examples of gobject.MainLoop(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module gobject , or try the search function .
Example #1
Source File: gtk2reactor.py    From python-for-android with Apache License 2.0 7 votes vote down vote up
def __init__(self, useGtk=True):
        self._simtag = None
        self._reads = set()
        self._writes = set()
        self._sources = {}
        posixbase.PosixReactorBase.__init__(self)
        # pre 2.3.91 the glib iteration and mainloop functions didn't release
        # global interpreter lock, thus breaking thread and signal support.
        if getattr(gobject, "pygtk_version", ()) >= (2, 3, 91) and not useGtk:
            self.context = gobject.main_context_default()
            self.__pending = self.context.pending
            self.__iteration = self.context.iteration
            self.loop = gobject.MainLoop()
            self.__crash = self.loop.quit
            self.__run = self.loop.run
        else:
            import gtk
            self.__pending = gtk.events_pending
            self.__iteration = gtk.main_iteration
            self.__crash = _our_mainquit
            self.__run = gtk.main 
Example #2
Source File: peripheral.py    From python-bluezero with MIT License 6 votes vote down vote up
def __init__(self, device_id=None):
        """Default initialiser.

        1. Initialises the program loop using ``GObject``.
        2. Registers the Application on the D-Bus.
        3. Initialises the list of services offered by the application.

        """
        # Initialise the loop that the application runs in
        GObject.threads_init()
        dbus.mainloop.glib.threads_init()
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        self.mainloop = GObject.MainLoop()

        # Initialise the D-Bus path and register it
        self.bus = dbus.SystemBus()
        self.path = '/ukBaz/bluezero/application{}'.format(id(self))
        self.bus_name = dbus.service.BusName('ukBaz.bluezero', self.bus)
        dbus.service.Object.__init__(self, self.bus_name, self.path)

        # Initialise services within the application
        self.services = []

        self.dongle = adapter.Adapter(device_id) 
Example #3
Source File: dirtyagent.py    From HomePWN with GNU General Public License v3.0 6 votes vote down vote up
def run_agent():
    if GObject:
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        bus = dbus.SystemBus()
        capability = "NoInputNoOutput"

        path = "/test/agent"
        agent = Agent(bus, path)

        mainloop = GObject.MainLoop()

        obj = bus.get_object(BUS_NAME, "/org/bluez")
        manager = dbus.Interface(obj, "org.bluez.AgentManager1")
        manager.RegisterAgent(path, capability)

        print("\n\n[+] Agent registered in background ")

        manager.RequestDefaultAgent(path)
        try:
            mainloop.run()
        except:
            print("\n[-] The agent has finished ")
    else:
        print("No agent running...") 
Example #4
Source File: pyplot.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def _backend_selection():
    """ If rcParams['backend_fallback'] is true, check to see if the
        current backend is compatible with the current running event
        loop, and if not switches to a compatible one.
    """
    backend = rcParams['backend']
    if not rcParams['backend_fallback'] or backend not in _interactive_bk:
        return
    is_agg_backend = rcParams['backend'].endswith('Agg')
    if 'wx' in sys.modules and not backend in ('WX', 'WXAgg'):
        import wx
        if wx.App.IsMainLoopRunning():
            rcParams['backend'] = 'wx' + 'Agg' * is_agg_backend
    elif 'PyQt4.QtCore' in sys.modules and not backend == 'Qt4Agg':
        import PyQt4.QtGui
        if not PyQt4.QtGui.qApp.startingUp():
            # The mainloop is running.
            rcParams['backend'] = 'qt4Agg'
    elif 'PyQt5.QtCore' in sys.modules and not backend == 'Qt5Agg':
        import PyQt5.QtWidgets
        if not PyQt5.QtWidgets.qApp.startingUp():
            # The mainloop is running.
            rcParams['backend'] = 'qt5Agg'
    elif ('gtk' in sys.modules and
          backend not in ('GTK', 'GTKAgg', 'GTKCairo')):
        if 'gi' in sys.modules:
            from gi.repository import GObject
            ml = GObject.MainLoop
        else:
            import gobject
            ml = gobject.MainLoop
        if ml().is_running():
            rcParams['backend'] = 'gtk' + 'Agg' * is_agg_backend
    elif 'Tkinter' in sys.modules and not backend == 'TkAgg':
        # import Tkinter
        pass  # what if anything do we need to do for tkinter? 
Example #5
Source File: pyplot.py    From Computable with MIT License 5 votes vote down vote up
def _backend_selection():
    """ If rcParams['backend_fallback'] is true, check to see if the
        current backend is compatible with the current running event
        loop, and if not switches to a compatible one.
    """
    backend = rcParams['backend']
    if not rcParams['backend_fallback'] or \
                     backend not in _interactive_bk:
        return
    is_agg_backend = rcParams['backend'].endswith('Agg')
    if 'wx' in sys.modules and not backend in ('WX', 'WXAgg'):
        import wx
        if wx.App.IsMainLoopRunning():
            rcParams['backend'] = 'wx' + 'Agg' * is_agg_backend
    elif 'PyQt4.QtCore' in sys.modules and not backend == 'Qt4Agg':
        import PyQt4.QtGui
        if not PyQt4.QtGui.qApp.startingUp():
            # The mainloop is running.
            rcParams['backend'] = 'qt4Agg'
    elif 'gtk' in sys.modules and not backend in ('GTK', 'GTKAgg',
                                                            'GTKCairo'):
        import gobject
        if gobject.MainLoop().is_running():
            rcParams['backend'] = 'gtk' + 'Agg' * is_agg_backend
    elif 'Tkinter' in sys.modules and not backend == 'TkAgg':
        # import Tkinter
        pass  # what if anything do we need to do for tkinter? 
Example #6
Source File: BlinkerBLE.py    From blinker-py with MIT License 5 votes vote down vote up
def __init__(self):
        # Thread.__init__(self)
        self._isClosed = False
        self.thread = None

        os.system('sudo service bluetooth stop')

        global mainloop

        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

        bus = dbus.SystemBus()

        service_manager = get_service_manager(bus)
        ad_manager = get_ad_manager(bus)

        app = BLEApplication(bus)

        # Create advertisement
        test_advertisement = BLEAdvertisement(bus, 0)

        mainloop = GObject.MainLoop()
        # mainloop = GLib.MainLoop()

        # Register gatt services
        service_manager.RegisterApplication(app.get_path(), {},
                                            reply_handler=register_app_cb,
                                            error_handler=register_app_error_cb)

        # Register advertisement
        ad_manager.RegisterAdvertisement(test_advertisement.get_path(), {},
                                        reply_handler=register_ad_cb,
                                        error_handler=register_ad_error_cb) 
Example #7
Source File: BlinkerBLE.py    From blinker-py with MIT License 5 votes vote down vote up
def mainInit():
    os.system('sudo service bluetooth stop')

    global mainloop

    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    bus = dbus.SystemBus()

    service_manager = get_service_manager(bus)
    ad_manager = get_ad_manager(bus)

    app = BLEApplication(bus)

    # Create advertisement
    test_advertisement = BLEAdvertisement(bus, 0)

    mainloop = GObject.MainLoop()

    # Register gatt services
    service_manager.RegisterApplication(app.get_path(), {},
                                        reply_handler=register_app_cb,
                                        error_handler=register_app_error_cb)

    # Register advertisement
    ad_manager.RegisterAdvertisement(test_advertisement.get_path(), {},
                                     reply_handler=register_ad_cb,
                                     error_handler=register_ad_error_cb)

    try:
        mainloop.run()
    except KeyboardInterrupt:
        BLINKER_LOG ("exit")

# class BlinkerBLEService(Thread): 
Example #8
Source File: agent.py    From bluetool with GNU General Public License v3.0 5 votes vote down vote up
def __init__(
            self, client_class, timeout=180, capability="KeyboardDisplay",
            path="/org/bluez/my_bluetooth_agent"):
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        self.client_class = client_class
        self.timeout = timeout
        self.capability = capability
        self.path = path
        self._bus = dbus.SystemBus()
        self._mainloop = GObject.MainLoop()
        _bluetooth.make_discoverable(False) 
Example #9
Source File: blueserver.py    From bluetool with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, tcp_port_in=8043, tcp_port_out=None, channel=1):
        self._spp = SerialPort(channel)
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        dbus.service.Object.__init__(
            self, dbus.SystemBus(), self._spp.profile_path)
        self.tcp_port_in = tcp_port_in
        self.tcp_port_out = tcp_port_out
        self._mainloop = GObject.MainLoop() 
Example #10
Source File: async_tools.py    From python-bluezero with MIT License 5 votes vote down vote up
def __init__(self):
        self.mainloop = GObject.MainLoop() 
Example #11
Source File: device.py    From python-bluezero with MIT License 5 votes vote down vote up
def __init__(self, adapter_addr, device_addr):
        """Default initialiser.

        Creates object for the specified remote Bluetooth device.
        This is on the specified adapter specified.

        :param adapter_addr: Address of the local Bluetooth adapter.
        :param device_addr: Address of the remote Bluetooth device.
        """
        self.bus = dbus.SystemBus()
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        self.mainloop = GObject.MainLoop()

        device_path = dbus_tools.get_dbus_path(adapter_addr, device_addr)
        if not device_path:
            raise ValueError("Cannot find a device: " + device_addr +
                             " using adapter: " + adapter_addr)

        self.remote_device_path = device_path
        self.remote_device_obj = self.bus.get_object(
            constants.BLUEZ_SERVICE_NAME,
            self.remote_device_path)
        self.remote_device_methods = dbus.Interface(
            self.remote_device_obj,
            constants.DEVICE_INTERFACE)
        self.remote_device_props = dbus.Interface(self.remote_device_obj,
                                                  dbus.PROPERTIES_IFACE) 
Example #12
Source File: gtk2reactor.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, useGtk=True):
        self.context = gobject.main_context_default()
        self.loop = gobject.MainLoop()
        posixbase.PosixReactorBase.__init__(self)
        # pre 2.3.91 the glib iteration and mainloop functions didn't release
        # global interpreter lock, thus breaking thread and signal support.
        if (hasattr(gobject, "pygtk_version") and gobject.pygtk_version >= (2, 3, 91)
            and not useGtk):
            self.__pending = self.context.pending
            self.__iteration = self.context.iteration
            self.__crash = self.loop.quit
            self.__run = self.loop.run
        else:
            import gtk
            self.__pending = gtk.events_pending
            self.__iteration = gtk.main_iteration
            self.__crash = _our_mainquit
            self.__run = gtk.main

    # The input_add function in pygtk1 checks for objects with a
    # 'fileno' method and, if present, uses the result of that method
    # as the input source. The pygtk2 input_add does not do this. The
    # function below replicates the pygtk1 functionality.

    # In addition, pygtk maps gtk.input_add to _gobject.io_add_watch, and
    # g_io_add_watch() takes different condition bitfields than
    # gtk_input_add(). We use g_io_add_watch() here in case pygtk fixes this
    # bug. 
Example #13
Source File: support.py    From Tickeys-linux with MIT License 5 votes vote down vote up
def install_gobject_iteration():
    '''Import and install gobject context iteration inside our event loop.
    This is used as soon as gobject is used (like gstreamer).
    '''

    from kivy.clock import Clock

    try:
        from gi.repository import GObject as gobject
    except ImportError:
        import gobject

    if hasattr(gobject, '_gobject_already_installed'):
        # already installed, don't do it twice.
        return

    gobject._gobject_already_installed = True

    # get gobject mainloop / context
    loop = gobject.MainLoop()
    gobject.threads_init()
    context = loop.get_context()

    # schedule the iteration each frame
    def _gobject_iteration(*largs):
        # XXX we need to loop over context here, otherwise, we might have a lag
        loop = 0
        while context.pending() and loop < 10:
            context.iteration(False)
            loop += 1
    Clock.schedule_interval(_gobject_iteration, 0)


# -----------------------------------------------------------------------------
# Android support
# ----------------------------------------------------------------------------- 
Example #14
Source File: support.py    From Tickeys-linux with MIT License 5 votes vote down vote up
def install_gobject_iteration():
    '''Import and install gobject context iteration inside our event loop.
    This is used as soon as gobject is used (like gstreamer).
    '''

    from kivy.clock import Clock

    try:
        from gi.repository import GObject as gobject
    except ImportError:
        import gobject

    if hasattr(gobject, '_gobject_already_installed'):
        # already installed, don't do it twice.
        return

    gobject._gobject_already_installed = True

    # get gobject mainloop / context
    loop = gobject.MainLoop()
    gobject.threads_init()
    context = loop.get_context()

    # schedule the iteration each frame
    def _gobject_iteration(*largs):
        # XXX we need to loop over context here, otherwise, we might have a lag
        loop = 0
        while context.pending() and loop < 10:
            context.iteration(False)
            loop += 1
    Clock.schedule_interval(_gobject_iteration, 0)


# -----------------------------------------------------------------------------
# Android support
# ----------------------------------------------------------------------------- 
Example #15
Source File: service.py    From cputemp with MIT License 5 votes vote down vote up
def __init__(self):
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        self.mainloop = GObject.MainLoop()
        self.bus = BleTools.get_bus()
        self.path = "/"
        self.services = []
        self.next_index = 0
        dbus.service.Object.__init__(self, self.bus, self.path) 
Example #16
Source File: wifimonitor.py    From pywificontrol with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        self.bus = dbus.SystemBus()
        self._mainloop = GObject.MainLoop()

        self.wifi_manager = WiFiControl()

        self.callbacks = {}

        self.current_state = self.OFF_STATE
        self.current_ssid = None 
Example #17
Source File: demo.py    From bt-manager with GNU General Public License v3.0 5 votes vote down vote up
def timeout_handler(signum, frame):
    while gobject.MainLoop().get_context().pending():
        gobject.MainLoop().get_context().iteration(False) 
Example #18
Source File: pyplot.py    From neural-network-animation with MIT License 5 votes vote down vote up
def _backend_selection():
    """ If rcParams['backend_fallback'] is true, check to see if the
        current backend is compatible with the current running event
        loop, and if not switches to a compatible one.
    """
    backend = rcParams['backend']
    if not rcParams['backend_fallback'] or \
                     backend not in _interactive_bk:
        return
    is_agg_backend = rcParams['backend'].endswith('Agg')
    if 'wx' in sys.modules and not backend in ('WX', 'WXAgg'):
        import wx
        if wx.App.IsMainLoopRunning():
            rcParams['backend'] = 'wx' + 'Agg' * is_agg_backend
    elif 'PyQt4.QtCore' in sys.modules and not backend == 'Qt4Agg':
        import PyQt4.QtGui
        if not PyQt4.QtGui.qApp.startingUp():
            # The mainloop is running.
            rcParams['backend'] = 'qt4Agg'
    elif 'PyQt5.QtCore' in sys.modules and not backend == 'Qt5Agg':
        import PyQt5.QtWidgets
        if not PyQt5.QtWidgets.qApp.startingUp():
            # The mainloop is running.
            rcParams['backend'] = 'qt5Agg'
    elif ('gtk' in sys.modules
            and backend not in ('GTK', 'GTKAgg', 'GTKCairo')
            and 'gi.repository.GObject' not in sys.modules):
        import gobject
        if gobject.MainLoop().is_running():
            rcParams['backend'] = 'gtk' + 'Agg' * is_agg_backend
    elif 'Tkinter' in sys.modules and not backend == 'TkAgg':
        # import Tkinter
        pass  # what if anything do we need to do for tkinter? 
Example #19
Source File: pyplot.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def _backend_selection():
    """ If rcParams['backend_fallback'] is true, check to see if the
        current backend is compatible with the current running event
        loop, and if not switches to a compatible one.
    """
    backend = rcParams['backend']
    if not rcParams['backend_fallback'] or \
                     backend not in _interactive_bk:
        return
    is_agg_backend = rcParams['backend'].endswith('Agg')
    if 'wx' in sys.modules and not backend in ('WX', 'WXAgg'):
        import wx
        if wx.App.IsMainLoopRunning():
            rcParams['backend'] = 'wx' + 'Agg' * is_agg_backend
    elif 'PyQt4.QtCore' in sys.modules and not backend == 'Qt4Agg':
        import PyQt4.QtGui
        if not PyQt4.QtGui.qApp.startingUp():
            # The mainloop is running.
            rcParams['backend'] = 'qt4Agg'
    elif 'gtk' in sys.modules and not backend in ('GTK', 'GTKAgg',
                                                            'GTKCairo'):
        import gobject
        if gobject.MainLoop().is_running():
            rcParams['backend'] = 'gtk' + 'Agg' * is_agg_backend
    elif 'Tkinter' in sys.modules and not backend == 'TkAgg':
        # import Tkinter
        pass  # what if anything do we need to do for tkinter? 
Example #20
Source File: recipe-334779.py    From code with MIT License 4 votes vote down vote up
def __init__(self):

            self.main_loop = gobject.MainLoop()            

            # Create a window with a horizontal scale.
            self.wnd = gtk.Window()
            self.wnd.set_default_size(640, 480)
            self.wnd.set_title('Have fun with the transparency slider')

            hscale = gtk.HScale()
            hscale.set_digits(0)
            hscale.set_increments(1, 10)
            hscale.set_range(0, 100)
            hscale.set_value(100)

            hscale.connect('value_changed', self.set_window_alpha)

            self.wnd.add(hscale)

            # Note: gtk window must be realized before installing extensions.
            self.wnd.realize()
            self.wnd.show_all()

            self.win32ext = GTKWin32Ext(self.wnd)

            self.win32ext.add_notify_icon()

            # GTK menus from the notify icon!
            menu = gtk.Menu()

            menu_item = gtk.MenuItem('Baloons!')
            menu_item.connect_object('activate', self.menu_cb, self.wnd)
            menu.append(menu_item)
                
            menu_item = gtk.MenuItem('Fadeout Window')
            menu_item.connect('activate', self.fadeoutwindow)
            menu.append(menu_item)
                
            menu_item = gtk.MenuItem('Window Disappeared?')
            menu_item.connect('activate', self.fadeinwindow)
            menu.append(menu_item)
            
            menu.show_all()
            self.win32ext.notify_icon.menu = menu

            # Set up the callback messages
            self.win32ext.message_map({
                WM_TRAYMESSAGE: self.on_notifyicon_activity
                })