gstreamer-python 1.27.90__cp312-cp312-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. gstreamer_python/Lib/girepository-1.0/GdkPixbuf-2.0.typelib +0 -0
  2. gstreamer_python/Lib/girepository-1.0/HarfBuzz-0.0.typelib +0 -0
  3. gstreamer_python/Lib/girepository-1.0/Json-1.0.typelib +0 -0
  4. gstreamer_python/Lib/girepository-1.0/Pango-1.0.typelib +0 -0
  5. gstreamer_python/Lib/girepository-1.0/PangoCairo-1.0.typelib +0 -0
  6. gstreamer_python/Lib/girepository-1.0/Soup-3.0.typelib +0 -0
  7. gstreamer_python/Lib/gstreamer-1.0/gstpython.dll +0 -0
  8. gstreamer_python/Lib/site-packages/PyGObject-3.50.2.dist-info/METADATA +21 -0
  9. gstreamer_python/Lib/site-packages/cairo/__init__.py +25 -0
  10. gstreamer_python/Lib/site-packages/cairo/__init__.pyi +5889 -0
  11. gstreamer_python/Lib/site-packages/cairo/_cairo.cp312-win_amd64.pyd +0 -0
  12. gstreamer_python/Lib/site-packages/cairo/include/py3cairo.h +266 -0
  13. gstreamer_python/Lib/site-packages/cairo/py.typed +0 -0
  14. gstreamer_python/Lib/site-packages/gi/__init__.py +197 -0
  15. gstreamer_python/Lib/site-packages/gi/_constants.py +47 -0
  16. gstreamer_python/Lib/site-packages/gi/_error.py +55 -0
  17. gstreamer_python/Lib/site-packages/gi/_gi.cp312-win_amd64.pyd +0 -0
  18. gstreamer_python/Lib/site-packages/gi/_gi_cairo.cp312-win_amd64.pyd +0 -0
  19. gstreamer_python/Lib/site-packages/gi/_gtktemplate.py +307 -0
  20. gstreamer_python/Lib/site-packages/gi/_option.py +379 -0
  21. gstreamer_python/Lib/site-packages/gi/_ossighelper.py +275 -0
  22. gstreamer_python/Lib/site-packages/gi/_propertyhelper.py +402 -0
  23. gstreamer_python/Lib/site-packages/gi/_signalhelper.py +249 -0
  24. gstreamer_python/Lib/site-packages/gi/docstring.py +205 -0
  25. gstreamer_python/Lib/site-packages/gi/events.py +674 -0
  26. gstreamer_python/Lib/site-packages/gi/importer.py +153 -0
  27. gstreamer_python/Lib/site-packages/gi/module.py +269 -0
  28. gstreamer_python/Lib/site-packages/gi/overrides/GES.py +94 -0
  29. gstreamer_python/Lib/site-packages/gi/overrides/GIMarshallingTests.py +72 -0
  30. gstreamer_python/Lib/site-packages/gi/overrides/GLib.py +882 -0
  31. gstreamer_python/Lib/site-packages/gi/overrides/GObject.py +692 -0
  32. gstreamer_python/Lib/site-packages/gi/overrides/Gdk.py +444 -0
  33. gstreamer_python/Lib/site-packages/gi/overrides/GdkPixbuf.py +53 -0
  34. gstreamer_python/Lib/site-packages/gi/overrides/Gio.py +655 -0
  35. gstreamer_python/Lib/site-packages/gi/overrides/Gst.py +1273 -0
  36. gstreamer_python/Lib/site-packages/gi/overrides/GstAnalytics.py +106 -0
  37. gstreamer_python/Lib/site-packages/gi/overrides/GstApp.py +50 -0
  38. gstreamer_python/Lib/site-packages/gi/overrides/GstAudio.py +18 -0
  39. gstreamer_python/Lib/site-packages/gi/overrides/GstPbutils.py +99 -0
  40. gstreamer_python/Lib/site-packages/gi/overrides/GstVideo.py +17 -0
  41. gstreamer_python/Lib/site-packages/gi/overrides/Gtk.py +1707 -0
  42. gstreamer_python/Lib/site-packages/gi/overrides/Pango.py +58 -0
  43. gstreamer_python/Lib/site-packages/gi/overrides/__init__.py +357 -0
  44. gstreamer_python/Lib/site-packages/gi/overrides/_gi_gst.cp312-win_amd64.pyd +0 -0
  45. gstreamer_python/Lib/site-packages/gi/overrides/_gi_gst_analytics.cp312-win_amd64.pyd +0 -0
  46. gstreamer_python/Lib/site-packages/gi/overrides/keysyms.py +53 -0
  47. gstreamer_python/Lib/site-packages/gi/pygtkcompat.py +26 -0
  48. gstreamer_python/Lib/site-packages/gi/repository/__init__.py +28 -0
  49. gstreamer_python/Lib/site-packages/gi/types.py +350 -0
  50. gstreamer_python/Lib/site-packages/pycairo-1.27.0.dist-info/METADATA +9 -0
  51. gstreamer_python/__init__.py +32 -0
  52. gstreamer_python-1.27.90.dist-info/METADATA +26 -0
  53. gstreamer_python-1.27.90.dist-info/RECORD +55 -0
  54. gstreamer_python-1.27.90.dist-info/WHEEL +5 -0
  55. gstreamer_python-1.27.90.dist-info/top_level.txt +1 -0
