/
view_base.py
546 lines (444 loc) · 20.2 KB
/
view_base.py
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
# ***************************************************************************
# * Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * Copyright (c) 2009, 2010 Ken Cline <cline@frii.com> *
# * Copyright (c) 2019 Eliud Cabrera Castillo <e.cabrera-castillo@tum.de> *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * 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 Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
"""Provides the viewprovider code for the base Draft object.
Many viewprovider classes may inherit this class in order to have
the same basic behavior."""
## @package view_base
# \ingroup draftviewproviders
# \brief Provides the viewprovider code for the base Draft object.
## \addtogroup draftviewproviders
# @{
import PySide.QtCore as QtCore
from PySide.QtCore import QT_TRANSLATE_NOOP
import FreeCAD as App
import draftutils.utils as utils
import draftutils.gui_utils as gui_utils
if App.GuiUp:
from pivy import coin
import FreeCADGui as Gui
import Draft_rc
# The module is used to prevent complaints from code checkers (flake8)
bool(Draft_rc.__name__)
class ViewProviderDraft(object):
"""The base class for Draft view providers.
Parameters
----------
vobj : a base C++ view provider
The view provider of the scripted object (`obj.ViewObject`),
which commonly may be of types `PartGui::ViewProvider2DObjectPython`,
`PartGui::ViewProviderPython`, or `Gui::ViewProviderPythonFeature`.
A basic view provider is instantiated during the creation
of the base C++ object, for example,
`Part::Part2DObjectPython`, `Part::FeaturePython`,
or `App::FeaturePython`.
>>> obj = App.ActiveDocument.addObject('Part::Part2DObjectPython')
>>> vobj = obj.ViewObject
>>> ViewProviderDraft(vobj)
This view provider class instance is stored in the `Proxy` attribute
of the base view provider.
::
vobj.Proxy = self
Attributes
----------
Object : the base C++ object
The scripted document object that is associated
with this view provider, which commonly may be of types
`Part::Part2DObjectPython`, `Part::FeaturePython`,
or `App::FeaturePython`.
texture : coin.SoTexture2
A texture that could be added to this object.
texcoords : coin.SoTextureCoordinatePlane
The coordinates defining a plane to use for aligning the texture.
These class attributes are accessible through the `Proxy` object:
`vobj.Proxy.Object`, `vobj.Proxy.texture`, etc.
"""
def __init__(self, vobj):
self.Object = vobj.Object
self.texture = None
self.texcoords = None
self._set_properties(vobj)
# This class is assigned to the Proxy attribute
vobj.Proxy = self
def _set_properties(self, vobj):
"""Set the properties of objects if they don't exist."""
if not hasattr(vobj, "Pattern"):
vobj.addProperty("App::PropertyEnumeration",
"Pattern",
"Draft",
QT_TRANSLATE_NOOP("App::Property",
"Defines an SVG pattern."))
patterns = list(utils.svg_patterns().keys())
patterns.sort()
vobj.Pattern = ["None"] + patterns
if not hasattr(vobj, "PatternSize"):
vobj.addProperty("App::PropertyFloat",
"PatternSize",
"Draft",
QT_TRANSLATE_NOOP("App::Property",
"Defines the size of the SVG pattern."))
vobj.PatternSize = utils.get_param("HatchPatternSize", 1)
def __getstate__(self):
"""Return a tuple of all serializable objects or None.
When saving the document this view provider object gets stored
using Python's `json` module.
Since we have some un-serializable objects (Coin objects) in here
we must define this method to return a tuple of all serializable
objects or `None`.
Override this method to define the serializable objects to return.
By default it returns `None`.
Returns
-------
None
"""
return None
def __setstate__(self, state):
"""Set some internal properties for all restored objects.
When a document is restored this method is used to set some properties
for the objects stored with `json`.
Override this method to define the properties to change for the
restored serialized objects.
By default no objects were serialized with `__getstate__`,
so nothing needs to be done here, and it returns `None`.
Parameters
----------
state : state
A serialized object.
Returns
-------
None
"""
return None
def attach(self, vobj):
"""Set up the scene sub-graph of the view provider.
This method should always be defined, even if it does nothing.
Override this method to set up a custom scene.
Parameters
----------
vobj : the view provider of the scripted object.
This is `obj.ViewObject`.
"""
self.texture = None
self.texcoords = None
self.Object = vobj.Object
self.onChanged(vobj, "Pattern")
return
def updateData(self, obj, prop):
"""Run when an object property is changed.
Override this method to handle the behavior of the view provider
depending on changes that occur to the real object's properties.
By default, no property is tested, and it does nothing.
Parameters
----------
obj : the base C++ object
The scripted document object that is associated
with this view provider, which commonly may be of types
`Part::Part2DObjectPython`, `Part::FeaturePython`,
or `App::FeaturePython`.
prop : str
Name of the property that was modified.
"""
return
def getDisplayModes(self, vobj):
"""Return a list of display modes.
Override this method to return a list of strings with
display mode styles, such as `'Flat Lines'`, `'Shaded'`,
`'Wireframe'`, `'Points'`.
By default it returns an empty list.
Parameters
----------
vobj : the view provider of the scripted object.
This is `obj.ViewObject`.
Returns
-------
list
Empty list `[ ]`
"""
modes = []
return modes
def getDefaultDisplayMode(self):
"""Return the default mode defined in getDisplayModes.
Override this method to return a string with the default display mode.
By default it returns `'Flat Lines'`.
Returns
-------
str
`'Flat Lines'`
"""
return "Flat Lines"
def setDisplayMode(self, mode):
"""Map the modes defined in attach with those in getDisplayModes.
This method is optional.
By default since they have the same names nothing needs to be done,
and it just returns the input `mode`.
Parameters
----------
str
A string defining a display mode such as
`'Flat Lines'`, `'Shaded'`, `'Wireframe'`, `'Points'`.
"""
return mode
def onChanged(self, vobj, prop):
"""Run when a view property is changed.
Override this method to handle the behavior
of the view provider depending on changes that occur to its properties
such as line color, line width, point color, point size,
draw style, shape color, transparency, and others.
This method updates the texture and pattern if
the properties `TextureImage`, `Pattern`, `DiffuseColor`,
and `PatternSize` change.
Parameters
----------
vobj : the view provider of the scripted object.
This is `obj.ViewObject`.
prop : str
Name of the property that was modified.
"""
# treatment of patterns and image textures
if prop in ("TextureImage", "Pattern", "DiffuseColor"):
if hasattr(self.Object, "Shape"):
if self.Object.Shape.Faces:
path = None
if hasattr(vobj, "TextureImage"):
if vobj.TextureImage:
path = vobj.TextureImage
if not path:
if hasattr(vobj, "Pattern"):
if str(vobj.Pattern) in list(utils.svg_patterns().keys()):
path = utils.svg_patterns()[vobj.Pattern][1]
else:
path = "None"
if path and vobj.RootNode:
if vobj.RootNode.getChildren().getLength() > 2:
if vobj.RootNode.getChild(2).getChildren().getLength() > 0:
innodes = vobj.RootNode.getChild(2).getChild(0).getChildren().getLength()
if innodes > 2:
r = vobj.RootNode.getChild(2).getChild(0).getChild(innodes-1)
i = QtCore.QFileInfo(path)
if self.texture:
r.removeChild(self.texture)
self.texture = None
if self.texcoords:
r.removeChild(self.texcoords)
self.texcoords = None
if i.exists():
size = None
if ".SVG" in path.upper():
size = utils.get_param("HatchPatternResolution", 128)
if not size:
size = 128
im = gui_utils.load_texture(path, size)
if im:
self.texture = coin.SoTexture2()
self.texture.image = im
r.insertChild(self.texture, 1)
if size:
s = 1
if hasattr(vobj, "PatternSize"):
if vobj.PatternSize:
s = vobj.PatternSize
self.texcoords = coin.SoTextureCoordinatePlane()
self.texcoords.directionS.setValue(s, 0, 0)
self.texcoords.directionT.setValue(0, s, 0)
r.insertChild(self.texcoords, 2)
elif prop == "PatternSize":
if hasattr(self, "texcoords"):
if self.texcoords:
s = 1
if vobj.PatternSize:
s = vobj.PatternSize
vS = App.Vector(self.texcoords.directionS.getValue().getValue())
vT = App.Vector(self.texcoords.directionT.getValue().getValue())
vS.Length = s
vT.Length = s
self.texcoords.directionS.setValue(vS.x, vS.y, vS.z)
self.texcoords.directionT.setValue(vT.x, vT.y, vT.z)
return
def _update_pattern_size(self, vobj):
"""Update the pattern size. Helper method in onChanged."""
if hasattr(self, "texcoords") and self.texcoords:
s = 1
if vobj.PatternSize:
s = vobj.PatternSize
vS = App.Vector(self.texcoords.directionS.getValue().getValue())
vT = App.Vector(self.texcoords.directionT.getValue().getValue())
vS.Length = s
vT.Length = s
self.texcoords.directionS.setValue(vS.x, vS.y, vS.z)
self.texcoords.directionT.setValue(vT.x, vT.y, vT.z)
def execute(self, vobj):
"""Run when the object is created or recomputed.
Override this method to produce effects when the object
is newly created, and whenever the document is recomputed.
By default it does nothing.
Parameters
----------
vobj : the view provider of the scripted object.
This is `obj.ViewObject`.
"""
return
def setEdit(self, vobj, mode=0):
"""Enter edit mode of the object.
Override this method to define a custom command to run when entering
the edit mode of the object in the tree view.
It must return `True` to successfully enter edit mode.
If the conditions to edit are not met, it should return `False`,
in which case the edit mode is not started.
By default it runs the `Draft_Edit` GuiCommand.
::
Gui.runCommand('Draft_Edit')
Parameters
----------
vobj : the view provider of the scripted object.
This is `obj.ViewObject`.
mode : int, optional
It defaults to 0, in which case
it runs the `Draft_Edit` GuiCommand.
It indicates the type of edit in the underlying C++ code.
Returns
-------
bool or None
It is `True` if `mode` is 0, and `Draft_Edit` ran successfully.
None if mode is not zero.
It is `False` otherwise.
"""
if mode != 0:
# Act like this function doesn't even exist, so the command falls back to Part (e.g. in the
# case of an unrecognized context menu action)
return None
elif App.GuiUp and "Draft_Edit" in Gui.listCommands(): # remove App.GuiUp guard after splitting every viewprovider
Gui.runCommand("Draft_Edit")
return True
else:
App.Console.PrintWarning(QT_TRANSLATE_NOOP("draft",
"Please load the Draft Workbench to enable editing this object"))
return False
def unsetEdit(self, vobj, mode=0):
"""Terminate the edit mode of the object.
Override this method to define a custom command to run when
terminating the edit mode of the object in the tree view.
It should return `True` to indicate that the method already
cleaned up everything and there is no need to call
the `usetEdit` method of the base class.
It should return `False` to indicate that cleanup
is still required, so the `unsetEdit` method of the base class
is invoked to do the rest.
By default it runs the `finish` method of the active
Draft GuiCommand, and closes the task panel.
::
App.activeDraftCommand.finish()
Gui.Control.closeDialog()
Parameters
----------
vobj : the view provider of the scripted object.
This is `obj.ViewObject`.
mode : int, optional
It defaults to 0.
It indicates the type of edit in the underlying C++ code.
Returns
-------
bool
This method always returns `False` so it passes
control to the base class to finish the edit mode.
"""
if mode != 0:
return False
if App.activeDraftCommand:
App.activeDraftCommand.finish()
if App.GuiUp: # remove guard after splitting every viewprovider
Gui.Control.closeDialog()
return False
def getIcon(self):
"""Return the path to the icon used by the view provider.
The path can be a full path in the system, or a relative path
inside the compiled resource file.
It can also be a string that defines the icon in XPM format.
Override this method to provide a specific icon
for the object in the tree view.
By default it returns the path to the `Draft_Draft.svg` icon.
Returns
-------
str
`':/icons/Draft_Draft.svg'`
"""
if hasattr(self.Object,"Proxy") and hasattr(self.Object.Proxy,"Type"):
tp = self.Object.Proxy.Type
if tp in ('Line', 'Wire', 'Polyline'):
return ":/icons/Draft_N-Linear.svg"
elif tp in ('Rectangle', 'Polygon'):
return ":/icons/Draft_N-Polygon.svg"
elif tp in ('Circle', 'Ellipse', 'BSpline', 'BezCurve', 'Fillet'):
return ":/icons/Draft_N-Curve.svg"
elif tp in ("ShapeString"):
return ":/icons/Draft_ShapeString_tree.svg"
if hasattr(self.Object,"AutoUpdate") and not self.Object.AutoUpdate:
import TechDrawGui
return ":/icons/TechDraw_TreePageUnsync.svg"
return ":/icons/Draft_Draft.svg"
def claimChildren(self):
"""Return objects that will be placed under it in the tree view.
Override this method to return a list with objects
that will appear under this object in the tree view.
That is, this object becomes the `parent`,
and all those under it are the `children`.
By default the returned list is composed of objects from
`Object.Base`, `Object.Objects`, `Object.Components`,
and `Object.Group`, if they exist.
Returns
-------
list
List of objects.
"""
objs = []
if hasattr(self.Object, "Base"):
objs.append(self.Object.Base)
if hasattr(self.Object, "Objects"):
objs.extend(self.Object.Objects)
if hasattr(self.Object, "Components"):
objs.extend(self.Object.Components)
if hasattr(self.Object, "Group"):
objs.extend(self.Object.Group)
return objs
# Alias for compatibility with v0.18 and earlier
_ViewProviderDraft = ViewProviderDraft
class ViewProviderDraftAlt(ViewProviderDraft):
"""A view provider that doesn't absorb its base object in the tree view.
The `claimChildren` method is overridden to return an empty list.
"""
def __init__(self, vobj):
super(ViewProviderDraftAlt, self).__init__(vobj)
def claimChildren(self):
objs = []
return objs
# Alias for compatibility with v0.18 and earlier
_ViewProviderDraftAlt = ViewProviderDraftAlt
class ViewProviderDraftPart(ViewProviderDraftAlt):
"""A view provider that displays a Part icon instead of a Draft icon.
The `getIcon` method is overridden to provide `Part_3D_object.svg`.
"""
def __init__(self, vobj):
super(ViewProviderDraftPart, self).__init__(vobj)
def getIcon(self):
return ":/icons/Part_3D_object.svg"
# Alias for compatibility with v0.18 and earlier
_ViewProviderDraftPart = ViewProviderDraftPart
## @}