module.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. # -*- Mode: Python; py-indent-offset: 4 -*-
  2. # vim: tabstop=4 shiftwidth=4 expandtab
  3. #
  4. # Copyright (C) 2007-2009 Johan Dahlin <johan@gnome.org>
  5. #
  6. # module.py: dynamic module for introspected libraries.
  7. #
  8. # This library is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU Lesser General Public
  10. # License as published by the Free Software Foundation; either
  11. # version 2.1 of the License, or (at your option) any later version.
  12. #
  13. # This library is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. # Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public
  19. # License along with this library; if not, write to the Free Software
  20. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
  21. # USA
  22. from __future__ import absolute_import
  23. import sys
  24. import importlib
  25. _have_py3 = (sys.version_info[0] >= 3)
  26. try:
  27. maketrans = ''.maketrans
  28. except AttributeError:
  29. # fallback for Python 2
  30. from string import maketrans
  31. import gi
  32. from ._gi import \
  33. Repository, \
  34. FunctionInfo, \
  35. RegisteredTypeInfo, \
  36. EnumInfo, \
  37. ObjectInfo, \
  38. InterfaceInfo, \
  39. ConstantInfo, \
  40. StructInfo, \
  41. UnionInfo, \
  42. CallbackInfo, \
  43. Struct, \
  44. Boxed, \
  45. CCallback, \
  46. enum_add, \
  47. enum_register_new_gtype_and_add, \
  48. flags_add, \
  49. flags_register_new_gtype_and_add, \
  50. _gobject
  51. from .types import \
  52. GObjectMeta, \
  53. StructMeta
  54. GInterface = _gobject.GInterface
  55. from ._constants import \
  56. TYPE_NONE, \
  57. TYPE_BOXED, \
  58. TYPE_POINTER, \
  59. TYPE_ENUM, \
  60. TYPE_FLAGS
  61. repository = Repository.get_default()
  62. # Cache of IntrospectionModules that have been loaded.
  63. _introspection_modules = {}
  64. def get_parent_for_object(object_info):
  65. parent_object_info = object_info.get_parent()
  66. if not parent_object_info:
  67. # If we reach the end of the introspection info class hierarchy, look
  68. # for an existing wrapper on the GType and use it as a base for the
  69. # new introspection wrapper. This allows static C wrappers already
  70. # registered with the GType to be used as the introspection base
  71. # (_gobject.GObject for example)
  72. gtype = object_info.get_g_type()
  73. if gtype and gtype.pytype:
  74. return gtype.pytype
  75. # Otherwise use builtins.object as the base
  76. return object
  77. namespace = parent_object_info.get_namespace()
  78. name = parent_object_info.get_name()
  79. module = importlib.import_module('gi.repository.' + namespace)
  80. return getattr(module, name)
  81. def get_interfaces_for_object(object_info):
  82. interfaces = []
  83. for interface_info in object_info.get_interfaces():
  84. namespace = interface_info.get_namespace()
  85. name = interface_info.get_name()
  86. module = importlib.import_module('gi.repository.' + namespace)
  87. interfaces.append(getattr(module, name))
  88. return interfaces
  89. class IntrospectionModule(object):
  90. """An object which wraps an introspection typelib.
  91. This wrapping creates a python module like representation of the typelib
  92. using gi repository as a foundation. Accessing attributes of the module
  93. will dynamically pull them in and create wrappers for the members.
  94. These members are then cached on this introspection module.
  95. """
  96. def __init__(self, namespace, version=None):
  97. """Might raise gi._gi.RepositoryError"""
  98. repository.require(namespace, version)
  99. self._namespace = namespace
  100. self._version = version
  101. self.__name__ = 'gi.repository.' + namespace
  102. self.__path__ = repository.get_typelib_path(self._namespace)
  103. if _have_py3:
  104. # get_typelib_path() delivers bytes, not a string
  105. self.__path__ = self.__path__.decode('UTF-8')
  106. if self._version is None:
  107. self._version = repository.get_version(self._namespace)
  108. def __getattr__(self, name):
  109. info = repository.find_by_name(self._namespace, name)
  110. if not info:
  111. raise AttributeError("%r object has no attribute %r" % (
  112. self.__name__, name))
  113. if isinstance(info, EnumInfo):
  114. g_type = info.get_g_type()
  115. wrapper = g_type.pytype
  116. if wrapper is None:
  117. if info.is_flags():
  118. if g_type.is_a(TYPE_FLAGS):
  119. wrapper = flags_add(g_type)
  120. else:
  121. assert g_type == TYPE_NONE
  122. wrapper = flags_register_new_gtype_and_add(info)
  123. else:
  124. if g_type.is_a(TYPE_ENUM):
  125. wrapper = enum_add(g_type)
  126. else:
  127. assert g_type == TYPE_NONE
  128. wrapper = enum_register_new_gtype_and_add(info)
  129. wrapper.__info__ = info
  130. wrapper.__module__ = 'gi.repository.' + info.get_namespace()
  131. # Don't use upper() here to avoid locale specific
  132. # identifier conversion (e. g. in Turkish 'i'.upper() == 'i')
  133. # see https://bugzilla.gnome.org/show_bug.cgi?id=649165
  134. ascii_upper_trans = maketrans(
  135. 'abcdefgjhijklmnopqrstuvwxyz',
  136. 'ABCDEFGJHIJKLMNOPQRSTUVWXYZ')
  137. for value_info in info.get_values():
  138. value_name = value_info.get_name_unescaped().translate(ascii_upper_trans)
  139. setattr(wrapper, value_name, wrapper(value_info.get_value()))
  140. for method_info in info.get_methods():
  141. setattr(wrapper, method_info.__name__, method_info)
  142. if g_type != TYPE_NONE:
  143. g_type.pytype = wrapper
  144. elif isinstance(info, RegisteredTypeInfo):
  145. g_type = info.get_g_type()
  146. # Create a wrapper.
  147. if isinstance(info, ObjectInfo):
  148. parent = get_parent_for_object(info)
  149. interfaces = tuple(interface for interface in get_interfaces_for_object(info)
  150. if not issubclass(parent, interface))
  151. bases = (parent,) + interfaces
  152. metaclass = GObjectMeta
  153. elif isinstance(info, CallbackInfo):
  154. bases = (CCallback,)
  155. metaclass = GObjectMeta
  156. elif isinstance(info, InterfaceInfo):
  157. bases = (GInterface,)
  158. metaclass = GObjectMeta
  159. elif isinstance(info, (StructInfo, UnionInfo)):
  160. if g_type.is_a(TYPE_BOXED):
  161. bases = (Boxed,)
  162. elif (g_type.is_a(TYPE_POINTER) or
  163. g_type == TYPE_NONE or
  164. g_type.fundamental == g_type):
  165. bases = (Struct,)
  166. else:
  167. raise TypeError("unable to create a wrapper for %s.%s" % (info.get_namespace(), info.get_name()))
  168. metaclass = StructMeta
  169. else:
  170. raise NotImplementedError(info)
  171. # Check if there is already a Python wrapper that is not a parent class
  172. # of the wrapper being created. If it is a parent, it is ok to clobber
  173. # g_type.pytype with a new child class wrapper of the existing parent.
  174. # Note that the return here never occurs under normal circumstances due
  175. # to caching on the __dict__ itself.
  176. if g_type != TYPE_NONE:
  177. type_ = g_type.pytype
  178. if type_ is not None and type_ not in bases:
  179. self.__dict__[name] = type_
  180. return type_
  181. dict_ = {
  182. '__info__': info,
  183. '__module__': 'gi.repository.' + self._namespace,
  184. '__gtype__': g_type
  185. }
  186. wrapper = metaclass(name, bases, dict_)
  187. # Register the new Python wrapper.
  188. if g_type != TYPE_NONE:
  189. g_type.pytype = wrapper
  190. elif isinstance(info, FunctionInfo):
  191. wrapper = info
  192. elif isinstance(info, ConstantInfo):
  193. wrapper = info.get_value()
  194. else:
  195. raise NotImplementedError(info)
  196. # Cache the newly created wrapper which will then be
  197. # available directly on this introspection module instead of being
  198. # lazily constructed through the __getattr__ we are currently in.
  199. self.__dict__[name] = wrapper
  200. return wrapper
  201. def __repr__(self):
  202. path = repository.get_typelib_path(self._namespace)
  203. if _have_py3:
  204. # get_typelib_path() delivers bytes, not a string
  205. path = path.decode('UTF-8')
  206. return "<IntrospectionModule %r from %r>" % (self._namespace, path)
  207. def __dir__(self):
  208. # Python's default dir() is just dir(self.__class__) + self.__dict__.keys()
  209. result = set(dir(self.__class__))
  210. result.update(self.__dict__.keys())
  211. # update *set* because some repository attributes have already been
  212. # wrapped by __getattr__() and included in self.__dict__; but skip
  213. # Callback types, as these are not real objects which we can actually
  214. # get
  215. namespace_infos = repository.get_infos(self._namespace)
  216. result.update(info.get_name() for info in namespace_infos if
  217. not isinstance(info, CallbackInfo))
  218. return list(result)
  219. def get_introspection_module(namespace):
  220. """
  221. :Returns:
  222. An object directly wrapping the gi module without overrides.
  223. Might raise gi._gi.RepositoryError
  224. """
  225. if namespace in _introspection_modules:
  226. return _introspection_modules[namespace]
  227. version = gi.get_required_version(namespace)
  228. module = IntrospectionModule(namespace, version)
  229. _introspection_modules[namespace] = module
  230. return module