Python gi.repository.GLib.MainLoop() Examples

The following are 21 code examples of gi.repository.GLib.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 gi.repository.GLib , or try the search function .
Example #1
Source File: test_file_output.py    From brave with Apache License 2.0 6 votes vote down vote up
def assert_valid_output_file(output_video_location):
    '''
    Given a file, validates it is a video (mp4) file
    '''
    import gi
    gi.require_version('Gst', '1.0')
    from gi.repository import Gst, GLib

    Gst.init(None)
    mainloop = GLib.MainLoop()

    # We create a pipeline so that we can read the file and check it:
    pipeline = Gst.ElementFactory.make("playbin")
    pipeline.set_property('uri','file://'+output_video_location)
    playsink = pipeline.get_by_name('playsink')
    playsink.set_property('video-sink', Gst.ElementFactory.make('fakesink'))
    pipeline.set_state(Gst.State.PAUSED)

    def after_a_second():
        assert pipeline.get_state(0).state == Gst.State.PAUSED
        element = pipeline.get_by_name('inputselector1')
        caps = element.get_static_pad('src').get_current_caps()
        assert caps.to_string() == 'audio/x-raw, format=(string)F32LE, layout=(string)interleaved, rate=(int)48000, channels=(int)2, channel-mask=(bitmask)0x0000000000000003'

        element = pipeline.get_by_name('inputselector0')
        caps = element.get_static_pad('src').get_current_caps()
        assert caps.to_string() == 'video/x-raw, format=(string)NV12, width=(int)640, height=(int)360, interlace-mode=(string)progressive, multiview-mode=(string)mono, multiview-flags=(GstVideoMultiviewFlagsSet)0:ffffffff:/right-view-first/left-flipped/left-flopped/right-flipped/right-flopped/half-aspect/mixed-mono, pixel-aspect-ratio=(fraction)1/1, chroma-site=(string)jpeg, colorimetry=(string)bt601, framerate=(fraction)30/1'

        pipeline.set_state(Gst.State.NULL)
        mainloop.quit()

    GLib.timeout_add(1000, after_a_second)
    mainloop.run() 
Example #2
Source File: ui.py    From pantalaimon with Apache License 2.0 6 votes vote down vote up
def run(self):
            self.loop = GLib.MainLoop()

            if self.config.notifications:
                try:
                    notify2.init("pantalaimon", mainloop=self.loop)
                    self.notifications = True
                except dbus.DBusException:
                    logger.error(
                        "Notifications are enabled but no notification "
                        "server could be found, disabling notifications."
                    )
                    self.notifications = False

            GLib.timeout_add(100, self.message_callback)
            if not self.loop:
                return

            self.loop.run() 
Example #3
Source File: panctl.py    From pantalaimon with Apache License 2.0 6 votes vote down vote up
def main():
    loop = asyncio.get_event_loop()
    glib_loop = GLib.MainLoop()

    try:
        panctl = PanCtl()
    except GLib.Error as e:
        print(f"Error, {e}")
        sys.exit(-1)

    fut = loop.run_in_executor(None, glib_loop.run)

    try:
        loop.run_until_complete(panctl.loop())
    except KeyboardInterrupt:
        pass

    GLib.idle_add(glib_loop.quit)
    loop.run_until_complete(fut) 
Example #4
Source File: dbus_ctrl.py    From simLAB with GNU General Public License v2.0 6 votes vote down vote up
def run(self):
        logging.info('D-Bus process started')
        GLib.threads_init()  # allow threads in GLib
        GLib.idle_add(self._idleQueueSync)

        DBusGMainLoop(set_as_default=True)
        dbusService = SessionDBus(self.taskQueue, self.resultQueue)

        try:
            GLib.MainLoop().run()
        except KeyboardInterrupt:
            logging.debug("\nThe MainLoop will close...")
            GLib.MainLoop().quit()
        return 
