FreeCAD

Форк
0
/
DocumentObject.py 
313 строк · 12.6 Кб
1
# FreeCAD module providing base classes for document objects and view provider  
2
# (c) 2011 Werner Mayer LGPL
3

4
import FreeCAD
5

6
class DocumentObject(object):
7
    """The Document object is the base class for all FreeCAD objects."""
8

9
    def __init__(self):
10
        self.__object__=None
11
        self.initialised=False
12
    #------------------------------Methods for the user to override :
13

14
    def execute(self):
15
        "this method is executed on object creation and whenever the document is recomputed"
16
        raise NotImplementedError("Not yet implemented")
17

18
    def init(self):
19
        #will be called just after object creation, you can use this for example to create properties
20
        pass
21
    def propertyChanged(self,prop):
22
        #will be called each time a property is changed
23
        pass
24
    #--------------------------------
25

26

27
    def __getattr__(self, attr):
28
        if attr !="__object__" and hasattr(self.__object__,attr):
29
            return getattr(self.__object__,attr)
30
        else:
31
            return object.__getattribute__(self,attr)
32
    def __setattr__(self, attr, value):
33
        if attr !="__object__" and hasattr(self.__object__,attr):
34
            setattr(self.__object__,attr,value)
35
        else:
36
            object.__setattr__(self,attr,value)
37
    def onChanged(self,prop):
38
        if prop=="Proxy":
39
            #recreate the functions in the __object__
40
            d = self.__class__.__dict__
41
            for key in d:
42
                item = d[key]
43
                #check if the function is valid
44
                if hasattr(item, '__call__') and key!="onChanged" and key!="execute" and key!="init" and key[0]!="_":
45
                    #check if the function doesn't already exist in the object:
46
                    if not(hasattr(self.__object__,key)):
47
                        #add a link to the Proxy function in the __object__ :
48
                        self.addProperty("App::PropertyPythonObject", key, "", "",2)
49
                        setattr(self.__object__,key,getattr(self,key))
50
                    else:
51
                        FreeCAD.Console.PrintWarning('!!! The function : "'+key+'" already exist in the object, cannot override. !!!\n')
52
            #call the init function
53
            if hasattr(self,'initialised'):
54
                if self.initialised==False:
55
                    self.init()
56
                    self.initialised = True
57
        self.propertyChanged(prop)
58
    def addProperty(self,typ,name='',group='',doc='',attr=0,readonly=False,hidden=False):
59
        "adds a new property to this object"
60
        return self.__object__.addProperty(typ,name,group,doc,attr,readonly,hidden)
61
    def supportedProperties(self):
62
        "lists the property types supported by this object"
63
        return self.__object__.supportedProperties()
64
    def isDerivedFrom(self, obj):
65
        """returns True if this object is derived from the given C++ class, for
66
        example Part::Feature"""
67
        return self.__object__.isDerivedFrom(obj)
68
    def getAllDerivedFrom(self):
69
        "returns all parent C++ classes of this object"
70
        return self.__object__.getAllDerivedFrom()
71
    def getProperty(self,attr):
72
        "returns the value of a given property"
73
        return self.__object__.getPropertyByName(attr)
74
    def getTypeOfProperty(self,attr):
75
        "returns the type of a given property"
76
        return self.__object__.getTypeOfProperty(attr)
77
    def getGroupOfProperty(self,attr):
78
        "returns the group of a given property"
79
        return self.__object__.getGroupOfProperty(attr)
80
    def getDocumentationOfProperty(self,attr):
81
        "returns the documentation string of a given property"
82
        return self.__object__.getDocumentationOfProperty(attr)
83
    def getEnumerationsOfProperty(self,attr):
84
        "returns the documentation string of a given property"
85
        return self.__object__.getEnumerationsOfProperty(attr)
86
    def touch(self):
87
        "marks this object to be recomputed"
88
        return self.__object__.touch()
89
    def purgeTouched(self):
90
        "removes the to-be-recomputed flag of this object"
91
        return self.__object__.purgeTouched()
92
    def __setstate__(self,value):
93
        """allows to save custom attributes of this object as strings, so
94
        they can be saved when saving the FreeCAD document"""
95
        return None
