Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/tutorius/properties.py
blob: 137e7565884a8eb0a31e7e11391e0ac7951ee348 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# Copyright (C) 2009, Tutorius.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
"""
This module contains properties class that can be included in other types.
TutoriusProperties have the same behaviour as python properties (assuming you
also use the TPropContainer), with the added benefit of having builtin dialog
prompts and constraint validation.
"""

#from sugar.tutorius.constraints import *
from constraints import *
from copy import copy

class TPropContainer(object):
    """
    A class containing properties. This does the attribute wrapping between
    the container instance and the property value. As properties are on the
    containing classes, they allow static introspection of those types
    at the cost of needing a mapping between container instances, and 
    property values. This is what TPropContainer does.
    """
    def __init__(self):
        """
        Prepares the instance for property value storage. This is done at
        object initialization, thus allowing initial mapping of properties
        declared on the class. Properties won't work correctly without
        this call.
        """
        # create property value storage
        object.__setattr__(self, "_props", {})
        for attr_name in dir(type(self)):
            propinstance = object.__getattribute__(self, attr_name)
            if isinstance(propinstance, TutoriusProperty):
                # only care about TutoriusProperty instances
                propinstance.tname = attr_name
                self._props[attr_name] = propinstance.validate(
                        copy(propinstance.default))

    def __getattribute__(self, name):
        """
        Process the 'fake' read of properties in the appropriate instance
        container. Pass 'real' attributes as usual.
        """
        try:
            props = object.__getattribute__(self, "_props")
        except AttributeError:
            # necessary for deepcopy as order of init can't be guaranteed
            object.__setattr__(self, "_props", {})
            props = object.__getattribute__(self, "_props")

        try:
            # try gettin value from property storage
            # if it's not in the map, it's not a property or its default wasn't
            # set at initialization.
            return props[name]
        except KeyError:
            return object.__getattribute__(self, name)

    def __setattr__(self, name, value):
        """
        Process the 'fake' write of properties in the appropriate instance
        container. Pass 'real' attributes as usual.

        @param name the name of the property
        @param value the value to assign to name
        @return the setted value
        """
        props = object.__getattribute__(self, "_props")
        try:
            # We attempt to get the property object with __getattribute__ 
            # to work through inheritance and benefit of the MRO.
            return props.__setitem__(name,
                    object.__getattribute__(self, name).validate(value))
        except AttributeError:
            return object.__setattr__(self, name, value)

    def get_properties(self):
        """
        Return the list of property names.
        """
        return object.__getattribute__(self, "_props").keys()

class TutoriusProperty(object):
    """
    The base class for all actions' properties. The interface is the following :
    
    value : the value of the property
    
    type : the type of the property
    
    get_contraints() : the constraints inserted on this property. They define
    what is acceptable or not as values.
    """
    def __init__(self):
        super(TutoriusProperty, self).__init__()
        self.type = None
        self._constraints = None
        self.default = None
        
    def get_constraints(self):
        """
        Returns the list of constraints associated to this property.
        """
        if self._constraints is None:
            self._constraints = []
            for i in dir(self):
                typ = getattr(self, i)
                if isinstance(typ, Constraint):
                    self._constraints.append(i)
        return self._constraints

    def validate(self, value):
        """
        Validates the value of the property. If the value does not respect
        the constraints on the property, this method will raise an exception.
        
        The exception should be of the type related to the constraint that
        failed. E.g. When a int is to be set with a value that 
        """
        for constraint_name in self.get_constraints():
            constraint = getattr(self, constraint_name)
            constraint.validate(value)
        return value
        
    def type(self,value):################################################
        """
        Allow to use type() for TutoriusProperty like for Python elements
        """
        if value != None :
            print "salut" 
            return self.type    

class TAddonListProperty(TutoriusProperty):
    """
    Stores an addon component list as a property.
    The purpose of this class is to allow correct mapping of properties
    through encapsulated hierarchies.
    """
    pass

    
    def get_constraints(self):
        """
        Returns the list of constraints associated to this property.
        """
        if self._constraints is None:
            self._constraints = []
            for i in dir(self):
                typ = getattr(self, i)
                if isinstance(typ, Constraint):
                    self._constraints.append(i)
        return self._constraints

class TIntProperty(TutoriusProperty):
    """
    Represents an integer. Can have an upper value limit and/or a lower value
    limit.
    """
    
    def __init__(self, value, lower_limit=None, upper_limit=None):
        TutoriusProperty.__init__(self)
        self.type = "int"
        self.upper_limit = UpperLimitConstraint(upper_limit)
        self.lower_limit = LowerLimitConstraint(lower_limit)
        self.type_check = IntCheckConstraint()##########################################################
        self.default = self.validate(value)
    #faut_il convertir value en int quelque part ? 
class TFloatProperty(TutoriusProperty):
    """
    Represents a floating point number. Can have an upper value limit and/or
    a lower value limit.
    """
    def __init__(self, value, lower_limit=None, upper_limit=None):
        TutoriusProperty.__init__(self)
        self.type = "float"
        self.type_check = FloatCheckConstraint()##########################################################
        self.upper_limit = UpperLimitConstraint(upper_limit)
        self.lower_limit = LowerLimitConstraint(lower_limit)
        
        self.default = self.validate(value)
    #faut_il convertir value en float quelque part ?
