forked from mwganson/DynamicData
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamicDataCmd.py
More file actions
1441 lines (1298 loc) · 61.1 KB
/
DynamicDataCmd.py
File metadata and controls
1441 lines (1298 loc) · 61.1 KB
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
###################################################################################
#
# DynamicDataCmd.py
#
# Copyright 2018-2019 Mark Ganson <TheMarkster> mwganson at gmail
#
# 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 Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#
###################################################################################
__title__ = "DynamicData"
__author__ = "Mark Ganson <TheMarkster>"
__url__ = "https://github.com/mwganson/DynamicData"
__date__ = "2020.09.10"
__version__ = "2.22"
version = 2.22
mostRecentTypes=[]
mostRecentTypesLength = 5 #will be updated from parameters
from FreeCAD import Gui
from PySide import QtCore, QtGui
import FreeCAD, FreeCADGui, Part, os, math, re
__dir__ = os.path.dirname(__file__)
iconPath = os.path.join( __dir__, 'Resources', 'icons' )
keepToolbar = True
windowFlags = QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowCloseButtonHint
def initialize():
Gui.addCommand("DynamicDataCreateObject", DynamicDataCreateObjectCommandClass())
Gui.addCommand("DynamicDataAddProperty", DynamicDataAddPropertyCommandClass())
Gui.addCommand("DynamicDataRemoveProperty", DynamicDataRemovePropertyCommandClass())
Gui.addCommand("DynamicDataImportNamedConstraints", DynamicDataImportNamedConstraintsCommandClass())
Gui.addCommand("DynamicDataImportAliases", DynamicDataImportAliasesCommandClass())
Gui.addCommand("DynamicDataSettings", DynamicDataSettingsCommandClass())
Gui.addCommand("DynamicDataCopyProperty", DynamicDataCopyPropertyCommandClass())
propertyTypes =[
"Acceleration",
"Angle",
"Area",
"Bool",
"Color",
"Direction",
"Distance",
"File",
"FileIncluded",
"Float",
"FloatConstraint",
"FloatList",
"Font",
"Force",
"Integer",
"IntegerConstraint",
"IntegerList",
"Length",
"Link",
"LinkChild",
"LinkGlobal",
"LinkList",
"LinkListChild",
"LinkListGlobal",
"LinkSubList",
# "Material",
"MaterialList",
"Matrix",
"Path",
"Percent",
"Placement",
"PlacementLink",
"Position",
"Precision",
"Pressure",
"Quantity",
"QuantityConstraint",
"Speed",
"String",
"StringList",
"Vector",
"VectorList",
"VectorDistance",
"Volume"]
nonLinkableTypes=[ #cannot be linked with setExpresion()
"Bool",
"Color",
"File",
"FileIncluded",
"FloatList",
"Font",
"IntegerList",
"Link",
"LinkChild",
"LinkGlobal",
"LinkList",
"LinkListChild",
"LinkListGlobal",
"LinkSubList",
#"Material",
"MaterialList",
"Matrix",
"Path",
"PlacementLink",
"String",
"StringList",
"VectorList"]
xyzTypes = [#x,y,z elements must be linked separately
"Direction",
"Position",
"Vector",
"VectorDistance"]
#######################################################################################
# Keep Toolbar active even after leaving workbench
class DynamicDataSettingsCommandClass(object):
"""Settings, currently only whether to keep toolbar after leaving workbench"""
global mostRecentTypes
def __init__(self):
pass
def GetResources(self):
return {'Pixmap' : os.path.join( iconPath , 'Settings.svg') , # the name of an icon file available in the resources
'MenuText': "&Settings" ,'Accel': "Ctrl+Shift+D,S",
'ToolTip' : "Workbench settings dialog"}
def Activated(self):
global mostRecentTypes
doc = FreeCAD.ActiveDocument
from PySide import QtGui
window = QtGui.QApplication.activeWindow()
pg = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/DynamicData")
keep = pg.GetBool('KeepToolbar',True)
mostRecentTypesLength = pg.GetInt('mruLength',5)
items=["Keep the toolbar active","Do not keep the toolbar active","Change length ("+str(mostRecentTypesLength)+") of most recently used type list","Support ViewObject properties", "Do not support ViewObject properties","Add to active container on creation", "Do not add to active container on creation","Cancel"]
if pg.GetBool("KeepToolbar",True):
items[0]="*"+items[0]
else:
items[1] = "*"+items[1]
if pg.GetBool("SupportViewObjectProperties",False):
items[3] = "*"+items[3]
else:
items[4] = "*"+items[4]
if pg.GetBool("AddToActiveContainer",False):
items[5] = "*"+items[5]
else:
items[6] = "*"+items[6]
item,ok = QtGui.QInputDialog.getItem(window,'DynamicData','Settings\n\nSelect the settings option\n',items,0,False,windowFlags)
if ok and item == items[-1]:
return
elif ok and item == items[0]:
keep = True
pg.SetBool('KeepToolbar', keep)
elif ok and item==items[1]:
keep = False
pg.SetBool('KeepToolbar', keep)
elif ok and item==items[3]:
pg.SetBool('SupportViewObjectProperties',True)
elif ok and item==items[4]:
pg.SetBool('SupportViewObjectProperties',False)
elif ok and item==items[5]:
pg.SetBool('AddToActiveContainer',True)
elif ok and item==items[6]:
pg.SetBool('AddToActiveContainer',False)
elif ok and item==items[2]:
count,ok = QtGui.QInputDialog.getInt(window,'DynamicData','Settings\n\nHow many items in most recently used type list?\n\nCurrent setting = '+str(mostRecentTypesLength)+'\n',mostRecentTypesLength,0,20,1,windowFlags)
if ok:
if count != mostRecentTypesLength:
pg.SetInt('mruLength',count)
mostRecentTypesLength = count
mostRecentTypes = ([""]*25) [:count]
for ii in range(0,count):
mru = pg.GetString('mru'+str(ii),"")
if not mru in mostRecentTypes:
mostRecentTypes[ii]=mru
return
def IsActive(self):
return True
#Gui.addCommand("DynamicDataKeepToolbar", DynamicDataKeepToolbarCommandClass())
####################################################################################
# Create the dynamic data container object
class DynamicDataCreateObjectCommandClass(object):
"""Create Object command"""
def GetResources(self):
return {'Pixmap' : os.path.join( iconPath , 'CreateObject.svg') ,
'MenuText': "&Create Object" ,'Accel': "Ctrl+Shift+D,C",
'ToolTip' : "Create the DynamicData object to contain the custom properties"}
def Activated(self):
doc = FreeCAD.ActiveDocument
#doc.openTransaction("CreateObject")
a = doc.addObject("App::FeaturePython","dd")
doc.recompute()
a.addProperty("App::PropertyStringList","DynamicData").DynamicData=self.getHelp()
doc.recompute()
setattr(a.ViewObject,'DisplayMode',['0']) #avoid enumeration -1 warning
#doc.commitTransaction()
a.touch()
doc.recompute()
Gui.Selection.clearSelection()
pg = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/DynamicData")
if pg.GetBool('AddToActiveContainer',False):
body = Gui.ActiveDocument.ActiveView.getActiveObject("pdbody")
part = Gui.ActiveDocument.ActiveView.getActiveObject("part")
if body:
body.Group += [a]
elif part:
part.Group += [a]
doc.recompute()
Gui.Selection.addSelection(a) #select so the user can immediately add a new property
doc.recompute()
return
def IsActive(self):
if not FreeCAD.ActiveDocument:
return False
return True
def getHelp(self):
return ["Created with DynamicData (v"+str(version)+") workbench.",
"This is a simple container object built",
"for holding custom properties. Worbench",
"installation is not required to use the",
"container object -- instead only for",
"adding / removing custom properties.",
"(But this can also be done via scripting.)"
]
#Gui.addCommand("DynamicDataCreateObject", DynamicDataCreateObjectCommandClass())
class MultiTextInput(QtGui.QDialog):
def __init__(self):
QtGui.QDialog.__init__(self)
layout = QtGui.QGridLayout()
#layout.setColumnStretch(1, 1)
self.label = QtGui.QLabel(self)
self.spacer = QtGui.QLabel(" ")
self.label2 = QtGui.QLabel(self)
self.label2.setStyleSheet('color: red')
self.nameLabel = QtGui.QLabel("Name: dd")
self.nameEdit = QtGui.QLineEdit(self)
self.nameEdit.editingFinished.connect(self.on_edit_finished)
self.nameEdit.textChanged.connect(self.on_text_changed)
self.valueLabel = QtGui.QLabel("Value: ")
self.valueEdit = QtGui.QLineEdit(self)
self.valueEdit.textChanged.connect(self.on_value_changed)
self.groupLabel = QtGui.QLabel("Group: ")
self.groupEdit = QtGui.QLineEdit(self)
self.tooltipLabel = QtGui.QLabel("Tooltip: ")
self.tooltipPrependLabel = QtGui.QLabel("")
self.tooltipEdit = QtGui.QLineEdit(self)
layout.addWidget(self.label, 0, 0, 2, 5)
layout.addWidget(self.spacer, 3, 0, 1, 5)
layout.addWidget(self.nameLabel, 4, 0, 1, 1)
layout.addWidget(self.nameEdit, 4, 1, 1, 5)
layout.addWidget(self.valueLabel, 5, 0, 1, 1)
layout.addWidget(self.valueEdit, 5, 1, 1, 5)
layout.addWidget(self.groupLabel, 6, 0, 1, 1)
layout.addWidget(self.groupEdit, 6, 1, 1, 5)
layout.addWidget(self.tooltipLabel, 7, 0, 1, 1)
layout.addWidget(self.tooltipPrependLabel, 7, 1, 1, 1)
layout.addWidget(self.tooltipEdit, 7, 2, 1, 4)
layout.addWidget(self.spacer, 8, 0, 1, 5)
layout.addWidget(self.label2, 9, 0, 1, 5)
buttons = QtGui.QDialogButtonBox(
QtGui.QDialogButtonBox.Ok.__or__(QtGui.QDialogButtonBox.Cancel),
QtCore.Qt.Horizontal, self)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
buttons.setCenterButtons(True)
layout.addWidget(buttons, 10, 0, 1, 5)
self.setLayout(layout)
def on_value_changed(self): #commented out for now because it throws exceptions even inside try: except: block
pass
#obj = FreeCAD.ActiveDocument.ActiveObject
#val = self.valueEdit.text()
#result = "Invalid expression as of yet"
#if len(val) > 1 and val[0] == "=":
# try:
# result = obj.evalExpression(val[1:])
# self.label2.setStyleSheet('color: black')
# except:
# self.label2.setStyleSheet('color: red')
# self.label2.setText(str(result))
def on_text_changed(self):
self.on_edit_finished()
def on_edit_finished(self):
if ";" in self.nameEdit.text():
hasValue = False
propertyName = self.nameEdit.text()
split = propertyName.split(';')
propertyName = split[0].replace(' ','_')
if len(propertyName)==0:
propertyName = "Prop"
if len(split)>1: #has a group name
if len(split[1])>0: #allow for ;; empty string to mean use current group name
self.groupEdit.setText(split[1])
if len(split)>2: #has a tooltip
if len(split[2])>0:
self.tooltipEdit.setText(split[2])
if len(split)==4: #has a value
hasValue = True
val = split[3]
self.groupEdit.setEnabled(False)
if hasValue:
self.valueEdit.setText(val)
self.valueEdit.setEnabled(False)
self.tooltipEdit.setEnabled(False)
else:
self.groupEdit.setEnabled(True)
self.valueEdit.setEnabled(True)
self.tooltipEdit.setEnabled(True)
propertyName = self.nameEdit.text()
obj = FreeCAD.ActiveDocument.ActiveObject
if hasattr(obj,'dd'+propertyName):
self.label2.setText('Property name already exists')
else:
self.label2.setText('')
######################################################################################
# Add a dynamic property to the object
class DynamicDataAddPropertyCommandClass(object):
"""Add Property Command"""
global mostRecentTypes
global mostRecentTypesLength
def getPropertyTypes(self):
return propertyTypes
def GetResources(self):
return {'Pixmap' : os.path.join( iconPath , 'AddProperty.svg') ,
'MenuText': "&Add Property" ,'Accel': "Ctrl+Shift+D,A",
'ToolTip' : "Add a custom property to the DynamicData object"}
def Activated(self):
global mostRecentTypes
global mostRecentTypesLength
doc = FreeCAD.ActiveDocument
obj = Gui.Selection.getSelectionEx()[0].Object
if not 'FeaturePython' in str(obj.TypeId):
FreeCAD.Console.PrintError('DynamicData Workbench: Cannot add property to non-FeaturePython objects.\n')
return
doc.openTransaction("dd Add Property")
#add the property
window = QtGui.QApplication.activeWindow()
items = self.getPropertyTypes()
recent = []
separator = "-----"
pg = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/DynamicData")
mostRecentTypesLength = pg.GetInt('mruLength',5)
for ii in range(mostRecentTypesLength-1,-1,-1):
if mostRecentTypes[ii]:
recent.insert(0,mostRecentTypes[ii])
pg.SetString('mru'+str(ii), mostRecentTypes[ii])
if len(recent) > 0:
recent += [separator]
item,ok = QtGui.QInputDialog.getItem(window,'DynamicData','Add Property Tool\n\nSelect Property Type',recent+items,0,False,windowFlags)
if not ok or item==separator:
return
else:
if not item in mostRecentTypes:
mostRecentTypes.insert(0,item)
else:
mostRecentTypes.remove(item) #ensure it is at front of the list
mostRecentTypes.insert(0,item)
if len(mostRecentTypes)>mostRecentTypesLength:
mostRecentTypes = mostRecentTypes[:mostRecentTypesLength]
for ii in range(mostRecentTypesLength-1,-1,-1):
if mostRecentTypes[ii]:
pg.SetString('mru'+str(ii), mostRecentTypes[ii])
dlg = MultiTextInput()
dlg.setWindowFlags(windowFlags)
dlg.setWindowTitle("DynamicData")
dlg.label.setText("Old-style name;group;tip;value syntax\nstill supported in Name field\n\nIn Value field:\nUse =expr for expressions, e.g. =Box.Height")
# obj = FreeCAD.ActiveDocument.ActiveObject
vals=['']
for ii in range(1,1000):
vals.append(str(ii))
idx = 0
while hasattr(obj,'dd' + item + str(vals[idx])):
idx += 1
item + str(vals[idx])
dlg.nameEdit.setText(item + vals[idx])
if hasattr(obj,'dd'+ item + vals[idx]):
dlg.label2.setText('Property name already exists')
else:
dlg.label2.setText('')
dlg.nameEdit.selectAll()
if "List" in item:
dlg.valueLabel.setText("Values:")
dlg.label.setText("List values should be semicolon delimited, e.g. 1;2;3;7")
dlg.groupEdit.setText(self.groupName)
dlg.tooltipLabel.setText("Tooltip:")
dlg.tooltipPrependLabel.setText("["+item+"]")
ok = dlg.exec_()
if not ok:
return
if not ";" in dlg.nameEdit.text():
self.propertyName = dlg.nameEdit.text()+";"+dlg.groupEdit.text()+";"+dlg.tooltipEdit.text()+";"+dlg.valueEdit.text()
else:
self.propertyName = dlg.nameEdit.text()
if len(self.propertyName)==0:
self.propertyName=';;;' #use defaults
if 'dd' in self.propertyName[:2] or 'Dd' in self.propertyName[:2]:
self.propertyName = self.propertyName[2:] #strip dd temporarily
cap = lambda x: x[0].upper() + x[1:] #credit: PradyJord from stackoverflow for this trick
self.propertyName = cap(self.propertyName) #capitalize first character to add space between dd and self.propertyName
self.tooltip='['+item+'] ' #e.g. [Float]
val=None
vals=[]
hasVal = False
listval = ''
if ';' in self.propertyName:
split = self.propertyName.split(';')
self.propertyName = split[0].replace(' ','_')
if len(self.propertyName)==0:
self.propertyName = self.defaultPropertyName
if len(split)>1: #has a group name
if len(split[1])>0: #allow for ;; empty string to mean use current group name
self.groupName = split[1]
if len(split)>2: #has a tooltip
if len(split[2])>0:
self.tooltip = self.tooltip + split[2]
if len(split)>=4: #has a value
if "=list(" in split[3]:
listval = split[3]
for ii in range(4, len(split)):
listval += ';' + split[ii]
val = split[3]
if len(val)>0:
hasVal = True
if len(split)>4 and 'List' in item: #multiple values for list type property
hasVal = True
for ii in range(3,len(split)):
try:
if len(split[ii])>0:
vals.append(self.eval_expr(split[ii]))
except:
vals.append(split[ii])
if hasattr(obj,'dd'+self.propertyName):
FreeCAD.Console.PrintError('DyamicData: Unable to add property: dd'+self.propertyName+' because it already exists.\n')
return
p = obj.addProperty('App::Property'+item,'dd'+self.propertyName,str(self.groupName),self.tooltip)
if hasVal and len(vals)==0:
if val[0] == "=":
try:
obj.setExpression('dd'+self.propertyName, val[1:])
obj.touch()
doc.recompute()
doc.commitTransaction()
return
except:
FreeCAD.Console.PrintWarning('DynamicData: Unable to set expreesion: '+str(val[1:])+'\n')
doc.commitTransaction()
return
try:
atr = self.eval_expr(val)
except:
try:
atr = val
except:
FreeCAD.Console.PrintWarning('DynamicData: Unable to set value: '+str(val)+'\n')
try:
setattr(p,'dd'+self.propertyName,atr)
except:
FreeCAD.Console.PrintWarning('DynamicData: Unable to set attribute: '+str(val)+'\n')
elif hasVal and len(vals)>0:
if listval:
try:
obj.setExpression('dd'+self.propertyName, listval[1:]) #[1:] strips the "="
obj.touch()
doc.recompute()
doc.commitTransaction()
return
except:
FreeCAD.Console.PrintWarning('DynamicData: Unable to set expression: '+str(listval[1:])+'\n')
doc.commitTransaction()
return
try:
setattr(p,'dd'+self.propertyName,list(vals))
except:
FreeCAD.Console.PrintWarning('DynamicData: Unable to set list attribute: '+str(vals)+'\n')
obj.touch()
doc.recompute()
doc.commitTransaction()
doc.recompute()
return
def IsActive(self):
if not FreeCAD.ActiveDocument:
return False
selection = Gui.Selection.getSelectionEx()
if not selection:
return False
if not hasattr(selection[0].Object,"DynamicData"):
return False
return True
def __init__(self):
#global mostRecentTypes
global mostRecentTypesLength
import ast, locale
import operator as op
self.groupName="DefaultGroup"
self.defaultPropertyName="Prop"
self.tooltip="tip"
pg = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/DynamicData")
mostRecentTypesLength = pg.GetInt('mruLength',5)
for ii in range(0, mostRecentTypesLength):
mostRecentTypes.append(pg.GetString('mru'+str(ii),""))
self.SEPARATOR = locale.localeconv()['decimal_point']
self.SEPARATOR_STANDIN = 'p'
self.DEGREES_INDICATOR = 'd'
self.RADIANS_INDICATOR = 'r'
# for evaluating math expressions in gui input text fields
# credit "jfs" of stackoverflow for these 2 functions, which I modified for my needs
# supported operators
self.operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor, #ast.BitXor: op.pow would remap ^ to pow()
ast.USub: op.neg}
#add some constants and references that might be useful for users
self.constants = {'pi':math.pi,'e':math.e, 'phi':16180339887e-10, 'golden':16180339887e-10,'golden_ratio':16180339887e-10,
'inch':254e-1, 'in':254e-1,'inches':254e-1, 'thou':254e-4}
self.references= {'version':'version'}
self.maths = {'cos':'cos','acos':'acos','tan':'tan','atan':'atan','sin':'sin','asin':'asin','log':'log','tlog':'log10'}
def eval_this(self,node):
import ast
import operator as op
if isinstance(node, ast.Num): # <number>
return node.n
elif isinstance(node, ast.BinOp): # <left> <operator> <right>
return self.operators[type(node.op)](self.eval_this(node.left), self.eval_this(node.right))
elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
return self.operators[type(node.op)](self.eval_this(node.operand))
#provide support for constants and references
elif node.id:
if node.id in self.constants:
return self.constants[node.id]
elif node.id in self.references: #e.g. references[node.id] is a string, e.g. 'version' representing global variable version
return globals()[self.references[node.id]]
elif node.id[:3] in self.maths:
func = getattr(math, self.maths[node.id[:3]])
opstring = node.id[3:].replace(self.SEPARATOR_STANDIN,self.SEPARATOR)
if opstring[-1:]==self.DEGREES_INDICATOR:
opstring = opstring[:-1]
return func(float(opstring)*math.pi/180.0)
elif opstring[-1:]==self.RADIANS_INDICATOR:
opstring = opstring[:-1]
return func(float(opstring))
else:
return func(float(opstring))
elif node.id[:4] in self.maths:
func = getattr(math, self.maths[node.id[:4]])
opstring = node.id[4:].replace(self.SEPARATOR_STANDIN,self.SEPARATOR)
if opstring[-1:]==self.DEGREES_INDICATOR:
opstring = opstring[:-1]
return func(float(opstring)*math.pi/180.0)
elif opstring[-1:]==self.RADIANS_INDICATOR:
opstring = opstring[:-1]
return func(float(opstring))
else:
return func(float(opstring))
else:
App.Console.PrintMessage('unsupported token: '+node.id+'\n')
else:
raise TypeError(node)
def eval_expr(self,expr):
import ast
import operator as op
"""
>>> eval_expr('2^6')
4
>>> eval_expr('2**6')
64
>>> eval_expr('1 + 2*3**(4^5) / (6 + -7)')
-5.0
"""
return self.eval_this(ast.parse(expr, mode='eval').body)
#Gui.addCommand("DynamicDataAddProperty", DynamicDataAddPropertyCommandClass())
########################################################################################
# Remove custom dynamic property
class DynamicDataRemovePropertyCommandClass(object):
"""Remove Property Command"""
def GetResources(self):
return {'Pixmap' : os.path.join( iconPath , 'RemoveProperty.svg') ,
'MenuText': "&Remove Property" ,'Accel': "Ctrl+Shift+D,R",
'ToolTip' : "Remove a custom property from the DynamicData object"}
def getProperties(self,obj):
cell_regex = re.compile('^dd.*$') #all we are interested in will begin with 'dd'
prop = []
for p in obj.PropertiesList:
if cell_regex.search(p):
prop.append(p)
return prop
def Activated(self):
doc = FreeCAD.ActiveDocument
selection = Gui.Selection.getSelectionEx()
if not selection:
return
obj = selection[0].Object
#remove the property
window = QtGui.QApplication.activeWindow()
items = self.getProperties(obj)
if len(items)==0:
FreeCAD.Console.PrintMessage("DyanmicData: no properties to remove. Add some properties first.\n")
return
items.insert(0,"<Remove all properties>")
item,ok = QtGui.QInputDialog.getItem(window,'DynamicData','Remove Property Tool\n\nSelect property to remove',items,0,False,windowFlags)
if not ok:
return
if item==items[0]:
doc.openTransaction("dd RemoveProperties")
for ii in range(1,len(items)):
obj.removeProperty(items[ii])
doc.commitTransaction()
else:
doc.openTransaction("dd RemoveProperty")
obj.removeProperty(item)
doc.commitTransaction()
doc.recompute()
return
def IsActive(self):
if not FreeCAD.ActiveDocument:
return False
selection = Gui.Selection.getSelectionEx()
if not selection:
return False
obj = selection[0].Object
if len(self.getProperties(obj))==0:
return False
if not hasattr(selection[0].Object,"DynamicData"):
return False
return True
#Gui.addCommand("DynamicDataRemoveProperty", DynamicDataRemovePropertyCommandClass())
########################################################################################
# Import aliases from spreadsheet
class DynamicDataImportAliasesCommandClass(object):
"""Import Aliases Command"""
def getProperties(self,obj):
cell_regex = re.compile('^dd.*$') #all we are interested in will begin with 'dd'
prop = []
for p in obj.PropertiesList:
if cell_regex.search(p):
prop.append(p)
return prop
def GetResources(self):
return {'Pixmap' : os.path.join( iconPath , 'ImportAliases.svg') ,
'MenuText': "&Import Aliases" ,
'ToolTip' : "Import aliases from selected spreadsheet(s) into selected dd object"}
def Activated(self):
sheets=[]
dd = None
doc = FreeCAD.ActiveDocument
selection = Gui.Selection.getSelectionEx()
cap = lambda x: x[0].upper() + x[1:] #credit: PradyJord from stackoverflow for this trick
if not selection:
return
for sel in selection:
obj = sel.Object
if "Spreadsheet.Sheet" in str(type(obj)) and not obj.Label[-1:] == '_': #ignore spreadsheet label's ending in underscore
sheets.append(obj)
elif "FeaturePython" in str(type(obj)) and hasattr(obj,"DynamicData"):
if not dd:
dd = obj
else:
FreeCAD.Console.PrintMessage("Can only have one dd object selected for this operation\n")
return
if len(sheets)==0:
#todo: handle no selected spreadsheets. For now, just return
FreeCAD.Console.PrintMessage("DynamicData: No selected spreadsheet(s)\n")
return
if not dd:
#todo: handle no dd object selected. For now, just return
FreeCAD.Console.PrintMessage("DynamicData: No selected dd object\n")
return
#sanity check
window = QtGui.QApplication.activeWindow()
items=["Do the import, I know what I\'m doing","Cancel"]
item,ok = QtGui.QInputDialog.getItem(window,'DynamicData: Sanity Check',
'Warning: This will modify your spreadsheet. \n\
\n\
It will import the aliases from the spreadsheet and reset them to \n\
point to the dd object. After the import is done you should make any changes \n\
to the dd property rather than to the alias cell in the spreadsheet. \n\
\n\
All imports come in as values, not as expressions.\n\
\n\
For example: diameter=radius*2 imports as 10.0 mm, not as an expression radius*2\n\
\n\
You should still keep your spreadsheet because other expressions referencing aliases in the\n\
spreadsheet will still be referencing them. The difference is now the spreadsheet cells \n\
will be referencing the dd object. Again, make any changes to the dd property, not to the spreadsheet.\n\
\n\
For example: \n\
Dependency graph:\n\
before import: constraint -> spreadsheet\n\
after import: constraint -> spreadsheet -> dd object\n\
\n\
You can partially undo this operation. If undone, the changes to the spreadsheet will be \n\
reverted, but you will still need to manually remove the new properties from the dd object.\n\
The new properties will remain after the undo, but they will no longer reference anything. \n\
\n\
You should save your document before proceeding.\n',items,0,False,windowFlags)
if not ok or item==items[-1]:
return
FreeCAD.ActiveDocument.openTransaction("dd Import Aliases") #setup undo
aliases=[]
for sheet in sheets:
for line in sheet.cells.Content.splitlines():
if "<Cells Count=" in line or "</Cells>" in line:
continue
if not "alias=" in line:
continue
idx = line.find("alias=\"")+len("alias=\"")
idx2 = line.find("\"",idx)
if not line[idx:idx2][-1]=="_": #skip aliases that end in an underscore
aliases.append(line[idx:idx2])
else:
FreeCAD.Console.PrintWarning('DynamicData: skipping alias \"'+line[idx:idx2]+'\" because it ends in an underscore (_).\n')
for alias in aliases:
atr = getattr(sheet,alias)
if "Base.Quantity" in str(type(atr)):
#handle quantity types
propertyType = atr.Unit.Type #e.g. 'Length'
#handle inconsistencies in naming convention between unit types and property types
if 'Velocity' in propertyType:
propertyType='Speed'
userString = atr.UserString
elif "'float\'" in str(type(atr)):
#handle float types
propertyType='Float'
userString=atr
elif "'int\'" in str(type(atr)):
#handle int types (actually, just treat them as floats
#since many users no doubt will expect this behavior for imported aliases)
propertyType='Float'
userString=atr
elif "unicode" in str(type(atr)) or '<class \'str\'>' in str(type(atr)):
#handle unicode string types
propertyType='String'
userString=atr
else:
FreeCAD.Console.PrintError('DynamicData: please report: unknown property type error importing alias from spreadsheet ('+str(type(atr))+')\n')
continue
name = 'dd'+sheet.Label+'_'+cap(alias)
if not hasattr(dd,name): #avoid adding the same property again
dd.addProperty('App::Property'+propertyType,name,'Imported from: '+sheet.Label, propertyType)
setattr(dd,name,userString)
FreeCAD.Console.PrintMessage('DynamicData: adding property: '+name+' to dd object, resetting spreadsheet: '+sheet.Label+'.'+alias+' to point to '+dd.Label+'.'+name+'\n')
sheet.set(alias,str(dd.Label+'.'+name))
else:
FreeCAD.Console.PrintWarning('DynamicData: skipping existing property: '+name+'\n')
continue
FreeCAD.ActiveDocument.commitTransaction()
doc.recompute()
if len(aliases)==0:
FreeCAD.Console.PrintMessage('DynamicData: No aliases found.\n')
return
return
def IsActive(self):
sheets=[]
dd = None
doc = FreeCAD.ActiveDocument
selection = Gui.Selection.getSelectionEx()
if not selection:
return
for sel in selection:
obj = sel.Object
if "Spreadsheet.Sheet" in str(type(obj)) and not obj.Label[-1:] == '_': #ignore spreadsheet labels ending in underscore
sheets.append(obj)
elif "FeaturePython" in str(type(obj)) and hasattr(obj,"DynamicData"):
if not dd:
dd = obj
else:
return False #more than 1 dd object selected
if len(sheets)==0:
return False
if not dd:
return False
return True
#Gui.addCommand("DynamicDataImportAliases", DynamicDataImportAliasesCommandClass())
########################################################################################
# Import named constraints from sketch
class DynamicDataImportNamedConstraintsCommandClass(object):
"""Import Named Constraints Command"""
def getProperties(self,obj):
cell_regex = re.compile('^dd.*$') #all we are interested in will begin with 'dd'
prop = []
for p in obj.PropertiesList:
if cell_regex.search(p):
prop.append(p)
return prop
def GetResources(self):
return {'Pixmap' : os.path.join( iconPath , 'ImportNamedConstraints.svg') ,
'MenuText': "&Import Named Constraints" ,
'ToolTip' : "Import named constraints from selected sketch(es) into selected dd object"}
def Activated(self):
sketches=[]
dd = None
doc = FreeCAD.ActiveDocument
selection = Gui.Selection.getSelectionEx()
cap = lambda x: x[0].upper() + x[1:] #credit: PradyJord from stackoverflow for this trick
if not selection:
return
for sel in selection:
obj = sel.Object
if "Sketcher.SketchObject" in str(type(obj)) and not obj.Label[-1:] == '_': #ignore sketch labels ending in underscore
sketches.append(obj)
elif "FeaturePython" in str(type(obj)) and hasattr(obj,"DynamicData"):
if not dd:
dd = obj
else:
FreeCAD.Console.PrintMessage("Can only have one dd object selected for this operation\n")
return
if len(sketches)==0:
#todo: handle no selected sketches. For now, just return
FreeCAD.Console.PrintMessage("DynamicData: No selected sketch(es)\n")
return
if not dd:
#todo: handle no dd object selected. For now, just return
FreeCAD.Console.PrintMessage("DynamicData: No selected dd object\n")
return
#sanity check
window = QtGui.QApplication.activeWindow()
items=["Do the import, I know what I\'m doing","Cancel"]
item,ok = QtGui.QInputDialog.getItem(window,'DynamicData: Sanity Check',
'Warning: This will modify your sketch. \n\
It will import the named constraints from the sketch and reset them to \n\
point to the dd object. After the import is done you should make changes \n\
to the dd object property rather than to the constraint itself. \n\
\n\
All imports come in as values.\n\
\n\
For example: diameter=radius*2 imports as 10.0 mm, not as an expression radius*2\n\
\n\
For that reason, it might be necessary to rework some formulas in some cases \n\
in order to maintain the parametricity of your model. \n\
\n\
This operation can be partially undone. The sketch will be reset, but you will \n\
still need to remove the newly created properties from the dd object. The properties \n\
will still be there, but they won\'t be linked to anything. \n\
\n\
You should save your document before proceeding\n',items,0,False,windowFlags)
if not ok or item==items[-1]:
return
FreeCAD.ActiveDocument.openTransaction("dd Import Constraints") #setup undo
constraints=[]
for sketch in sketches:
for con in sketch.Constraints:
if not con.Name or con.Name[-1:]=='_': #ignore constraint names ending in underscore
continue
if ' ' in con.Name:
FreeCAD.Console.PrintWarning('DynamicData: skipping \"'+con.Name+'\" Spaces invalid in constraint names.\n')
continue
if not con.Driving:
FreeCAD.Console.PrintWarning('DynamicData: skipping \"'+con.Name+'\" Reference constraints skipped.\n')
continue
constraints.append({'constraintName':con.Name,'value':con.Value,'constraintType':con.Type,'sketchLabel':sketch.Label, 'sketch':sketch})
try:
pass
#sketch.setExpression('Constraints.'+con.Name, dd.Label+'.dd'+sketch.Label+cap(con.Name))
except:
FreeCAD.Console.PrintError('DynamicData: Exception setting expression for '+con.Name+' (skipping)\n')
constraints.pop() #remove the constraint that gave the error
if len(constraints)==0:
FreeCAD.Console.PrintMessage('DynamicData: No named constraints found.\n')
return
for con in constraints:
propertyType = "Length"
value = con['value']
if con['constraintType']=='Angle':
propertyType="Angle"
value *= (180.0/math.pi)
name = 'dd'+con['sketchLabel']+cap(con['constraintName'])
if not hasattr(dd,name): #avoid adding the same property again
dd.addProperty('App::Property'+propertyType,name,'Imported from:'+con['sketchLabel'],'['+propertyType+'] constraint type: ['+con['constraintType']+']')
setattr(dd,name,value)
FreeCAD.Console.PrintMessage('DynamicData: adding property: '+name+' to dd object\n')
sketch = con['sketch']
sketch.setExpression('Constraints.'+con['constraintName'], dd.Label+'.dd'+sketch.Label+cap(con['constraintName']))
else:
FreeCAD.Console.PrintWarning('DynamicData: skipping existing property: '+name+'\n')
FreeCAD.ActiveDocument.commitTransaction()
doc.recompute()
return
def IsActive(self):
sketches=[]
dd = None
doc = FreeCAD.ActiveDocument
selection = Gui.Selection.getSelectionEx()
if not selection:
return
for sel in selection:
obj = sel.Object
if "Sketcher.SketchObject" in str(type(obj)) and not obj.Label[-1:] == '_': #ignore sketch labels ending in underscore
sketches.append(obj)
elif "FeaturePython" in str(type(obj)) and hasattr(obj,"DynamicData"):
if not dd:
dd = obj