| 1 |
# -*- Mode: Python; py-indent-offset: 4 -*- |
| 2 |
# pygobject - Python bindings for the GObject library |
| 3 |
# Copyright (C) 2021 Benjamin Berg <[email protected] |
| 4 |
# Copyright (C) 2019 James Henstridge <[email protected]> |
| 5 |
# |
| 6 |
# gi/asyncio.py: GObject asyncio integration |
| 7 |
# |
| 8 |
# This library is free software; you can redistribute it and/or |
| 9 |
# modify it under the terms of the GNU Lesser General Public |
| 10 |
# License as published by the Free Software Foundation; either |
| 11 |
# version 2.1 of the License, or (at your option) any later version. |
| 12 |
# |
| 13 |
# This library is distributed in the hope that it will be useful, |
| 14 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 16 |
# Lesser General Public License for more details. |
| 17 |
# |
| 18 |
# You should have received a copy of the GNU Lesser General Public |
| 19 |
# License along with this library; if not, see <http://www.gnu.org/licenses/>. |
| 20 |
|
| 21 |
__all__ = ["GLibEventLoop", "GLibEventLoopPolicy"] |
| 22 |
|
| 23 |
import contextlib |
| 24 |
import sys |
| 25 |
import asyncio |
| 26 |
from asyncio import coroutines |
| 27 |
import signal |
| 28 |
import threading |
| 29 |
import selectors |
| 30 |
import weakref |
| 31 |
import warnings |
| 32 |
from collections.abc import Mapping |
| 33 |
from contextlib import contextmanager |
| 34 |
from . import _ossighelper |
| 35 |
|
| 36 |
from gi.repository import GLib |
| 37 |
|
| 38 |
try: |
| 39 |
g_main_loop_run = super(GLib.MainLoop, GLib.MainLoop).run |
| 40 |
except AttributeError: |
| 41 |
g_main_loop_run = GLib.MainLoop.run |
| 42 |
|
| 43 |
|
| 44 |
class _IdleSource(GLib.Source): |
| 45 |
"""Internal helper source for idle task handling |
| 46 |
|
| 47 |
The only advantage is that we can keep the source around. |
| 48 |
""" |
| 49 |
|
| 50 |
def __init__(self, loop): |
| 51 |
super().__init__() |
| 52 |
|
| 53 |
self._loop = loop |
| 54 |
# _may_iterate will be False anyway, but might as well set it |
| 55 |
self.set_can_recurse(False) |
| 56 |
|
| 57 |
def prepare(self): |
| 58 |
if not self._loop._may_iterate: |
| 59 |
return False, -1 |
| 60 |
|
| 61 |
return bool(self._loop._idle_tasks), -1 |
| 62 |
|
| 63 |
def check(self): |
| 64 |
if not self._loop._may_iterate: |
| 65 |
return False |
| 66 |
|
| 67 |
return bool(self._loop._idle_tasks) |
| 68 |
|
| 69 |
def dispatch(self, callback, args): |
| 70 |
self._loop._glib_idle_dispatch() |
| 71 |
return GLib.SOURCE_CONTINUE |
| 72 |
|
| 73 |
|
| 74 |
class GLibTask(asyncio.Task): |
| 75 |
"""This is a simple asyncio.Task subclass that will be returned when using the |
| 76 |
GLibEventLoop. It adds functionality to set the priority that is used to |
| 77 |
iterate the task's coroutine. |
| 78 |
""" |
| 79 |
|
| 80 |
def __init__(self, *args, **kwargs): |
| 81 |
super().__init__(*args, **kwargs) |
| 82 |
|
| 83 |
self._glib_idle_priority = GLib.PRIORITY_DEFAULT |
| 84 |
|
| 85 |
def set_priority(self, priority): |
| 86 |
"""Set the GLib priority used to iterate the task's coroutine""" |
| 87 |
assert isinstance(priority, int) |
| 88 |
|
| 89 |
self._glib_idle_priority = priority |
| 90 |
|
| 91 |
def get_priority(self, priority): |
| 92 |
"""Get the GLib priority used to iterate the task's coroutine""" |
| 93 |
return self._glib_idle_priority |
| 94 |
|
| 95 |
@classmethod |
| 96 |
def _factory(cls, loop, coro, **kwargs): |
| 97 |
return GLibTask(coro, loop=loop, **kwargs) |
| 98 |
|
| 99 |
|
| 100 |
class _GLibEventLoopMixin: |
| 101 |
"""Base functionally required for both proactor and selector. |
| 102 |
|
| 103 |
The proactor/selector is always available through _selector, and we assume |
| 104 |
it has the following extra functionality that we provide: |
| 105 |
* _source: the GSource subclass |
| 106 |
* _dispatching: boolean whether it is dispatching currently |
| 107 |
* attach/detach: add/remove the GSource from the main context |
| 108 |
|
| 109 |
In principle, we simply override run_forever to call into GLib, with the |
| 110 |
assumption that a GSource is registered which will then call back into |
| 111 |
the python mainloop _run_once handler when needed. This in turn calls |
| 112 |
self._selector.select(), which means we just need to make sure to return |
| 113 |
our already prepared events at that point. |
| 114 |
|
| 115 |
If no main_context is passed, then the current default main context will |
| 116 |
be used when available. If the thread does not yet have any main context |
| 117 |
set, then a main context will be created. |
| 118 |
|
| 119 |
When creating an event loop like this, it should be used as a context |
| 120 |
manager. This ensure that the main context is set for the thread, that |
| 121 |
GLib routines will properly iterate the EventLoop and that no second |
| 122 |
EventLoop for the same main context is created by accident. |
| 123 |
""" |
| 124 |
|
| 125 |
def __init__(self, main_context): |
| 126 |
# This allows creating a reasonable GLibEventLoop for the current |
| 127 |
# thread without needing to pass anything. |
| 128 |
if main_context is None: |
| 129 |
main_context = GLib.MainContext.get_thread_default() |
| 130 |
|
| 131 |
if main_context is None: |
| 132 |
if threading.current_thread() is threading.main_thread(): |
| 133 |
# If there is none, and we are on the main thread, |
| 134 |
# then use the default context |
| 135 |
main_context = GLib.MainContext.default() |
| 136 |
else: |
| 137 |
# Otherwise, create a new context |
| 138 |
main_context = GLib.MainContext() |
| 139 |
|
| 140 |
self._context = main_context |
| 141 |
self._main_loop = GLib.MainLoop.new(self._context, False) |
| 142 |
self._quit_funcs = [] |
| 143 |
self._idle_tasks = [] |
| 144 |
self._may_iterate = False |
| 145 |
self._loop_enter_count = 0 |
| 146 |
self._loop_was_set = False |
| 147 |
self._ctx_was_set = False |
| 148 |
|
| 149 |
@contextmanager |
| 150 |
def paused(self): |
| 151 |
"""This context manager ensures the EventLoop is *not* being iterated. |
| 152 |
|
| 153 |
It purely exists to handle the case where python code iterates the main |
| 154 |
context more gracefully. |
| 155 |
""" |
| 156 |
# Nothing to do if we are not running or dispatched by ourselves |
| 157 |
if not self._may_iterate: |
| 158 |
yield |
| 159 |
return |
| 160 |
|
| 161 |
try: |
| 162 |
self._may_iterate = False |
| 163 |
self._selector.detach() |
| 164 |
yield |
| 165 |
finally: |
| 166 |
self._may_iterate = True |
| 167 |
self._selector.attach() |
| 168 |
|
| 169 |
@contextmanager |
| 170 |
def running(self, quit_func): |
| 171 |
"""This context manager ensures the EventLoop is marked as running |
| 172 |
while other API is iterating its main context. |
| 173 |
The passed quit function is used to stop all recursion levels when |
| 174 |
stop() is called. |
| 175 |
""" |
| 176 |
assert self._context.acquire() |
| 177 |
|
| 178 |
self._quit_funcs.append(quit_func) |
| 179 |
# Nested main context iteration (by using glib API) |
| 180 |
if self.is_running(): |
| 181 |
try: |
| 182 |
yield |
| 183 |
finally: |
| 184 |
self._context.release() |
| 185 |
self._quit_funcs.pop() |
| 186 |
# Stop recursively |
| 187 |
if self._stopping: |
| 188 |
self._quit_funcs[-1]() |
| 189 |
return |
| 190 |
|
| 191 |
# cpython >= 3.13 has _run_forever_setup (see also _GLibEventLoopRunMixin) |
| 192 |
if hasattr(self, "_run_forever_setup"): |
| 193 |
self._run_forever_setup() |
| 194 |
else: |
| 195 |
# Outermost nesting |
| 196 |
self._check_closed() |
| 197 |
self._set_coroutine_origin_tracking(self._debug) |
| 198 |
self._thread_id = threading.get_ident() |
| 199 |
|
| 200 |
old_agen_hooks = sys.get_asyncgen_hooks() |
| 201 |
sys.set_asyncgen_hooks( |
| 202 |
firstiter=self._asyncgen_firstiter_hook, |
| 203 |
finalizer=self._asyncgen_finalizer_hook, |
| 204 |
) |
| 205 |
asyncio._set_running_loop(self) |
| 206 |
|
| 207 |
try: |
| 208 |
assert not self._selector._source._dispatching |
| 209 |
self._may_iterate = True |
| 210 |
self._selector.attach() |
| 211 |
self._idle_source = _IdleSource(self) |
| 212 |
self._idle_source.attach(self._context) |
| 213 |
self._idle_source.set_name("GLibEventLoop._idle_source") |
| 214 |
if self._idle_tasks: |
| 215 |
self._idle_source.set_priority(self._idle_tasks[0][0]) |
| 216 |
with self: |
| 217 |
yield |
| 218 |
finally: |
| 219 |
self._may_iterate = False |
| 220 |
self._idle_source.destroy() |
| 221 |
self._idle_source = None |
| 222 |
self._selector.detach() |
| 223 |
self._context.release() |
| 224 |
self._thread_id = None |
| 225 |
|
| 226 |
if hasattr(self, "_run_forever_setup"): |
| 227 |
self._run_forever_cleanup() |
| 228 |
else: |
| 229 |
asyncio._set_running_loop(None) |
| 230 |
with contextlib.suppress(AttributeError): |
| 231 |
self._set_coroutine_origin_tracking(False) |
| 232 |
sys.set_asyncgen_hooks(*old_agen_hooks) |
| 233 |
|
| 234 |
self._stopping = False |
| 235 |
|
| 236 |
self._quit_funcs.pop() |
| 237 |
assert len(self._quit_funcs) == 0 |
| 238 |
|
| 239 |
def time(self): |
| 240 |
return GLib.get_monotonic_time() / 1000000 |
| 241 |
|
| 242 |
def _get_timeout_ms(self): |
| 243 |
if not self.is_running(): |
| 244 |
warnings.warn( |
| 245 |
"GLibEventLoop is iterated without being marked as running. Missing override or invalid use of existing API!", |
| 246 |
RuntimeWarning, |
| 247 |
) |
| 248 |
if self._stopping is True: |
| 249 |
warnings.warn( |
| 250 |
"GLibEventLoop is not stopping properly. Missing override or invalid use of existing API!", |
| 251 |
RuntimeWarning, |
| 252 |
) |
| 253 |
if self._ready: |
| 254 |
return 0 |
| 255 |
|
| 256 |
if self._scheduled: |
| 257 |
# The time is floor'ed here. |
| 258 |
# Python dispatches everything ready within the next _clock_resolution. |
| 259 |
timeout = int((self._scheduled[0]._when - self.time()) * 1000) |
| 260 |
return timeout if timeout >= 0 else 0 |
| 261 |
|
| 262 |
return -1 |
| 263 |
|
| 264 |
def _call_soon(self, callback, args, context): |
| 265 |
try: |
| 266 |
# Try to access the corresponding Task (or whatever) through the |
| 267 |
# self parameter of the bound method. |
| 268 |
# If _glib_idle_priority does not exist or it is not a bound method |
| 269 |
# then we'll just catch the AttributeError exception. |
| 270 |
priority = callback.__self__._glib_idle_priority |
| 271 |
except AttributeError: |
| 272 |
priority = GLib.PRIORITY_DEFAULT |
| 273 |
|
| 274 |
if priority == GLib.PRIORITY_DEFAULT: |
| 275 |
# Just use the underlying python dispatch. |
| 276 |
return super()._call_soon(callback, args, context) |
| 277 |
|
| 278 |
handle = asyncio.Handle(callback, args, self, context) |
| 279 |
self._idle_tasks.append((priority, handle)) |
| 280 |
self._idle_tasks.sort(key=lambda x: x[0]) |
| 281 |
|
| 282 |
# Update priority |
| 283 |
self._idle_source.set_priority(self._idle_tasks[0][0]) |
| 284 |
|
| 285 |
return handle |
| 286 |
|
| 287 |
def _glib_dispatch(self): |
| 288 |
assert self._may_iterate |
| 289 |
|
| 290 |
# The idle source disables itself and we are in the other which will not recurse |
| 291 |
self._may_iterate = False |
| 292 |
self._run_once() |
| 293 |
self._may_iterate = True |
| 294 |
|
| 295 |
def _glib_idle_dispatch(self): |
| 296 |
assert self._may_iterate |
| 297 |
|
| 298 |
# Pause so that the main Source is not going to dispatch |
| 299 |
# Note that this is pretty expensive, we could optimize it by detecting |
| 300 |
# it when it happens and only doing the detach/attach dance if needed. |
| 301 |
with self.paused(): |
| 302 |
priority = self._idle_source.get_priority() |
| 303 |
|
| 304 |
ready_handles = [] |
| 305 |
while self._idle_tasks and self._idle_tasks[0][0] == priority: |
| 306 |
ready_handles.append(self._idle_tasks.pop(0)[1]) |
| 307 |
|
| 308 |
for handle in ready_handles: |
| 309 |
handle._run() |
| 310 |
|
| 311 |
# There are (new) tasks available to run, ensure the priority is correct |
| 312 |
if self._idle_tasks: |
| 313 |
self._idle_source.set_priority(self._idle_tasks[0][0]) |
| 314 |
|
| 315 |
def stop(self): |
| 316 |
# Simply quit the mainloop |
| 317 |
self._stopping = True |
| 318 |
if self._quit_funcs: |
| 319 |
self._quit_funcs[-1]() |
| 320 |
|
| 321 |
def __repr__(self): |
| 322 |
return ( |
| 323 |
f"<{self.__class__.__name__} running={self.is_running()} " |
| 324 |
f"closed={self.is_closed()} debug={self.get_debug()} " |
| 325 |
f"ctx=0x{hash(self._context):X} loop=0x{hash(self._main_loop):X}>" |
| 326 |
) |
| 327 |
|
| 328 |
# The purpose of these mixins is to se the thread local main context, |
| 329 |
# which is useful for threading without an EventLoopPolicy. |
| 330 |
def __enter__(self): |
| 331 |
# Already entered, assume everything is fine |
| 332 |
if self._loop_enter_count > 0: |
| 333 |
self._loop_enter_count += 1 |
| 334 |
return |
| 335 |
|
| 336 |
if not self.is_running() and asyncio._get_running_loop() is not None: |
| 337 |
raise RuntimeError("Thread already has a python EventLoop") |
| 338 |
|
| 339 |
# Fetch the current MainContext to verify the state |
| 340 |
ctx = GLib.MainContext.get_thread_default() |
| 341 |
if ctx is None and threading.current_thread() is threading.main_thread(): |
| 342 |
ctx = GLib.MainContext.default() |
| 343 |
|
| 344 |
# Only permit a new EventLoop, if any old one is closed already |
| 345 |
if ( |
| 346 |
ctx is not None |
| 347 |
and hash(ctx) in GLibEventLoopPolicy._loops |
| 348 |
and not GLibEventLoopPolicy._loops[hash(ctx)].is_closed() |
| 349 |
): |
| 350 |
if GLibEventLoopPolicy._loops[hash(ctx)] is not self: |
| 351 |
raise RuntimeError( |
| 352 |
f"A GLibEventLoop is already registered through the policy ({GLibEventLoopPolicy._loops[hash(ctx)]}, self={self})" |
| 353 |
) |
| 354 |
|
| 355 |
self._loop_was_set = True |
| 356 |
else: |
| 357 |
GLibEventLoopPolicy._loops[hash(self._context)] = self |
| 358 |
|
| 359 |
if hash(ctx) != hash(self._context): |
| 360 |
GLib.MainContext.push_thread_default(self._context) |
| 361 |
self._ctx_was_set = True |
| 362 |
|
| 363 |
self._loop_enter_count += 1 |
| 364 |
|
| 365 |
def __exit__(self, exc_type, exc_value, traceback): |
| 366 |
self._loop_enter_count -= 1 |
| 367 |
if self._loop_enter_count == 0: |
| 368 |
if not self._loop_was_set: |
| 369 |
del GLibEventLoopPolicy._loops[hash(self._context)] |
| 370 |
if self._ctx_was_set: |
| 371 |
GLib.MainContext.pop_thread_default(self._context) |
| 372 |
self._loop_was_set = False |
| 373 |
self._ctx_was_set = False |
| 374 |
|
| 375 |
|
| 376 |
class _GLibEventLoopRunMixin: |
| 377 |
# This class exists so we don't need to copy the ProactorEventLoop.run_forever, |
| 378 |
# instead, we change the MRO using a metaclass, so that super() sees this class |
| 379 |
# when called in ProactorEventLoop.run_forever. |
| 380 |
# |
| 381 |
# This class is only needed for cpython < 3.13. |
| 382 |
|
| 383 |
def run_forever(self): |
| 384 |
# NOTE: self._check_running was only added in 3.8 (with a typo in 3.7) |
| 385 |
if self.is_running(): |
| 386 |
raise RuntimeError("This event loop is already running") |
| 387 |
|
| 388 |
with ( |
| 389 |
_ossighelper.register_sigint_fallback(self._main_loop.quit), |
| 390 |
self.running(self._main_loop.quit), |
| 391 |
): |
| 392 |
g_main_loop_run(self._main_loop) |
| 393 |
|
| 394 |
|
| 395 |
class _SourceBase(GLib.Source): |
| 396 |
"""Common Source functionality for both unix and win32""" |
| 397 |
|
| 398 |
def __init__(self, selector): |
| 399 |
super().__init__() |
| 400 |
|
| 401 |
self._dispatching = False |
| 402 |
|
| 403 |
# It is *not* safe to run the *python* part of the mainloop recursively. |
| 404 |
# This error must be caught further up in the chain, otherwise the |
| 405 |
# mainloop will be blocking without an obvious reason. |
| 406 |
self.set_can_recurse(False) |
| 407 |
self.set_name("python asyncio integration") |
| 408 |
|
| 409 |
self._selector = weakref.ref(selector) |
| 410 |
|
| 411 |
self._ready = [] |
| 412 |
|
| 413 |
def _loop(self): |
| 414 |
return self._selector()._loop |
| 415 |
|
| 416 |
def dispatch(self, callback, args): |
| 417 |
# Now, wag the dog by its tail |
| 418 |
self._dispatching = True |
| 419 |
try: |
| 420 |
self._loop()._glib_dispatch() |
| 421 |
finally: |
| 422 |
self._dispatching = False |
| 423 |
|
| 424 |
return GLib.SOURCE_CONTINUE |
| 425 |
|
| 426 |
def _get_ready(self): |
| 427 |
if not self._dispatching: |
| 428 |
raise RuntimeError( |
| 429 |
"gi.asyncio.Selector.select only works while it is dispatching!" |
| 430 |
) |
| 431 |
|
| 432 |
ready = self._ready |
| 433 |
self._ready = [] |
| 434 |
return ready |
| 435 |
|
| 436 |
|
| 437 |
class _SelectorMixin: |
| 438 |
"""A Mixin for common functionality of the Selector and Proactor.""" |
| 439 |
|
| 440 |
def __init__(self, context, loop): |
| 441 |
super().__init__() |
| 442 |
|
| 443 |
self._context = context |
| 444 |
self._loop = loop |
| 445 |
self._fd_to_key = {} |
| 446 |
|
| 447 |
self._source = _Source(self) |
| 448 |
|
| 449 |
def close(self): |
| 450 |
# See _Selector.unregister |
| 451 |
if self._source and hash(self._source): |
| 452 |
self._source.destroy() |
| 453 |
self._source = None |
| 454 |
super().close() |
| 455 |
|
| 456 |
def select(self, timeout=None): |
| 457 |
return self._source._get_ready() |
| 458 |
|
| 459 |
def _real_select(self, timeout=None): |
| 460 |
return super().select(timeout) |
| 461 |
|
| 462 |
|
| 463 |
if sys.platform != "win32": |
| 464 |
|
| 465 |
class GLibEventLoop( |
| 466 |
_GLibEventLoopMixin, _GLibEventLoopRunMixin, asyncio.SelectorEventLoop |
| 467 |
): |
| 468 |
"""An asyncio event loop that runs the python mainloop inside GLib. |
| 469 |
|
| 470 |
Based on the asyncio.SelectorEventLoop |
| 471 |
""" |
| 472 |
|
| 473 |
_GLIB_SIGNALS = { |
| 474 |
signal.SIGHUP, |
| 475 |
signal.SIGINT, |
| 476 |
signal.SIGTERM, |
| 477 |
signal.SIGUSR1, |
| 478 |
signal.SIGUSR2, |
| 479 |
signal.SIGWINCH, |
| 480 |
} |
| 481 |
|
| 482 |
# This is based on the selector event loop, but never actually runs select() |
| 483 |
# in the strict sense. |
| 484 |
# We use the selector to register all FDs with the main context using our |
| 485 |
# own GSource. For python timeouts/idle equivalent, we directly query them |
| 486 |
# from the context by providing the _get_timeout_ms function that the |
| 487 |
# GSource uses. This in turn accesses _ready and _scheduled to calculate |
| 488 |
# the timeout and whether python can dispatch anything non-FD based yet. |
| 489 |
# |
| 490 |
# The Selector select() method simply returns the information we already |
| 491 |
# collected. |
| 492 |
# |
| 493 |
# The rest is done by the mixin which overrides run_forever to simply |
| 494 |
# iterate the main context. |
| 495 |
def __init__(self, main_context=None): |
| 496 |
_GLibEventLoopMixin.__init__(self, main_context) |
| 497 |
|
| 498 |
# _UnixSelectorEventLoop uses _signal_handlers, we could do the same, |
| 499 |
# with the difference that close() would clean up the handlers for us. |
| 500 |
self.__signal_handlers = {} |
| 501 |
|
| 502 |
selector = _Selector(self._context, self) |
| 503 |
asyncio.SelectorEventLoop.__init__(self, selector) |
| 504 |
|
| 505 |
# Used by run_once to not busy loop if the timeout is floor'ed to zero |
| 506 |
self._clock_resolution = 1e-3 |
| 507 |
|
| 508 |
# Use our custom Task subclass |
| 509 |
self._task_factory = GLibTask._factory |
| 510 |
|
| 511 |
def add_signal_handler(self, sig, callback, *args): |
| 512 |
"""Add a handler for UNIX signal""" |
| 513 |
if coroutines.iscoroutine(callback) or coroutines.iscoroutinefunction( |
| 514 |
callback |
| 515 |
): |
| 516 |
raise TypeError("coroutines cannot be used with add_signal_handler()") |
| 517 |
self._check_closed() |
| 518 |
|
| 519 |
# Can be useful while testing failures |
| 520 |
# assert sig != signal.SIGALRM |
| 521 |
|
| 522 |
if sig not in self._GLIB_SIGNALS: |
| 523 |
return super().add_signal_handler(sig, callback, *args) |
| 524 |
|
| 525 |
# Pure python demands that there is only one signal handler |
| 526 |
source = self.__signal_handlers.get(sig, (None, None, None))[0] |
| 527 |
if source: |
| 528 |
source.destroy() |
| 529 |
|
| 530 |
# Set up a new source with a higher priority than our main one |
| 531 |
source = GLib.unix_signal_source_new(sig) |
| 532 |
source.set_name(f"asyncio signal watch for {sig}") |
| 533 |
source.set_priority(GLib.PRIORITY_HIGH) |
| 534 |
source.attach(self._context) |
| 535 |
source.set_callback(self._signal_cb, sig) |
| 536 |
|
| 537 |
self.__signal_handlers[sig] = (source, callback, args) |
| 538 |
del source |
| 539 |
return None |
| 540 |
|
| 541 |
def remove_signal_handler(self, sig): |
| 542 |
if sig not in self._GLIB_SIGNALS: |
| 543 |
return super().remove_signal_handler(sig) |
| 544 |
|
| 545 |
try: |
| 546 |
source, _, _ = self.__signal_handlers[sig] |
| 547 |
del self.__signal_handlers[sig] |
| 548 |
# Really unref the underlying GSource so that GLib resets the signal handler |
| 549 |
source.destroy() |
| 550 |
source._clear_boxed() |
| 551 |
|
| 552 |
# GLib does not restore the original signal handler. |
| 553 |
# Try to restore the python handler for SIGINT, this makes |
| 554 |
# Ctrl+C work after the mainloop has quit. |
| 555 |
if ( |
| 556 |
sig == signal.SIGINT |
| 557 |
and _ossighelper.PyOS_getsig(signal.SIGINT) == 0 |
| 558 |
and _ossighelper.startup_sigint_ptr > 0 |
| 559 |
): |
| 560 |
_ossighelper.PyOS_setsig( |
| 561 |
signal.SIGINT, _ossighelper.startup_sigint_ptr |
| 562 |
) |
| 563 |
|
| 564 |
return True |
| 565 |
except KeyError: |
| 566 |
return False |
| 567 |
|
| 568 |
def _signal_cb(self, sig): |
| 569 |
_source, cb, args = self.__signal_handlers.get(sig) |
| 570 |
|
| 571 |
# Pass over to python mainloop |
| 572 |
self.call_soon(cb, *args) |
| 573 |
|
| 574 |
def close(self): |
| 575 |
super().close() |
| 576 |
for s in list(self.__signal_handlers): |
| 577 |
self.remove_signal_handler(s) |
| 578 |
|
| 579 |
def _fileobj_to_fd(fileobj): |
| 580 |
# Note: SelectorEventloop should only be passing FDs |
| 581 |
if isinstance(fileobj, int): |
| 582 |
return fileobj |
| 583 |
return fileobj.fileno() |
| 584 |
|
| 585 |
class _Source(_SourceBase): |
| 586 |
def prepare(self): |
| 587 |
timeout = self._loop()._get_timeout_ms() |
| 588 |
|
| 589 |
# NOTE: Always return False, FDs are queried in check and the timeout |
| 590 |
# needs to be rechecked anyway. |
| 591 |
return False, timeout |
| 592 |
|
| 593 |
def check(self): |
| 594 |
ready = [] |
| 595 |
|
| 596 |
for key in self._selector()._fd_to_key.values(): |
| 597 |
condition = self.query_unix_fd(key._tag) |
| 598 |
events = 0 |
| 599 |
# ERR/HUP/NVAL trigger both read/write (PRI cannot happen) |
| 600 |
if condition & ~GLib.IOCondition.OUT: |
| 601 |
events |= selectors.EVENT_READ |
| 602 |
if condition & ~GLib.IOCondition.IN: |
| 603 |
events |= selectors.EVENT_WRITE |
| 604 |
if events: |
| 605 |
ready.append((key, events)) |
| 606 |
self._ready = ready |
| 607 |
|
| 608 |
timeout = self._loop()._get_timeout_ms() |
| 609 |
if timeout == 0: |
| 610 |
return True |
| 611 |
|
| 612 |
return bool(ready) |
| 613 |
|
| 614 |
class _SelectorKey(selectors.SelectorKey): |
| 615 |
# Subclass to attach _tag |
| 616 |
pass |
| 617 |
|
| 618 |
class _FileObjectMapping(Mapping): |
| 619 |
def __init__(self, fd_dict): |
| 620 |
self.fd_dict = fd_dict |
| 621 |
|
| 622 |
def __len__(self): |
| 623 |
return len(self.fd_dict) |
| 624 |
|
| 625 |
def get(self, fileobj, default=None): |
| 626 |
fd = _fileobj_to_fd(fileobj) |
| 627 |
return self.fd_dict.get(fd, default) |
| 628 |
|
| 629 |
def __getitem__(self, fileobj): |
| 630 |
value = self.get(fileobj) |
| 631 |
if value is None: |
| 632 |
raise KeyError(f"{fileobj!r} is not registered") |
| 633 |
return value |
| 634 |
|
| 635 |
def __iter__(self): |
| 636 |
return iter(self.fd_dict) |
| 637 |
|
| 638 |
class _Selector(_SelectorMixin, selectors.BaseSelector): |
| 639 |
"""A Selector for gi.events.GLibEventLoop registering python IO with GLib.""" |
| 640 |
|
| 641 |
def __init__(self, context, loop): |
| 642 |
super().__init__(context, loop) |
| 643 |
self._map = _FileObjectMapping(self._fd_to_key) |
| 644 |
|
| 645 |
def attach(self): |
| 646 |
self._source.attach(self._loop._context) |
| 647 |
|
| 648 |
def detach(self): |
| 649 |
self._source.destroy() |
| 650 |
self._source = _Source(self) |
| 651 |
# re-register the keys with the new source |
| 652 |
for key in self._fd_to_key.values(): |
| 653 |
self._register_key(key) |
| 654 |
|
| 655 |
def _register_key(self, key): |
| 656 |
condition = GLib.IOCondition(0) |
| 657 |
if key.events & selectors.EVENT_READ: |
| 658 |
condition |= GLib.IOCondition.IN |
| 659 |
if key.events & selectors.EVENT_WRITE: |
| 660 |
condition |= GLib.IOCondition.OUT |
| 661 |
key._tag = self._source.add_unix_fd(key.fd, condition) |
| 662 |
|
| 663 |
def register(self, fileobj, events, data=None): |
| 664 |
if (not events) or ( |
| 665 |
events & ~(selectors.EVENT_READ | selectors.EVENT_WRITE) |
| 666 |
): |
| 667 |
raise ValueError(f"Invalid events: {events!r}") |
| 668 |
|
| 669 |
fd = _fileobj_to_fd(fileobj) |
| 670 |
if fd in self._fd_to_key: |
| 671 |
raise KeyError(f"{fileobj!r} (FD {fd}) is already registered") |
| 672 |
|
| 673 |
key = _SelectorKey(fileobj, fd, events, data) |
| 674 |
|
| 675 |
self._register_key(key) |
| 676 |
|
| 677 |
self._fd_to_key[fd] = key |
| 678 |
return key |
| 679 |
|
| 680 |
def unregister(self, fileobj): |
| 681 |
# NOTE: may be called after __del__ has been called. |
| 682 |
fd = _fileobj_to_fd(fileobj) |
| 683 |
key = self._fd_to_key[fd] |
| 684 |
|
| 685 |
# As __del__ might have happened, the source may be an empty shell |
| 686 |
# object and calling a function on it will crash us. |
| 687 |
# Catch this by checking that the contained pointer is not NULL. |
| 688 |
if self._source and hash(self._source): |
| 689 |
self._source.remove_unix_fd(key._tag) |
| 690 |
del self._fd_to_key[fd] |
| 691 |
|
| 692 |
return key |
| 693 |
|
| 694 |
# We could override modify, but it is only slightly when the "events" change. |
| 695 |
|
| 696 |
def get_key(self, fileobj): |
| 697 |
return self._map[fileobj] |
| 698 |
|
| 699 |
def get_map(self): |
| 700 |
"""Return a mapping of file objects or file descriptors to |
| 701 |
selector keys. |
| 702 |
""" |
| 703 |
return self._map |
| 704 |
|
| 705 |
|
| 706 |
else: |
| 707 |
|
| 708 |
class _PushRunMixinBackMeta(type): |
| 709 |
# This metaclass changes the MRO so that when run_forever is called, it |
| 710 |
# first calls asyncio.ProactorEventLoop and then chains into |
| 711 |
# _GLibEventLoopRunMixin.run_forever using super(). |
| 712 |
# The alternative would be to copy asyncio.ProactorEventLoop.run_forever |
| 713 |
def mro(cls): |
| 714 |
mro = type.mro(cls) |
| 715 |
idx = mro.index(_GLibEventLoopRunMixin) |
| 716 |
|
| 717 |
return [*mro[:idx], mro[idx + 1], mro[idx], *mro[idx + 2 :]] |
| 718 |
|
| 719 |
class GLibEventLoop( |
| 720 |
_GLibEventLoopMixin, |
| 721 |
_GLibEventLoopRunMixin, |
| 722 |
asyncio.ProactorEventLoop, |
| 723 |
metaclass=_PushRunMixinBackMeta, |
| 724 |
): |
| 725 |
"""An asyncio event loop that runs the python mainloop inside GLib. |
| 726 |
|
| 727 |
Based on the asyncio.WindowsProactorEventLoopPolicy |
| 728 |
""" |
| 729 |
|
| 730 |
# This is based on the Windows ProactorEventLoop |
| 731 |
def __init__(self, main_context=None): |
| 732 |
_GLibEventLoopMixin.__init__(self, main_context) |
| 733 |
|
| 734 |
proactor = _Proactor(self._context, self) |
| 735 |
# Sets both self._proactor and self._selector to the proactor |
| 736 |
asyncio.ProactorEventLoop.__init__(self, proactor) |
| 737 |
|
| 738 |
# Used by run_once to not busy loop if the timeout is floor'ed to zero |
| 739 |
self._clock_resolution = 1e-3 |
| 740 |
|
| 741 |
# Use our custom Task subclass |
| 742 |
self._task_factory = GLibTask._factory |
| 743 |
|
| 744 |
class _Source(_SourceBase): |
| 745 |
def __init__(self, proactor): |
| 746 |
super().__init__(proactor) |
| 747 |
|
| 748 |
# None denotes it is disabled (and will also not handle timeouts) |
| 749 |
self._poll_fd = None |
| 750 |
|
| 751 |
def enable(self): |
| 752 |
assert self._poll_fd is None |
| 753 |
|
| 754 |
self._poll_fd = GLib.PollFD(self._selector()._iocp, GLib.IO_IN) |
| 755 |
self.add_poll(self._poll_fd) |
| 756 |
|
| 757 |
def disable(self): |
| 758 |
self.remove_poll(self._poll_fd) |
| 759 |
self._poll_fd = None |
| 760 |
|
| 761 |
def prepare(self): |
| 762 |
# Disabled, do not handle timeouts either |
| 763 |
if self._poll_fd is None: |
| 764 |
return False, -1 |
| 765 |
|
| 766 |
timeout = self._loop()._get_timeout_ms() |
| 767 |
|
| 768 |
return bool(self._ready), timeout |
| 769 |
|
| 770 |
def check(self): |
| 771 |
if self._poll_fd is None: |
| 772 |
return False |
| 773 |
|
| 774 |
if self._poll_fd.revents: |
| 775 |
self._ready.extend(self._selector()._real_select(0)) |
| 776 |
|
| 777 |
if self._ready: |
| 778 |
return True |
| 779 |
|
| 780 |
return self._loop()._get_timeout_ms() == 0 |
| 781 |
|
| 782 |
class _Proactor(_SelectorMixin, asyncio.IocpProactor): |
| 783 |
"""A Proactor for gi.events.GLibEventLoop registering python IO with GLib.""" |
| 784 |
|
| 785 |
def __init__(self, context, loop): |
| 786 |
super().__init__(context, loop) |
| 787 |
|
| 788 |
# We always use the same Source on windows, it disables itself |
| 789 |
self._source = _Source(self) |
| 790 |
self._source.attach(context) |
| 791 |
|
| 792 |
def attach(self): |
| 793 |
self._source.enable() |
| 794 |
|
| 795 |
def detach(self): |
| 796 |
self._source.disable() |
| 797 |
|
| 798 |
|
| 799 |
# The following are deprecated in 3.13 and will be removed in 3.16, |
| 800 |
# keep current code working that uses it to the point that we can. |
| 801 |
# NOTE: Convenient filtering was added in python 3.10, just ignore all warnings |
| 802 |
with warnings.catch_warnings(): |
| 803 |
AbstractEventLoopPolicy = getattr(asyncio, "AbstractEventLoopPolicy", object) |
| 804 |
|
| 805 |
_set_event_loop_policy = getattr(asyncio, "set_event_loop_policy", lambda: None) |
| 806 |
_get_event_loop_policy = getattr(asyncio, "get_event_loop_policy", lambda: None) |
| 807 |
|
| 808 |
|
| 809 |
class GLibEventLoopPolicy(AbstractEventLoopPolicy): |
| 810 |
"""An asyncio event loop policy that runs the GLib main loop. |
| 811 |
|
| 812 |
NOTE: Python 3.16 is removing the concept of the event loop policy. |
| 813 |
FIXME: say what to do in the future |
| 814 |
|
| 815 |
The policy allows creating a new EventLoop for threads other than the main |
| 816 |
thread. For the main thread, you can use get_event_loop() to retrieve the |
| 817 |
correct mainloop and run it. |
| 818 |
|
| 819 |
Note that, unlike GLib, python does not support running the EventLoop |
| 820 |
recursively. You should never iterate the GLib.MainContext from within |
| 821 |
the python EventLoop as doing so prevents asyncio events from being |
| 822 |
dispatched. |
| 823 |
|
| 824 |
As such, do not use API such as GLib.MainLoop.run or Gtk.Dialog.run. |
| 825 |
Instead use the proper asynchronous patterns to prevent entirely blocking |
| 826 |
asyncio. |
| 827 |
""" |
| 828 |
|
| 829 |
_loops = {} |
| 830 |
# COMPAT: child watchers were removed in cpython 3.12 |
| 831 |
_child_watcher = None |
| 832 |
|
| 833 |
def __init__(self): |
| 834 |
self.__orig_policy = None |
| 835 |
|
| 836 |
def get_event_loop(self): |
| 837 |
"""Get the event loop for the current context. |
| 838 |
|
| 839 |
Returns an event loop object for the thread default GLib.MainContext |
| 840 |
or in case of the main thread for the default GLib.MainContext. |
| 841 |
|
| 842 |
An exception will be thrown if there is no GLib.MainContext for the |
| 843 |
current thread. In that case, using new_event_loop() will create a new |
| 844 |
main context and main loop which can subsequently attached to the thread |
| 845 |
by calling set_event_loop(). |
| 846 |
|
| 847 |
Returns a new GLibEventLoop or raises an exception. |
| 848 |
""" |
| 849 |
return self._get_event_loop(force_implicit=True) |
| 850 |
|
| 851 |
def get_event_loop_for_context(self, ctx): |
| 852 |
"""Get the event loop for a specific context.""" |
| 853 |
return self._get_event_loop_for_context(ctx, force_implicit=True) |
| 854 |
|
| 855 |
@classmethod |
| 856 |
def _get_event_loop(cls, force_implicit=False): |
| 857 |
# Get the thread default main context |
| 858 |
ctx = GLib.MainContext.get_thread_default() |
| 859 |
# If there is none, and we are on the main thread, then use the default context |
| 860 |
if ctx is None and threading.current_thread() is threading.main_thread(): |
| 861 |
ctx = GLib.MainContext.default() |
| 862 |
|
| 863 |
# We do not create a main context implicitly; |
| 864 |
# we create a mainloop for an existing context though |
| 865 |
if ctx is None: |
| 866 |
if not force_implicit: |
| 867 |
return None |
| 868 |
|
| 869 |
raise RuntimeError( |
| 870 |
f"There is no main context set for thread {threading.current_thread().name!r}." |
| 871 |
) |
| 872 |
|
| 873 |
return cls._get_event_loop_for_context(ctx, force_implicit=force_implicit) |
| 874 |
|
| 875 |
@classmethod |
| 876 |
def _get_event_loop_for_context(cls, ctx, force_implicit=False): |
| 877 |
"""Get the event loop for a specific context.""" |
| 878 |
# Note: We cannot attach it to ctx, as getting the default will always |
| 879 |
# return a new python wrapper. But, we can use hash() as that returns |
| 880 |
# the pointer to the C structure. |
| 881 |
try: |
| 882 |
loop = cls._loops[hash(ctx)] |
| 883 |
if not loop.is_closed(): |
| 884 |
return loop |
| 885 |
except KeyError: |
| 886 |
pass |
| 887 |
|
| 888 |
if not force_implicit: |
| 889 |
with warnings.catch_warnings(): |
| 890 |
if not isinstance(_get_event_loop_policy(), GLibEventLoopPolicy): |
| 891 |
return None |
| 892 |
|
| 893 |
cls._loops[hash(ctx)] = GLibEventLoop(ctx) |
| 894 |
if cls._child_watcher and ctx == GLib.MainContext.default(): |
| 895 |
cls._child_watcher.attach_loop(cls._loops[hash(ctx)]) |
| 896 |
return cls._loops[hash(ctx)] |
| 897 |
|
| 898 |
def set_event_loop(self, loop): |
| 899 |
"""Set the event loop for the current context (python thread) to loop. |
| 900 |
|
| 901 |
This is only permitted if the thread has no thread default main context |
| 902 |
with the main thread using the default main context. |
| 903 |
""" |
| 904 |
# Only accept glib event loops, otherwise things will just mess up |
| 905 |
assert loop is None or isinstance(loop, GLibEventLoop) |
| 906 |
|
| 907 |
ctx = ctx_td = GLib.MainContext.get_thread_default() |
| 908 |
if ctx is None and threading.current_thread() is threading.main_thread(): |
| 909 |
ctx = GLib.MainContext.default() |
| 910 |
|
| 911 |
if loop is None: |
| 912 |
# We do permit unsetting the current loop/context |
| 913 |
old = self._loops.pop(hash(ctx), None) |
| 914 |
if old: |
| 915 |
if hash(old._context) != hash(ctx): |
| 916 |
warnings.warn( |
| 917 |
"GMainContext was changed unknowingly by asyncio integration!", |
| 918 |
RuntimeWarning, |
| 919 |
) |
| 920 |
if ctx_td: |
| 921 |
GLib.MainContext.pop_thread_default(ctx_td) |
| 922 |
else: |
| 923 |
# Only allow attaching if the thread has no main context yet |
| 924 |
if ctx: |
| 925 |
raise RuntimeError( |
| 926 |
f"Thread {threading.current_thread().name!r} already has a main context, " |
| 927 |
"get_event_loop() will create a new loop if needed" |
| 928 |
) |
| 929 |
|
| 930 |
GLib.MainContext.push_thread_default(loop._context) |
| 931 |
self._loops[hash(loop._context)] = loop |
| 932 |
|
| 933 |
def new_event_loop(self): |
| 934 |
"""Create and return a new event loop that iterates a new |
| 935 |
GLib.MainContext. |
| 936 |
""" |
| 937 |
return GLibEventLoop(GLib.MainContext()) |
| 938 |
|
| 939 |
def __enter__(self): |
| 940 |
with warnings.catch_warnings(): |
| 941 |
self.__orig_policy = _get_event_loop_policy() |
| 942 |
_set_event_loop_policy(self) |
| 943 |
|
| 944 |
return self |
| 945 |
|
| 946 |
def __exit__(self, exc_type, exc_value, traceback): |
| 947 |
# We shouldn't have any running loops at this point, and the ones that |
| 948 |
# got created should be closed eventually. |
| 949 |
# Explicitly close all loops here, it is not reasonable for them to be |
| 950 |
# used after we unregister the EventLoopPolicy below. |
| 951 |
for loop in self._loops.values(): |
| 952 |
loop.close() |
| 953 |
|
| 954 |
with warnings.catch_warnings(): |
| 955 |
_set_event_loop_policy(self.__orig_policy) |
| 956 |
|
| 957 |
# Do not supress any exceptions |
| 958 |
return False |
| 959 |
|
| 960 |
# NOTE: We do *not* provide a GLib based ChildWatcher implementation! |
| 961 |
# This is *intentional* and *required*. The issue is that python provides |
| 962 |
# API which uses wait4() internally. GLib at the same time uses a thread to |
| 963 |
# handle SIGCHLD signals, which causes a race condition resulting in a |
| 964 |
# critical warning. |
| 965 |
# We just provide a reasonable sane child watcher and disallow the user |
| 966 |
# from choosing one as e.g. MultiLoopChildWatcher is problematic. |
| 967 |
# |
| 968 |
# COMPAT: child watchers were removed in python 3.12 |
| 969 |
if sys.platform != "win32" and hasattr( |
| 970 |
AbstractEventLoopPolicy, "get_child_watcher" |
| 971 |
): |
| 972 |
|
| 973 |
@classmethod |
| 974 |
def get_child_watcher(cls): |
| 975 |
if cls._child_watcher is None: |
| 976 |
cls._child_watcher = asyncio.ThreadedChildWatcher() |
| 977 |
|
| 978 |
if threading.current_thread() is threading.main_thread(): |
| 979 |
cls._child_watcher.attach_loop(cls._get_event_loop()) |
| 980 |
|
| 981 |
return cls._child_watcher |