Debian Codegraph @

gi/_propertyhelper.py

raw
1 # pygobject - Python bindings for the GObject library
2 # Copyright (C) 2007 Johan Dahlin
3 #
4 # gi/_propertyhelper.py: GObject property wrapper/helper
5 #
6 # This library is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU Lesser General Public
8 # License as published by the Free Software Foundation; either
9 # version 2.1 of the License, or (at your option) any later version.
10 #
11 # This library is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # Lesser General Public License for more details.
15 #
16 # You should have received a copy of the GNU Lesser General Public
17 # License along with this library; if not, see <http://www.gnu.org/licenses/>.
18
19 from . import _gi
20 from ._constants import (
21 TYPE_NONE,
22 TYPE_INTERFACE,
23 TYPE_CHAR,
24 TYPE_UCHAR,
25 TYPE_BOOLEAN,
26 TYPE_INT,
27 TYPE_UINT,
28 TYPE_LONG,
29 TYPE_ULONG,
30 TYPE_INT64,
31 TYPE_UINT64,
32 TYPE_ENUM,
33 TYPE_FLAGS,
34 TYPE_FLOAT,
35 TYPE_DOUBLE,
36 TYPE_STRING,
37 TYPE_POINTER,
38 TYPE_BOXED,
39 TYPE_PARAM,
40 TYPE_OBJECT,
41 TYPE_PYOBJECT,
42 TYPE_GTYPE,
43 TYPE_STRV,
44 TYPE_VARIANT,
45 )
46
47
48 try:
49 # Only available in Python 3.8 or later.
50 from typing import get_origin
51 except ImportError:
52 from typing import _GenericAlias
53
54 def get_origin(type_: object) -> type | None:
55 """Get the unsubscripted version of a type."""
56 if isinstance(type_, _GenericAlias):
57 return type_.__origin__
58 return None
59
60
61 G_MAXFLOAT = _gi.G_MAXFLOAT
62 G_MAXDOUBLE = _gi.G_MAXDOUBLE
63 G_MININT = _gi.G_MININT
64 G_MAXINT = _gi.G_MAXINT
65 G_MAXUINT = _gi.G_MAXUINT
66 G_MINLONG = _gi.G_MINLONG
67 G_MAXLONG = _gi.G_MAXLONG
68 G_MAXULONG = _gi.G_MAXULONG
69
70
71 class Property:
72 """Creates a new Property which when used in conjunction with
73 GObject subclass will create a Python property accessor for the
74 GObject ParamSpec.
75
76 :param callable getter:
77 getter to get the value of the property
78 :param callable setter:
79 setter to set the value of the property
80 :param type type:
81 type of property
82 :param default:
83 default value, must match the property type.
84 :param str nick:
85 short description
86 :param str blurb:
87 long description
88 :param GObject.ParamFlags flags:
89 parameter flags
90 :keyword minimum:
91 minimum allowed value (int, float, long only)
92 :keyword maximum:
93 maximum allowed value (int, float, long only)
94
95 .. code-block:: python
96
97 class MyObject(GObject.Object):
98 prop = GObject.Property(type=str)
99
100
101 obj = MyObject()
102 obj.prop = "value"
103
104 obj.prop # now is 'value'
105
106 The API is similar to the builtin :py:func:`property`:
107
108 .. code-block:: python
109
110 class AnotherObject(GObject.Object):
111 value = 0
112
113 @GObject.Property
114 def prop(self):
115 "Read only property."
116 return 1
117
118 @GObject.Property(type=int)
119 def propInt(self):
120 "Read-write integer property."
121 return self.value
122
123 @propInt.setter
124 def propInt(self, value):
125 self.value = value
126 """
127
128 _type_from_pytype_lookup = {
129 int: TYPE_INT,
130 bool: TYPE_BOOLEAN,
131 float: TYPE_DOUBLE,
132 str: TYPE_STRING,
133 object: TYPE_PYOBJECT,
134 }
135
136 _min_value_lookup = {
137 TYPE_UINT: 0,
138 TYPE_ULONG: 0,
139 TYPE_UINT64: 0,
140 # Remember that G_MINFLOAT and G_MINDOUBLE are something different.
141 TYPE_FLOAT: -G_MAXFLOAT,
142 TYPE_DOUBLE: -G_MAXDOUBLE,
143 TYPE_INT: G_MININT,
144 TYPE_LONG: G_MINLONG,
145 TYPE_INT64: -(2**63),
146 }
147
148 _max_value_lookup = {
149 TYPE_UINT: G_MAXUINT,
150 TYPE_ULONG: G_MAXULONG,
151 TYPE_INT64: 2**63 - 1,
152 TYPE_UINT64: 2**64 - 1,
153 TYPE_FLOAT: G_MAXFLOAT,
154 TYPE_DOUBLE: G_MAXDOUBLE,
155 TYPE_INT: G_MAXINT,
156 TYPE_LONG: G_MAXLONG,
157 }
158
159 _default_lookup = {
160 TYPE_INT: 0,
161 TYPE_UINT: 0,
162 TYPE_LONG: 0,
163 TYPE_ULONG: 0,
164 TYPE_INT64: 0,
165 TYPE_UINT64: 0,
166 TYPE_STRING: "",
167 TYPE_FLOAT: 0.0,
168 TYPE_DOUBLE: 0.0,
169 }
170
171 class __metaclass__(type):
172 def __repr__(self):
173 return "<class 'GObject.Property'>"
174
175 def __init__(
176 self,
177 getter=None,
178 setter=None,
179 type=None,
180 default=None,
181 nick="",
182 blurb="",
183 flags=_gi.PARAM_READWRITE,
184 minimum=None,
185 maximum=None,
186 ):
187 self.name = None
188
189 if type is None:
190 type = object
191 self.type = self._type_from_python(type)
192 self.default = self._get_default(default)
193 self._check_default()
194
195 if not isinstance(nick, str):
196 raise TypeError("nick must be a string")
197 self.nick = nick
198
199 if not isinstance(blurb, str):
200 raise TypeError("blurb must be a string")
201 self.blurb = blurb
202 # Always clobber __doc__ with blurb even if blurb is empty because
203 # we don't want the lengthy Property class documentation showing up
204 # on instances.
205 self.__doc__ = blurb
206 self.flags = flags
207
208 # Call after setting blurb for potential __doc__ usage.
209 if getter and not setter:
210 setter = self._readonly_setter
211 elif setter and not getter:
212 getter = self._writeonly_getter
213 elif not setter and not getter:
214 getter = self._default_getter
215 setter = self._default_setter
216 self.getter(getter)
217 # do not call self.setter() here, as this defines the property name
218 # already
219 self.fset = setter
220
221 if minimum is not None:
222 if minimum < self._get_minimum():
223 msg = f"Minimum for type {self.type:s} cannot be lower than {self._get_minimum():d}"
224 raise TypeError(msg)
225 else:
226 minimum = self._get_minimum()
227 self.minimum = minimum
228 if maximum is not None:
229 if maximum > self._get_maximum():
230 msg = f"Maximum for type {self.type:s} cannot be higher than {self._get_maximum():d}"
231 raise TypeError(msg)
232 else:
233 maximum = self._get_maximum()
234 self.maximum = maximum
235
236 self._exc = None
237
238 def __repr__(self):
239 return f"<GObject Property {self.name or '(uninitialized)'} ({self.type.name})>"
240
241 def __get__(self, instance, klass):
242 if instance is None:
243 return self
244
245 self._exc = None
246 value = self.fget(instance)
247 if self._exc:
248 exc = self._exc
249 self._exc = None
250 raise exc
251
252 return value
253
254 def __set__(self, instance, value):
255 if instance is None:
256 raise TypeError
257
258 self._exc = None
259 instance.set_property(self.name, value)
260 if self._exc:
261 exc = self._exc
262 self._exc = None
263 raise exc
264
265 def __call__(self, fget):
266 """Allows application of the getter along with init arguments."""
267 return self.getter(fget)
268
269 def getter(self, fget):
270 """Set the getter function to fget. For use as a decorator."""
271 if fget.__doc__:
272 # Always clobber docstring and blurb with the getter docstring.
273 self.blurb = fget.__doc__
274 self.__doc__ = fget.__doc__
275 self.fget = fget
276 return self
277
278 def setter(self, fset):
279 """Set the setter function to fset. For use as a decorator."""
280 self.fset = fset
281 # with a setter decorator, we must ignore the name of the method in
282 # install_properties, as this does not need to be a valid property name
283 # and does not define the property name. So set the name here.
284 if not self.name:
285 self.name = self.fget.__name__
286 return self
287
288 def _type_from_python(self, type_):
289 if type_ in self._type_from_pytype_lookup:
290 return self._type_from_pytype_lookup[type_]
291
292 # Support instances of generic types such as Gio.ListStore[Gio.File]
293 origin = get_origin(type_)
294 if origin is not None:
295 type_ = origin
296
297 if isinstance(type_, type) and issubclass(
298 type_, (_gi.GObject, _gi.GEnum, _gi.GFlags, _gi.GBoxed, _gi.GInterface)
299 ):
300 return type_.__gtype__
301 if type_ in (
302 TYPE_NONE,
303 TYPE_INTERFACE,
304 TYPE_CHAR,
305 TYPE_UCHAR,
306 TYPE_INT,
307 TYPE_UINT,
308 TYPE_BOOLEAN,
309 TYPE_LONG,
310 TYPE_ULONG,
311 TYPE_INT64,
312 TYPE_UINT64,
313 TYPE_FLOAT,
314 TYPE_DOUBLE,
315 TYPE_POINTER,
316 TYPE_BOXED,
317 TYPE_PARAM,
318 TYPE_OBJECT,
319 TYPE_STRING,
320 TYPE_PYOBJECT,
321 TYPE_GTYPE,
322 TYPE_STRV,
323 TYPE_VARIANT,
324 ):
325 return type_
326 raise TypeError(f"Unsupported type: {type_!r}")
327
328 def _get_default(self, default):
329 if default is not None:
330 return default
331 return self._default_lookup.get(self.type, None)
332
333 def _check_default(self):
334 ptype = self.type
335 default = self.default
336 if ptype == TYPE_BOOLEAN and (default not in (True, False)):
337 raise TypeError(f"default must be True or False, not {default!r}")
338 if ptype == TYPE_PYOBJECT:
339 if default is not None:
340 raise TypeError("object types does not have default values")
341 elif ptype == TYPE_GTYPE:
342 if default is not None:
343 raise TypeError("GType types does not have default values")
344 elif ptype.is_a(TYPE_ENUM):
345 if default is None:
346 raise TypeError("enum properties needs a default value")
347 if not _gi.GType(default).is_a(ptype):
348 raise TypeError(
349 f"enum value {default} must be an instance of {ptype!r}"
350 )
351 elif ptype.is_a(TYPE_FLAGS):
352 if not _gi.GType(default).is_a(ptype):
353 raise TypeError(
354 f"flags value {default} must be an instance of {ptype!r}"
355 )
356 elif ptype.is_a(TYPE_STRV) and default is not None:
357 if not isinstance(default, list):
358 raise TypeError(f"Strv value {default!r} must be a list")
359 for val in default:
360 if type(val) not in (str, bytes):
361 raise TypeError(f"Strv value {default!s} must contain only strings")
362 elif (
363 ptype.is_a(TYPE_VARIANT)
364 and default is not None
365 and (
366 not hasattr(default, "__gtype__")
367 or not _gi.GType(default).is_a(TYPE_VARIANT)
368 )
369 ):
370 raise TypeError(f"variant value {default} must be an instance of {ptype!r}")
371
372 def _get_minimum(self):
373 return self._min_value_lookup.get(self.type, None)
374
375 def _get_maximum(self):
376 return self._max_value_lookup.get(self.type, None)
377
378 #
379 # Getter and Setter
380 #
381
382 def _default_setter(self, instance, value):
383 setattr(instance, "_property_helper_" + self.name, value)
384
385 def _default_getter(self, instance):
386 return getattr(instance, "_property_helper_" + self.name, self.default)
387
388 def _readonly_setter(self, instance, value):
389 self._exc = TypeError(
390 f"{self.name} property of {type(instance).__name__} is read-only"
391 )
392
393 def _writeonly_getter(self, instance):
394 self._exc = TypeError(
395 f"{self.name} property of {type(instance).__name__} is write-only"
396 )
397
398 #
399 # Public API
400 #
401
402 def get_pspec_args(self):
403 ptype = self.type
404 if ptype in (
405 TYPE_INT,
406 TYPE_UINT,
407 TYPE_LONG,
408 TYPE_ULONG,
409 TYPE_INT64,
410 TYPE_UINT64,
411 TYPE_FLOAT,
412 TYPE_DOUBLE,
413 ):
414 args = self.minimum, self.maximum, self.default
415 elif (
416 ptype in (TYPE_STRING, TYPE_BOOLEAN)
417 or ptype.is_a(TYPE_ENUM)
418 or ptype.is_a(TYPE_FLAGS)
419 or ptype.is_a(TYPE_VARIANT)
420 ):
421 args = (self.default,)
422 elif (
423 ptype in (TYPE_PYOBJECT, TYPE_GTYPE)
424 or ptype.is_a(TYPE_OBJECT)
425 or ptype.is_a(TYPE_BOXED)
426 ):
427 args = ()
428 else:
429 raise NotImplementedError(ptype)
430
431 return (self.type, self.nick, self.blurb, *args, self.flags)
432
433
434 def install_properties(cls):
435 """Scans the given class for instances of Property and merges them
436 into the classes __gproperties__ dict if it exists or adds it if not.
437 """
438 gproperties = cls.__dict__.get("__gproperties__", {})
439
440 props = []
441 for name, prop in cls.__dict__.items():
442 if isinstance(prop, Property): # not same as the built-in
443 # if a property was defined with a decorator, it may already have
444 # a name; if it was defined with an assignment (prop = Property(...))
445 # we set the property's name to the member name
446 if not prop.name:
447 prop.name = name
448 # we will encounter the same property multiple times in case of
449 # custom setter methods
450 if prop.name in gproperties:
451 if gproperties[prop.name] == prop.get_pspec_args():
452 continue
453 raise ValueError(
454 f"Property {prop.name} was already found in __gproperties__"
455 )
456 gproperties[prop.name] = prop.get_pspec_args()
457 props.append(prop)
458
459 if not props:
460 return
461
462 cls.__gproperties__ = gproperties
463
464 if "do_get_property" in cls.__dict__ or "do_set_property" in cls.__dict__:
465 for prop in props:
466 if prop.fget != prop._default_getter or prop.fset != prop._default_setter:
467 raise TypeError(
468 f"GObject subclass {cls.__name__!r} defines do_get/set_property"
469 " and it also uses a property with a custom setter"
470 " or getter. This is not allowed"
471 )
472
473 def obj_get_property(self, pspec):
474 name = pspec.name.replace("-", "_")
475 return getattr(self, name, None)
476
477 cls.do_get_property = obj_get_property
478
479 def obj_set_property(self, pspec, value):
480 name = pspec.name.replace("-", "_")
481 prop = getattr(cls, name, None)
482 if prop:
483 prop.fset(self, value)
484
485 cls.do_set_property = obj_set_property