Debian Codegraph @

gi/_gtktemplate.py

raw
1 # Copyright 2015 Dustin Spicuzza <[email protected]>
2 # 2018 Nikita Churaev <[email protected]>
3 # 2018 Christoph Reiter <[email protected]>
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 os
21 from collections import abc
22 from functools import partial
23
24 from gi.repository import GLib, GObject, Gio
25
26
27 def _extract_handler_and_args(obj_or_map, handler_name):
28 handler = None
29 if isinstance(obj_or_map, abc.Mapping):
30 handler = obj_or_map.get(handler_name, None)
31 else:
32 handler = getattr(obj_or_map, handler_name, None)
33
34 if handler is None:
35 raise AttributeError(f"Handler {handler_name} not found")
36
37 args = ()
38 if isinstance(handler, abc.Sequence):
39 if len(handler) == 0:
40 raise TypeError(f"Handler {handler} tuple can not be empty")
41 args = handler[1:]
42 handler = handler[0]
43
44 elif not callable(handler):
45 raise TypeError(f"Handler {handler} is not a method, function or tuple")
46
47 return handler, args
48
49
50 def define_builder_scope():
51 from gi.repository import Gtk
52
53 class BuilderScope(GObject.GObject, Gtk.BuilderScope):
54 def __init__(self, scope_object=None):
55 super().__init__()
56 self._scope_object = scope_object
57
58 def do_create_closure(self, builder, func_name, flags, obj):
59 current_object = builder.get_current_object() or self._scope_object
60
61 if not self._scope_object:
62 current_object = builder.get_current_object()
63 if func_name not in current_object.__gtktemplate_methods__:
64 return None
65
66 current_object.__gtktemplate_handlers__.add(func_name)
67 handler_name = current_object.__gtktemplate_methods__[func_name]
68 else:
69 current_object = self._scope_object
70 handler_name = func_name
71
72 swapped = int(flags & Gtk.BuilderClosureFlags.SWAPPED)
73 if swapped:
74 raise RuntimeError(f"{GObject.ConnectFlags.SWAPPED!r} not supported")
75 return None
76
77 handler, args = _extract_handler_and_args(current_object, handler_name)
78
79 if obj:
80 p = partial(handler, *args, swap_data=obj)
81 else:
82 p = partial(handler, *args)
83
84 p.__gtk_template__ = True
85 return p
86
87 return BuilderScope
88
89
90 def connect_func(builder, obj, signal_name, handler_name, connect_object, flags, cls):
91 if handler_name not in cls.__gtktemplate_methods__:
92 return
93
94 method_name = cls.__gtktemplate_methods__[handler_name]
95 template_inst = builder.get_object(cls.__gtype_name__)
96 template_inst.__gtktemplate_handlers__.add(handler_name)
97 handler = getattr(template_inst, method_name)
98
99 after = int(flags & GObject.ConnectFlags.AFTER)
100 swapped = int(flags & GObject.ConnectFlags.SWAPPED)
101 if swapped:
102 raise RuntimeError(f"{GObject.ConnectFlags.SWAPPED!r} not supported")
103
104 if connect_object is not None:
105 func = obj.connect_object_after if after else obj.connect_object
106 func(signal_name, handler, connect_object)
107 else:
108 func = obj.connect_after if after else obj.connect
109 func(signal_name, handler)
110
111
112 def register_template(cls):
113 from gi.repository import Gtk
114
115 bound_methods = {}
116 bound_widgets = {}
117
118 for attr_name, obj in list(cls.__dict__.items()):
119 if isinstance(obj, CallThing):
120 setattr(cls, attr_name, obj._func)
121 handler_name = obj._name
122 if handler_name is None:
123 handler_name = attr_name
124
125 if handler_name in bound_methods:
126 old_attr_name = bound_methods[handler_name]
127 raise RuntimeError(
128 f"Error while exposing handler {handler_name!r} as {attr_name!r}, "
129 f"already available as {old_attr_name!r}"
130 )
131 bound_methods[handler_name] = attr_name
132 elif isinstance(obj, Child):
133 widget_name = obj._name
134 if widget_name is None:
135 widget_name = attr_name
136
137 if widget_name in bound_widgets:
138 old_attr_name = bound_widgets[widget_name]
139 raise RuntimeError(
140 f"Error while exposing child {widget_name!r} as {attr_name!r}, "
141 f"already available as {old_attr_name!r}"
142 )
143 bound_widgets[widget_name] = attr_name
144 cls.bind_template_child_full(widget_name, obj._internal, 0)
145
146 cls.__gtktemplate_methods__ = bound_methods
147 cls.__gtktemplate_widgets__ = bound_widgets
148
149 if Gtk._version == "4.0":
150 BuilderScope = define_builder_scope()
151 cls.set_template_scope(BuilderScope())
152 else:
153 cls.set_connect_func(connect_func, cls)
154
155 base_init_template = cls.init_template
156 cls.__dontuse_ginstance_init__ = lambda s: init_template(s, cls, base_init_template)
157 # To make this file work with older PyGObject we expose our init code
158 # as init_template() but make it a noop when we call it ourselves first
159 cls.init_template = cls.__dontuse_ginstance_init__
160
161
162 def init_template(self, cls, base_init_template):
163 self.init_template = lambda: None
164
165 if self.__class__ is not cls:
166 raise TypeError(
167 "Inheritance from classes with @Gtk.Template decorators "
168 "is not allowed at this time"
169 )
170
171 self.__gtktemplate_handlers__ = set()
172
173 base_init_template(self)
174
175 for widget_name, attr_name in self.__gtktemplate_widgets__.items():
176 self.__dict__[attr_name] = self.get_template_child(cls, widget_name)
177
178 for handler_name, attr_name in self.__gtktemplate_methods__.items():
179 if handler_name not in self.__gtktemplate_handlers__:
180 raise RuntimeError(
181 f"Handler '{handler_name}' was declared with @Gtk.Template.Callback "
182 "but was not present in template"
183 )
184
185
186 class Child:
187 def __init__(self, name=None, **kwargs):
188 self._name = name
189 self._internal = kwargs.pop("internal", False)
190 if kwargs:
191 raise TypeError(f"Unhandled arguments: {kwargs!r}")
192
193
194 class CallThing:
195 def __init__(self, name, func):
196 self._name = name
197 self._func = func
198
199
200 class Callback:
201 def __init__(self, name=None):
202 self._name = name
203
204 def __call__(self, func):
205 return CallThing(self._name, func)
206
207
208 def validate_resource_path(path):
209 """Raises GLib.Error in case the resource doesn't exist."""
210 try:
211 Gio.resources_get_info(path, Gio.ResourceLookupFlags.NONE)
212 except GLib.Error:
213 # resources_get_info() doesn't handle overlays but we keep using it
214 # as a fast path.
215 # https://gitlab.gnome.org/GNOME/pygobject/issues/230
216 Gio.resources_lookup_data(path, Gio.ResourceLookupFlags.NONE)
217
218
219 class Template:
220 def __init__(self, **kwargs):
221 self.string = None
222 self.filename = None
223 self.resource_path = None
224 if "string" in kwargs:
225 self.string = kwargs.pop("string")
226 elif "filename" in kwargs:
227 self.filename = kwargs.pop("filename")
228 elif "resource_path" in kwargs:
229 self.resource_path = kwargs.pop("resource_path")
230 else:
231 raise TypeError(
232 "Requires one of the following arguments: "
233 "string, filename, resource_path"
234 )
235
236 if kwargs:
237 raise TypeError(f"Unhandled keyword arguments {kwargs!r}")
238
239 @classmethod
240 def from_file(cls, filename):
241 return cls(filename=filename)
242
243 @classmethod
244 def from_string(cls, string):
245 return cls(string=string)
246
247 @classmethod
248 def from_resource(cls, resource_path):
249 return cls(resource_path=resource_path)
250
251 Callback = Callback
252
253 Child = Child
254
255 def __call__(self, cls):
256 from gi.repository import Gtk
257
258 if not isinstance(cls, type) or not issubclass(cls, Gtk.Widget):
259 raise TypeError("Can only use @Gtk.Template on Widgets")
260
261 if "__gtype_name__" not in cls.__dict__:
262 raise TypeError(
263 f"{cls.__name__!r} does not have a __gtype_name__. Set it to the name "
264 "of the class in your template"
265 )
266
267 if hasattr(cls, "__gtktemplate_methods__"):
268 raise TypeError("Cannot nest template classes")
269
270 if self.string is not None:
271 data = self.string
272 if not isinstance(data, bytes):
273 data = data.encode("utf-8")
274 bytes_ = GLib.Bytes.new(data)
275 cls.set_template(bytes_)
276 register_template(cls)
277 return cls
278 if self.resource_path is not None:
279 validate_resource_path(self.resource_path)
280 cls.set_template_from_resource(self.resource_path)
281 register_template(cls)
282 return cls
283 assert self.filename is not None
284 file_ = Gio.File.new_for_path(os.fspath(self.filename))
285 bytes_ = GLib.Bytes.new(file_.load_contents()[1])
286 cls.set_template(bytes_)
287 register_template(cls)
288 return cls
289
290
291 __all__ = ["Template"]