Example #5
Source File: main_loop.py    From anyMesh-Python with MIT License 6 votes vote down vote up
def _test_run_screen_event_loop(self):
        """
        >>> w = _refl("widget")
        >>> scr = _refl("screen")
        >>> scr.get_cols_rows_rval = (10, 5)
        >>> scr.get_input_rval = [], []
        >>> ml = MainLoop(w, screen=scr)
        >>> def stop_now(loop, data):
        ...     raise ExitMainLoop()
        >>> handle = ml.set_alarm_in(0, stop_now)
        >>> try:
        ...     ml._run_screen_event_loop()
        ... except ExitMainLoop:
        ...     pass
        screen.get_cols_rows()
        widget.render((10, 5), focus=True)
        screen.draw_screen((10, 5), None)
        screen.set_input_timeouts(0)
        screen.get_input(True)
        """ 
Example #6
Source File: main_loop.py    From anyMesh-Python with MIT License 5 votes vote down vote up
def _test_run(self):
        """
        >>> w = _refl("widget")   # _refl prints out function calls
        >>> w.render_rval = "fake canvas"  # *_rval is used for return values
        >>> scr = _refl("screen")
        >>> scr.get_input_descriptors_rval = [42]
        >>> scr.get_cols_rows_rval = (20, 10)
        >>> scr.started = True
        >>> scr._urwid_signals = {}
        >>> evl = _refl("event_loop")
        >>> evl.enter_idle_rval = 1
        >>> evl.watch_file_rval = 2
        >>> ml = MainLoop(w, [], scr, event_loop=evl)
        >>> ml.run()    # doctest:+ELLIPSIS
        screen.set_mouse_tracking()
        screen.get_cols_rows()
        widget.render((20, 10), focus=True)
        screen.draw_screen((20, 10), 'fake canvas')
        screen.get_input_descriptors()
        event_loop.watch_file(42, <bound method ...>)
        event_loop.enter_idle(<bound method ...>)
        event_loop.run()
        event_loop.remove_enter_idle(1)
        event_loop.remove_watch_file(2)
        >>> scr.started = False
        >>> ml.run()    # doctest:+ELLIPSIS
        screen.run_wrapper(<bound method ...>)
        """ 
Example #7
Source File: dbus_client.py    From gateway with Apache License 2.0 5 votes vote down vote up
def __init__(self, logger=None, c_extension=True, ignored_ep_filter=None):

        # logger
        self.logger = logger or logging.getLogger(__name__)

        # Main loop for events
        self.loop = GLib.MainLoop()

        # Connect to session bus
        self.bus = SystemBus()

        # Manage sink list
        self.sink_manager = SinkManager(
            bus=self.bus,
            on_new_sink_cb=self.on_sink_connected,
            on_sink_removal_cb=self.on_sink_disconnected,
            on_stack_started=self.on_stack_started,
            logger=self.logger,
        )

        self.ignore_ep_filter = ignored_ep_filter

        # Register for packet on Dbus
        if c_extension:
            self.logger.info("Starting dbus client with c extension")
            self.c_extension_thread = DbusEventHandler(
                self._on_data_received_c, self.logger
            )
        else:
            self.logger.info("Starting dbus client without c extension")
            # Subscribe to all massages received from any sink (no need for
            # connected sink for that)
            self.bus.subscribe(
                signal="MessageReceived",
                object="/com/wirepas/sink",
                signal_fired=self._on_data_received,
            )

            self.c_extension_thread = None 
Example #8
Source File: spotrec.py    From SpotRec with MIT License 5 votes vote down vote up
def __init__(self):
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

        try:
            bus = dbus.SessionBus()
            player = bus.get_object(self.dbus_dest, self.dbus_path)
            self.iface = dbus.Interface(player, "org.freedesktop.DBus.Properties")
            self.update_metadata()
        except DBusException:
            log.error("Failed to connect to Spotify. (Maybe it's not running yet?)")
            sys.exit(1)
            pass

        self.track = self.get_track(self.metadata)
        self.trackid = self.metadata.get(dbus.String(u'mpris:trackid'))
        self.playbackstatus = self.iface.Get(self.mpris_player_string, "PlaybackStatus")

        self.iface.connect_to_signal("PropertiesChanged", self.on_playing_uri_changed)

        class DBusListenerThread(Thread):
            def run(self2):
                # Run the GLib event loop to process DBus signals as they arrive
                self.glibloop = GLib.MainLoop()
                self.glibloop.run()

                # run() blocks this thread. This gets printed after it's dead.
                log.info(f"[{app_name}] GLib Loop thread killed")

        dbuslistener = DBusListenerThread()
        dbuslistener.start()

        log.info(f"[{app_name}] Spotify DBus listener started")

        log.info(f"[{app_name}] Current song: " + self.track)
        log.info(f"[{app_name}] Current state: " + self.playbackstatus)

    # TODO: this is a dirty solution (uses cmdline instead of python for now) 
