Debian Codegraph @

gi/overrides/__init__.py

raw
1 import functools
2 import types
3 import warnings
4 import importlib
5 import sys
6
7 from gi import PyGIDeprecationWarning
8 from gi._gi import CallableInfo, pygobject_new_full
9 from gi._constants import TYPE_NONE, TYPE_INVALID
10
11 # support overrides in different directories than our gi module
12 from pkgutil import extend_path
13
14 __path__ = extend_path(__path__, __name__)
15
16
17 # namespace -> (attr, replacement)
18 _deprecated_attrs = {}
19
20
21 class OverridesProxyModule(types.ModuleType):
22 """Wraps a introspection module and contains all overrides"""
23
24 __slots__ = ("_deprecations", "_introspection_module")
25
26 def __init__(self, introspection_module):
27 super().__init__(introspection_module.__name__)
28 self._introspection_module = introspection_module
29 self._deprecations = {}
30
31 def __getattr__(self, name):
32 if name in self._deprecations:
33 value, warning = self._deprecations[name]
34 warnings.warn(warning, stacklevel=2)
35 return value
36 return getattr(self._introspection_module, name)
37
38 def __delattr__(self, name):
39 found = False
40 if name in self.__dict__:
41 del self.__dict__[name]
42 found = True
43 if name in self._deprecations:
44 del self._deprecations[name]
45 found = True
46 try:
47 delattr(self._introspection_module, name)
48 except AttributeError:
49 # Silence the exception if the attribute was previously found.
50 if not found:
51 raise
52
53 def __dir__(self):
54 result = set(super().__dir__())
55 result.update(self._deprecations.keys())
56 result.update(dir(self._introspection_module))
57 return sorted(result)
58
59 def __repr__(self):
60 return f"<{type(self).__name__} {self._introspection_module!r}>"
61
62
63 class _DeprecatedAttribute:
64 """A deprecation descriptor for OverridesProxyModule subclasses.
65
66 Emits a PyGIDeprecationWarning on every access and tries to act as a
67 normal instance attribute (can be replaced and deleted).
68 """
69
70 def __init__(self, namespace, attr, value, replacement):
71 self._attr = attr
72 self._value = value
73 self._warning = PyGIDeprecationWarning(
74 f"{namespace}.{attr} is deprecated; use {replacement} instead"
75 )
76
77 def __get__(self, instance, owner):
78 if instance is None:
79 raise AttributeError(self._attr)
80 warnings.warn(self._warning, stacklevel=2)
81 return self._value
82
83 def __set__(self, instance, value):
84 attr = self._attr
85 # delete the descriptor, then set the instance value
86 delattr(type(instance), attr)
87 setattr(instance, attr, value)
88
89 def __delete__(self, instance):
90 # delete the descriptor
91 delattr(type(instance), self._attr)
92
93
94 def load_overrides(introspection_module):
95 """Loads overrides for an introspection module.
96
97 Either returns the same module again in case there are no overrides or a
98 proxy module including overrides. Doesn't cache the result.
99 """
100 namespace = introspection_module.__name__.rsplit(".", 1)[-1]
101 module_key = "gi.repository." + namespace
102
103 # We use sys.modules so overrides can import from gi.repository
104 # but restore everything at the end so this doesn't have any side effects
105 has_old = module_key in sys.modules
106 old_module = sys.modules.get(module_key)
107
108 proxy = OverridesProxyModule(introspection_module)
109 sys.modules[module_key] = proxy
110
111 # backwards compat:
112 # gedit uses gi.importer.modules['Gedit']._introspection_module
113 from ..importer import modules
114
115 assert hasattr(proxy, "_introspection_module")
116 modules[namespace] = proxy
117
118 try:
119 override_package_name = "gi.overrides." + namespace
120 spec = importlib.util.find_spec(override_package_name)
121 override_loader = spec.loader if spec is not None else None
122
123 # Avoid checking for an ImportError, an override might
124 # depend on a missing module thus causing an ImportError
125 if override_loader is None:
126 return introspection_module
127
128 override_mod = importlib.import_module(override_package_name)
129
130 finally:
131 del modules[namespace]
132 del sys.modules[module_key]
133 if has_old:
134 sys.modules[module_key] = old_module
135
136 # backwards compat: for gst-python/gstmodule.c,
137 # which tries to access Gst.Fraction through
138 # Gst._overrides_module.Fraction. We assign the proxy instead as that
139 # contains all overridden classes like Fraction during import anyway and
140 # there is no need to keep the real override module alive.
141 proxy._overrides_module = proxy
142
143 override_all = []
144 if hasattr(override_mod, "__all__"):
145 override_all = override_mod.__all__
146
147 for var in override_all:
148 try:
149 item = getattr(override_mod, var)
150 except (AttributeError, TypeError):
151 # Gedit puts a non-string in __all__, so catch TypeError here
152 continue
153 setattr(proxy, var, item)
154
155 # Replace deprecated module level attributes with a descriptor
156 # which emits a warning when accessed.
157 for attr, replacement in _deprecated_attrs.pop(namespace, []):
158 try:
159 value = getattr(proxy, attr)
160 except AttributeError:
161 raise AssertionError(
162 f"{attr} was set deprecated but wasn't added to __all__"
163 )
164 delattr(proxy, attr)
165 proxy._deprecations[attr] = (
166 value,
167 PyGIDeprecationWarning(
168 f"{namespace}.{attr} is deprecated; use {replacement} instead"
169 ),
170 )
171
172 return proxy
173
174
175 def override(type_):
176 """Decorator for registering an override.
177
178 Other than objects added to __all__, these can get referenced in the same
179 override module via the gi.repository module (get_parent_for_object() does
180 for example), so they have to be added to the module immediately.
181 """
182 if isinstance(type_, CallableInfo):
183 func = type_
184 namespace = func.__module__.rsplit(".", 1)[-1]
185 module = sys.modules["gi.repository." + namespace]
186
187 def wrapper(func):
188 setattr(module, func.__name__, func)
189 return func
190
191 return wrapper
192 if isinstance(type_, types.FunctionType):
193 raise TypeError(f"func must be a gi function, got {type_}")
194 try:
195 info = getattr(type_, "__info__")
196 except AttributeError:
197 raise TypeError(
198 f"Can not override a type {type_.__name__}, which is not in a gobject "
199 "introspection typelib"
200 )
201
202 if not type_.__module__.startswith("gi.overrides"):
203 raise KeyError(
204 "You have tried override outside of the overrides module. "
205 f"This is not allowed ({type_}, {type_.__module__})"
206 )
207
208 g_type = info.get_g_type()
209 assert g_type != TYPE_NONE
210 if g_type != TYPE_INVALID:
211 g_type.pytype = type_
212
213 namespace = type_.__module__.rsplit(".", 1)[-1]
214 module = sys.modules["gi.repository." + namespace]
215 setattr(module, type_.__name__, type_)
216
217 return type_
218
219
220 overridefunc = override
221 """Deprecated"""
222
223
224 def deprecated(fn, replacement):
225 """Decorator for marking methods and classes as deprecated."""
226
227 @functools.wraps(fn)
228 def wrapped(*args, **kwargs):
229 warnings.warn(
230 f"{fn.__name__} is deprecated; use {replacement} instead",
231 PyGIDeprecationWarning,
232 stacklevel=2,
233 )
234 return fn(*args, **kwargs)
235
236 return wrapped
237
238
239 def deprecated_attr(namespace, attr, replacement):
240 """Marks a module level attribute as deprecated. Accessing it will emit
241 a PyGIDeprecationWarning warning.
242
243 e.g. for ``deprecated_attr("GObject", "STATUS_FOO", "GLib.Status.FOO")``
244 accessing GObject.STATUS_FOO will emit:
245
246 "GObject.STATUS_FOO is deprecated; use GLib.Status.FOO instead"
247
248 :param str namespace:
249 The namespace of the override this is called in.
250 :param str namespace:
251 The attribute name (which gets added to __all__).
252 :param str replacement:
253 The replacement text which will be included in the warning.
254 """
255 _deprecated_attrs.setdefault(namespace, []).append((attr, replacement))
256
257
258 def deprecated_init(
259 super_init_func,
260 arg_names,
261 ignore=(),
262 deprecated_aliases={},
263 deprecated_defaults={},
264 category=PyGIDeprecationWarning,
265 stacklevel=2,
266 ):
267 """Wrapper for deprecating GObject based __init__ methods which specify
268 defaults already available or non-standard defaults.
269
270 :param callable super_init_func:
271 Initializer to wrap.
272 :param list arg_names:
273 Ordered argument name list.
274 :param list ignore:
275 List of argument names to ignore when calling the wrapped function.
276 This is useful for function which take a non-standard keyword that is munged elsewhere.
277 :param dict deprecated_aliases:
278 Dictionary mapping a keyword alias to the actual g_object_newv keyword.
279 :param dict deprecated_defaults:
280 Dictionary of non-standard defaults that will be used when the
281 keyword is not explicitly passed.
282 :param Exception category:
283 Exception category of the error.
284 :param int stacklevel:
285 Stack level for the deprecation passed on to warnings.warn
286 :returns: Wrapped version of ``super_init_func`` which gives a deprecation
287 warning when non-keyword args or aliases are used.
288 :rtype: callable
289 """
290
291 # We use a list of argument names to maintain order of the arguments
292 # being deprecated. This allows calls with positional arguments to
293 # continue working but with a deprecation message.
294 def new_init(self, *args, **kwargs):
295 """Initializer for a GObject based classes with support for property
296 sets through the use of explicit keyword arguments.
297 """
298 # Print warnings for calls with positional arguments.
299 if args:
300 warnings.warn(
301 "Using positional arguments with the GObject constructor has been deprecated. "
302 'Please specify keyword(s) for "{}" or use a class specific constructor. '
303 "See: https://wiki.gnome.org/Projects/PyGObject/InitializerDeprecations".format(
304 ", ".join(arg_names[: len(args)])
305 ),
306 category,
307 stacklevel=stacklevel,
308 )
309 new_kwargs = dict(zip(arg_names, args))
310 else:
311 new_kwargs = {}
312 new_kwargs.update(kwargs)
313
314 # Print warnings for alias usage and transfer them into the new key.
315 aliases_used = []
316 for key, alias in deprecated_aliases.items():
317 if alias in new_kwargs:
318 new_kwargs[key] = new_kwargs.pop(alias)
319 aliases_used.append(key)
320
321 if aliases_used:
322 warnings.warn(
323 'The keyword(s) "{}" have been deprecated in favor of "{}" respectively. '
324 "See: https://wiki.gnome.org/Projects/PyGObject/InitializerDeprecations".format(
325 ", ".join(deprecated_aliases[k] for k in sorted(aliases_used)),
326 ", ".join(sorted(aliases_used)),
327 ),
328 category,
329 stacklevel=stacklevel,
330 )
331
332 # Print warnings for defaults different than what is already provided by the property
333 defaults_used = []
334 for key in deprecated_defaults:
335 if key not in new_kwargs:
336 new_kwargs[key] = deprecated_defaults[key]
337 defaults_used.append(key)
338
339 if defaults_used:
340 warnings.warn(
341 "Initializer is relying on deprecated non-standard "
342 "defaults. Please update to explicitly use: {} "
343 "See: https://wiki.gnome.org/Projects/PyGObject/InitializerDeprecations".format(
344 ", ".join(
345 f"{k}={deprecated_defaults[k]}" for k in sorted(defaults_used)
346 )
347 ),
348 category,
349 stacklevel=stacklevel,
350 )
351
352 # Remove keywords that should be ignored.
353 for key in ignore:
354 if key in new_kwargs:
355 new_kwargs.pop(key)
356
357 return super_init_func(self, **new_kwargs)
358
359 return new_init
360
361
362 def strip_boolean_result(method, exc_type=None, exc_str=None, fail_ret=None):
363 """Translate method's return value for stripping off success flag.
364
365 There are a lot of methods which return a "success" boolean and have
366 several out arguments. Translate such a method to return the out arguments
367 on success and None on failure.
368 """
369
370 @functools.wraps(method)
371 def wrapped(*args, **kwargs):
372 ret = method(*args, **kwargs)
373 if ret[0]:
374 if len(ret) == 2:
375 return ret[1]
376 return ret[1:]
377 if exc_type:
378 raise exc_type(exc_str or "call failed")
379 return fail_ret
380
381 return wrapped
382
383
384 def wrap_list_store_sort_func(func):
385 def wrap(a, b, *user_data):
386 a = pygobject_new_full(a, False)
387 b = pygobject_new_full(b, False)
388 return func(a, b, *user_data)
389
390 return wrap
391
392
393 def wrap_list_store_equal_func(func):
394 def wrap(a, b, *user_data):
395 a = pygobject_new_full(a, False)
396 b = pygobject_new_full(b, False)
397 return func(a, b, *user_data)
398
399 return wrap