class TStringProperty(TutoriusProperty):
    """
    Represents a string. Can have a maximum size limit.
    """
    def __init__(self, value, size_limit=None):
        TutoriusProperty.__init__(self)
        self.type = "string"
        self.size_limit = MaxSizeConstraint(size_limit)
        
        self.default = self.validate(value)
    
class TArrayProperty(TutoriusProperty):#############################################################
    """
    Represents an array of values. Can have a maximum number of element 
    limit, but there are no constraints on the content of the array.
    """
    def __init__(self, value, min_size_limit=None, max_size_limit=None):
        TutoriusProperty.__init__(self)
        self.type = "array"
        self.indexeur = value #stock la value, pour l'indexation
        self.max_size_limit = MaxSizeConstraint(max_size_limit)
        self.min_size_limit = MinSizeConstraint(min_size_limit)
        self.default = self.validate(value)    
        
    def __getitem__(self, key): # TArrayProperty object now supports indexing
        return self.indexeur[key] #     used in overlayer.py
        
    #def append(self, value) ?: #invalide
    #et enlever un element ?    
            
class TColorProperty(TutoriusProperty):
    """
    Represents a RGB color with 3 8-bit integer values.
    
    The value of the property is the array [R, G, B]
    """
    def __init__(self, red=None, green=None, blue=None):
        TutoriusProperty.__init__(self)
        self.type = "color"#Forcer 
        
        self.color_constraint = ColorConstraint()
        
        self._red = red or 0
        self._green = green or 0
        self._blue = blue or 0
        
        self.default = self.validate([self._red, self._green, self._blue])
 
class TFileProperty(TutoriusProperty):
    """
    Represents a path to a file on the disk.
    """
    def __init__(self, path):
        """
        Defines the path to an existing file on disk file.
        
        For now, the path may be relative or absolute, as long as it exists on
        the local machine.
        TODO : Make sure that we have a file scheme that supports distribution
        on other computers (LP 355197)
        """
        TutoriusProperty.__init__(self)
        
        self.type = "file"
        
        self.file_constraint = FileConstraint()
        
        self.default = self.validate(path)
    
class TEnumProperty(TutoriusProperty):
    """
    Represents a value in a given enumeration. This means that the value will
    always be one in the enumeration and nothing else.
    
    """
    def __init__(self, value, accepted_values):
        """
        Creates the enumeration property.
        
        @param value The initial value of the enum. Must be part of 
        accepted_values
        @param accepted_values A list of values that the property can take
        """
        TutoriusProperty.__init__(self)
        
        self.type = "enum"
        
        self.enum_constraint = EnumConstraint(accepted_values)
        
        self.default = self.validate(value)
    
class TBooleanProperty(TutoriusProperty):
    """
    Represents a True or False value.
    """
    def __init__(self, value=False):
        TutoriusProperty.__init__(self)
        
        self.type = "boolean"
        
        self.boolean_constraint = BooleanConstraint()
        
        self.default = self.validate(value)
    
class TUAMProperty(TutoriusProperty):
    """
    Represents a widget of the interface by storing its UAM.
    """
    # TODO : Pending UAM check-in (LP 355199)
    pass

class TAddonProperty(TutoriusProperty):
    """
    Reprensents an embedded tutorius Addon Component (action, trigger, etc.)
    The purpose of this class is to flag the container for proper
    serialization, as the contained object can't be directly dumped to text
    for its attributes to be saved.
    """
    class NullAction(TPropContainer):
        def do(self): pass
        def undo(self): pass

    def __init__(self):
        super(TAddonProperty, self).__init__()
        self.type = "addon"
        self.default = self.NullAction()

    def validate(self, value):
        if isinstance(value, TPropContainer):
            return super(TAddonProperty, self).validate(value)
        raise ValueError("Expected TPropContainer instance as TaddonProperty value")
           
class TPositionProperty(TutoriusProperty):#########################################################
    """
    Represents a tuple of two int. The first value is the  x position and the second the y position
    """
    def __init__(self, (x, y)):
        TutoriusProperty.__init__(self)
        self.type = "position"
        self._x=x or 0 #peut etre superflu ? 
        self._y=y or 0
        self.typeCheck = ListIntCheckConstraint()
        self.indexeur = [self._x, self._y]
        self.default = self.validate((self._x,self._y))        
    
    #def __getitem__(self, key): # TPositionProperty object now supports indexing
        #return self.indexeur[key] #use in overlayer.py
        
    #fonctionnement obscur pour la modification des valeur a l'interieur du tuple position (par le clavier)
                              
class TArrayOneTypeProperty(TutoriusProperty):######################################################
    """      
    Represents an array list of Tutorius_properties. All the elements in the list must have the same type. The list must not be empty
    """
    def __init__(self, value, tutoProp):
        TutoriusProperty.__init__(self)
        self.type = tutoProp.type
        #self.indexeur = value #stock la value, pour l'indexation
        self.required_type = SameTypeConstraint(tutoProp) #tutoProp doit etre instancie avant celle de TArrayOneType
        self.default = self.validate(value)
        
        # Tester
    #une fonction pour ajouter de la forme t=t.default + value
    #zqrning sur le append

   #ToDo : Forcer l'utilisateur a utiliser des tuples (immuable). Bug : ((0,0)) = (0,0) 
   #ToDo : Forcer l'initialisation de la propriete a sa valeur par defaut  (pour int fonctionnement ok pour TArray non)