Example #9
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 #10
Source File: dbus_client.py    From weresync with Apache License 2.0 5 votes vote down vote up
def _unthreaded_subscribe_to_signals(
        partition_status_callback, copy_status_callback, boot_status_callback):
    drive_copier.PartitionStatus.connect(partition_status_callback)
    drive_copier.CopyStatus.connect(copy_status_callback)
    drive_copier.BootStatus.connect(boot_status_callback)
    loop = GLib.MainLoop()
    loop.run() 
Example #11
Source File: daemon.py    From weresync with Apache License 2.0 5 votes vote down vote up
def run():
    """Function which starts the daemon and publishes the
    :class:`~weresync.daemon.copier.DriveCopier` over dbus."""
    utils.start_logging_handler(DEFAULT_DAEMON_LOG_LOCATION)
    utils.enable_localization()
    with SystemBus() as bus:
        with bus.publish("net.manilas.weresync.DriveCopier", DriveCopier()):
            GLib.idle_add(lambda: LOGGER.debug("Starting GLib loop"))
            loop = GLib.MainLoop()
            loop.run() 
Example #12
Source File: dbus.py    From btk with MIT License 5 votes vote down vote up
def __init__(self, bus, path):
        self.loop = GLib.MainLoop()

        interface_info = Gio.DBusNodeInfo.new_for_xml(self.__doc__).interfaces[0]

        method_outargs = {}
        method_inargs = {}
        for method in interface_info.methods:
            method_outargs[method.name] = '(' + ''.join([arg.signature for arg in method.out_args]) + ')'
            method_inargs[method.name] = tuple(arg.signature for arg in method.in_args)

        self.method_inargs = method_inargs
        self.method_outargs = method_outargs

        bus.register_object(object_path=path, interface_info=interface_info, method_call_closure=self.on_method_call) 
Example #13
Source File: main_loop.py    From anyMesh-Python with MIT License 5 votes vote down vote up
def __init__(self):
        from gi.repository import GLib
        self.GLib = GLib
        self._alarms = []
        self._watch_files = {}
        self._idle_handle = 0
        self._glib_idle_enabled = False # have we called glib.idle_add?
        self._idle_callbacks = {}
        self._loop = GLib.MainLoop()
        self._exc_info = None
        self._enable_glib_idle() 
Example #14
Source File: main_loop.py    From anyMesh-Python with MIT License 5 votes vote down vote up
def _test_process_input(self):
        """
        >>> w = _refl("widget")
        >>> w.selectable_rval = True
        >>> scr = _refl("screen")
        >>> scr.get_cols_rows_rval = (10, 5)
        >>> ml = MainLoop(w, [], scr)
        >>> ml.process_input(['enter', ('mouse drag', 1, 14, 20)])
        screen.get_cols_rows()
        widget.selectable()
        widget.keypress((10, 5), 'enter')
        widget.mouse_event((10, 5), 'mouse drag', 1, 14, 20, focus=True)
        True
        """ 
Example #15
Source File: notify_send_py.py    From notify-send.py with MIT License 5 votes vote down vote up
def __init__(self, loop=None):
        self.loop = loop or GLib.MainLoop() 
Example #16
Source File: glib_events.py    From pychess with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *, context=None, application=None):
        self._application = application
        self._running = False
        self._argv = None

        super().__init__(context)
        if application is None:
            self._mainloop = GLib.MainLoop(self._context) 
Example #17
Source File: gstreamer_pipeline.py    From video-analytics-serving with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def gobject_mainloop():
        gi.require_version('Gst', '1.0')
        from gi.repository import GLib
        GStreamerPipeline._mainloop = GLib.MainLoop()
        try:
            GStreamerPipeline._mainloop.run()
        except KeyboardInterrupt:
            pass 
