# -*- Mode: Python; py-indent-offset: 4 -*- # pygobject - Python bindings for the GObject library # Copyright (C) 2021 Benjamin Berg # # gi/asyncio.py: GObject asyncio integration # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, see . __all__ = [] import sys import asyncio from asyncio import events import threading from gi.repository import GLib class EventLoop(asyncio.SelectorEventLoop): """An asyncio event loop that runs the python mainloop inside GLib. Based on the asyncio.SelectorEventLoop""" # This is based on the selector event loop, but never actually runs select() # in the strict sense. # We use the selector to register all FDs with the main context using our # own GSource. For python timeouts/idle equivalent, we directly query them # from the context by providing the _get_timeout_ms function that the # GSource uses. This in turn accesses _ready and _scheduled to calculate # the timeout and whether python can dispatch anything non-FD based yet. # # To simplify matters, we call the normal _run_once method of the base # class which will call select(). As we know that we are ready at the time # that select() will return immediately with the FD information we have # gathered already. # # With that, we just need to override and slightly modify the run_forever # method so that it calls g_main_loop_run instead of looping _run_once. def __init__(self, main_context): # A mainloop in case we want to run our context assert main_context is not None self._context = main_context self._main_loop = GLib.MainLoop.new(self._context, False) selector = _Selector(self._context, self) super().__init__(selector) # Used by run_once to not busy loop if the timeout is floor'ed to zero self._clock_resolution = 1e-3 def run_forever(self): self._check_closed() self._check_running() self._set_coroutine_origin_tracking(self._debug) self._thread_id = threading.get_ident() old_agen_hooks = sys.get_asyncgen_hooks() sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook, finalizer=self._asyncgen_finalizer_hook) try: self._selector.attach() events._set_running_loop(self) g_main_loop_run(self._main_loop) finally: self._selector.detach() self._thread_id = None self._stopping = False events._set_running_loop(None) self._set_coroutine_origin_tracking(False) sys.set_asyncgen_hooks(*old_agen_hooks) def time(self): return GLib.get_monotonic_time() / 1000000 def _get_timeout_ms(self): if self._ready or self._stopping: return 0 if self._scheduled: timeout = (self._scheduled[0]._when - self.time()) * 1000 return timeout if timeout >= 0 else 0 return -1 def is_running(self): # If we are currently the owner, then the context is running # (and we are being dispatched by it) if self._context.is_owner(): return True # Otherwise, it might (but shouldn't) be running in a different thread # Try aquiring it, if that fails, another thread is owning it if not self._context.acquire(): return True self._context.release() return False def stop(self): # asyncio.BaseEventLoop.stop() documents that the callbacks should be # executed once even if the stop() call occured before the run_forever # was even executed. # To mimic this behaviour, we also set self._stopping (to calculate a # zero timeout) and queue the mainloop quit using call_soon. # # NOTE: Not thread-safe, but neither is the base implementation. if not self._stopping: self._stopping = True self.call_soon(self._main_loop.quit) class EventLoopPolicy(events.AbstractEventLoopPolicy): """An asyncio event loop policy that runs the GLib main loop. The policy allows creating a new EventLoop for threads other than the main thread. For the main thread, you can use get_event_loop() to retrieve the correct mainloop and run it. Note that, unlike GLib, python does not support running the EventLoop recursively. You should never iterate the GLib.MainContext from within the python EventLoop as doing so prevents asyncio events from being dispatched. As such, do not use API such as GLib.MainLoop.run or Gtk.Dialog.run. Instead use the proper asynchronous patterns to prevent entirely blocking asyncio. """ _loops = {} def get_event_loop(self): """Get the event loop for the current context. Returns an event loop object for the thread default GLib.MainContext or in case of the main thread for the default GLib.MainContext. If no GLib.MainContext is It should never return None.""" # Get the thread default main context ctx = GLib.MainContext.get_thread_default() # If there is none, and we are on the main thread, then use the default context if ctx is None and threading.current_thread() is threading.main_thread(): ctx = GLib.MainContext.default() # We do not create a main context implicitly; # we create a mainloop for an existing context though if ctx is None: raise RuntimeError('There is no main context set for thread %r.' % threading.current_thread().name) # Note: We cannot attach it to ctx, as getting the default will always # return a new python wrapper. But, we can use hash() as that returns # the pointer to the C structure. try: return self._loops[ctx] except KeyError: pass self._loops[ctx] = EventLoop(ctx) return self._loops[ctx] def set_event_loop(self, loop): """Set the event loop for the current context to loop. This is not permitted for the main thread or if the thread already has a main context associated with it. """ # Only accept glib event loops, otherwise things will just mess up assert loop is None or isinstance(loop, EventLoop) # Refuse operating on the main thread. Technically we could allow it, # but I can't think of a use-case and doing it is dangerous. # Also, if someone *really* wants they can still push a new the thread # default main context and call get_event_loop(). if threading.current_thread() is threading.main_thread(): raise RuntimeError('Changing the main loop/context of the main thread is not supported') ctx = GLib.MainContext.get_thread_default() if loop is None: # We do permit unsetting the current loop/context if ctx: GLib.MainContext.pop_thread_default(ctx) self._loops.pop(ctx, None) else: # For now, force unsetting the main loop first if ctx: raise RuntimeError('Thread %r already has a main context' % threading.current_thread().name) GLib.Maincontext.push_thread_default(ctx) self._loops[ctx] = loop def new_event_loop(self): """Create and return a new event loop that iterates a new GLib.MainContext.""" return EventLoop(GLib.MainContext()) # Child processes handling (Unix only). def get_child_watcher(self): "Get the watcher for child processes." raise NotImplementedError def set_child_watcher(self, watcher): """Set the watcher for child processes.""" raise NotImplementedError # Extend SelectorKey to store the GLib source tag class _SelectorKey(selectors.SelectorKey): __slots__ = ('_tag') def _fileobj_to_fd(fileobj): # Note: SelectorEventloop should only be passing FDs if isinstance(fileobj, int): return fileobj else: return fileobj.fileno() class _Selector(selectors.BaseSelector, GLib.Source): """A Selector for gi.asyncio.EventLoop registering python IO with GLib.""" def __init__(self, context, loop): super().__init__() # It is *not* safe to run the *python* part of the mainloop recursively. # (This is the default, but make it explicit.) self.set_can_recurse(False) self.set_name('python asyncio integration') self._context = context self._loop = loop self._dispatching = False self._fd_to_key = {} self._ready = [] def close(self): self._source.clear() self._source.destroy() super().close() def register(self, fileobj, events, data=None): if (not events) or (events & ~(EVENT_READ | EVENT_WRITE)): raise ValueError("Invalid events: {!r}".format(events)) fd = _fileobj_to_fd(fileobj) assert fd not in self._fd_to_key key = _SelectorKey(fileobj, fd, events, data) condition = GLib.IOCondition(0) if events & selectors.EVENT_READ: condition |= GLib.IOCondition.IN | GLib.IOCondition.HUP if events & selectors.EVENT_WRITE: condition |= GLib.IOCondition.OUT key._tag = self.add_unix_fd(fd, condition) self._fd_to_key[fd] = key return key def unregister(self, fileobj): fd = _fileobj_to_fd(fileobj) key = self._fd_to_key[fd] self.remove_unix_fd(tag) return key def modify(self, fileobj, events, data=None): fd = _fileobj_to_fd(fileobj) key = self._fd_to_key[fd] key.events = events key.data = data condition = GLib.IOCondition(0) if events & selectors.EVENT_READ: condition |= GLib.IOCondition.IN | GLib.IOCondition.HUP if events & selectors.EVENT_WRITE: condition |= GLib.IOCondition.OUT self.modify_unix_fd(key._tag, condition) return key def get_key(self, fileobj): fd = _fileobj_to_fd(fileobj) return self._fd_to_key[fd] def get_map(self): """Return a mapping of file objects to selector keys.""" # Horribly inefficient # It should never be called and exists just to prevent issues if e.g. # python decides to use it for debug purposes. return { k.fileobj: k for k in self._fd_to_key.values() } def select(self, timeout=None): if not self._dispatching: raise RuntimeError("gi.asyncio.Selector.select only works while it is dispatching!") ready = self._ready self._ready = [] return ready # GLib.Source functions def prepare(self): timeout = self._loop._get_timeout_ms() # NOTE: Always return False, FDs are queried in check and the timeout # needs to be rechecked anyway. return False, timeout def check(self): ready = [] for key in self.self._fd_to_key.values(): condition = self.query_unix_fd(key._tag) events = 0 if condition & (GLib.IOCondition.IN | GLib.IOCondition.HUP): events |= selectors.EVENT_READ has_events = True if condition & GLib.IOCondition.OUT: events |= selectors.EVENT_WRITE has_events = True if events: ready.append((key, events)) self._ready = ready timeout = self._loop._get_timeout_ms() if timeout == 0: return True return bool(ready) def dispatch(self, callback, args): # Now, wag the dog by its tail self._dispatching = True try: self._loop._run_once() finally: self._dispatching = False return GLib.SOURCE_CONTINUE