Debian Codegraph @

gi/module.py

raw
1 # Copyright (C) 2007-2009 Johan Dahlin <[email protected]>
2 #
3 # module.py: dynamic module for introspected libraries.
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 importlib
21 from contextlib import suppress
22 from threading import Lock
23 from types import ModuleType
24
25 import gi
26 import warnings
27
28 from ._gi import (
29 CallableInfo,
30 Repository,
31 FunctionInfo,
32 RegisteredTypeInfo,
33 EnumInfo,
34 ObjectInfo,
35 InterfaceInfo,
36 ConstantInfo,
37 StructInfo,
38 UnionInfo,
39 CallbackInfo,
40 Struct,
41 Boxed,
42 Fundamental,
43 CCallback,
44 enum_add,
45 flags_add,
46 GInterface,
47 )
48 from .types import GObjectMeta, StructMeta
49
50 from ._constants import TYPE_NONE, TYPE_BOXED, TYPE_POINTER
51
52
53 repository = Repository.get_default()
54
55 # Cache of IntrospectionModules that have been loaded.
56 _introspection_modules = {}
57
58
59 def get_parent_for_object(object_info):
60 parent_object_info = object_info.get_parent()
61
62 if not parent_object_info:
63 # If we reach the end of the introspection info class hierarchy, look
64 # for an existing wrapper on the GType and use it as a base for the
65 # new introspection wrapper. This allows static C wrappers already
66 # registered with the GType to be used as the introspection base
67 # (_gi.GObject for example)
68 gtype = object_info.get_g_type()
69 if gtype and gtype.pytype:
70 return gtype.pytype
71
72 if object_info.get_fundamental() and gtype.is_instantiatable():
73 return Fundamental
74
75 # Otherwise use builtins.object as the base
76 return object
77
78 namespace = parent_object_info.get_namespace()
79 name = parent_object_info.get_name()
80
81 module = importlib.import_module("gi.repository." + namespace)
82 return getattr(module, name)
83
84
85 def get_interfaces_for_object(object_info):
86 interfaces = []
87 for interface_info in object_info.get_interfaces():
88 namespace = interface_info.get_namespace()
89 name = interface_info.get_name()
90
91 module = importlib.import_module("gi.repository." + namespace)
92 interfaces.append(getattr(module, name))
93 return interfaces
94
95
96 class IntrospectionModule(ModuleType):
97 """An object which wraps an introspection typelib.
98
99 This wrapping creates a python module like representation of the typelib
100 using gi repository as a foundation. Accessing attributes of the module
101 will dynamically pull them in and create wrappers for the members.
102 These members are then cached on this introspection module.
103 """
104
105 def __init__(self, namespace, version=None):
106 """Might raise gi._gi.RepositoryError."""
107 repository.require(namespace, version)
108 super().__init__(f"gi.repository.{namespace}")
109 self._namespace = namespace
110 self._version = version
111
112 path = repository.get_typelib_path(self._namespace)
113 self.__path__ = [path]
114
115 if self._version is None:
116 self._version = repository.get_version(self._namespace)
117
118 self._lock = Lock()
119
120 def __getattr__(self, name):
121 info = repository.find_by_name(self._namespace, name)
122 if not info:
123 raise AttributeError(f"{self.__name__!r} object has no attribute {name!r}")
124
125 if isinstance(info, EnumInfo):
126 g_type = info.get_g_type()
127
128 with self._lock:
129 wrapper = g_type.pytype
130
131 if wrapper is None:
132 if info.is_flags():
133 wrapper = flags_add(self, name, g_type, info)
134 else:
135 wrapper = enum_add(self, name, g_type, info)
136
137 wrapper.__info__ = info
138 for method_info in info.get_methods():
139 setattr(wrapper, method_info.__name__, method_info)
140
141 if g_type != TYPE_NONE:
142 g_type.pytype = wrapper
143
144 elif isinstance(info, RegisteredTypeInfo):
145 g_type = info.get_g_type()
146
147 # Create a wrapper.
148 if isinstance(info, ObjectInfo):
149 parent = get_parent_for_object(info)
150 interfaces = tuple(
151 interface
152 for interface in get_interfaces_for_object(info)
153 if not issubclass(parent, interface)
154 )
155 bases = (parent, *interfaces)
156 metaclass = GObjectMeta
157 elif isinstance(info, CallbackInfo):
158 bases = (CCallback,)
159 metaclass = GObjectMeta
160 elif isinstance(info, InterfaceInfo):
161 bases = (GInterface,)
162 metaclass = GObjectMeta
163 elif isinstance(info, (StructInfo, UnionInfo)):
164 if g_type.is_a(TYPE_BOXED):
165 bases = (Boxed,)
166 elif (
167 g_type.is_a(TYPE_POINTER)
168 or g_type == TYPE_NONE
169 or g_type.fundamental == g_type
170 ):
171 bases = (Struct,)
172 else:
173 raise TypeError(
174 f"unable to create a wrapper for {info.get_namespace()}.{info.get_name()}"
175 )
176 metaclass = StructMeta
177 else:
178 raise NotImplementedError(info)
179
180 with self._lock:
181 # Check if there is already a Python wrapper that is not a parent class
182 # of the wrapper being created. If it is a parent, it is ok to clobber
183 # g_type.pytype with a new child class wrapper of the existing parent.
184 # Note that the return here never occurs under normal circumstances due
185 # to caching on the __dict__ itself.
186 if g_type != TYPE_NONE:
187 type_ = g_type.pytype
188 if type_ is not None and type_ not in bases:
189 self.__dict__[name] = type_
190 return type_
191
192 dict_ = {
193 "__info__": info,
194 "__module__": self.__name__,
195 "__gtype__": g_type,
196 }
197 wrapper = metaclass(name, bases, dict_)
198
199 # Register the new Python wrapper.
200 if g_type != TYPE_NONE:
201 g_type.pytype = wrapper
202
203 elif isinstance(info, FunctionInfo):
204 wrapper = info
205 elif isinstance(info, ConstantInfo):
206 wrapper = info.get_value()
207 else:
208 raise NotImplementedError(info)
209
210 # Cache the newly created wrapper which will then be
211 # available directly on this introspection module instead of being
212 # lazily constructed through the __getattr__ we are currently in.
213 self.__dict__[name] = wrapper
214 return wrapper
215
216 def __repr__(self):
217 path = repository.get_typelib_path(self._namespace)
218 return f"<IntrospectionModule {self._namespace!r} from {path!r}>"
219
220 def __dir__(self):
221 result = set(super().__dir__())
222
223 # update *set* because some repository attributes have already been
224 # wrapped by __getattr__() and included in self.__dict__; but skip
225 # Callback types, as these are not real objects which we can actually
226 # get
227 namespace_infos = repository.get_infos(self._namespace)
228 result.update(
229 info.get_name()
230 for info in namespace_infos
231 if not isinstance(info, CallbackInfo)
232 )
233
234 return list(result)
235
236
237 def get_introspection_module(namespace):
238 """:Returns:
239 An object directly wrapping the gi module without overrides.
240
241 Might raise gi._gi.RepositoryError
242 """
243 if namespace in _introspection_modules:
244 return _introspection_modules[namespace]
245
246 version = gi.get_required_version(namespace)
247 module = IntrospectionModule(namespace, version)
248 _introspection_modules[namespace] = module
249 return module
250
251
252 def get_platform_specific_module(namespace):
253 """Return the platform-specific module for the given namespace, if available."""
254 with suppress((ValueError, ImportError)):
255 gi.require_version(f"{namespace._namespace}Unix", namespace._version)
256 return importlib.import_module(f"gi.repository.{namespace._namespace}Unix")
257
258 with suppress((ValueError, ImportError)):
259 gi.require_version(f"{namespace._namespace}Win32", namespace._version)
260 return importlib.import_module(f"gi.repository.{namespace._namespace}Win32")
261
262 return None
263
264
265 def get_fallback_platform_specific_module_symbol(
266 namespace, platform_namespace, symbol, prefix="g"
267 ):
268 """Return the original attribute and the wrapper attribute name for a
269 platform-specific symbol fallback.
270 """
271 with warnings.catch_warnings():
272 warnings.simplefilter("ignore", gi.PyGIDeprecationWarning)
273 original_attr = getattr(platform_namespace, symbol)
274 wrapper_attr = symbol
275
276 assert platform_namespace._namespace.startswith(namespace._namespace)
277 platform_name = f"{platform_namespace._namespace[len(namespace._namespace) :]}"
278 platform_name_lower = platform_name.lower()
279
280 if isinstance(
281 original_attr, CallableInfo
282 ) and original_attr.get_symbol().startswith(f"{prefix}_{platform_name_lower}_"):
283 wrapper_attr = f"{platform_name_lower}_{symbol}"
284 else:
285 try:
286 info = getattr(original_attr, "__info__")
287 type_name = info.get_type_name()
288 if not type_name or type_name.startswith(f"G{platform_name}"):
289 wrapper_attr = f"{platform_name}{symbol}"
290 except AttributeError:
291 pass
292
293 return (original_attr, wrapper_attr)