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