Imported Upstream version 3.7.3
[platform/upstream/python-gobject.git] / gi / _gobject / propertyhelper.py
1 # -*- Mode: Python; py-indent-offset: 4 -*-
2 # pygobject - Python bindings for the GObject library
3 # Copyright (C) 2007 Johan Dahlin
4 #
5 #   gobject/propertyhelper.py: GObject property wrapper/helper
6 #
7 # This library is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU Lesser General Public
9 # License as published by the Free Software Foundation; either
10 # version 2.1 of the License, or (at your option) any later version.
11 #
12 # This library is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 # Lesser General Public License for more details.
16 #
17 # You should have received a copy of the GNU Lesser General Public
18 # License along with this library; if not, write to the Free Software
19 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
20 # USA
21
22 import sys
23
24 from . import _gobject
25
26 from .constants import \
27     TYPE_NONE, TYPE_INTERFACE, TYPE_CHAR, TYPE_UCHAR, \
28     TYPE_BOOLEAN, TYPE_INT, TYPE_UINT, TYPE_LONG, \
29     TYPE_ULONG, TYPE_INT64, TYPE_UINT64, TYPE_ENUM, TYPE_FLAGS, \
30     TYPE_FLOAT, TYPE_DOUBLE, TYPE_STRING, \
31     TYPE_POINTER, TYPE_BOXED, TYPE_PARAM, TYPE_OBJECT, \
32     TYPE_PYOBJECT, TYPE_GTYPE, TYPE_STRV, TYPE_VARIANT
33 from ._gobject import \
34     G_MAXFLOAT, G_MAXDOUBLE, \
35     G_MININT, G_MAXINT, G_MAXUINT, G_MINLONG, G_MAXLONG, \
36     G_MAXULONG
37
38 if sys.version_info >= (3, 0):
39     _basestring = str
40     _long = int
41 else:
42     _basestring = basestring
43     _long = long
44
45
46 class Property(object):
47     """
48     Creates a new property which in conjunction with GObject subclass will
49     create a property proxy:
50
51     >>> class MyObject(GObject.GObject):
52     >>> ... prop = GObject.Property(type=str)
53
54     >>> obj = MyObject()
55     >>> obj.prop = 'value'
56
57     >>> obj.prop
58     'value'
59
60     The API is similar to the builtin property:
61
62     class AnotherObject(GObject.GObject):
63         @GObject.Property
64         def prop(self):
65             '''Read only property.'''
66             return ...
67
68         @GObject.Property(type=int)
69         def propInt(self):
70             '''Read-write integer property.'''
71             return ...
72
73         @propInt.setter
74         def propInt(self, value):
75             ...
76     """
77     _type_from_pytype_lookup = {
78         # Put long_ first in case long_ and int are the same so int clobbers long_
79         _long: TYPE_LONG,
80         int: TYPE_INT,
81         bool: TYPE_BOOLEAN,
82         float: TYPE_DOUBLE,
83         str: TYPE_STRING,
84         object: TYPE_PYOBJECT,
85     }
86
87     _min_value_lookup = {
88         TYPE_UINT: 0,
89         TYPE_ULONG: 0,
90         TYPE_UINT64: 0,
91         # Remember that G_MINFLOAT and G_MINDOUBLE are something different.
92         TYPE_FLOAT: -G_MAXFLOAT,
93         TYPE_DOUBLE: -G_MAXDOUBLE,
94         TYPE_INT: G_MININT,
95         TYPE_LONG: G_MINLONG,
96         TYPE_INT64: -2 ** 63,
97     }
98
99     _max_value_lookup = {
100         TYPE_UINT: G_MAXUINT,
101         TYPE_ULONG: G_MAXULONG,
102         TYPE_INT64: 2 ** 63 - 1,
103         TYPE_UINT64: 2 ** 64 - 1,
104         TYPE_FLOAT: G_MAXFLOAT,
105         TYPE_DOUBLE: G_MAXDOUBLE,
106         TYPE_INT: G_MAXINT,
107         TYPE_LONG: G_MAXLONG,
108     }
109
110     _default_lookup = {
111         TYPE_INT: 0,
112         TYPE_UINT: 0,
113         TYPE_LONG: 0,
114         TYPE_ULONG: 0,
115         TYPE_INT64: 0,
116         TYPE_UINT64: 0,
117         TYPE_STRING: '',
118         TYPE_FLOAT: 0.0,
119         TYPE_DOUBLE: 0.0,
120     }
121
122     class __metaclass__(type):
123         def __repr__(self):
124             return "<class 'GObject.Property'>"
125
126     def __init__(self, getter=None, setter=None, type=None, default=None,
127                  nick='', blurb='', flags=_gobject.PARAM_READWRITE,
128                  minimum=None, maximum=None):
129         """
130         @param  getter: getter to get the value of the property
131         @type   getter: callable
132         @param  setter: setter to set the value of the property
133         @type   setter: callable
134         @param    type: type of property
135         @type     type: type
136         @param default: default value
137         @param    nick: short description
138         @type     nick: string
139         @param   blurb: long description
140         @type    blurb: string
141         @param flags:    parameter flags, one of:
142         - gobject.PARAM_READABLE
143         - gobject.PARAM_READWRITE
144         - gobject.PARAM_WRITABLE
145         - gobject.PARAM_CONSTRUCT
146         - gobject.PARAM_CONSTRUCT_ONLY
147         - gobject.PARAM_LAX_VALIDATION
148         @keyword minimum:  minimum allowed value (int, float, long only)
149         @keyword maximum:  maximum allowed value (int, float, long only)
150         """
151
152         if type is None:
153             type = object
154         self.type = self._type_from_python(type)
155         self.default = self._get_default(default)
156         self._check_default()
157
158         if not isinstance(nick, _basestring):
159             raise TypeError("nick must be a string")
160         self.nick = nick
161
162         if not isinstance(blurb, _basestring):
163             raise TypeError("blurb must be a string")
164         self.blurb = blurb
165         # Always clobber __doc__ with blurb even if blurb is empty because
166         # we don't want the lengthy Property class documentation showing up
167         # on instances.
168         self.__doc__ = blurb
169
170         if flags < 0 or flags > 32:
171             raise TypeError("invalid flag value: %r" % (flags,))
172         self.flags = flags
173
174         # Call after setting blurb for potential __doc__ usage.
175         if getter and not setter:
176             setter = self._readonly_setter
177         elif setter and not getter:
178             getter = self._writeonly_getter
179         elif not setter and not getter:
180             getter = self._default_getter
181             setter = self._default_setter
182         self.getter(getter)
183         self.setter(setter)
184
185         if minimum is not None:
186             if minimum < self._get_minimum():
187                 raise TypeError(
188                     "Minimum for type %s cannot be lower than %d" % (
189                     self.type, self._get_minimum()))
190         else:
191             minimum = self._get_minimum()
192         self.minimum = minimum
193         if maximum is not None:
194             if maximum > self._get_maximum():
195                 raise TypeError(
196                     "Maximum for type %s cannot be higher than %d" % (
197                     self.type, self._get_maximum()))
198         else:
199             maximum = self._get_maximum()
200         self.maximum = maximum
201
202         self.name = None
203
204         self._exc = None
205
206     def __repr__(self):
207         return '<GObject Property %s (%s)>' % (
208             self.name or '(uninitialized)',
209             _gobject.type_name(self.type))
210
211     def __get__(self, instance, klass):
212         if instance is None:
213             return self
214
215         self._exc = None
216         value = instance.get_property(self.name)
217         if self._exc:
218             exc = self._exc
219             self._exc = None
220             raise exc
221
222         return value
223
224     def __set__(self, instance, value):
225         if instance is None:
226             raise TypeError
227
228         self._exc = None
229         instance.set_property(self.name, value)
230         if self._exc:
231             exc = self._exc
232             self._exc = None
233             raise exc
234
235     def __call__(self, fget):
236         """Allows application of the getter along with init arguments."""
237         return self.getter(fget)
238
239     def getter(self, fget):
240         """Set the getter function to fget. For use as a decorator."""
241         if fget.__doc__:
242             # Always clobber docstring and blurb with the getter docstring.
243             self.blurb = fget.__doc__
244             self.__doc__ = fget.__doc__
245         self.fget = fget
246         return self
247
248     def setter(self, fset):
249         """Set the setter function to fset. For use as a decorator."""
250         self.fset = fset
251         return self
252
253     def _type_from_python(self, type_):
254         if type_ in self._type_from_pytype_lookup:
255             return self._type_from_pytype_lookup[type_]
256         elif (isinstance(type_, type) and
257               issubclass(type_, (_gobject.GObject,
258                                  _gobject.GEnum,
259                                  _gobject.GFlags,
260                                  _gobject.GBoxed))):
261             return type_.__gtype__
262         elif type_ in (TYPE_NONE, TYPE_INTERFACE, TYPE_CHAR, TYPE_UCHAR,
263                        TYPE_INT, TYPE_UINT, TYPE_BOOLEAN, TYPE_LONG,
264                        TYPE_ULONG, TYPE_INT64, TYPE_UINT64,
265                        TYPE_FLOAT, TYPE_DOUBLE, TYPE_POINTER,
266                        TYPE_BOXED, TYPE_PARAM, TYPE_OBJECT, TYPE_STRING,
267                        TYPE_PYOBJECT, TYPE_GTYPE, TYPE_STRV, TYPE_VARIANT):
268             return type_
269         else:
270             raise TypeError("Unsupported type: %r" % (type_,))
271
272     def _get_default(self, default):
273         if default is not None:
274             return default
275         return self._default_lookup.get(self.type, None)
276
277     def _check_default(self):
278         ptype = self.type
279         default = self.default
280         if (ptype == TYPE_BOOLEAN and (default not in (True, False))):
281             raise TypeError(
282                 "default must be True or False, not %r" % (default,))
283         elif ptype == TYPE_PYOBJECT:
284             if default is not None:
285                 raise TypeError("object types does not have default values")
286         elif ptype == TYPE_GTYPE:
287             if default is not None:
288                 raise TypeError("GType types does not have default values")
289         elif _gobject.type_is_a(ptype, TYPE_ENUM):
290             if default is None:
291                 raise TypeError("enum properties needs a default value")
292             elif not _gobject.type_is_a(default, ptype):
293                 raise TypeError("enum value %s must be an instance of %r" %
294                                 (default, ptype))
295         elif _gobject.type_is_a(ptype, TYPE_FLAGS):
296             if not _gobject.type_is_a(default, ptype):
297                 raise TypeError("flags value %s must be an instance of %r" %
298                                 (default, ptype))
299         elif _gobject.type_is_a(ptype, TYPE_STRV) and default is not None:
300             if not isinstance(default, list):
301                 raise TypeError("Strv value %s must be a list" % repr(default))
302             for val in default:
303                 if type(val) not in (str, bytes):
304                     raise TypeError("Strv value %s must contain only strings" % str(default))
305         elif _gobject.type_is_a(ptype, TYPE_VARIANT) and default is not None:
306             if not hasattr(default, '__gtype__') or not _gobject.type_is_a(default, TYPE_VARIANT):
307                 raise TypeError("variant value %s must be an instance of %r" %
308                                 (default, ptype))
309
310     def _get_minimum(self):
311         return self._min_value_lookup.get(self.type, None)
312
313     def _get_maximum(self):
314         return self._max_value_lookup.get(self.type, None)
315
316     #
317     # Getter and Setter
318     #
319
320     def _default_setter(self, instance, value):
321         setattr(instance, '_property_helper_' + self.name, value)
322
323     def _default_getter(self, instance):
324         return getattr(instance, '_property_helper_' + self.name, self.default)
325
326     def _readonly_setter(self, instance, value):
327         self._exc = TypeError("%s property of %s is read-only" % (
328             self.name, type(instance).__name__))
329
330     def _writeonly_getter(self, instance):
331         self._exc = TypeError("%s property of %s is write-only" % (
332             self.name, type(instance).__name__))
333
334     #
335     # Public API
336     #
337
338     def get_pspec_args(self):
339         ptype = self.type
340         if ptype in (TYPE_INT, TYPE_UINT, TYPE_LONG, TYPE_ULONG,
341                      TYPE_INT64, TYPE_UINT64, TYPE_FLOAT, TYPE_DOUBLE):
342             args = self.minimum, self.maximum, self.default
343         elif (ptype == TYPE_STRING or ptype == TYPE_BOOLEAN or
344               ptype.is_a(TYPE_ENUM) or ptype.is_a(TYPE_FLAGS) or
345               ptype.is_a(TYPE_VARIANT)):
346             args = (self.default,)
347         elif ptype in (TYPE_PYOBJECT, TYPE_GTYPE):
348             args = ()
349         elif ptype.is_a(TYPE_OBJECT) or ptype.is_a(TYPE_BOXED):
350             args = ()
351         else:
352             raise NotImplementedError(ptype)
353
354         return (self.type, self.nick, self.blurb) + args + (self.flags,)
355
356
357 def install_properties(cls):
358     """
359     Scans the given class for instances of Property and merges them
360     into the classes __gproperties__ dict if it exists or adds it if not.
361     """
362     gproperties = cls.__dict__.get('__gproperties__', {})
363
364     props = []
365     for name, prop in cls.__dict__.items():
366         if isinstance(prop, Property):  # not same as the built-in
367             if name in gproperties:
368                 raise ValueError('Property %s was already found in __gproperties__' % name)
369             prop.name = name
370             gproperties[name] = prop.get_pspec_args()
371             props.append(prop)
372
373     if not props:
374         return
375
376     cls.__gproperties__ = gproperties
377
378     if 'do_get_property' in cls.__dict__ or 'do_set_property' in cls.__dict__:
379         for prop in props:
380             if prop.fget != prop._default_getter or prop.fset != prop._default_setter:
381                 raise TypeError(
382                     "GObject subclass %r defines do_get/set_property"
383                     " and it also uses a property with a custom setter"
384                     " or getter. This is not allowed" % (
385                     cls.__name__,))
386
387     def obj_get_property(self, pspec):
388         name = pspec.name.replace('-', '_')
389         prop = getattr(cls, name, None)
390         if prop:
391             return prop.fget(self)
392     cls.do_get_property = obj_get_property
393
394     def obj_set_property(self, pspec, value):
395         name = pspec.name.replace('-', '_')
396         prop = getattr(cls, name, None)
397         if prop:
398             prop.fset(self, value)
399     cls.do_set_property = obj_set_property