Debian Codegraph @

gi/overrides/Gio.py

raw
1 # Copyright (C) 2010 Ignacio Casal Quinteiro <[email protected]>
2 #
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License, or (at your option) any later version.
7 #
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 # Lesser General Public License for more details.
12 #
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
16 # USA
17
18 import asyncio
19 import warnings
20
21 from .._ossighelper import register_sigint_fallback, get_event_loop
22 from ..overrides import (
23 override,
24 deprecated_attr,
25 deprecated_init,
26 wrap_list_store_equal_func,
27 wrap_list_store_sort_func,
28 )
29 from ..module import (
30 get_introspection_module,
31 get_fallback_platform_specific_module_symbol,
32 get_platform_specific_module,
33 )
34 from gi import PyGIWarning
35
36
37 from gi.repository import GLib
38 from gi.repository import GObject
39
40 from typing import Generic, TypeVar, overload
41 from collections.abc import Callable, Generator, Sequence
42
43 import sys
44
45 Gio = get_introspection_module("Gio")
46
47 __all__ = []
48
49
50 class ActionMap(Gio.ActionMap):
51 def add_action_entries(self, entries, user_data=None):
52 """The ``add_action_entries()`` method is a convenience function for creating
53 multiple :class:`~gi.repository.Gio.SimpleAction` instances and adding them
54 to a :class:`~gi.repository.Gio.ActionMap`.
55 Each action is constructed as per one entry.
56
57 :param list entries:
58 List of entry tuples for :meth:`add_action` method. The entry tuple can
59 vary in size with the following information:
60
61 * The name of the action. Must be specified.
62 * The callback to connect to the "activate" signal of the
63 action. Since GLib 2.40, this can be ``None`` for stateful
64 actions, in which case the default handler is used. For
65 boolean-stated actions with no parameter, this is a toggle.
66 For other state types (and parameter type equal to the state
67 type) this will be a function that just calls change_state
68 (which you should provide).
69 * The type of the parameter that must be passed to the activate
70 function for this action, given as a single :class:`~gi.repository.GLib.Variant` type
71 string (or ``None`` for no parameter)
72 * The initial state for this action, given in GLib.Variant text
73 format. The state is parsed with no extra type information, so
74 type tags must be added to the string if they are necessary.
75 Stateless actions should give ``None`` here.
76 * The callback to connect to the "change-state" signal of the
77 action. All stateful actions should provide a handler here;
78 stateless actions should not.
79
80 :param user_data:
81 The user data for signal connections, or ``None``
82 """
83 try:
84 iter(entries)
85 except TypeError:
86 raise TypeError("entries must be iterable")
87
88 def _process_action(
89 name, activate=None, parameter_type=None, state=None, change_state=None
90 ):
91 if parameter_type:
92 if not GLib.VariantType.string_is_valid(parameter_type):
93 msg = f"The type string '{parameter_type}' given as the parameter type for action '{name}' is not a valid GVariant type string. "
94 raise TypeError(msg)
95 variant_parameter = GLib.VariantType.new(parameter_type)
96 else:
97 variant_parameter = None
98
99 if state is not None:
100 # stateful action
101 variant_state = GLib.Variant.parse(None, state, None, None)
102 action = Gio.SimpleAction.new_stateful(
103 name, variant_parameter, variant_state
104 )
105 if change_state is not None:
106 action.connect("change-state", change_state, user_data)
107 else:
108 # stateless action
109 if change_state is not None:
110 msg = f"Stateless action '{name}' should give None for 'change_state', not '{change_state}'."
111 raise ValueError(msg)
112 action = Gio.SimpleAction(name=name, parameter_type=variant_parameter)
113
114 if activate is not None:
115 action.connect("activate", activate, user_data)
116 self.add_action(action)
117
118 for entry in entries:
119 # using inner function above since entries can leave out optional arguments
120 _process_action(*entry)
121
122
123 ActionMap = override(ActionMap)
124 __all__.append("ActionMap")
125
126
127 class Application(Gio.Application):
128 def __init__(self, *args, **kwargs):
129 super().__init__(*args, **kwargs)
130
131 self._asyncio_tasks = set()
132
133 def run(self, *args, **kwargs):
134 with (
135 register_sigint_fallback(self.quit),
136 get_event_loop(GLib.MainContext.default()).running(self.quit),
137 ):
138 return Gio.Application.run(self, *args, **kwargs)
139
140 def create_asyncio_task(self, coro):
141 """Safely create an asyncio task. The application will not quit until the
142 task completes. For potentially longer running tasks, you should add
143 cancellation logic to abort a task when it is not needed anymore (e.g.
144 cancelling it from the Gtk.Window.do_unmap event).
145
146 Note that python will only log a raised exception if the Task is
147 destroyed without the result having been collected. However, this does
148 also not happen when the task is cancelled. As such, be careful to not
149 cancel tasks that are already finished.
150
151 You can deal with this by either only storing a weak reference to the
152 Task, by explicitly collecting the result, or by only cancelling it if
153 it is not done already.
154 """
155 # First create the task (in case it raises an exception)
156 task = asyncio.create_task(coro)
157
158 self.hold()
159
160 # Store a reference to the task so that it cannot be garbage collected
161 self._asyncio_tasks.add(task)
162
163 def done_cb(task):
164 nonlocal self
165 self._asyncio_tasks.discard(task)
166 self.release()
167
168 task.add_done_callback(done_cb)
169 return task
170
171
172 Application = override(Application)
173 __all__.append("Application")
174
175
176 def _warn_init(cls, instead=None):
177 def new_init(self, *args, **kwargs):
178 super(cls, self).__init__(*args, **kwargs)
179 name = cls.__module__.rsplit(".", 1)[-1] + "." + cls.__name__
180 if instead:
181 warnings.warn(
182 (f"{name} shouldn't be instantiated directly, use {instead} instead."),
183 PyGIWarning,
184 stacklevel=2,
185 )
186 else:
187 warnings.warn(
188 f"{name} shouldn't be instantiated directly.",
189 PyGIWarning,
190 stacklevel=2,
191 )
192
193 return new_init
194
195
196 @override
197 class VolumeMonitor(Gio.VolumeMonitor):
198 # https://bugzilla.gnome.org/show_bug.cgi?id=744690
199 __init__ = _warn_init(Gio.VolumeMonitor, "Gio.VolumeMonitor.get()")
200
201
202 __all__.append("VolumeMonitor")
203
204
205 @override
206 class DBusAnnotationInfo(Gio.DBusAnnotationInfo):
207 __init__ = _warn_init(Gio.DBusAnnotationInfo)
208
209
210 __all__.append("DBusAnnotationInfo")
211
212
213 @override
214 class DBusArgInfo(Gio.DBusArgInfo):
215 __init__ = _warn_init(Gio.DBusArgInfo)
216
217
218 __all__.append("DBusArgInfo")
219
220
221 @override
222 class DBusMethodInfo(Gio.DBusMethodInfo):
223 __init__ = _warn_init(Gio.DBusMethodInfo)
224
225
226 __all__.append("DBusMethodInfo")
227
228
229 @override
230 class DBusSignalInfo(Gio.DBusSignalInfo):
231 __init__ = _warn_init(Gio.DBusSignalInfo)
232
233
234 __all__.append("DBusSignalInfo")
235
236
237 @override
238 class DBusInterfaceInfo(Gio.DBusInterfaceInfo):
239 __init__ = _warn_init(Gio.DBusInterfaceInfo)
240
241
242 __all__.append("DBusInterfaceInfo")
243
244
245 @override
246 class DBusNodeInfo(Gio.DBusNodeInfo):
247 __init__ = _warn_init(Gio.DBusNodeInfo)
248
249
250 __all__.append("DBusNodeInfo")
251
252
253 class FileEnumerator(Gio.FileEnumerator):
254 def __iter__(self):
255 return self
256
257 def __next__(self):
258 file_info = self.next_file(None)
259
260 if file_info is not None:
261 return file_info
262 raise StopIteration
263
264
265 FileEnumerator = override(FileEnumerator)
266 __all__.append("FileEnumerator")
267
268
269 class MenuItem(Gio.MenuItem):
270 def set_attribute(self, attributes):
271 for name, format_string, value in attributes:
272 self.set_attribute_value(name, GLib.Variant(format_string, value))
273
274
275 MenuItem = override(MenuItem)
276 __all__.append("MenuItem")
277
278
279 class Settings(Gio.Settings):
280 """Provide dictionary-like access to GLib.Settings."""
281
282 __init__ = deprecated_init(
283 Gio.Settings.__init__, arg_names=("schema", "path", "backend")
284 )
285
286 def __contains__(self, key):
287 return key in self.list_keys()
288
289 def __len__(self):
290 return len(self.list_keys())
291
292 def __iter__(self):
293 yield from self.list_keys()
294
295 def __bool__(self):
296 # for "if mysettings" we don't want a dictionary-like test here, just
297 # if the object isn't None
298 return True
299
300 def __getitem__(self, key):
301 # get_value() aborts the program on an unknown key
302 if key not in self:
303 raise KeyError(f"unknown key: {key!r}")
304
305 return self.get_value(key).unpack()
306
307 def __setitem__(self, key, value):
308 # set_value() aborts the program on an unknown key
309 if key not in self:
310 raise KeyError(f"unknown key: {key!r}")
311
312 # determine type string of this key
313 range = self.get_range(key)
314 type_ = range.get_child_value(0).get_string()
315 v = range.get_child_value(1)
316 if type_ == "type":
317 # v is boxed empty array, type of its elements is the allowed value type
318 type_str = v.get_child_value(0).get_type_string()
319 assert type_str.startswith("a")
320 type_str = type_str[1:]
321 elif type_ == "enum":
322 # v is an array with the allowed values
323 assert v.get_child_value(0).get_type_string().startswith("a")
324 type_str = v.get_child_value(0).get_child_value(0).get_type_string()
325 allowed = v.unpack()
326 if value not in allowed:
327 raise ValueError(f"value {value} is not an allowed enum ({allowed})")
328 elif type_ == "range":
329 tuple_ = v.get_child_value(0)
330 type_str = tuple_.get_child_value(0).get_type_string()
331 min_, max_ = tuple_.unpack()
332 if value < min_ or value > max_:
333 raise ValueError(f"value {value} not in range ({min_} - {max_})")
334 else:
335 raise NotImplementedError(
336 "Cannot handle allowed type range class " + str(type_)
337 )
338
339 self.set_value(key, GLib.Variant(type_str, value))
340
341 def keys(self):
342 return self.list_keys()
343
344
345 Settings = override(Settings)
346 __all__.append("Settings")
347
348
349 class _DBusProxyMethodCall:
350 """Helper class to implement DBusProxy method calls."""
351
352 def __init__(self, dbus_proxy, method_name):
353 self.dbus_proxy = dbus_proxy
354 self.method_name = method_name
355
356 def __async_result_handler(self, obj, result, user_data):
357 (result_callback, error_callback, real_user_data) = user_data
358 try:
359 ret = obj.call_finish(result)
360 except Exception:
361 _etype, e = sys.exc_info()[:2]
362 # return exception as value
363 if error_callback:
364 error_callback(obj, e, real_user_data)
365 else:
366 result_callback(obj, e, real_user_data)
367 return
368
369 result_callback(obj, self._unpack_result(ret), real_user_data)
370
371 def __call__(
372 self,
373 *args,
374 result_handler=None,
375 error_handler=None,
376 user_data=None,
377 flags=0,
378 timeout=-1,
379 ):
380 # the first positional argument is the signature, unless we are calling
381 # a method without arguments; then signature is implied to be '()'.
382 if args:
383 signature = args[0]
384 args = args[1:]
385 if not isinstance(signature, str):
386 raise TypeError(
387 f"first argument must be the method signature string: {signature!r}"
388 )
389 else:
390 signature = "()"
391
392 arg_variant = GLib.Variant(signature, tuple(args))
393
394 if result_handler is not None:
395 # asynchronous call
396 user_data = (result_handler, error_handler, user_data)
397 self.dbus_proxy.call(
398 self.method_name,
399 arg_variant,
400 flags,
401 timeout,
402 None,
403 self.__async_result_handler,
404 user_data,
405 )
406 else:
407 # synchronous call
408 result = self.dbus_proxy.call_sync(
409 self.method_name, arg_variant, flags, timeout, None
410 )
411 return self._unpack_result(result)
412 return None
413
414 @classmethod
415 def _unpack_result(klass, result):
416 """Convert a D-BUS return variant into an appropriate return value."""
417 result = result.unpack()
418
419 # to be compatible with standard Python behaviour, unbox
420 # single-element tuples and return None for empty result tuples
421 if len(result) == 1:
422 result = result[0]
423 elif len(result) == 0:
424 result = None
425
426 return result
427
428
429 class DBusProxy(Gio.DBusProxy):
430 """Provide comfortable and pythonic method calls.
431
432 This marshalls the method arguments into a GVariant, invokes the
433 call_sync() method on the DBusProxy object, and unmarshalls the result
434 GVariant back into a Python tuple.
435
436 The first argument always needs to be the D-Bus signature tuple of the
437 method call. Example:
438
439 proxy = Gio.DBusProxy.new_sync(...)
440 result = proxy.MyMethod('(is)', 42, 'hello')
441
442 The exception are methods which take no arguments, like
443 proxy.MyMethod('()'). For these you can omit the signature and just write
444 proxy.MyMethod().
445
446 Optional keyword arguments:
447
448 - timeout: timeout for the call in milliseconds (default to D-Bus timeout)
449
450 - flags: Combination of Gio.DBusCallFlags.*
451
452 - result_handler: Do an asynchronous method call and invoke
453 result_handler(proxy_object, result, user_data) when it finishes.
454
455 - error_handler: If the asynchronous call raises an exception,
456 error_handler(proxy_object, exception, user_data) is called when it
457 finishes. If error_handler is not given, result_handler is called with
458 the exception object as result instead.
459
460 - user_data: Optional user data to pass to result_handler for
461 asynchronous calls.
462
463 Example for asynchronous calls:
464
465 def mymethod_done(proxy, result, user_data):
466 if isinstance(result, Exception):
467 # handle error
468 else:
469 # do something with result
470
471 proxy.MyMethod('(is)', 42, 'hello',
472 result_handler=mymethod_done, user_data='data')
473 """
474
475 def __getattr__(self, name):
476 if name.startswith("do_"):
477 return self[name]
478 return _DBusProxyMethodCall(self, name)
479
480
481 DBusProxy = override(DBusProxy)
482 __all__.append("DBusProxy")
483
484
485 ObjectItemType = TypeVar("ObjectItemType", bound=GObject.Object)
486
487
488 class ListModel(Gio.ListModel, Generic[ObjectItemType]):
489 @overload
490 def __getitem__(self, key: slice) -> list[ObjectItemType]: ...
491
492 @overload
493 def __getitem__(self, key: int) -> ObjectItemType: ...
494
495 def __getitem__(self, key):
496 if isinstance(key, slice):
497 return [self.get_item(i) for i in range(*key.indices(len(self)))]
498 if isinstance(key, int):
499 if key < 0:
500 key += len(self)
501 if key < 0:
502 raise IndexError
503 ret = self.get_item(key)
504 if ret is None:
505 raise IndexError
506 return ret
507 raise TypeError
508
509 def __contains__(self, item: ObjectItemType) -> bool:
510 pytype = self.get_item_type().pytype
511 if not isinstance(item, pytype):
512 raise TypeError(f"Expected type {pytype.__module__}.{pytype.__name__}")
513 return any(i == item for i in self)
514
515 def __len__(self) -> int:
516 return self.get_n_items()
517
518 def __iter__(self) -> Generator[ObjectItemType, None, None]:
519 for i in range(len(self)):
520 yield self.get_item(i)
521
522
523 ListModel = override(ListModel)
524 __all__.append("ListModel")
525
526
527 class ListStore(Gio.ListStore, Generic[ObjectItemType]):
528 # Describing the variadic arguments requires TypeVarTuple and unpacking syntax in type annotation:
529 # compare_func: Callable[Concatenate[ObjectItemType, ObjectItemType, *TypedVarTuple('Args')], int]
530 # *user_data: *TypedVarTuple('Args')
531 # Since those are only available on Python ≥ 3.11, let's keep the arguments untyped for now.
532 def sort(self, compare_func: Callable[..., int], *user_data) -> None:
533 compare_func = wrap_list_store_sort_func(compare_func)
534 return super().sort(compare_func, *user_data)
535
536 def insert_sorted(
537 self, item: ObjectItemType, compare_func: Callable[..., int], *user_data
538 ) -> None:
539 compare_func = wrap_list_store_sort_func(compare_func)
540 return super().insert_sorted(item, compare_func, *user_data)
541
542 def __delitem__(self, key: int | slice) -> None:
543 if isinstance(key, slice):
544 start, stop, step = key.indices(len(self))
545 if step == 1:
546 self.splice(start, max(stop - start, 0), [])
547 elif step == -1:
548 self.splice(stop + 1, max(start - stop, 0), [])
549 else:
550 for i in sorted(range(start, stop, step), reverse=True):
551 self.remove(i)
552 elif isinstance(key, int):
553 if key < 0:
554 key += len(self)
555 if key < 0 or key >= len(self):
556 raise IndexError
557 self.remove(key)
558 else:
559 raise TypeError
560
561 @overload
562 def __setitem__(self, key: slice, value: Sequence[ObjectItemType]) -> None: ...
563
564 @overload
565 def __setitem__(self, key: int, value: ObjectItemType) -> None: ...
566
567 def __setitem__(self, key, value):
568 if isinstance(key, slice):
569 pytype = self.get_item_type().pytype
570 valuelist = []
571 for v in value:
572 if not isinstance(v, pytype):
573 raise TypeError(
574 f"Expected type {pytype.__module__}.{pytype.__name__}"
575 )
576 valuelist.append(v)
577
578 start, stop, step = key.indices(len(self))
579 if step == 1:
580 self.splice(start, max(stop - start, 0), valuelist)
581 else:
582 indices = list(range(start, stop, step))
583 if len(indices) != len(valuelist):
584 raise ValueError
585
586 if step == -1:
587 self.splice(stop + 1, max(start - stop, 0), valuelist[::-1])
588 else:
589 for i, v in zip(indices, valuelist):
590 self.splice(i, 1, [v])
591 elif isinstance(key, int):
592 if key < 0:
593 key += len(self)
594 if key < 0 or key >= len(self):
595 raise IndexError
596
597 pytype = self.get_item_type().pytype
598 if not isinstance(value, pytype):
599 raise TypeError(f"Expected type {pytype.__module__}.{pytype.__name__}")
600
601 self.splice(key, 1, [value])
602 else:
603 raise TypeError
604
605 def find_with_equal_func(self, item, equal_func, *user_data):
606 # find_with_equal_func() is not suited for language bindings,
607 # see: https://gitlab.gnome.org/GNOME/glib/-/issues/2447.
608 # Use find_with_equal_func_full() instead.
609 equal_func = wrap_list_store_equal_func(equal_func)
610 return self.find_with_equal_func_full(item, equal_func, *user_data)
611
612
613 ListStore = override(ListStore)
614 __all__.append("ListStore")
615
616
617 class DataInputStream(Gio.DataInputStream):
618 def __iter__(self):
619 return self
620
621 def __next__(self):
622 line = self.read_line_utf8(None)[0]
623
624 if line is not None:
625 return line
626 raise StopIteration
627
628
629 DataInputStream = override(DataInputStream)
630 __all__.append("DataInputStream")
631
632
633 class File(Gio.File):
634 def __fspath__(self):
635 path = self.peek_path()
636 # A file isn't guaranteed to have a path associated and returning
637 # `None` here will result in a `TypeError` trying to subscribe to it.
638 if path is None or path == "":
639 raise TypeError("File has no associated path.")
640 return path
641
642
643 File = override(File)
644 __all__.append("File")
645
646
647 GioPlatform = get_platform_specific_module(Gio)
648
649 if GioPlatform:
650 # Add support for using platform-specific Gio symbols.
651 gio_globals = globals()
652
653 for attr in dir(GioPlatform):
654 if attr.startswith("_"):
655 continue
656
657 original_attr, wrapper_attr = get_fallback_platform_specific_module_symbol(
658 Gio, GioPlatform, attr
659 )
660
661 if (
662 wrapper_attr == attr
663 and (GLib.MAJOR_VERSION, GLib.MINOR_VERSION) >= (2, 86)
664 and hasattr(Gio, wrapper_attr)
665 ):
666 warnings.warn(
667 (
668 f"Name conflict for platform-specific symbol {GioPlatform._namespace}.{attr}."
669 + " No wrapper will be created."
670 ),
671 PyGIWarning,
672 stacklevel=2,
673 )
674
675 if (
676 wrapper_attr in __all__
677 or wrapper_attr in gio_globals
678 or hasattr(Gio, wrapper_attr)
679 ):
680 continue
681
682 gio_globals[wrapper_attr] = original_attr
683 deprecated_attr(
684 Gio._namespace, wrapper_attr, f"{GioPlatform._namespace}.{attr}"
685 )
686 __all__.append(wrapper_attr)