96
    def __getstate__(self):
97
        """reads values previously saved with __setstate__()"""
98
        return None
99
    @property
100
    def PropertiesList(self):
101
        "lists the current properties of this object"
102
        return self.__object__.PropertiesList
103
    @property
104
    def Type(self):
105
        "shows the C++ class of this object"
106
        return self.__object__.Type
107
    @property
108
    def Module(self):
109
        "gives the module this object is defined in"
110
        return self.__object__.Module
111
    @property
112
    def Content(self):
113
        """shows the contents of the properties of this object as an xml string.
114
        This is the content that is saved when the file is saved by FreeCAD"""
115
        return self.__object__.Content
116
    @property
117
    def MemSize(self):
118
        "shows the amount of memory this object uses"
119
        return self.__object__.MemSize
120
    @property
121
    def Name(self):
122
        "the name ofthis object, unique in the FreeCAD document"
123
        return self.__object__.Name
124
    @property
125
    def Document(self):
126
        "the document this object is part of"
127
        return self.__object__.Document
128
    @property
129
    def State(self):
130
        "shows if this object is valid (presents no errors)"
131
        return self.__object__.State
132
    @property
133
    def ViewObject(self):
134
        return self.__object__.ViewObject
135
    @ViewObject.setter
136
    def ViewObject(self,value):
137
        """returns or sets the ViewObject associated with this object. Returns
138
        None if FreeCAD is running in console mode"""
139
        self.__object__.ViewObject=value
140
    @property
141
    def InList(self):
142
        "lists the parents of this object"
143
        return self.__object__.InList
144
    @property
145
    def OutList(self):
146
        "lists the children of this object"
147
        return self.__object__.OutList
148

149

150

151

152
class ViewProvider(object):
153
    """The ViewProvider is the counterpart of the DocumentObject in
154
    the GUI space. It is only present when FreeCAD runs in GUI mode.
155
    It contains all that is needed to represent the DocumentObject in
156
    the 3D view and the FreeCAD interface"""
157
    def __init__(self):
158
        self.__vobject__=None
159
    #def getIcon(self):
160
    #    return ""
161
    #def claimChildren(self):
162
    #    return self.__vobject__.Object.OutList
163
    #def setEdit(self,mode):
164
    #    return False
165
    #def unsetEdit(self,mode):
166
    #    return False
167
    #def attach(self):
168
    #    return None
169
    #def updateData(self, prop):
170
    #    return None
171
    #def onChanged(self, prop):
172
    #    return None
173
    def addDisplayMode(self,node,mode):
174
        "adds a coin node as a display mode to this object"
175
        self.__vobject__.addDisplayMode(node,mode)
176
    #def getDefaultDisplayMode(self):
177
    #    return ""
178
    #def getDisplayModes(self):
179
    #    return []
180
    #def setDisplayMode(self,mode):
181
    #    return mode
182
    def addProperty(self,type,name='',group='',doc='',attr=0,readonly=False,hidden=False):
183
        "adds a new property to this object"
184
        self.__vobject__.addProperty(type,name,group,doc,attr,readonly,hidden)
185
    def update(self):
186
        "this method is executed whenever any of the properties of this ViewProvider changes"
187
        self.__vobject__.update()
188
    def show(self):
189
        "switches this object to visible"
190
        self.__vobject__.show()
191
    def hide(self):
192
        "switches this object to invisible"
193
        self.__vobject__.hide()
194
    def isVisible(self):
195
        "shows whether this object is visible or invisible"
196
        return self.__vobject__.isVisible()
197
    def toString(self):
198
        "returns a string representation of the coin node of this object"
199
        return self.__vobject__.toString()
200
    def setTransformation(self,trsf):
201
        "defines a transformation for this object"
202
        return self.__vobject__.setTransformation(trsf)
203
    def supportedProperties(self):
204
        "lists the property types this ViewProvider supports"
205
        return self.__vobject__.supportedProperties()
206
    def isDerivedFrom(self, obj):
207
        """returns True if this object is derived from the given C++ class, for
208
        example Part::Feature"""
209
        return self.__vobject__.isDerivedFrom(obj)
210
    def getAllDerivedFrom(self):