@@ -0,0 +1,674 @@
1
+ # -*- Mode: Python; py-indent-offset: 4 -*-
2
+ # pygobject - Python bindings for the GObject library
3
+ # Copyright (C) 2021 Benjamin Berg <bberg@redhat.com
4
+ # Copyright (C) 2019 James Henstridge <james@jamesh.id.au>
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__ = ['GLibEventLoopPolicy', 'GLibEventLoop']
22
+
23
+ import sys
24
+ import asyncio
25
+ from asyncio import coroutines
26
+ import signal
27
+ import threading
28
+ import selectors
29
+ import weakref
30
+ import warnings
31
+ from collections.abc import Mapping
32
+ from contextlib import contextmanager
33
+ from . import _ossighelper
34
+
35
+ from gi.repository import GLib
36
+
37
+ try:
38
+ g_main_loop_run = super(GLib.MainLoop, GLib.MainLoop).run
39
+ except AttributeError:
40
+ g_main_loop_run = GLib.MainLoop.run
41
+
42
+
43
+ class _GLibEventLoopMixin:
44
+ """
45
+ Base functionally required for both proactor and selector.
46
+
47
+ The proactor/selector is always available through _selector, and we assume
48
+ it has the following extra functionality that we provide:
49
+ * _source: the GSource subclass
50
+ * _dispatching: boolean whether it is dispatching currently
51
+ * attach/detach: add/remove the GSource from the main context
52
+
53
+ In principle, we simply override run_forever to call into GLib, with the
54
+ assumption that a GSource is registered which will then call back into
55
+ the python mainloop _run_once handler when needed. This in turn calls
56
+ self._selector.select(), which means we just need to make sure to return
57
+ our already prepared events at that point.
58
+ """
59
+
60
+ def __init__(self, main_context):
61
+ # A mainloop in case we want to run our context
62
+ assert main_context is not None
63
+ self._context = main_context
64
+ self._main_loop = GLib.MainLoop.new(self._context, False)
65
+ self._quit_funcs = []
66
+
67
+ @contextmanager
68
+ def paused(self):
69
+ """This context manager ensures the EventLoop is *not* being iterated.
70
+
71
+ It purely exist to handle the case where python code iterates the main
72
+ context more gracefully."""
73
+ # Nothing to do if we are not running or dispatched by ourselves
74
+ if not self.is_running() or self._selector._source._dispatching:
75
+ yield
76
+ return
77
+
78
+ try:
79
+ self._selector.detach()
80
+ yield
81
+ finally:
82
+ self._selector.attach()
83
+
84
+ @contextmanager
85
+ def running(self, quit_func):
86
+ """This context manager ensures the EventLoop is marked as running
87
+ while other API is iterating its main context.
88
+ The passed quit function is used to stop all recursion levels when
89
+ stop() is called.
90
+ """
91
+ assert self._context.acquire()
92
+
93
+ self._quit_funcs.append(quit_func)
94
+ # Nested main context iteration (by using glib API)
95
+ if self.is_running():
96
+ try:
97
+ yield
98
+ finally:
99
+ self._context.release()
100
+ self._quit_funcs.pop()
101
+ # Stop recursively
102
+ if self._stopping:
103
+ self._quit_funcs[-1]()
104
+ return
105
+
106
+ # Outermost nesting
107
+ self._check_closed()
108
+ self._set_coroutine_origin_tracking(self._debug)
109
+ self._thread_id = threading.get_ident()
110
+
111
+ old_agen_hooks = sys.get_asyncgen_hooks()
112
+ sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
113
+ finalizer=self._asyncgen_finalizer_hook)
114
+ try:
115
+ asyncio._set_running_loop(self)
116
+ assert not self._selector._source._dispatching
117
+ self._selector.attach()
118
+ yield
119
+ finally:
120
+ self._selector.detach()
121
+ self._context.release()
122
+ self._thread_id = None
123
+ asyncio._set_running_loop(None)
124
+ try:
125
+ self._set_coroutine_origin_tracking(False)
126
+ except AttributeError:
127
+ pass
128
+ sys.set_asyncgen_hooks(*old_agen_hooks)
129
+
130
+ self._quit_funcs.pop()
131
+ assert len(self._quit_funcs) == 0
132
+ self._stopping = False
133
+
134
+ def time(self):
135
+ return GLib.get_monotonic_time() / 1000000
136
+
137
+ def _get_timeout_ms(self):
138
+ if not self.is_running():
139
+ warnings.warn('GLibEventLoop is iterated without being marked as running. Missing override or invalid use of existing API!', RuntimeWarning)
140
+ if self._stopping is True:
141
+ warnings.warn('GLibEventLoop is not stopping properly. Missing override or invalid use of existing API!', RuntimeWarning)
142
+ if self._ready:
143
+ return 0
144
+
145
+ if self._scheduled:
146
+ # The time is floor'ed here.
147
+ # Python dispatches everything ready within the next _clock_resolution.
148
+ timeout = int((self._scheduled[0]._when - self.time()) * 1000)
149
+ return timeout if timeout >= 0 else 0
150
+
151
+ return -1
152
+
153
+ def stop(self):
154
+ # Simply quit the mainloop
155
+ self._stopping = True
156
+ if self._quit_funcs:
157
+ self._quit_funcs[-1]()
158
+
159
+ def __repr__(self):
160
+ return (
161
+ f'<{self.__class__.__name__} running={self.is_running()} '
162
+ f'closed={self.is_closed()} debug={self.get_debug()} '
163
+ f'ctx=0x{hash(self._context):X} loop=0x{hash(self._main_loop):X}>'
164
+ )
165
+
166
+
167
+ class _GLibEventLoopRunMixin:
168
+ # This class exists so we don't need to copy the ProactorEventLoop.run_forever,
169
+ # instead, we change the MRO using a metaclass, so that super() sees this class
170
+ # when called in ProactorEventLoop.run_forever.
171
+
172
+ def run_forever(self):
173
+ # NOTE: self._check_running was only added in 3.8 (with a typo in 3.7)
174
+ if self.is_running():
175
+ raise RuntimeError('This event loop is already running')
176
+
177
+ with _ossighelper.register_sigint_fallback(self._main_loop.quit):
178
+ with self.running(self._main_loop.quit):
179
+ g_main_loop_run(self._main_loop)
180
+
181
+
182
+ class _SourceBase(GLib.Source):
183
+ """Common Source functionality for both unix and win32"""
184
+ def __init__(self, selector):
185
+ super().__init__()
186
+
187
+ self._dispatching = False
188
+
189
+ # It is *not* safe to run the *python* part of the mainloop recursively.
190
+ # This error must be caught further up in the chain, otherwise the
191
+ # mainloop will be blocking without an obvious reason.
192
+ self.set_can_recurse(False)
193
+ self.set_name('python asyncio integration')
194
+
195
+ self._selector = selector
196
+ # NOTE: Avoid loop -> selector -> source -> loop reference cycle,
197
+ # we need the source to be destroyed *after* the selector. Otherwise
198
+ # we need a flag to deal with FDs being unregistered after __del__ has
199
+ # been called on the source.
200
+ self._loop = weakref.ref(selector._loop)
201
+
202
+ self._ready = []
203
+
204
+ def dispatch(self, callback, args):
205
+ # Now, wag the dog by its tail
206
+ self._dispatching = True
207
+ try:
208
+ self._loop()._run_once()
209
+ finally:
210
+ self._dispatching = False
211
+
212
+ return GLib.SOURCE_CONTINUE
213
+
214
+ def _get_ready(self):
215
+ if not self._dispatching:
216
+ raise RuntimeError("gi.asyncio.Selector.select only works while it is dispatching!")
217
+
218
+ ready = self._ready
219
+ self._ready = []
220
+ return ready
221
+
222
+
223
+ class _SelectorMixin:
224
+ """A Mixin for common functionality of the Selector and Proactor."""
225
+
226
+ def __init__(self, context, loop):
227
+ super().__init__()
228
+
229
+ self._context = context
230
+ self._loop = loop
231
+ self._fd_to_key = {}
232
+
233
+ self._source = _Source(self)
234
+
235
+ def close(self):
236
+ if self._source:
237
+ self._source.destroy()
238
+ self._source = None
239
+ super().close()
240
+
241
+ def select(self, timeout=None):
242
+ return self._source._get_ready()
243
+
244
+ def _real_select(self, timeout=None):
245
+ return super().select(timeout)
246
+
247
+
248
+ if sys.platform != 'win32':
249
+ class GLibEventLoop(_GLibEventLoopMixin, _GLibEventLoopRunMixin, asyncio.SelectorEventLoop):
250
+ """An asyncio event loop that runs the python mainloop inside GLib.
251
+
252
+ Based on the asyncio.SelectorEventLoop"""
253
+
254
+ _GLIB_SIGNALS = {signal.SIGHUP, signal.SIGINT, signal.SIGTERM, signal.SIGUSR1, signal.SIGUSR2, signal.SIGWINCH}
255
+
256
+ # This is based on the selector event loop, but never actually runs select()
257
+ # in the strict sense.
258
+ # We use the selector to register all FDs with the main context using our
259
+ # own GSource. For python timeouts/idle equivalent, we directly query them
260
+ # from the context by providing the _get_timeout_ms function that the
261
+ # GSource uses. This in turn accesses _ready and _scheduled to calculate
262
+ # the timeout and whether python can dispatch anything non-FD based yet.
263
+ #
264
+ # The Selector select() method simply returns the information we already
265
+ # collected.
266
+ #
267
+ # The rest is done by the mixin which overrides run_forever to simply
268
+ # iterate the main context.
269
+ def __init__(self, main_context):
270
+ _GLibEventLoopMixin.__init__(self, main_context)
271
+
272
+ # _UnixSelectorEventLoop uses _signal_handlers, we could do the same,
273
+ # with the difference that close() would clean up the handlers for us.
274
+ self.__signal_handlers = {}
275
+
276
+ selector = _Selector(self._context, self)
277
+ asyncio.SelectorEventLoop.__init__(self, selector)
278
+
279
+ # Used by run_once to not busy loop if the timeout is floor'ed to zero
280
+ self._clock_resolution = 1e-3
281
+
282
+ def add_signal_handler(self, sig, callback, *args):
283
+ """Add a handler for UNIX signal"""
284
+
285
+ if (coroutines.iscoroutine(callback) or
286
+ coroutines.iscoroutinefunction(callback)):
287
+ raise TypeError("coroutines cannot be used "
288
+ "with add_signal_handler()")
289
+ self._check_closed()
290
+
291
+ # Can be useful while testing failures
292
+ # assert sig != signal.SIGALRM
293
+
294
+ if sig not in self._GLIB_SIGNALS:
295
+ return super().add_signal_handler(sig, callback, *args)
296
+
297
+ # Pure python demands that there is only one signal handler
298
+ source, _, _ = self.__signal_handlers.get(sig, (None, None, None))
299
+ if source:
300
+ source.destroy()
301
+
302
+ # Setup a new source with a higher priority than our main one
303
+ source = GLib.unix_signal_source_new(sig)
304
+ source.set_name(f"asyncio signal watch for {sig}")
305
+ source.set_priority(GLib.PRIORITY_HIGH)
306
+ source.attach(self._context)
307
+ source.set_callback(self._signal_cb, sig)
308
+
309
+ self.__signal_handlers[sig] = (source, callback, args)
310
+ del source
311
+
312
+ def remove_signal_handler(self, sig):
313
+ if sig not in self._GLIB_SIGNALS:
314
+ return super().remove_signal_handler(sig)
315
+
316
+ try:
317
+ source, _, _ = self.__signal_handlers[sig]
318
+ del self.__signal_handlers[sig]
319
+ # Really unref the underlying GSource so that GLib resets the signal handler
320
+ source.destroy()
321
+ source._clear_boxed()
322
+
323
+ # GLib does not restore the original signal handler.
324
+ # Try to restore the python handler for SIGINT, this makes
325
+ # Ctrl+C work after the mainloop has quit.
326
+ if sig == signal.SIGINT and _ossighelper.PyOS_getsig(signal.SIGINT) == 0:
327
+ if _ossighelper.startup_sigint_ptr > 0:
328
+ _ossighelper.PyOS_setsig(signal.SIGINT, _ossighelper.startup_sigint_ptr)
329
+
330
+ return True
331
+ except KeyError:
332
+ return False
333
+
334
+ def _signal_cb(self, sig):
335
+ source, cb, args = self.__signal_handlers.get(sig)
336
+
337
+ # Pass over to python mainloop
338
+ self.call_soon(cb, *args)
339
+
340
+ def close(self):
341
+ super().close()
342
+ for s in list(self.__signal_handlers):
343
+ self.remove_signal_handler(s)
344
+
345
+ def _fileobj_to_fd(fileobj):
346
+ # Note: SelectorEventloop should only be passing FDs
347
+ if isinstance(fileobj, int):
348
+ return fileobj
349
+ else:
350
+ return fileobj.fileno()
351
+
352
+ class _Source(_SourceBase):
353
+ def prepare(self):
354
+ timeout = self._loop()._get_timeout_ms()
355
+
356
+ # NOTE: Always return False, FDs are queried in check and the timeout
357
+ # needs to be rechecked anyway.
358
+ return False, timeout
359
+
360
+ def check(self):
361
+ ready = []
362
+
363
+ for key in self._selector._fd_to_key.values():
364
+ condition = self.query_unix_fd(key._tag)
365
+ events = 0
366
+ # ERR/HUP/NVAL trigger both read/write (PRI cannot happen)
367
+ if condition & ~GLib.IOCondition.OUT:
368
+ events |= selectors.EVENT_READ
369
+ if condition & ~GLib.IOCondition.IN:
370
+ events |= selectors.EVENT_WRITE
371
+ if events:
372
+ ready.append((key, events))
373
+ self._ready = ready
374
+
375
+ timeout = self._loop()._get_timeout_ms()
376
+ if timeout == 0:
377
+ return True
378
+
379
+ return bool(ready)
380
+
381
+ class _SelectorKey(selectors.SelectorKey):
382
+ # Subclass to attach _tag
383
+ pass
384
+
385
+ class _FileObjectMapping(Mapping):
386
+ def __init__(self, fd_dict):
387
+ self.fd_dict = fd_dict
388
+
389
+ def __len__(self):
390
+ return len(self.fd_dict)
391
+
392
+ def get(self, fileobj, default=None):
393
+ fd = _fileobj_to_fd(fileobj)
394
+ return self.fd_dict.get(fd, default)
395
+
396
+ def __getitem__(self, fileobj):
397
+ value = self.get(fileobj)
398
+ if value is None:
399
+ raise KeyError("{!r} is not registered".format(fileobj))
400
+ return value
401
+
402
+ def __iter__(self):
403
+ return iter(self.fd_dict)
404
+
405
+ class _Selector(_SelectorMixin, selectors.BaseSelector):
406
+ """A Selector for gi.events.GLibEventLoop registering python IO with GLib."""
407
+
408
+ def __init__(self, context, loop):
409
+ super().__init__(context, loop)
410
+ self._map = _FileObjectMapping(self._fd_to_key)
411
+
412
+ def attach(self):
413
+ self._source.attach(self._loop._context)
414
+
415
+ def detach(self):
416
+ self._source.destroy()
417
+ self._source = _Source(self)
418
+ # re-register the keys with the new source
419
+ for key in self._fd_to_key.values():
420
+ self._register_key(key)
421
+
422
+ def _register_key(self, key):
423
+ condition = GLib.IOCondition(0)
424
+ if key.events & selectors.EVENT_READ:
425
+ condition |= GLib.IOCondition.IN
426
+ if key.events & selectors.EVENT_WRITE:
427
+ condition |= GLib.IOCondition.OUT
428
+ key._tag = self._source.add_unix_fd(key.fd, condition)
429
+
430
+ def register(self, fileobj, events, data=None):
431
+ if (not events) or (events & ~(selectors.EVENT_READ | selectors.EVENT_WRITE)):
432
+ raise ValueError("Invalid events: {!r}".format(events))
433
+
434
+ fd = _fileobj_to_fd(fileobj)
435
+ if fd in self._fd_to_key:
436
+ raise KeyError("{!r} (FD {}) is already registered"
437
+ .format(fileobj, fd))
438
+
439
+ key = _SelectorKey(fileobj, fd, events, data)
440
+
441
+ self._register_key(key)
442
+
443
+ self._fd_to_key[fd] = key
444
+ return key
445
+
446
+ def unregister(self, fileobj):
447
+ # NOTE: may be called after __del__ has been called.
448
+ fd = _fileobj_to_fd(fileobj)
449
+ key = self._fd_to_key[fd]
450
+
451
+ if self._source:
452
+ self._source.remove_unix_fd(key._tag)
453
+ del self._fd_to_key[fd]
454
+
455
+ return key
456
+
457
+ # We could override modify, but it is only slightly when the "events" change.
458
+
459
+ def get_key(self, fileobj):
460
+ return self._map[fileobj]
461
+
462
+ def get_map(self):
463
+ """Return a mapping of file objects or file descriptors to
464
+ selector keys."""
465
+ return self._map
466
+
467
+
468
+ else:
469
+ class _PushRunMixinBackMeta(type):
470
+ # This metaclass changes the MRO so that when run_forever is called, it
471
+ # first calls asyncio.ProactorEventLoop and then chains into
472
+ # _GLibEventLoopRunMixin.run_forever using super().
473
+ # The alternative would be to copy asyncio.ProactorEventLoop.run_forever
474
+ def mro(cls):
475
+ mro = type.mro(cls)
476
+ idx = mro.index(_GLibEventLoopRunMixin)
477
+
478
+ return [*mro[:idx], mro[idx + 1], mro[idx], *mro[idx + 2:]]
479
+
480
+ class GLibEventLoop(_GLibEventLoopMixin, _GLibEventLoopRunMixin, asyncio.ProactorEventLoop, metaclass=_PushRunMixinBackMeta):
481
+ """An asyncio event loop that runs the python mainloop inside GLib.
482
+
483
+ Based on the asyncio.WindowsProactorEventLoopPolicy"""
484
+
485
+ # This is based on the Windows ProactorEventLoop
486
+ def __init__(self, main_context):
487
+ _GLibEventLoopMixin.__init__(self, main_context)
488
+
489
+ proactor = _Proactor(self._context, self)
490
+ # Sets both self._proactor and self._selector to the proactor
491
+ asyncio.ProactorEventLoop.__init__(self, proactor)
492
+
493
+ # Used by run_once to not busy loop if the timeout is floor'ed to zero
494
+ self._clock_resolution = 1e-3
495
+
496
+ class _Source(_SourceBase):
497
+ def __init__(self, proactor):
498
+ self._proactor = proactor
499
+ super().__init__(proactor)
500
+
501
+ # None denotes it is disabled (and will also not handle timeouts)
502
+ self._poll_fd = None
503
+
504
+ def enable(self):
505
+ assert self._poll_fd is None
506
+
507
+ self._poll_fd = GLib.PollFD(self._proactor._iocp, GLib.IO_IN)
508
+ self.add_poll(self._poll_fd)
509
+
510
+ def disable(self):
511
+ self.remove_poll(self._poll_fd)
512
+ self._poll_fd = None
513
+
514
+ def prepare(self):
515
+ # Disabled, do not handle timeouts either
516
+ if self._poll_fd is None:
517
+ return False, -1
518
+
519
+ timeout = self._loop()._get_timeout_ms()
520
+
521
+ return bool(self._ready), timeout
522
+
523
+ def check(self):
524
+ if self._poll_fd is None:
525
+ return False
526
+
527
+ if self._poll_fd.revents:
528
+ self._ready.extend(self._proactor._real_select(0))
529
+
530
+ if self._ready:
531
+ return True
532
+
533
+ if self._loop()._get_timeout_ms() == 0:
534
+ return True
535
+
536
+ return False
537
+
538
+ class _Proactor(_SelectorMixin, asyncio.IocpProactor):
539
+ """A Proactor for gi.events.GLibEventLoop registering python IO with GLib."""
540
+
541
+ def __init__(self, context, loop):
542
+ super().__init__(context, loop)
543
+
544
+ # We always use the same Source on windows, it disables itself
545
+ self._source = _Source(self)
546
+ self._source.attach(context)
547
+
548
+ def attach(self):
549
+ self._source.enable()
550
+
551
+ def detach(self):
552
+ self._source.disable()
553
+
554
+
555
+ class GLibEventLoopPolicy(asyncio.AbstractEventLoopPolicy):
556
+ """An asyncio event loop policy that runs the GLib main loop.
557
+
558
+ The policy allows creating a new EventLoop for threads other than the main
559
+ thread. For the main thread, you can use get_event_loop() to retrieve the
560
+ correct mainloop and run it.
561
+
562
+ Note that, unlike GLib, python does not support running the EventLoop
563
+ recursively. You should never iterate the GLib.MainContext from within
564
+ the python EventLoop as doing so prevents asyncio events from being
565
+ dispatched.
566
+
567
+ As such, do not use API such as GLib.MainLoop.run or Gtk.Dialog.run.
568
+ Instead use the proper asynchronous patterns to prevent entirely blocking
569
+ asyncio.
570
+ """
571
+
572
+ def __init__(self):
573
+ self._loops = {}
574
+ self._child_watcher = None
575
+
576
+ def get_event_loop(self):
577
+ """Get the event loop for the current context.
578
+
579
+ Returns an event loop object for the thread default GLib.MainContext
580
+ or in case of the main thread for the default GLib.MainContext.
581
+
582
+ An exception will be thrown if there is no GLib.MainContext for the
583
+ current thread. In that case, using new_event_loop() will create a new
584
+ main context and main loop which can subsequently attached to the thread
585
+ by calling set_event_loop().
586
+
587
+ Returns a new GLibEventLoop or raises an exception."""
588
+
589
+ # Get the thread default main context
590
+ ctx = GLib.MainContext.get_thread_default()
591
+ # If there is none, and we are on the main thread, then use the default context
592
+ if ctx is None and threading.current_thread() is threading.main_thread():
593
+ ctx = GLib.MainContext.default()
594
+
595
+ # We do not create a main context implicitly;
596
+ # we create a mainloop for an existing context though
597
+ if ctx is None:
598
+ raise RuntimeError('There is no main context set for thread %r.'
599
+ % threading.current_thread().name)
600
+
601
+ return self.get_event_loop_for_context(ctx)
602
+
603
+ def get_event_loop_for_context(self, ctx):
604
+ """Get the event loop for a specific context."""
605
+ # Note: We cannot attach it to ctx, as getting the default will always
606
+ # return a new python wrapper. But, we can use hash() as that returns
607
+ # the pointer to the C structure.
608
+ try:
609
+ loop = self._loops[hash(ctx)]
610
+ if not loop.is_closed():
611
+ return loop
612
+ except KeyError:
613
+ pass
614
+
615
+ self._loops[hash(ctx)] = GLibEventLoop(ctx)
616
+ if self._child_watcher and ctx == GLib.MainContext.default():
617
+ self._child_watcher.attach_loop(self.get_event_loop())
618
+ return self._loops[hash(ctx)]
619
+
620
+ def set_event_loop(self, loop):
621
+ """Set the event loop for the current context (python thread) to loop.
622
+
623
+ This is only permitted if the thread has no thread default main context
624
+ with the main thread using the default main context.
625
+ """
626
+
627
+ # Only accept glib event loops, otherwise things will just mess up
628
+ assert loop is None or isinstance(loop, GLibEventLoop)
629
+
630
+ ctx = ctx_td = GLib.MainContext.get_thread_default()
631
+ if ctx is None and threading.current_thread() is threading.main_thread():
632
+ ctx = GLib.MainContext.default()
633
+
634
+ if loop is None:
635
+ # We do permit unsetting the current loop/context
636
+ old = self._loops.pop(hash(ctx), None)
637
+ if old:
638
+ if hash(old._context) != hash(ctx):
639
+ warnings.warn('GMainContext was changed unknowingly by asyncio integration!', RuntimeWarning)
640
+ if ctx_td:
641
+ GLib.MainContext.pop_thread_default(ctx_td)
642
+ else:
643
+ # Only allow attaching if the thread has no main context yet
644
+ if ctx:
645
+ raise RuntimeError('Thread %r already has a main context, get_event_loop() will create a new loop if needed'
646
+ % threading.current_thread().name)
647
+
648
+ GLib.MainContext.push_thread_default(loop._context)
649
+ self._loops[hash(loop._context)] = loop
650
+
651
+ def new_event_loop(self):
652
+ """Create and return a new event loop that iterates a new
653
+ GLib.MainContext."""
654
+
655
+ return GLibEventLoop(GLib.MainContext())
656
+
657
+ # NOTE: We do *not* provide a GLib based ChildWatcher implementation!
658
+ # This is *intentional* and *required*. The issue is that python provides
659
+ # API which uses wait4() internally. GLib at the same time uses a thread to
660
+ # handle SIGCHLD signals, which causes a race condition resulting in a
661
+ # critical warning.
662
+ # We just provide a reasonable sane child watcher and disallow the user
663
+ # from choosing one as e.g. MultiLoopChildWatcher is problematic.
664
+ #
665
+ # TODO: Use PidfdChildWatcher when available
666
+ if sys.platform != 'win32':
667
+ def get_child_watcher(self):
668
+ if self._child_watcher is None:
669
+ self._child_watcher = asyncio.ThreadedChildWatcher()
670
+
671
+ if threading.current_thread() is threading.main_thread():
672
+ self._child_watcher.attach_loop(self.get_event_loop())
673
+
674
+ return self._child_watcher