|
| 1 | +import sys |
1 | 2 | import asyncio
|
| 3 | +from asyncio import events |
2 | 4 | import threading
|
3 | 5 |
|
4 | 6 | from gi.repository import GLib
|
5 | 7 |
|
6 | 8 | from . import glib_selector
|
7 | 9 |
|
| 10 | +# The override for GLib.MainLoop.run installs a signal wakeup fd, |
| 11 | +# which interferes with asyncio signal handlers. Try to get the |
| 12 | +# direct version. |
| 13 | +try: |
| 14 | + g_main_loop_run = super(GLib.MainLoop, GLib.MainLoop).run |
| 15 | +except AttributeError: |
| 16 | + g_main_loop_run = GLib.MainLoop.run |
8 | 17 |
|
9 | 18 | __all__ = (
|
10 | 19 | 'GLibEventLoop',
|
|
13 | 22 |
|
14 | 23 |
|
15 | 24 | class GLibEventLoop(asyncio.SelectorEventLoop):
|
16 |
| - """An asyncio event loop that runs the GLib main loop""" |
| 25 | + """An asyncio event loop that runs the GLib context using a main loop""" |
17 | 26 |
|
18 |
| - def __init__(self, main_context=None): |
19 |
| - if main_context is None: |
20 |
| - main_context = GLib.MainContext.default() |
21 |
| - selector = glib_selector.GLibSelector(main_context) |
| 27 | + # This is based on the selector event loop, but never actually runs select() |
| 28 | + # in the strict sense. |
| 29 | + # We use the selector to register all FDs with the main context using our |
| 30 | + # own GSource. For python timeouts/idle equivalent, we directly query them |
| 31 | + # from the context by providing the _get_timeout_ms function that the |
| 32 | + # GSource uses. This in turn access _ready and _scheduled to calculate |
| 33 | + # the timeout and whether python can dispatch anything non-FD based yet. |
| 34 | + # |
| 35 | + # To simplify matters, we call the normal _run_once method of the base |
| 36 | + # class which will call select(). As we know that we are ready at the time |
| 37 | + # that select() will return immediately with the FD information we have |
| 38 | + # gathered already. |
| 39 | + # |
| 40 | + # With that, we just need to override and slightly modify the run_forever |
| 41 | + # method so that it calls g_main_loop_run instead of looping _run_once. |
| 42 | + |
| 43 | + def __init__(self, main_context): |
| 44 | + # A mainloop in case we want to run our context |
| 45 | + assert main_context is not None |
| 46 | + self._context = main_context |
| 47 | + self._main_loop = GLib.MainLoop.new(self._context, False) |
| 48 | + |
| 49 | + selector = glib_selector.GLibSelector(self._context, self) |
22 | 50 | super().__init__(selector)
|
23 | 51 |
|
| 52 | + # This is used by run_once to not busy loop if the timeout is floor'ed to zero |
| 53 | + self._clock_resolution = 1e-3 |
| 54 | + |
| 55 | + def run_forever(self): |
| 56 | + self._check_closed() |
| 57 | + self._check_running() |
| 58 | + self._set_coroutine_origin_tracking(self._debug) |
| 59 | + self._thread_id = threading.get_ident() |
| 60 | + |
| 61 | + old_agen_hooks = sys.get_asyncgen_hooks() |
| 62 | + sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook, |
| 63 | + finalizer=self._asyncgen_finalizer_hook) |
| 64 | + try: |
| 65 | + events._set_running_loop(self) |
| 66 | + g_main_loop_run(self._main_loop) |
| 67 | + finally: |
| 68 | + self._thread_id = None |
| 69 | + events._set_running_loop(None) |
| 70 | + self._set_coroutine_origin_tracking(False) |
| 71 | + sys.set_asyncgen_hooks(*old_agen_hooks) |
| 72 | + |
| 73 | + def time(self): |
| 74 | + return GLib.get_monotonic_time() / 1000000 |
| 75 | + |
| 76 | + def _get_timeout_ms(self): |
| 77 | + if self._ready: |
| 78 | + return 0 |
| 79 | + |
| 80 | + if self._scheduled: |
| 81 | + timeout = (self._scheduled[0]._when - self.time()) * 1000 |
| 82 | + return timeout if timeout >= 0 else 0 |
| 83 | + |
| 84 | + return -1 |
| 85 | + |
| 86 | + def is_running(self): |
| 87 | + # If we are currently the owner, then the context is running |
| 88 | + # (and we are being dispatched by it) |
| 89 | + if self._context.is_owner(): |
| 90 | + return True |
| 91 | + |
| 92 | + # Otherwise, it might (but shouldn't) be running in a different thread |
| 93 | + # Try aquiring it, if that fails, another thread is owning it |
| 94 | + if not self._context.acquire(): |
| 95 | + return True |
| 96 | + self._context.release() |
| 97 | + |
| 98 | + return False |
| 99 | + |
| 100 | + def stop(self): |
| 101 | + self._main_loop.quit() |
24 | 102 |
|
25 |
| -class GLibEventLoopPolicy(asyncio.DefaultEventLoopPolicy): |
| 103 | +class GLibEventLoopPolicy(events.AbstractEventLoopPolicy): |
26 | 104 | """An asyncio event loop policy that runs the GLib main loop"""
|
27 | 105 |
|
| 106 | + _loops = {} |
| 107 | + |
| 108 | + def get_event_loop(self): |
| 109 | + """Get the event loop for the current context. |
| 110 | +
|
| 111 | + Returns an event loop object implementing the BaseEventLoop interface, |
| 112 | + or raises an exception in case no event loop has been set for the |
| 113 | + current context and the current policy does not specify to create one. |
| 114 | +
|
| 115 | + It should never return None.""" |
| 116 | + # Get the thread default main context |
| 117 | + ctx = GLib.MainContext.get_thread_default() |
| 118 | + # If there is none, and we are on the main thread, then use the default context |
| 119 | + if ctx is None and threading.current_thread() is threading.main_thread(): |
| 120 | + ctx = GLib.MainContext.default() |
| 121 | + # Otherwise, if there is still none, create a new one for this thread and push it |
| 122 | + if ctx is None: |
| 123 | + ctx = GLib.MainContext.new() |
| 124 | + ctx.push_thread_default() |
| 125 | + |
| 126 | + # Note: We cannot attach it to ctx, as getting the default will always |
| 127 | + # return a new python wrapper. But, we can use hash() as that returns |
| 128 | + # the pointer to the C structure. |
| 129 | + if ctx in self._loops: |
| 130 | + loop = self._loops[ctx] |
| 131 | + # If the loop is already closed, then return a new one instead |
| 132 | + if not loop._closed: |
| 133 | + return loop |
| 134 | + |
| 135 | + self._loops[ctx] = GLibEventLoop(ctx) |
| 136 | + return self._loops[ctx] |
| 137 | + |
| 138 | + def set_event_loop(self, loop): |
| 139 | + """Set the event loop for the current context to loop.""" |
| 140 | + raise NotImplementedError |
| 141 | + |
28 | 142 | def new_event_loop(self):
|
29 |
| - if threading.current_thread() != threading.main_thread(): |
30 |
| - raise RuntimeError("GLibEventLoopPolicy only allows the main " |
31 |
| - "thread to create event loops") |
32 |
| - return GLibEventLoop() |
| 143 | + """Create and return a new event loop object according to this |
| 144 | + policy's rules. If there's need to set this loop as the event loop for |
| 145 | + the current context, set_event_loop must be called explicitly.""" |
| 146 | + raise NotImplementedError |
| 147 | + |
| 148 | + # Child processes handling (Unix only). |
| 149 | + |
| 150 | + def get_child_watcher(self): |
| 151 | + "Get the watcher for child processes." |
| 152 | + raise NotImplementedError |
| 153 | + |
| 154 | + def set_child_watcher(self, watcher): |
| 155 | + """Set the watcher for child processes.""" |
| 156 | + raise NotImplementedError |
| 157 | + |
0 commit comments