211
        "returns all parent C++ classes of this object"
212
        return self.__vobject__.getAllDerivedFrom()
213
    def getProperty(self,attr):
214
        "returns the value of a given property"
215
        return self.__vobject__.getPropertyByName(attr)
216
    def getTypeOfProperty(self,attr):
217
        "returns the type of a given property"
218
        return self.__vobject__.getTypeOfProperty(attr)
219
    def getGroupOfProperty(self,attr):
220
        "returns the group of a given property"
221
        return self.__vobject__.getGroupOfProperty(attr)
222
    def getDocumentationOfProperty(self,attr):
223
        "returns the documentation string of a given property"
224
        return self.__vobject__.getDocumentationOfProperty(attr)
225
    def __setstate__(self,value):
226
        """allows to save custom attributes of this object as strings, so
227
        they can be saved when saving the FreeCAD document"""
228
        return None
229
    def __getstate__(self):
230
        """reads values previously saved with __setstate__()"""
231
        return None
232
    @property
233
    def Annotation(self):
234
        "returns the Annotation coin node of this object"
235
        return self.__vobject__.Annotation
236
    @property
237
    def RootNode(self):
238
        "returns the Root coin node of this object"
239
        return self.__vobject__.RootNode
240
    @property
241
    def DisplayModes(self):
242
        "lists the display modes of this object"
243
        return self.__vobject__.listDisplayModes()
244
    @property
245
    def PropertiesList(self):
246
        "lists the current properties of this object"
247
        return self.__vobject__.PropertiesList
248
    @property
249
    def Type(self):
250
        "shows the C++ class of this object"
251
        return self.__vobject__.Type
252
    @property
253
    def Module(self):
254
        "gives the module this object is defined in"
255
        return self.__vobject__.Module
256
    @property
257
    def Content(self):
258
        """shows the contents of the properties of this object as an xml string.
259
        This is the content that is saved when the file is saved by FreeCAD"""
260
        return self.__vobject__.Content
261
    @property
262
    def MemSize(self):
263
        "shows the amount of memory this object uses"
264
        return self.__vobject__.MemSize
265
    @property
266
    def Object(self):
267
        "returns the DocumentObject this ViewProvider is associated to"
268
        return self.__vobject__.Object
269

270

271
#Example :
272
import Part
273

274
class Box(DocumentObject):
275
    #type :
276
    type = "Part::FeaturePython"
277

278
    #-----------------------------INIT----------------------------------------
279
    def init(self):
280
        self.addProperty("App::PropertyLength","Length","Box","Length of the box").Length=1.0
281
        self.addProperty("App::PropertyLength","Width","Box","Width of the box").Width=1.0
282
        self.addProperty("App::PropertyLength","Height","Box", "Height of the box").Height=1.0
283

284
    #-----------------------------BEHAVIOR------------------------------------
285
    def propertyChanged(self,prop):
286
        FreeCAD.Console.PrintMessage("Box property changed : "+ prop+ "\n")
287
        if prop == "Length" or prop == "Width" or prop == "Height":
288
            self._recomputeShape()
289

290
    def execute(self):
291
        FreeCAD.Console.PrintMessage("Recompute Python Box feature\n")
292
        self._recomputeShape()
293

294
    #---------------------------PUBLIC FUNCTIONS-------------------------------
295
    #These functions will be present in the object
296
    def customFunctionSetLength(self,attr):
297
        self.Length = attr
298
        self._privateFunctionExample(attr)
299

300
    #---------------------------PRIVATE FUNCTIONS------------------------------
301
    #These function won't be present in the object (begin with '_')
302
    def _privateFunctionExample(self,attr):
303
        FreeCAD.Console.PrintMessage("The length : "+str(attr)+"\n")
304

305
    def _recomputeShape(self):
306
        if hasattr(self,"Length") and hasattr(self,"Width") and hasattr(self,"Height"):
307
            self.Shape = Part.makeBox(self.Length,self.Width,self.Height)
308

309

310
def makeBox():
311
    FreeCAD.newDocument()
312
    box = FreeCAD.ActiveDocument.addObject(Box.type,"MyBox",Box(),None)
313
    box.customFunctionSetLength(4)
314

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.