Example #18
Source File: signal.py    From pai with Eclipse Public License 2.0 5 votes vote down vote up
def _run(self):
        super(SignalTextInterface, self)._run()

        bus = SystemBus()

        self.signal = bus.get('org.asamk.Signal')
        self.signal.onMessageReceived = self.handle_message
        self.loop = GLib.MainLoop()

        logger.debug("Signal Interface Running")

        self.loop.run() 
Example #19
Source File: pomodoro-client.py    From i3-gnome-pomodoro with GNU General Public License v3.0 5 votes vote down vote up
def pomodoro_daemon():
    pomodoro = get_pomodoro_proxy()
    pomodoro.StateChanged.connect(handle_state)
    GLib.MainLoop().run() 
Example #20
Source File: sniffer.py    From btle-sniffer with MIT License 5 votes vote down vote up
def run(self):
        """
        Run the Sniffer main loop.
        """
        if self.adapter is not None:
            self._log.debug("Clearing the BlueZ device registry.")
            for path, _ in get_known_devices():
                self.adapter.RemoveDevice(path)

            self._log.debug("Registering the signals InterfacesAdded and PropertiesChanged.")
            bus = pydbus.SystemBus()
            bus.subscribe(
                sender=SERVICE_NAME,
                iface=OBJECT_MANAGER_INTERFACE,
                signal="InterfacesAdded",
                signal_fired=self._cb_interfaces_added
            )
            bus.subscribe(
                sender=SERVICE_NAME,
                iface=OBJECT_MANAGER_INTERFACE,
                signal="InterfacesRemoved",
                signal_fired=self._cb_interfaces_removed
            )
            bus.subscribe(
                sender=SERVICE_NAME,
                iface=PROPERTIES_INTERFACE,
                signal="PropertiesChanged",
                arg0=DEVICE_INTERFACE,
                signal_fired=self._cb_properties_changed
            )

            self._log.debug("Running the main loop.")
            if self.output_path is not None and self.backup_interval > 0:
                GLib.timeout_add_seconds(self.backup_interval, self._cb_backup_registry)
            if self.attempt_connection:
                GLib.timeout_add_seconds(self.queueing_interval, self._cb_connect_check)
            loop = GLib.MainLoop()
            loop.run()
        else:
            raise ValueError("Sniffer.run can only be called in a context "
                             "(e.g. `with Sniffer(...) as s: s.run()`)") 
Example #21
Source File: main_loop.py    From anyMesh-Python with MIT License 4 votes vote down vote up
def _update(self, timeout=False):
        """
        >>> w = _refl("widget")
        >>> w.selectable_rval = True
        >>> w.mouse_event_rval = True
        >>> scr = _refl("screen")
        >>> scr.get_cols_rows_rval = (15, 5)
        >>> scr.get_input_nonblocking_rval = 1, ['y'], [121]
        >>> evl = _refl("event_loop")
        >>> ml = MainLoop(w, [], scr, event_loop=evl)
        >>> ml._input_timeout = "old timeout"
        >>> ml._update()    # doctest:+ELLIPSIS
        event_loop.remove_alarm('old timeout')
        screen.get_input_nonblocking()
        event_loop.alarm(1, <function ...>)
        screen.get_cols_rows()
        widget.selectable()
        widget.keypress((15, 5), 'y')
        >>> scr.get_input_nonblocking_rval = None, [("mouse press", 1, 5, 4)
        ... ], []
        >>> ml._update()
        screen.get_input_nonblocking()
        widget.mouse_event((15, 5), 'mouse press', 1, 5, 4, focus=True)
        >>> scr.get_input_nonblocking_rval = None, [], []
        >>> ml._update()
        screen.get_input_nonblocking()
        """
        if self._input_timeout is not None and not timeout:
            # cancel the timeout, something else triggered the update
            self.event_loop.remove_alarm(self._input_timeout)
        self._input_timeout = None

        max_wait, keys, raw = self.screen.get_input_nonblocking()
        
        if max_wait is not None:
            # if get_input_nonblocking wants to be called back
            # make sure it happens with an alarm
            self._input_timeout = self.event_loop.alarm(max_wait, 
                lambda: self._update(timeout=True)) 

        keys = self.input_filter(keys, raw)

        if keys:
            self.process_input(keys)
            if 'window resize' in keys:
                self.screen_size = None