Debian Codegraph @

gi/types.py

raw
1 # Copyright (C) 2005-2009 Johan Dahlin <[email protected]>
2 #
3 # types.py: base types for introspected items.
4 #
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License, or (at your option) any later version.
9 #
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
18 # USA
19
20 import re
21 import warnings
22
23 from ._constants import TYPE_INVALID
24 from .docstring import generate_doc_string
25
26 from ._gi import (
27 InterfaceInfo,
28 ObjectInfo,
29 StructInfo,
30 VFuncInfo,
31 register_interface_info,
32 hook_up_vfunc_implementation,
33 GInterface,
34 PyGIWarning,
35 )
36 from . import _gi
37
38 StructInfo, GInterface
39
40 from . import _propertyhelper as propertyhelper
41 from . import _signalhelper as signalhelper
42
43
44 def snake_case(name):
45 s1 = re.sub(r"(.)([A-Z][a-z]+)", r"\1_\2", name)
46 return re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
47
48
49 class MetaClassHelper:
50 def _setup_methods(cls):
51 for method_info in cls.__info__.get_methods():
52 name = method_info.__name__
53 if method_info.is_constructor():
54 method_info = classmethod(method_info)
55 elif not method_info.is_method():
56 method_info = staticmethod(method_info)
57 setattr(cls, name, method_info)
58
59 def _setup_class_methods(cls):
60 info = cls.__info__
61 class_struct = info.get_class_struct()
62 if class_struct is None:
63 return
64 for method_info in class_struct.get_methods():
65 name = method_info.__name__
66 # Don't mask regular methods or base class methods with TypeClass methods.
67 if not hasattr(cls, name):
68 setattr(cls, name, classmethod(method_info))
69
70 def _setup_fields(cls):
71 for field_info in cls.__info__.get_fields():
72 name = field_info.get_name().replace("-", "_")
73 setattr(cls, name, property(field_info.get_value, field_info.set_value))
74
75 def _setup_constants(cls):
76 for constant_info in cls.__info__.get_constants():
77 name = constant_info.get_name()
78 value = constant_info.get_value()
79 setattr(cls, name, value)
80
81 def _setup_vfuncs(cls):
82 for vfunc_name, py_vfunc in cls.__dict__.items():
83 if not vfunc_name.startswith("do_") or not callable(py_vfunc):
84 continue
85
86 skip_ambiguity_check = False
87
88 # If a method name starts with "do_" assume it is a vfunc, and search
89 # in the base classes for a method with the same name to override.
90 # Recursion is necessary as overriden methods in most immediate parent
91 # classes may shadow vfuncs from classes higher in the hierarchy.
92 vfunc_info = None
93 for base in cls.__mro__:
94 method = getattr(base, vfunc_name, None)
95 method = getattr(method, "__func__", method)
96 if method is not None and isinstance(method, VFuncInfo):
97 vfunc_info = method
98 break
99
100 if not hasattr(base, "__info__") or not hasattr(
101 base.__info__, "get_vfuncs"
102 ):
103 continue
104
105 base_name = snake_case(base.__info__.get_type_name())
106
107 for v in base.__info__.get_vfuncs():
108 if vfunc_name == f"do_{base_name}_{v.get_name()}":
109 vfunc_info = v
110 skip_ambiguity_check = True
111 break
112
113 if vfunc_info:
114 break
115
116 # If we did not find a matching method name in the bases, we might
117 # be overriding an interface virtual method. Since interfaces do not
118 # provide implementations, there will be no method attribute installed
119 # on the object. Instead we have to search through
120 # InterfaceInfo.get_vfuncs(). Note that the infos returned by
121 # get_vfuncs() use the C vfunc name (ie. there is no "do_" prefix).
122 if vfunc_info is None:
123 vfunc_info = find_vfunc_info_in_interface(
124 cls.__bases__, vfunc_name[len("do_") :]
125 )
126
127 if vfunc_info is not None:
128 # Check to see if there are vfuncs with the same name in the bases.
129 # We have no way of specifying which one we are supposed to override.
130 if not skip_ambiguity_check:
131 ambiguous_base = find_vfunc_conflict_in_bases(
132 vfunc_info, cls.__bases__
133 )
134 if ambiguous_base is not None:
135 base_info = vfunc_info.get_container()
136 raise TypeError(
137 f"Method {vfunc_name}() on class {cls.__info__.get_namespace()}.{cls.__info__.get_name()} is ambiguous "
138 f"with methods in base classes {base_info.get_namespace()}.{base_info.get_name()} and {ambiguous_base.__info__.get_namespace()}.{ambiguous_base.__info__.get_name()}"
139 )
140 hook_up_vfunc_implementation(vfunc_info, cls.__gtype__, py_vfunc)
141
142 def _setup_native_vfuncs(cls):
143 # Only InterfaceInfo and ObjectInfo have the get_vfuncs() method.
144 # We skip InterfaceInfo because interfaces have no implementations for vfuncs.
145 # Also check if __info__ in __dict__, not hasattr('__info__', ...)
146 # because we do not want to accidentally retrieve __info__ from a base class.
147 class_info = cls.__dict__.get("__info__")
148 if class_info is None or not isinstance(class_info, ObjectInfo):
149 return
150
151 # Special case skipping of vfuncs for GObject.Object because they will break
152 # the static bindings which will try to use them.
153 if cls.__module__ == "gi.repository.GObject" and cls.__name__ == "Object":
154 return
155
156 for vfunc_info in class_info.get_vfuncs():
157 name = f"do_{vfunc_info.__name__}"
158 setattr(cls, name, vfunc_info)
159
160
161 def find_vfunc_info_in_interface(bases, vfunc_name):
162 for base in bases:
163 # All wrapped interfaces inherit from GInterface.
164 # This can be seen in IntrospectionModule.__getattr__() in module.py.
165 # We do not need to search regular classes here, only wrapped interfaces.
166 # We also skip GInterface, because it is not wrapped and has no __info__ attr.
167 # Skip bases without __info__ (static _gi.GObject)
168 if (
169 base is GInterface
170 or not issubclass(base, GInterface)
171 or not hasattr(base, "__info__")
172 ):
173 continue
174
175 # Only look at this classes vfuncs if it is an interface.
176 if isinstance(base.__info__, InterfaceInfo):
177 for vfunc in base.__info__.get_vfuncs():
178 if vfunc.get_name() == vfunc_name:
179 return vfunc
180
181 # Recurse into the parent classes
182 vfunc = find_vfunc_info_in_interface(base.__bases__, vfunc_name)
183 if vfunc is not None:
184 return vfunc
185
186 return None
187
188
189 def find_vfunc_conflict_in_bases(vfunc, bases):
190 for klass in bases:
191 if not hasattr(klass, "__info__") or not hasattr(klass.__info__, "get_vfuncs"):
192 continue
193 vfuncs = klass.__info__.get_vfuncs()
194 vfunc_name = vfunc.get_name()
195 for v in vfuncs:
196 if v.get_name() == vfunc_name and v != vfunc:
197 return klass
198
199 aklass = find_vfunc_conflict_in_bases(vfunc, klass.__bases__)
200 if aklass is not None:
201 return aklass
202 return None
203
204
205 class _GObjectMetaBase(type):
206 """Metaclass for automatically registering GObject classes."""
207
208 def __new__(cls, name, bases, namespace, **kwargs):
209 if "__slots__" in namespace:
210 warnings.warn(
211 f"GObject derived class {name} shouldn't use __slots__.",
212 PyGIWarning,
213 stacklevel=2,
214 )
215 del namespace["__slots__"]
216
217 return super().__new__(cls, name, bases, namespace, **kwargs)
218
219 def __init__(cls, name, bases, dict_):
220 type.__init__(cls, name, bases, dict_)
221 propertyhelper.install_properties(cls)
222 signalhelper.install_signals(cls)
223 cls._type_register(cls.__dict__)
224
225 def _type_register(cls, namespace):
226 # don't register the class if already registered
227 if "__gtype__" in namespace:
228 return
229
230 # Do not register a new GType for the overrides, as this would sort of
231 # defeat the purpose of overrides...
232 if cls.__module__.startswith("gi.overrides."):
233 return
234
235 _gi.type_register(cls, namespace.get("__gtype_name__"))
236
237
238 _gi._install_metaclass(_GObjectMetaBase)
239
240
241 class GObjectMeta(_GObjectMetaBase, MetaClassHelper):
242 """Meta class used for GI GObject based types."""
243
244 def __init__(cls, name, bases, dict_):
245 super().__init__(name, bases, dict_)
246 is_gi_defined = False
247 if cls.__module__ == "gi.repository." + cls.__info__.get_namespace():
248 is_gi_defined = True
249
250 is_python_defined = False
251 if not is_gi_defined and cls.__module__ != GObjectMeta.__module__:
252 is_python_defined = True
253
254 if is_python_defined:
255 cls._setup_vfuncs()
256 elif is_gi_defined:
257 if isinstance(cls.__info__, ObjectInfo):
258 cls._setup_class_methods()
259 cls._setup_methods()
260 cls._setup_constants()
261 cls._setup_native_vfuncs()
262
263 if isinstance(cls.__info__, ObjectInfo):
264 cls._setup_fields()
265 elif isinstance(cls.__info__, InterfaceInfo):
266 register_interface_info(cls.__info__.get_g_type())
267
268 def mro(cls):
269 return mro(cls)
270
271 @property
272 def __doc__(cls):
273 """Meta class property which shows up on any class using this meta-class."""
274 if cls == GObjectMeta:
275 return ""
276
277 doc = cls.__dict__.get("__doc__", None)
278 if doc is not None:
279 return doc
280
281 # For repository classes, dynamically generate a doc string if it wasn't overridden.
282 if cls.__module__.startswith(("gi.repository.", "gi.overrides")):
283 return generate_doc_string(cls.__info__)
284
285 return None
286
287
288 def mro(C):
289 """Compute the class precedence list (mro) according to C3, with GObject
290 interface considerations.
291
292 We override Python's MRO calculation to account for the fact that
293 GObject classes are not affected by the diamond problem:
294 http://en.wikipedia.org/wiki/Diamond_problem
295
296 Based on http://www.python.org/download/releases/2.3/mro/
297 """
298 # TODO: If this turns out being too slow, consider using generators
299 bases = []
300 bases_of_subclasses = [[C]]
301
302 if C.__bases__:
303 for base in C.__bases__:
304 # Python causes MRO's to be calculated starting with the lowest
305 # base class and working towards the descendant, storing the result
306 # in __mro__ at each point. Therefore at this point we know that
307 # we already have our base class MRO's available to us, there is
308 # no need for us to (re)calculate them.
309 bases_of_subclasses += [list(base.__mro__)]
310 bases_of_subclasses += [list(C.__bases__)]
311
312 while bases_of_subclasses:
313 for subclass_bases in bases_of_subclasses:
314 candidate = subclass_bases[0]
315 not_head = [s for s in bases_of_subclasses if candidate in s[1:]]
316 if not_head and GInterface not in candidate.__bases__:
317 candidate = None # conflict, reject candidate
318 else:
319 break
320
321 if candidate is None:
322 raise TypeError("Cannot create a consistent method resolution order (MRO)")
323
324 bases.append(candidate)
325
326 for subclass_bases in bases_of_subclasses[:]: # remove candidate
327 if subclass_bases and subclass_bases[0] == candidate:
328 del subclass_bases[0]
329 if not subclass_bases:
330 bases_of_subclasses.remove(subclass_bases)
331
332 return bases
333
334
335 def nothing(*args, **kwargs):
336 pass
337
338
339 class StructMeta(type, MetaClassHelper):
340 """Meta class used for GI Struct based types."""
341
342 def __init__(cls, name, bases, dict_):
343 super().__init__(name, bases, dict_)
344
345 # Avoid touching anything else than the base class.
346 g_type = cls.__info__.get_g_type()
347 if g_type != TYPE_INVALID and g_type.pytype is not None:
348 return
349
350 cls._setup_fields()
351 cls._setup_methods()
352
353 for method_info in cls.__info__.get_methods():
354 if (
355 method_info.is_constructor()
356 and method_info.__name__ == "new"
357 and (not method_info.get_arguments() or cls.__info__.get_size() == 0)
358 ):
359 cls.__new__ = staticmethod(method_info)
360 # Boxed will raise an exception
361 # if arguments are given to __init__
362 cls.__init__ = nothing
363 break
364
365 @property
366 def __doc__(cls):
367 if cls == StructMeta:
368 return ""
369 return generate_doc_string(cls.__info__)