-
Notifications
You must be signed in to change notification settings - Fork 58
/
SheetMetalTools.py
549 lines (466 loc) · 20.4 KB
/
SheetMetalTools.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
547
548
549
# -*- coding: utf-8 -*-
##############################################################################
#
# SheetMetalBend.py
#
# Copyright 2024 Shai Seger <shaise at gmail dot com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser 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 Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#
##############################################################################
import os
import re
import FreeCAD
import Part
from SheetMetalLogger import SMLogger
translate = FreeCAD.Qt.translate
mod_path = os.path.dirname(__file__)
icons_path = os.path.join(mod_path, "Resources", "icons")
panels_path = os.path.join(mod_path, "Resources", "panels")
language_path = os.path.join(mod_path, "translations")
params = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/SheetMetal")
smEpsilon = 0.0000001
class SMException(Exception):
''' Sheet Metal Custom Exception '''
def isGuiLoaded():
if hasattr(FreeCAD, "GuiUp"):
return FreeCAD.GuiUp
return False
if isGuiLoaded():
from PySide import QtCore, QtGui
from FreeCAD import Gui
def smWarnDialog(msg):
diag = QtGui.QMessageBox(
QtGui.QMessageBox.Warning,
FreeCAD.Qt.translate("QMessageBox", "Error in macro MessageBox"),
msg,
)
diag.setWindowModality(QtCore.Qt.ApplicationModal)
diag.exec_()
class SMSingleSelectionObserver:
''' used for tasks that needs to be aware of selection changes '''
def __init__(self):
self.button = None
def addSelection(self, document, obj, element, position):
taskSingleSelectionChanged(self.button)
smSingleSelObserver = SMSingleSelectionObserver()
Gui.Selection.addObserver(smSingleSelObserver)
def smSelectGreedy():
if hasattr(Gui.Selection, "setSelectionStyle"): # compatibility with FC link version
Gui.Selection.setSelectionStyle(Gui.Selection.SelectionStyle.GreedySelection)
def smSelectNormal():
if hasattr(Gui.Selection, "setSelectionStyle"): # compatibility with FC link version
Gui.Selection.setSelectionStyle(Gui.Selection.SelectionStyle.NormalSelection)
def smHideObjects(*args):
for arg in args:
if arg:
obj = Gui.ActiveDocument.getObject(arg.Name)
if obj:
obj.Visibility = False
# Task panel helper code
def taskPopulateSelectionList(qwidget, baseObject):
qwidget.clear()
obj, items = baseObject
if not isinstance(items, list):
items = [items]
for subf in items:
# FreeCAD.Console.PrintLog("item: " + subf + "\n")
item = QtGui.QTreeWidgetItem(qwidget)
item.setText(0, obj.Name)
item.setIcon(0, QtGui.QIcon(":/icons/Tree_Part.svg"))
item.setText(1, subf)
def taskPopulateSelectionSingle(textbox, baseObject):
if baseObject is None:
textbox.setText("")
elif isinstance(baseObject, tuple):
obj, items = baseObject
item = "None" if len(items) == 0 else items[0]
textbox.setText(f"{obj.Name}: {item}")
else:
textbox.setText(baseObject.Name)
def updateSelectionElements(obj, allowedTypes):
if not obj:
return
sel = Gui.Selection.getSelectionEx()[0]
if not sel.HasSubObjects:
return
subItems = []
for element in sel.SubElementNames:
if smStripTrailingNumber(element) in allowedTypes:
subItems.append(element)
if len(subItems) == 0:
return
#print(sel.Object, subItems)
obj.baseObject = (sel.Object, subItems)
def _taskToggleSelectionMode(isChecked, addRemoveButton, treeWidget, obj, allowedTypes):
if isChecked:
obj.Visibility=False
obj.baseObject[0].Visibility=True
Gui.Selection.clearSelection()
Gui.Selection.addSelection(obj.baseObject[0],obj.baseObject[1])
smSelectGreedy()
addRemoveButton.setText('Preview')
else:
updateSelectionElements(obj, allowedTypes)
Gui.Selection.clearSelection()
smSelectNormal()
obj.Document.recompute()
obj.baseObject[0].Visibility=False
obj.Visibility=True
addRemoveButton.setText('Select')
taskPopulateSelectionList(treeWidget, obj.baseObject)
def taskConnectSelection(addRemoveButton, treeWidget, obj, allowedTypes):
taskPopulateSelectionList(treeWidget, obj.baseObject)
addRemoveButton.toggled.connect(
lambda value: _taskToggleSelectionMode(value, addRemoveButton, treeWidget,
obj, allowedTypes))
def _taskToggleSingleSelMode(task, isChecked, button, textbox, obj, selProperty, allowedTypes):
prop = getattr(obj, selProperty)
baseObject = obj.baseObject[0] if hasattr(obj, "baseObject") else None
Gui.Selection.clearSelection()
if isChecked:
if smSingleSelObserver.button is not None:
smSingleSelObserver.button.toggle()
if baseObject is not None:
baseObject.Visibility=True
obj.Visibility=False
prop.Visibility=True
button.activeTypes = allowedTypes
button.activeObject = obj
button.activeProperty = selProperty
button.saveText = button.text()
smSingleSelObserver.button = button
textbox.setText(f"Select {button.saveText}...")
button.setText("Cancel...")
else:
smSingleSelObserver.button = None
if baseObject is not None:
baseObject.Visibility=False
obj.Visibility=True
prop.Visibility=False
task.activeSelection = {}
taskPopulateSelectionSingle(textbox, prop)
button.setText(button.saveText)
def taskConnectSelectionSingle(task, button, textbox, obj, selProperty, allowedTypes):
taskPopulateSelectionSingle(textbox, getattr(obj, selProperty))
button.setCheckable(True)
button.toggled.connect(
lambda value: _taskToggleSingleSelMode(
task, value, button, textbox, obj, selProperty, allowedTypes))
def taskSingleSelectionChanged(button):
if button is None:
return
selobj = Gui.Selection.getSelectionEx()[0]
if len(selobj.SubElementNames) != 1:
return
selitem = selobj.SubElementNames[0]
selobj = selobj.Object
if isinstance(button.activeTypes, tuple):
# make sure object is of disired type or linked to one
objType, subObjTypes = button.activeTypes
if not selobj.isDerivedFrom(objType):
if selobj.isDerivedFrom("App::Link"):
selobj = selobj.LinkedObject
elif selobj.isDerivedFrom("Part::Part2DObject"):
selobj = selobj.Objects[0]
if not (selobj.isDerivedFrom(objType)):
return
else:
subObjTypes = button.activeTypes
if len(subObjTypes) == 0 or smStripTrailingNumber(selitem) in subObjTypes:
baseObject = selobj if len(subObjTypes) == 0 else (selobj, [selitem])
setattr(button.activeObject, button.activeProperty, baseObject)
button.activeObject.Document.recompute()
button.toggle()
def _taskUpdateValue(value, obj, objvar, callback):
setattr(obj, objvar, value)
try: # avoid intermitant changes
obj.recompute()
except:
pass
if callback is not None:
callback(value)
def _taskEditFinished(obj):
obj.Document.recompute()
def _getVarValue(obj, objvar):
if not hasattr(obj, objvar):
# Can happen if an old file is loaded and some props were renamed
obj.recompute()
return getattr(obj, objvar)
def taskConnectSpin(task, formvar, objvar, callback = None):
formvar.setProperty("value", _getVarValue(task.obj, objvar))
Gui.ExpressionBinding(formvar).bind(task.obj, objvar)
formvar.valueChanged.connect(lambda value: _taskUpdateValue(value, task.obj, objvar, callback))
formvar.editingFinished.connect(lambda: _taskEditFinished(task.obj))
def taskConnectCheck(task, formvar, objvar, callback = None):
formvar.setChecked(_getVarValue(task.obj, objvar))
if callback is not None:
callback(formvar.isChecked())
formvar.toggled.connect(lambda value: _taskUpdateValue(value, task.obj, objvar, callback))
def taskConnectEnum(task, formvar, objvar, callback = None):
val = _getVarValue(task.obj, objvar)
enumlist = task.obj.getEnumerationsOfProperty(objvar)
formvar.setProperty("currentIndex", enumlist.index(val))
formvar.currentIndexChanged.connect(lambda value: _taskUpdateValue(value, task.obj, objvar, callback))
def taskAccept(task, addRemoveButton = None):
if addRemoveButton is not None and addRemoveButton.isChecked():
addRemoveButton.toggle()
if smSingleSelObserver.button is not None:
smSingleSelObserver.button.toggle()
FreeCAD.ActiveDocument.recompute()
task.obj.Document.commitTransaction()
Gui.Control.closeDialog()
Gui.ActiveDocument.resetEdit()
return True
def taskReject(task, addRemoveButton = None):
if addRemoveButton is not None and addRemoveButton.isChecked():
smSelectNormal()
if smSingleSelObserver.button is not None:
smSingleSelObserver.button.toggle()
FreeCAD.ActiveDocument.abortTransaction()
Gui.Control.closeDialog()
FreeCAD.ActiveDocument.recompute()
Gui.ActiveDocument.resetEdit()
def taskSaveDefaults(obj, defaultDict, varList):
for var in varList:
defaultDict[var] = getattr(obj, var)
def taskRestoreDefaults(obj, defaultDict):
for var, value in defaultDict.items():
setattr(obj, var, value)
def taskLoadUI(*args):
if len(args) == 1:
path = os.path.join(panels_path, args[0])
return Gui.PySideUic.loadUi(path)
forms = []
for uiFile in args:
path = os.path.join(panels_path, uiFile)
forms.append(Gui.PySideUic.loadUi(path))
return forms
def smAddNewObject(baseObj, newObj, activeBody, taskPanel):
if activeBody is not None:
activeBody.addObject(newObj)
viewConf = GetViewConfig(baseObj)
SetViewConfig(newObj, viewConf)
Gui.Selection.clearSelection()
#newObj.baseObject[0].ViewObject.Visibility = False
baseObj.ViewObject.Visibility = False
dialog = taskPanel(newObj)
FreeCAD.ActiveDocument.recompute()
Gui.Control.showDialog(dialog)
return
def smCreateNewObject(baseObj, name):
doc = FreeCAD.ActiveDocument
activeBody = None
view = Gui.ActiveDocument.ActiveView
if hasattr(view, 'getActiveObject'):
activeBody = view.getActiveObject('pdbody')
if not smIsOperationLegal(activeBody, baseObj):
return None, None
doc.openTransaction(name)
if activeBody is None or not smIsPartDesign(baseObj):
newObj = doc.addObject("Part::FeaturePython", name)
activeBody = None
else:
newObj = doc.addObject("PartDesign::FeaturePython", name)
return (newObj, activeBody)
#************************************************************************************
#* View providers for part and part design
#************************************************************************************
class SMViewProvider:
"A View provider for sheetmetal objects. supports Part/Part-Design types"
def __init__(self, obj):
obj.Proxy = self
self.Object = obj.Object
def attach(self, obj):
self.Object = obj.Object
return
def setupContextMenu(self, viewObject, menu):
action = menu.addAction(FreeCAD.Qt.translate(
"QObject", "Edit %1").replace("%1", viewObject.Object.Label))
action.triggered.connect(
lambda: self.startDefaultEditMode(viewObject))
return False
def startDefaultEditMode(self, viewObject):
viewObject.Document.setEdit(viewObject.Object, 0)
def updateData(self, fp, prop):
return
def getDisplayModes(self, obj):
modes = []
return modes
def setDisplayMode(self, mode):
return mode
def onChanged(self, vp, prop):
return
def __getstate__(self):
# return {'ObjectName' : self.Object.Name}
return None
def __setstate__(self, state):
self.loads(state)
# dumps and loads replace __getstate__ and __setstate__ post v. 0.21.2
def dumps(self):
return None
def loads(self, state):
if state is not None:
doc = FreeCAD.ActiveDocument
self.Object = doc.getObject(state['ObjectName'])
def claimChildren(self):
objs = []
if not smIsPartDesign(self.Object) and hasattr(self.Object, "baseObject"):
objs.append(self.Object.baseObject[0])
if hasattr(self.Object, "Sketch"):
objs.append(self.Object.Sketch)
return objs
def setEdit(self, vobj, mode):
if not hasattr(self, "getTaskPanel"):
return False
taskd = self.getTaskPanel(vobj.Object)
if smIsPartDesign(self.Object):
self.Object.ViewObject.Visibility = True
FreeCAD.ActiveDocument.openTransaction(self.Object.Name)
Gui.Control.showDialog(taskd)
return True
def unsetEdit(self, _vobj, _mode):
Gui.Control.closeDialog()
if hasattr(self.Object, "baseObject"):
self.Object.baseObject[0].ViewObject.Visibility = False
self.Object.ViewObject.Visibility = True
return False
# Else: In case no gui is loaded
else:
def smWarnDialog(msg):
SMLogger.warning(msg)
def smHideObjects(*args):
pass
def smStripTrailingNumber(item):
return re.sub(r'\d+$', '', item)
def smBelongToBody(item, body):
if body is None:
return False
for obj in body.Group:
if obj.Name == item.Name:
return True
return False
def smIsSketchObject(obj):
return obj.TypeId.startswith("Sketcher::")
def smIsPartDesign(obj):
if smIsSketchObject(obj):
if hasattr(obj, "getParents"): # FreeCAD Linkstage compatibility
if len(obj.getParents()) == 0:
return False
return isinstance(obj.getParents()[0][0], Part.BodyBase)
return isinstance(obj.getParent(), Part.BodyBase)
return obj.TypeId.startswith("PartDesign::")
def smIsOperationLegal(body, selobj):
# FreeCAD.Console.PrintLog(str(selobj) + " " + str(body) + " " + str(smBelongToBody(selobj, body)) + "\n")
if smIsPartDesign(selobj) and not smBelongToBody(selobj, body):
smWarnDialog(
translate(
"QMessageBox",
"The selected geometry does not belong to the active Body.\n"
"Please make the container of this item active by\n"
"double clicking on it.",
)
)
return False
return True
def is_autolink_enabled():
return params.GetInt("AutoLinkBendRadius", 0)
def GetViewConfig(obj):
viewconf = {}
if hasattr(obj.ViewObject, "ShapeColor"):
viewconf["objShapeCol"] = obj.ViewObject.ShapeColor
viewconf["objShapeTsp"] = obj.ViewObject.Transparency
viewconf["objDiffuseCol"] = obj.ViewObject.DiffuseColor
# TODO: Make the individual face colors be retained
# needDiffuseColorExtension = ( len(selobj.ViewObject.DiffuseColor) < len(selobj.Shape.Faces) )
else:
return None
return viewconf
def SetViewConfig(obj, viewconf):
if hasattr(obj.ViewObject, "ShapeColor") and viewconf:
obj.ViewObject.ShapeColor = viewconf["objShapeCol"]
obj.ViewObject.Transparency = viewconf["objShapeTsp"]
obj.ViewObject.DiffuseColor = viewconf["objDiffuseCol"]
def getOriginalBendObject(obj):
for item in obj.OutListRecursive:
if hasattr(item, "Proxy"):
proxy = item.Proxy.__class__.__name__
if (proxy == 'SMBaseBend'
or proxy == 'SMBendWall'
or proxy == 'SMSolidBend'
or proxy == 'SMFoldWall'
):
if not getOriginalBendObject(item):
return item
return None
def getElementFromTNP(tnpName):
names = tnpName.split('.')
if len(names) > 1:
FreeCAD.Console.PrintWarning("Warning: Tnp Name still visible: " + tnpName + "\n")
return names[len(names) - 1].lstrip('?')
def smAddProperty(obj, proptype, name, proptip, defval=None,
paramgroup="Parameters", replacedname = None):
"""
Add a property to a given object.
Args:
- obj: The object to which the property should be added.
- proptype: The type of the property (e.g., "App::PropertyLength", "App::PropertyBool").
- name: The name of the property. Non-translatable.
- proptip: The tooltip for the property. Need to be translated from outside.
- defval: The default value for the property (optional).
- paramgroup: The parameter group to which the property should belong (default is "Parameters").
- replacedname: If a property is renamed, for backward compatibility, add the replaced name
to the old one so data can be extracted from it in old files
"""
if not hasattr(obj, name):
obj.addProperty(proptype, name, paramgroup, proptip)
if defval is not None:
setattr(obj, name, defval)
# replaced name is either given or automatically search for
# old lower case version of the same parameter
if replacedname is None and name[0].isupper():
replacedname = name[0].lower() + name[1:]
if replacedname is not None and hasattr(obj, replacedname):
setattr(obj, name, getattr(obj, replacedname))
#obj.removeProperty(replacedname)
obj.setEditorMode(replacedname, 2) # Hide
def smAddLengthProperty(obj, name, proptip, defval, paramgroup="Parameters"):
smAddProperty(obj, "App::PropertyLength", name, proptip, defval, paramgroup)
def smAddBoolProperty(obj, name, proptip, defval, paramgroup="Parameters"):
smAddProperty(obj, "App::PropertyBool", name, proptip, defval, paramgroup)
def smAddDistanceProperty(obj, name, proptip, defval, paramgroup="Parameters"):
smAddProperty(obj, "App::PropertyDistance", name, proptip, defval, paramgroup)
def smAddAngleProperty(obj, name, proptip, defval, paramgroup="Parameters"):
smAddProperty(obj, "App::PropertyAngle", name, proptip, defval, paramgroup)
def smAddFloatProperty(obj, name, proptip, defval, paramgroup="Parameters"):
smAddProperty(obj, "App::PropertyFloat", name, proptip, defval, paramgroup)
def smAddEnumProperty(
obj, name, proptip, enumlist, defval=None, paramgroup="Parameters"
):
if not hasattr(obj, name):
_tip_ = FreeCAD.Qt.translate("App::Property", proptip)
obj.addProperty("App::PropertyEnumeration", name, paramgroup, _tip_)
setattr(obj, name, enumlist)
if defval is not None:
setattr(obj, name, defval)
def smGetBodyOfItem(obj):
if hasattr(obj, "getParent"):
return obj.getParent()
elif hasattr(obj, "getParents"): # probably FreeCadLink version
parent, _ = obj.getParents()[0]
return parent
return None