Debian Codegraph @

gi/overrides/GLib.py

raw
1 # Copyright (C) 2010 Tomeu Vizoso <[email protected]>
2 # Copyright (C) 2011, 2012 Canonical Ltd.
3 #
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License, or (at your option) any later version.
8 #
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 # Lesser General Public License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
17 # USA
18
19 from __future__ import annotations
20
21 import contextlib
22 import warnings
23 import sys
24 import socket
25 import typing
26
27 from .._ossighelper import register_sigint_fallback, get_event_loop
28 from ..module import (
29 get_fallback_platform_specific_module_symbol,
30 get_platform_specific_module,
31 )
32 from .._gi import (
33 variant_type_from_string,
34 source_new,
35 source_set_callback,
36 io_channel_read,
37 main_context_query,
38 PyGIWarning,
39 )
40 from ..overrides import override, deprecated, deprecated_attr
41 from gi import PyGIDeprecationWarning, version_info
42
43 # Typing relies on https://github.com/pygobject/pygobject-stubs.
44 if typing.TYPE_CHECKING:
45 # Import stubs for type checking this file.
46 # FIXME: For IDE typing support, you need to copy
47 # pygobject-stubs/src/gi-stubs/repository/*.pyi to gi/repository/
48 from gi.repository import GLib
49 from typing_extensions import Self
50
51 # Type annotations cannot have `GLib.` prefix because they are copied into
52 # GLib stubs module which cannot refer to itself. Use type aliases.
53 IOChannel = GLib.IOChannel
54 IOCondition = GLib.IOCondition
55 PollFD = GLib.PollFD
56 else:
57 from gi.module import get_introspection_module
58
59 GLib = get_introspection_module("GLib")
60
61 __all__ = []
62
63 # Types and functions still needed from static bindings
64 from gi import _gi
65 from gi._error import GError
66
67 Error = GError
68 Pid = _gi.Pid
69 spawn_async = _gi.spawn_async
70
71
72 def threads_init():
73 warnings.warn(
74 "Since version 3.11, calling threads_init is no longer needed. "
75 "See: https://pygobject.gnome.org/guide/threading.html#threads-faq",
76 PyGIDeprecationWarning,
77 stacklevel=2,
78 )
79
80
81 def gerror_matches(self, domain: str | int, code: int) -> bool:
82 # Handle cases where self.domain was set to an integer for compatibility
83 # with the introspected GLib.Error.
84 if isinstance(self.domain, str):
85 self_domain_quark = GLib.quark_from_string(self.domain)
86 else:
87 self_domain_quark = self.domain
88 return (self_domain_quark, self.code) == (domain, code)
89
90
91 def gerror_new_literal(domain: int, message: str, code: int) -> GError:
92 domain_quark = GLib.quark_to_string(domain)
93 return GError(message, domain_quark, code)
94
95
96 # Monkey patch methods that rely on GLib introspection to be loaded at runtime.
97 Error.__name__ = "Error"
98 Error.__module__ = "gi.repository.GLib"
99 Error.__gtype__ = GLib.Error.__gtype__
100 Error.matches = gerror_matches
101 Error.new_literal = staticmethod(gerror_new_literal)
102
103
104 __all__ += [
105 "Error",
106 "GError",
107 "Pid",
108 "spawn_async",
109 "threads_init",
110 ]
111
112
113 class _VariantCreator:
114 _LEAF_CONSTRUCTORS = {
115 "b": GLib.Variant.new_boolean,
116 "y": GLib.Variant.new_byte,
117 "n": GLib.Variant.new_int16,
118 "q": GLib.Variant.new_uint16,
119 "i": GLib.Variant.new_int32,
120 "u": GLib.Variant.new_uint32,
121 "x": GLib.Variant.new_int64,
122 "t": GLib.Variant.new_uint64,
123 "h": GLib.Variant.new_handle,
124 "d": GLib.Variant.new_double,
125 "s": GLib.Variant.new_string,
126 "o": GLib.Variant.new_object_path,
127 "g": GLib.Variant.new_signature,
128 "v": GLib.Variant.new_variant,
129 }
130
131 def _create(self, format, value):
132 """Create a GVariant object from given format and a value that matches
133 the format.
134
135 This method recursively calls itself for complex structures (arrays,
136 dictionaries, boxed).
137
138 Returns the generated GVariant.
139
140 If value is None it will generate an empty GVariant container type.
141 """
142 gvtype = GLib.VariantType(format)
143 if format in self._LEAF_CONSTRUCTORS:
144 return self._LEAF_CONSTRUCTORS[format](value)
145
146 # Since we discarded all leaf types, this must be a container
147 builder = GLib.VariantBuilder.new(gvtype)
148 if value is None:
149 return builder.end()
150
151 if gvtype.is_maybe():
152 builder.add_value(self._create(gvtype.element().dup_string(), value))
153 return builder.end()
154
155 try:
156 iter(value)
157 except TypeError:
158 raise TypeError(
159 f"Could not create array, tuple or dictionary entry from non iterable value {format} {value}"
160 )
161
162 if gvtype.is_tuple() and gvtype.n_items() != len(value):
163 raise TypeError(
164 f"Tuple mismatches value's number of elements {format} {value}"
165 )
166 if gvtype.is_dict_entry() and len(value) != 2:
167 raise TypeError(
168 f"Dictionary entries must have two elements {format} {value}"
169 )
170
171 if gvtype.is_array():
172 element_type = gvtype.element().dup_string()
173 if isinstance(value, dict):
174 value = value.items()
175 for i in value:
176 builder.add_value(self._create(element_type, i))
177 else:
178 remainer_format = format[1:]
179 for i in value:
180 dup = variant_type_from_string(remainer_format).dup_string()
181 builder.add_value(self._create(dup, i))
182 remainer_format = remainer_format[len(dup) :]
183
184 return builder.end()
185
186
187 class Variant(GLib.Variant):
188 @staticmethod
189 def __new__(cls: type[Self], format_string: str, value: typing.Any) -> Self:
190 """Create a GVariant from a native Python object.
191
192 format_string is a standard GVariant type signature, value is a Python
193 object whose structure has to match the signature.
194
195 Examples:
196 GLib.Variant('i', 1)
197 GLib.Variant('(is)', (1, 'hello'))
198 GLib.Variant('(asa{sv})', ([], {'foo': GLib.Variant('b', True),
199 'bar': GLib.Variant('i', 2)}))
200
201 """
202 if not GLib.VariantType.string_is_valid(format_string):
203 raise TypeError("Invalid GVariant format string '%s'", format_string)
204 creator = _VariantCreator()
205 v = creator._create(format_string, value)
206 v.format_string = format_string
207 return v
208
209 @staticmethod
210 def new_tuple(*elements: Variant) -> Variant: # type: ignore[override]
211 return GLib.Variant.new_tuple(elements) # type: ignore[arg-type, return-value]
212
213 def __del__(self):
214 with contextlib.suppress(ImportError):
215 # Calling unref will cause gi and gi.repository.GLib to be
216 # imported. However, if the program is exiting, then these
217 # modules have likely been removed from sys.modules and will
218 # raise an exception. Assume that's the case for ImportError
219 # and ignore the exception since everything will be cleaned
220 # up, anyway.
221 self.unref()
222
223 def __str__(self) -> str:
224 return self.print_(True)
225
226 def __repr__(self) -> str:
227 if hasattr(self, "format_string"):
228 f = self.format_string
229 else:
230 f = self.get_type_string()
231 return f"GLib.Variant('{f}', {self.print_(False)})"
232
233 def __eq__(self, other: object) -> bool:
234 if not isinstance(other, Variant):
235 return False
236 try:
237 return self.equal(other)
238 except TypeError:
239 return False
240
241 def __ne__(self, other: object) -> bool:
242 if not isinstance(other, Variant):
243 return True
244 try:
245 return not self.equal(other)
246 except TypeError:
247 return True
248
249 def __hash__(self) -> int:
250 # We're not using just hash(self.unpack()) because otherwise we'll have
251 # hash collisions between the same content in different variant types,
252 # which will cause a performance issue in set/dict/etc.
253 return hash((self.get_type_string(), self.unpack()))
254
255 def unpack(self) -> typing.Any:
256 """Decompose a GVariant into a native Python object."""
257 type_string = self.get_type_string()
258
259 # simple values
260 match type_string:
261 case "b":
262 return self.get_boolean()
263 case "y":
264 return self.get_byte()
265 case "n":
266 return self.get_int16()
267 case "q":
268 return self.get_uint16()
269 case "i":
270 return self.get_int32()
271 case "u":
272 return self.get_uint32()
273 case "x":
274 return self.get_int64()
275 case "t":
276 return self.get_uint64()
277 case "h":
278 return self.get_handle()
279 case "d":
280 return self.get_double()
281 case "s":
282 return self.get_string()
283 case "o":
284 return self.get_string() # object path
285 case "g":
286 return self.get_string() # signature
287
288 # tuple
289 if type_string.startswith("("):
290 return tuple(
291 self.get_child_value(i).unpack() for i in range(self.n_children())
292 )
293
294 # dictionary
295 if type_string.startswith("a{"):
296 res: dict[bool | float | str, typing.Any] = {}
297 for i in range(self.n_children()):
298 v = self.get_child_value(i)
299 res[v.get_child_value(0).unpack()] = v.get_child_value(1).unpack()
300 return res
301
302 # array
303 if type_string.startswith("a"):
304 return [self.get_child_value(i).unpack() for i in range(self.n_children())]
305
306 # variant (just unbox transparently)
307 if type_string.startswith("v"):
308 return self.get_variant().unpack()
309
310 # maybe
311 if type_string.startswith("m"):
312 if not self.n_children():
313 return None
314 return self.get_child_value(0).unpack()
315
316 raise NotImplementedError("unsupported GVariant type " + type_string)
317
318 @classmethod
319 def split_signature(klass, signature):
320 """Return a list of the element signatures of the topmost signature tuple.
321
322 If the signature is not a tuple, it returns one element with the entire
323 signature. If the signature is an empty tuple, the result is [].
324
325 This is useful for e. g. iterating over method parameters which are
326 passed as a single Variant.
327 """
328 if signature == "()":
329 return []
330
331 if not signature.startswith("("):
332 return [signature]
333
334 result = []
335 head = ""
336 tail = signature[1:-1] # eat the surrounding ()
337 while tail:
338 c = tail[0]
339 head += c
340 tail = tail[1:]
341
342 if c in ("m", "a"):
343 # prefixes, keep collecting
344 continue
345 if c in ("(", "{"):
346 # consume until corresponding )/}
347 level = 1
348 up = c
349 down = ")" if up == "(" else "}"
350 while level > 0:
351 c = tail[0]
352 head += c
353 tail = tail[1:]
354 if c == up:
355 level += 1
356 elif c == down:
357 level -= 1
358
359 # otherwise we have a simple type
360 result.append(head)
361 head = ""
362
363 return result
364
365 #
366 # Pythonic iterators
367 #
368
369 def __len__(self) -> int:
370 if self.get_type_string() in ["s", "o", "g"]:
371 return len(self.get_string())
372 # Array, dict, tuple
373 if self.get_type_string().startswith("a") or self.get_type_string().startswith(
374 "("
375 ):
376 return self.n_children()
377 raise TypeError(
378 f"GVariant type {self.get_type_string()} does not have a length"
379 )
380
381 def __getitem__(self, key: str | int) -> typing.Any:
382 # dict
383 if self.get_type_string().startswith("a{"):
384 if isinstance(key, str):
385 val = self.lookup_value(key, variant_type_from_string("*"))
386 if val is None:
387 raise KeyError(key)
388 return val.unpack()
389 # lookup_value() only works for string keys, which is certainly
390 # the common case; we have to do painful iteration for other
391 # key types
392 for i in range(self.n_children()):
393 v = self.get_child_value(i)
394 if v.get_child_value(0).unpack() == key:
395 return v.get_child_value(1).unpack()
396 raise KeyError(key)
397
398 if not isinstance(key, int):
399 raise ValueError("Key must be an integer for arrays, tuples and strings")
400
401 # array/tuple
402 if self.get_type_string().startswith("a") or self.get_type_string().startswith(
403 "("
404 ):
405 if key < 0:
406 key = self.n_children() + key
407 if key < 0 or key >= self.n_children():
408 raise IndexError("list index out of range")
409 return self.get_child_value(key).unpack()
410
411 # string
412 if self.get_type_string() in ["s", "o", "g"]:
413 return self.get_string().__getitem__(key)
414
415 raise TypeError(f"GVariant type {self.get_type_string()} is not a container")
416
417 #
418 # Pythonic bool operations
419 #
420
421 def __nonzero__(self):
422 return self.__bool__()
423
424 def __bool__(self) -> bool:
425 if self.get_type_string() in ["y", "n", "q", "i", "u", "x", "t", "h", "d"]:
426 return self.unpack() != 0
427 if self.get_type_string() in ["b"]:
428 return self.get_boolean()
429 if self.get_type_string() in ["s", "o", "g"]:
430 return len(self.get_string()) != 0
431 # Array, dict, tuple
432 if self.get_type_string().startswith("a") or self.get_type_string().startswith(
433 "("
434 ):
435 return self.n_children() != 0
436 # unpack works recursively, hence bool also works recursively
437 return bool(self.unpack())
438
439 def keys(self) -> typing.Iterable[bool | float | str]:
440 if not self.get_type_string().startswith("a{"):
441 raise TypeError(
442 f"GVariant type {self.get_type_string()} is not a dictionary"
443 )
444
445 res = []
446 for i in range(self.n_children()):
447 v = self.get_child_value(i)
448 res.append(v.get_child_value(0).unpack())
449 return res
450
451 def get_string(self) -> str:
452 value: str
453 value, _length = super().get_string() # type: ignore[misc]
454 return value
455
456
457 __all__.append("Variant")
458
459
460 def markup_escape_text(text: str | bytes, length: int = -1) -> str:
461 if isinstance(text, bytes):
462 return GLib.markup_escape_text(text.decode("UTF-8"), length)
463 return GLib.markup_escape_text(text, length)
464
465
466 __all__.append("markup_escape_text")
467
468
469 # backwards compatible names from old static bindings
470 for n in [
471 "DESKTOP",
472 "DOCUMENTS",
473 "DOWNLOAD",
474 "MUSIC",
475 "PICTURES",
476 "PUBLIC_SHARE",
477 "TEMPLATES",
478 "VIDEOS",
479 ]:
480 attr = "USER_DIRECTORY_" + n
481 deprecated_attr("GLib", attr, "GLib.UserDirectory.DIRECTORY_" + n)
482 globals()[attr] = getattr(GLib.UserDirectory, "DIRECTORY_" + n)
483 __all__.append(attr)
484
485 for n in ["ERR", "HUP", "IN", "NVAL", "OUT", "PRI"]:
486 globals()["IO_" + n] = getattr(GLib.IOCondition, n)
487 __all__.append("IO_" + n)
488
489 for n in [
490 "APPEND",
491 "GET_MASK",
492 "IS_READABLE",
493 "IS_SEEKABLE",
494 "MASK",
495 "NONBLOCK",
496 "SET_MASK",
497 ]:
498 attr = "IO_FLAG_" + n
499 deprecated_attr("GLib", attr, "GLib.IOFlags." + n)
500 globals()[attr] = getattr(GLib.IOFlags, n)
501 __all__.append(attr)
502
503 # spelling for the win
504 IO_FLAG_IS_WRITEABLE = GLib.IOFlags.IS_WRITABLE
505 deprecated_attr("GLib", "IO_FLAG_IS_WRITEABLE", "GLib.IOFlags.IS_WRITABLE")
506 __all__.append("IO_FLAG_IS_WRITEABLE")
507
508 for n in ["AGAIN", "EOF", "ERROR", "NORMAL"]:
509 attr = "IO_STATUS_" + n
510 globals()[attr] = getattr(GLib.IOStatus, n)
511 deprecated_attr("GLib", attr, "GLib.IOStatus." + n)
512 __all__.append(attr)
513
514 for n in [
515 "CHILD_INHERITS_STDIN",
516 "DO_NOT_REAP_CHILD",
517 "FILE_AND_ARGV_ZERO",
518 "LEAVE_DESCRIPTORS_OPEN",
519 "SEARCH_PATH",
520 "STDERR_TO_DEV_NULL",
521 "STDOUT_TO_DEV_NULL",
522 ]:
523 attr = "SPAWN_" + n
524 globals()[attr] = getattr(GLib.SpawnFlags, n)
525 deprecated_attr("GLib", attr, "GLib.SpawnFlags." + n)
526 __all__.append(attr)
527
528 for n in [
529 "HIDDEN",
530 "IN_MAIN",
531 "REVERSE",
532 "NO_ARG",
533 "FILENAME",
534 "OPTIONAL_ARG",
535 "NOALIAS",
536 ]:
537 attr = "OPTION_FLAG_" + n
538 globals()[attr] = getattr(GLib.OptionFlags, n)
539 deprecated_attr("GLib", attr, "GLib.OptionFlags." + n)
540 __all__.append(attr)
541
542 for n in ["UNKNOWN_OPTION", "BAD_VALUE", "FAILED"]:
543 attr = "OPTION_ERROR_" + n
544 deprecated_attr("GLib", attr, "GLib.OptionError." + n)
545 globals()[attr] = getattr(GLib.OptionError, n)
546 __all__.append(attr)
547
548
549 # these are not currently exported in GLib gir, presumably because they are
550 # platform dependent; so get them from our static bindings
551 for name in [
552 "G_MINFLOAT",
553 "G_MAXFLOAT",
554 "G_MINDOUBLE",
555 "G_MAXDOUBLE",
556 "G_MINSHORT",
557 "G_MAXSHORT",
558 "G_MAXUSHORT",
559 "G_MININT",
560 "G_MAXINT",
561 "G_MAXUINT",
562 "G_MINLONG",
563 "G_MAXLONG",
564 "G_MAXULONG",
565 "G_MAXSIZE",
566 "G_MINSSIZE",
567 "G_MAXSSIZE",
568 "G_MINOFFSET",
569 "G_MAXOFFSET",
570 ]:
571 attr = name.split("_", 1)[-1]
572 globals()[attr] = getattr(_gi, name)
573 __all__.append(attr)
574
575
576 class MainLoop(GLib.MainLoop):
577 @staticmethod
578 def __new__(cls: type[Self], context: MainContext | None = None) -> Self:
579 return GLib.MainLoop.new(context, False) # type: ignore[return-value]
580
581 def run(self) -> None:
582 with (
583 register_sigint_fallback(self.quit),
584 get_event_loop(self.get_context()).running(self.quit),
585 ):
586 super().run()
587
588
589 MainLoop = override(MainLoop)
590 __all__.append("MainLoop")
591
592
593 class MainContext(GLib.MainContext):
594 # Backwards compatible API with default value
595 def iteration(self, may_block: bool = True) -> bool:
596 with get_event_loop(self).paused():
597 return super().iteration(may_block)
598
599 def query(self, max_priority: int) -> tuple[int, list[PollFD]]:
600 """Determines information necessary to poll this main loop.
601
602 :param max_priority: maximum priority source to check
603 :returns:
604 The timeout (msec) used for polling,
605 and the list of poll fd's.
606
607 Please also check the usage notes in the
608 `C documention <https://docs.gtk.org/glib/method.MainContext.query.html>`__.
609 """
610 return main_context_query(self, max_priority)
611
612
613 MainContext = override(MainContext)
614 __all__.append("MainContext")
615
616
617 class Source(GLib.Source):
618 # *args, **kwargs are kept for backwards compatibility.
619 # See https://gitlab.gnome.org/GNOME/pygobject/-/merge_requests/506#note_2652436.
620 @staticmethod
621 def __new__(cls: type[Self], *args, **kwargs) -> Self:
622 # use our custom pygi_source_new() here as g_source_new() is not
623 # bindable
624 source = source_new()
625 source.__class__ = cls
626 setattr(source, "__pygi_custom_source", True)
627 return source
628
629 def __del__(self) -> None:
630 if hasattr(self, "__pygi_custom_source"):
631 # We destroy and finalize the box from here, as GLib might hold
632 # a reference (e.g. while the source is pending), delaying the
633 # finalize call until a later point.
634 self.destroy()
635 self.finalize()
636 self._clear_boxed()
637
638 def finalize(self) -> None:
639 pass
640
641 def set_callback(
642 self, func: typing.Callable[..., bool], *user_data: typing.Any
643 ) -> None:
644 if hasattr(self, "__pygi_custom_source"):
645 # use our custom pygi_source_set_callback() if for a GSource object
646 # with custom functions
647 source_set_callback(self, func, *user_data)
648 else:
649 # otherwise, for Idle and Timeout, use the standard method
650 super().set_callback(func, *user_data)
651
652 def get_current_time(self) -> float:
653 return GLib.get_real_time() * 0.000001
654
655 get_current_time = deprecated(
656 get_current_time, "GLib.Source.get_time() or GLib.get_real_time()"
657 )
658
659 # as get/set_priority are introspected, we can't use the static
660 # property(get_priority, ..) here
661 def __get_priority(self) -> int:
662 return self.get_priority()
663
664 def __set_priority(self, value: int) -> None:
665 self.set_priority(value)
666
667 priority = property(__get_priority, __set_priority)
668
669 def __get_can_recurse(self) -> bool:
670 return self.get_can_recurse()
671
672 def __set_can_recurse(self, value: bool) -> None:
673 self.set_can_recurse(value)
674
675 can_recurse = property(__get_can_recurse, __set_can_recurse)
676
677
678 Source = override(Source)
679 __all__.append("Source")
680
681
682 class Idle(Source):
683 @staticmethod
684 def __new__(cls: type[Self], priority: int = GLib.PRIORITY_DEFAULT) -> Self:
685 source = GLib.idle_source_new()
686 source.__class__ = cls
687 return source # type: ignore[return-value]
688
689 def __init__(self, priority: int = GLib.PRIORITY_DEFAULT) -> None:
690 if priority != GLib.PRIORITY_DEFAULT:
691 self.set_priority(priority)
692
693
694 __all__.append("Idle")
695
696
697 class Timeout(Source):
698 @staticmethod
699 def __new__(
700 cls: type[Self], interval: int = 0, priority: int = GLib.PRIORITY_DEFAULT
701 ) -> Self:
702 source = GLib.timeout_source_new(interval)
703 source.__class__ = cls
704 return source # type: ignore[return-value]
705
706 def __init__(
707 self, interval: int = 0, priority: int = GLib.PRIORITY_DEFAULT
708 ) -> None:
709 if priority != GLib.PRIORITY_DEFAULT:
710 self.set_priority(priority)
711
712
713 __all__.append("Timeout")
714
715
716 # backwards compatible API
717 def idle_add(
718 function: typing.Callable[..., bool | None],
719 *user_data: typing.Any,
720 priority: int = GLib.PRIORITY_DEFAULT_IDLE,
721 ) -> int:
722 return GLib.idle_add(priority, function, *user_data)
723
724
725 __all__.append("idle_add")
726
727
728 def timeout_add(
729 interval: int,
730 function: typing.Callable[..., bool | None],
731 *user_data: typing.Any,
732 priority: int = GLib.PRIORITY_DEFAULT,
733 ) -> int:
734 return GLib.timeout_add(priority, interval, function, *user_data)
735
736
737 __all__.append("timeout_add")
738
739
740 def timeout_add_seconds(
741 interval: int,
742 function: typing.Callable[..., bool | None],
743 *user_data: typing.Any,
744 priority: int = GLib.PRIORITY_DEFAULT,
745 ) -> int:
746 return GLib.timeout_add_seconds(priority, interval, function, *user_data)
747
748
749 __all__.append("timeout_add_seconds")
750
751
752 # The GI GLib API uses g_io_add_watch_full renamed to g_io_add_watch with
753 # a signature of (channel, priority, condition, func, user_data).
754 # Prior to PyGObject 3.8, this function was statically bound with an API closer to the
755 # non-full version with a signature of: (fd, condition, func, *user_data)
756 # We need to support this until we are okay with breaking API in a way which is
757 # not backwards compatible.
758 #
759 # This needs to take into account several historical APIs:
760 # - calling with an fd as first argument
761 # - calling with a Python file object as first argument (we keep this one as
762 # it's really convenient and does not change the number of arguments)
763 # - calling without a priority as second argument
764 def _io_add_watch_get_args(channel, priority_, condition, *cb_and_user_data, **kwargs):
765 if not isinstance(priority_, int) or isinstance(priority_, GLib.IOCondition):
766 warnings.warn(
767 "Calling io_add_watch without priority as second argument is deprecated",
768 PyGIDeprecationWarning,
769 )
770 # shift the arguments around
771 user_data = cb_and_user_data
772 callback = condition
773 condition = priority_
774 if not callable(callback):
775 raise TypeError("third argument must be callable")
776
777 # backwards compatibility: Call with priority kwarg
778 if "priority" in kwargs:
779 warnings.warn(
780 "Calling io_add_watch with priority keyword argument is deprecated, put it as second positional argument",
781 PyGIDeprecationWarning,
782 )
783 priority_ = kwargs["priority"]
784 else:
785 priority_ = GLib.PRIORITY_DEFAULT
786 else:
787 if len(cb_and_user_data) < 1 or not callable(cb_and_user_data[0]):
788 raise TypeError("expecting callback as fourth argument")
789 callback = cb_and_user_data[0]
790 user_data = cb_and_user_data[1:]
791
792 # backwards compatibility: Allow calling with fd
793 if isinstance(channel, int):
794
795 def func_fdtransform(_, cond, *data):
796 return callback(channel, cond, *data)
797
798 real_channel = GLib.IOChannel.unix_new(channel)
799 elif isinstance(channel, socket.socket) and sys.platform == "win32":
800
801 def func_fdtransform(_, cond, *data):
802 return callback(channel, cond, *data)
803
804 real_channel = GLib.IOChannel.win32_new_socket(channel.fileno())
805 elif hasattr(channel, "fileno"):
806 # backwards compatibility: Allow calling with Python file
807 def func_fdtransform(_, cond, *data):
808 return callback(channel, cond, *data)
809
810 real_channel = GLib.IOChannel.unix_new(channel.fileno())
811 else:
812 assert isinstance(channel, GLib.IOChannel)
813 func_fdtransform = callback
814 real_channel = channel
815
816 return real_channel, priority_, condition, func_fdtransform, user_data
817
818
819 __all__.append("_io_add_watch_get_args")
820
821
822 def io_add_watch(*args, **kwargs) -> int:
823 """io_add_watch(channel, priority, condition, func, *user_data) -> event_source_id."""
824 channel, priority, condition, func, user_data = _io_add_watch_get_args(
825 *args, **kwargs
826 )
827 return GLib.io_add_watch(channel, priority, condition, func, *user_data)
828
829
830 __all__.append("io_add_watch")
831
832
833 # backwards compatible API
834 class IOChannel(GLib.IOChannel):
835 @staticmethod
836 def __new__(
837 cls: type[Self],
838 filedes: int | None = None,
839 filename: str | None = None,
840 mode: str | None = None,
841 hwnd: int | None = None,
842 ) -> Self:
843 if filedes is not None:
844 return GLib.IOChannel.unix_new(filedes) # type: ignore[return-value]
845 if filename is not None:
846 return GLib.IOChannel.new_file(filename, mode or "r") # type: ignore[return-value]
847 if hwnd is not None:
848 return GLib.IOChannel.win32_new_fd(hwnd) # type: ignore[return-value]
849 raise TypeError(
850 "either a valid file descriptor, file name, or window handle must be supplied"
851 )
852
853 def __init__(self, *args, **kwargs):
854 # Call super without arguments to avoid deprecation warning
855 return super().__init__()
856
857 def read(self, max_count: int = -1) -> bytes:
858 """Reads data from a :obj:`~gi.repository.GLib.IOChannel`."""
859 return io_channel_read(self, max_count)
860
861 def read_chars(self, max_count: int = -1) -> bytes:
862 """Alias for GLib.IOChannel.read()."""
863 return self.read(max_count)
864
865 def readline(self, size_hint: int = -1) -> str:
866 # note, size_hint is just to maintain backwards compatible API; the
867 # old static binding did not actually use it
868 (_status, buf, _length, _terminator_pos) = self.read_line()
869 if buf is None:
870 return ""
871 return buf
872
873 def readlines(self, size_hint: int = -1) -> list[str]:
874 # note, size_hint is just to maintain backwards compatible API;
875 # the old static binding did not actually use it
876 lines = []
877 status = GLib.IOStatus.NORMAL
878 while status == GLib.IOStatus.NORMAL:
879 (status, buf, _length, _terminator_pos) = self.read_line()
880 # note, this appends an empty line after EOF; this is
881 # bug-compatible with the old static bindings
882 if buf is None:
883 buf = ""
884 lines.append(buf)
885 return lines
886
887 def write(self, buf: str | bytes, buflen: int = -1) -> int:
888 if not isinstance(buf, bytes):
889 buf = buf.encode("UTF-8")
890 if buflen == -1:
891 buflen = len(buf)
892 (_status, written) = self.write_chars(buf, buflen)
893 return written
894
895 def writelines(self, lines: typing.Iterable[str | bytes]) -> None:
896 for line in lines:
897 self.write(line)
898
899 _whence_map = {0: GLib.SeekType.SET, 1: GLib.SeekType.CUR, 2: GLib.SeekType.END}
900
901 def seek(self, offset: int, whence: int = 0) -> GLib.IOStatus:
902 try:
903 w = self._whence_map[whence]
904 except KeyError:
905 raise ValueError("invalid 'whence' value")
906 return self.seek_position(offset, w)
907
908 def add_watch(
909 self,
910 condition: IOCondition,
911 callback: typing.Callable[..., bool | None],
912 *user_data: typing.Any,
913 priority: int = GLib.PRIORITY_DEFAULT,
914 ) -> int:
915 return io_add_watch(self, priority, condition, callback, *user_data)
916
917 add_watch = deprecated(add_watch, "GLib.io_add_watch()")
918
919 def __iter__(self):
920 return self
921
922 def __next__(self) -> str:
923 (status, buf, _length, _terminator_pos) = self.read_line()
924 if status == GLib.IOStatus.NORMAL:
925 return buf
926 raise StopIteration
927
928
929 IOChannel = override(IOChannel)
930 __all__.append("IOChannel")
931
932
933 class PollFD(GLib.PollFD):
934 @staticmethod
935 def __new__(cls: type[Self], fd: int, events: IOCondition) -> Self:
936 pollfd = GLib.PollFD()
937 pollfd.__class__ = cls
938 return pollfd
939
940 def __init__(self, fd: int, events: IOCondition) -> None:
941 self.fd = fd
942 self.events = events
943
944
945 PollFD = override(PollFD)
946 __all__.append("PollFD")
947
948
949 # The GI GLib API uses g_child_watch_add_full renamed to g_child_watch_add with
950 # a signature of (priority, pid, callback, data).
951 # Prior to PyGObject 3.8, this function was statically bound with an API closer to the
952 # non-full version with a signature of: (pid, callback, data=None, priority=GLib.PRIORITY_DEFAULT)
953 # We need to support this until we are okay with breaking API in a way which is
954 # not backwards compatible.
955 def _child_watch_add_get_args(priority_or_pid, pid_or_callback, *args, **kwargs):
956 user_data = []
957
958 if callable(pid_or_callback):
959 warnings.warn(
960 "Calling child_watch_add without priority as first argument is deprecated",
961 PyGIDeprecationWarning,
962 )
963 pid = priority_or_pid
964 callback = pid_or_callback
965 if len(args) == 0:
966 priority = kwargs.get("priority", GLib.PRIORITY_DEFAULT)
967 elif len(args) == 1:
968 user_data = args
969 priority = kwargs.get("priority", GLib.PRIORITY_DEFAULT)
970 elif len(args) == 2:
971 user_data = [args[0]]
972 priority = args[1]
973 else:
974 raise TypeError("expected at most 4 positional arguments")
975 else:
976 priority = priority_or_pid
977 pid = pid_or_callback
978 if "function" in kwargs:
979 callback = kwargs["function"]
980 user_data = args
981 elif len(args) > 0 and callable(args[0]):
982 callback = args[0]
983 user_data = args[1:]
984 else:
985 raise TypeError("expected callback as third argument")
986
987 if "data" in kwargs:
988 if user_data:
989 raise TypeError('got multiple values for "data" argument')
990 user_data = (kwargs["data"],)
991
992 return priority, pid, callback, user_data
993
994
995 # we need this to be accessible for unit testing
996 __all__.append("_child_watch_add_get_args")
997
998
999 def child_watch_add(*args, **kwargs):
1000 """child_watch_add(priority, pid, function, *data)."""
1001 priority, pid, function, data = _child_watch_add_get_args(*args, **kwargs)
1002 return GLib.child_watch_add(priority, pid, function, *data)
1003
1004
1005 __all__.append("child_watch_add")
1006
1007
1008 def get_current_time() -> float:
1009 return GLib.get_real_time() * 0.000001
1010
1011
1012 get_current_time = deprecated(get_current_time, "GLib.get_real_time()")
1013
1014 __all__.append("get_current_time")
1015
1016
1017 # backwards compatible API with default argument, and ignoring bytes_read
1018 # output argument
1019 def filename_from_utf8(utf8string: str, len: int = -1) -> str:
1020 return GLib.filename_from_utf8(utf8string, len)[0]
1021
1022
1023 __all__.append("filename_from_utf8")
1024
1025
1026 if hasattr(GLib, "unix_signal_add"):
1027 unix_signal_add_full = GLib.unix_signal_add
1028 __all__.append("unix_signal_add_full")
1029 deprecated_attr("GLib", "unix_signal_add_full", "GLib.unix_signal_add")
1030
1031
1032 # obsolete constants for backwards compatibility
1033 glib_version = (GLib.MAJOR_VERSION, GLib.MINOR_VERSION, GLib.MICRO_VERSION)
1034 __all__.append("glib_version")
1035 deprecated_attr(
1036 "GLib",
1037 "glib_version",
1038 "(GLib.MAJOR_VERSION, GLib.MINOR_VERSION, GLib.MICRO_VERSION)",
1039 )
1040
1041 pyglib_version = version_info
1042 __all__.append("pyglib_version")
1043 deprecated_attr("GLib", "pyglib_version", "gi.version_info")
1044
1045 GLibPlatform = get_platform_specific_module(GLib)
1046
1047 if GLibPlatform:
1048 # Add support for using platform-specific GLib symbols.
1049 glib_globals = globals()
1050
1051 for attr in dir(GLibPlatform):
1052 if attr.startswith("_"):
1053 continue
1054
1055 original_attr, wrapper_attr = get_fallback_platform_specific_module_symbol(
1056 GLib, GLibPlatform, attr
1057 )
1058
1059 if (
1060 wrapper_attr == attr
1061 and (GLib.MAJOR_VERSION, GLib.MINOR_VERSION) >= (2, 88)
1062 and hasattr(GLib, wrapper_attr)
1063 ):
1064 warnings.warn(
1065 (
1066 f"Name conflict for platform-specific symbol {GLibPlatform._namespace}.{attr}."
1067 + " No wrapper will be created."
1068 ),
1069 PyGIWarning,
1070 stacklevel=2,
1071 )
1072
1073 if (
1074 wrapper_attr in __all__
1075 or wrapper_attr in glib_globals
1076 or hasattr(GLib, wrapper_attr)
1077 ):
1078 continue
1079
1080 glib_globals[wrapper_attr] = original_attr
1081 deprecated_attr(
1082 GLib._namespace, wrapper_attr, f"{GLibPlatform._namespace}.{attr}"
1083 )
1084 __all__.append(wrapper_attr)
1085
1086 if hasattr(GLibPlatform, "signal_add"):
1087 deprecated_attr(
1088 "GLib", "unix_signal_add_full", f"{GLibPlatform._namespace}.signal_add"
1089 )