Debian Codegraph @

gi/__init__.py

raw
1 # Copyright (C) 2005-2009 Johan Dahlin <[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 # support overrides in different directories than our gi module
19 from pkgutil import extend_path
20
21 __path__ = extend_path(__path__, __name__)
22
23 import sys
24 import os
25 import importlib
26 import types
27
28 _static_binding_error = (
29 "When using gi.repository you must not import static "
30 'modules like "gobject". Please change all occurrences '
31 'of "import gobject" to "from gi.repository import GObject". '
32 "See: https://bugzilla.gnome.org/show_bug.cgi?id=709183"
33 )
34
35 # we can't have pygobject 2 loaded at the same time we load the internal _gobject
36 if "gobject" in sys.modules:
37 raise ImportError(_static_binding_error)
38
39
40 from . import _gi
41 from ._gi import _API as _API
42 from ._gi import Repository
43 from ._gi import PyGIDeprecationWarning # noqa: F401
44 from ._gi import PyGIWarning # noqa: F401
45
46 _versions = {}
47 _overridesdir = os.path.join(os.path.dirname(__file__), "overrides")
48
49 # Needed for compatibility with "pygobject.h"/pygobject_init()
50 _gobject = types.ModuleType("gi._gobject")
51 sys.modules[_gobject.__name__] = _gobject
52 _gobject._PyGObject_API = _gi._PyGObject_API
53 _gobject.pygobject_version = _gi.pygobject_version
54
55 version_info = _gi.pygobject_version[:]
56 __version__ = "{}.{}.{}".format(*version_info)
57
58 _gi.register_foreign()
59
60 # Options which can be enabled or disabled after importing 'gi'. This may affect
61 # repository imports or binding machinery in a backwards incompatible way.
62 _options = {
63 # When True, importing Gtk or Gdk will call Gtk.init() or Gdk.init() respectively.
64 "legacy_autoinit": True,
65 }
66
67
68 class OverrideImport:
69 def __init__(self, overrides_path):
70 self.overrides_path = overrides_path
71
72 def find_spec(self, fullname, path, target=None):
73 if not fullname.startswith("gi.overrides"):
74 return None
75 finder = importlib.machinery.PathFinder()
76 # From find_spec the docs:
77 # If name is for a submodule (contains a dot), the parent module is automatically imported.
78 return finder.find_spec(fullname, self.overrides_path)
79
80
81 _pgi_overrides_path = os.environ.get("PYGI_OVERRIDES_PATH", "")
82 if _pgi_overrides_path:
83 sys.meta_path.insert(0, OverrideImport(_pgi_overrides_path.split(os.pathsep)))
84
85
86 class _DummyStaticModule(types.ModuleType):
87 __path__ = None
88
89 def __getattr__(self, name):
90 raise AttributeError(_static_binding_error)
91
92
93 sys.modules["glib"] = _DummyStaticModule("glib", _static_binding_error)
94 sys.modules["gobject"] = _DummyStaticModule("gobject", _static_binding_error)
95 sys.modules["gio"] = _DummyStaticModule("gio", _static_binding_error)
96 sys.modules["gtk"] = _DummyStaticModule("gtk", _static_binding_error)
97 sys.modules["gtk.gdk"] = _DummyStaticModule("gtk.gdk", _static_binding_error)
98
99
100 def check_version(version):
101 if isinstance(version, str):
102 version_list = tuple(map(int, version.split(".")))
103 else:
104 version_list = version
105
106 if version_list > version_info:
107 raise ValueError(
108 f"pygobject's version {version} required, and available version "
109 f"{__version__} is not recent enough"
110 )
111
112
113 def require_version(namespace, version):
114 """Ensures the correct versions are loaded when importing `gi` modules.
115
116 :param namespace: The name of module to require.
117 :type namespace: str
118 :param version: The version of module to require.
119 :type version: str
120 :raises ValueError: If module/version is already loaded, already required, or unavailable.
121
122 :Example:
123
124 .. code-block:: python
125
126 import gi
127
128 gi.require_version("Gtk", "3.0")
129
130 """
131 repository = Repository.get_default()
132
133 if not isinstance(version, str):
134 raise ValueError("Namespace version needs to be a string.")
135
136 if namespace in repository.get_loaded_namespaces():
137 loaded_version = repository.get_version(namespace)
138 if loaded_version != version:
139 raise ValueError(
140 f"Namespace {namespace} is already loaded with version {loaded_version}"
141 )
142
143 if namespace in _versions and _versions[namespace] != version:
144 raise ValueError(
145 f"Namespace {namespace} already requires version {_versions[namespace]}"
146 )
147
148 available_versions = repository.enumerate_versions(namespace)
149 if not available_versions:
150 raise ValueError(f"Namespace {namespace} not available")
151
152 if version not in available_versions:
153 raise ValueError(f"Namespace {namespace} not available for version {version}")
154
155 _versions[namespace] = version
156
157
158 def require_versions(requires):
159 """Utility function for consolidating multiple `gi.require_version()` calls.
160
161 :param requires: The names and versions of modules to require.
162 :type requires: dict
163
164 :Example:
165
166 .. code-block:: python
167
168 import gi
169
170 gi.require_versions({"Gtk": "3.0", "GLib": "2.0", "Gio": "2.0"})
171 """
172 for module_name, module_version in requires.items():
173 require_version(module_name, module_version)
174
175
176 def get_required_version(namespace):
177 return _versions.get(namespace)
178
179
180 def require_foreign(namespace, symbol=None):
181 """Ensure the given foreign marshaling module is available and loaded.
182
183 :param str namespace:
184 Introspection namespace of the foreign module (e.g. "cairo")
185 :param symbol:
186 Optional symbol typename to ensure a converter exists.
187 :type symbol: str or None
188 :raises: ImportError
189
190 :Example:
191
192 .. code-block:: python
193
194 import gi
195 import cairo
196
197 gi.require_foreign("cairo")
198
199 """
200 try:
201 _gi.require_foreign(namespace, symbol)
202 except Exception as e:
203 raise ImportError(str(e))
204 importlib.import_module("gi.repository", namespace)
205
206
207 def get_option(name):
208 """Get option by name.
209
210 :param str name:
211 Name of the option.
212 """
213 return _options.get(name)
214
215
216 def disable_legacy_autoinit():
217 """Disable the legacy initialization of Gdk and Gtk.
218
219 These modules are automatically initialized on import from `gi.repository`.
220 This is not required, and was only kept for backwards compatibility reason.
221 This behavior may eventually be dropped for future Gtk major releases.
222
223 Usually, users should not manually perform these initializations but let
224 e.g. `Gtk.Application` manage it when needed.
225 """
226 _options["legacy_autoinit"] = False