-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathDynamicDataCmd.py
2940 lines (2595 loc) · 129 KB
/
DynamicDataCmd.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
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-2023 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__ = "2024.11.06"
__version__ = "2.69"
version = float(__version__)
mostRecentTypes=[]
mostRecentTypesLength = 5 #will be updated from parameters
from FreeCAD import Gui
from PySide import QtCore, QtGui
import FreeCAD, FreeCADGui, os, math, re, ast
App = FreeCAD
Gui = FreeCADGui
__dir__ = os.path.dirname(__file__)
iconPath = os.path.join( __dir__, 'Resources', 'icons' )
uiPath = os.path.join( __dir__, 'Resources', 'ui' )
keepToolbar = True
windowFlags = QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowCloseButtonHint
class DynamicDataBaseCommandClass:
"""Base class for all commands to provide some common code"""
#select objects dialog class
class SelectObjects(QtGui.QDialog):
def __init__(self, objects, label=""):
QtGui.QDialog.__init__(self)
scrollContents = QtGui.QWidget()
scrollingLayout = QtGui.QVBoxLayout(self)
scrollContents.setLayout(scrollingLayout)
scrollArea = QtGui.QScrollArea()
scrollArea.setVerticalScrollBarPolicy(QtGui.Qt.ScrollBarAlwaysOn)
scrollArea.setHorizontalScrollBarPolicy(QtGui.Qt.ScrollBarAlwaysOff)
scrollArea.setWidgetResizable(True)
scrollArea.setWidget(scrollContents)
self.signalsBlocked = False
vBoxLayout = QtGui.QVBoxLayout(self)
vBoxLayout.addWidget(QtGui.QLabel(label))
self.all = QtGui.QCheckBox("All")
self.all.stateChanged.connect(self.allStateChanged)
vBoxLayout.addWidget(self.all)
vBoxLayout.addWidget(scrollArea)
self.setLayout(vBoxLayout)
buttons = QtGui.QDialogButtonBox(
QtGui.QDialogButtonBox.Ok.__or__(QtGui.QDialogButtonBox.Cancel),
QtCore.Qt.Horizontal, self)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
self.checkBoxes = []
self.selected = []
for ii,object in enumerate(objects):
self.checkBoxes.append(QtGui.QCheckBox(object))
self.checkBoxes[-1].setCheckState(self.all.checkState())
self.checkBoxes[-1].stateChanged.connect(self.checkStateChanged)
scrollingLayout.addWidget(self.checkBoxes[-1])
vBoxLayout.addWidget(buttons)
def checkStateChanged(self, arg):
if not arg:
self.signalsBlocked = True
self.all.setCheckState(QtCore.Qt.Unchecked)
self.signalsBlocked = False
def allStateChanged(self, arg):
if self.signalsBlocked:
return
self.checkAll(self.all.checkState())
def checkAll(self, state):
for cb in self.checkBoxes:
cb.setCheckState(state)
def accept(self):
self.selected = []
for cb in self.checkBoxes:
if cb.checkState():
self.selected.append(cb.text())
super().accept()
### end of SelectObjects class definition
def getSelectedObjects(self, objs, label="", checkAll=True):
"""opens a dialog with objs (strings) in a checkboxed list, returns list of selected"""
if objs:
dlg = DynamicDataBaseCommandClass.SelectObjects(objs,label)
if checkAll:
dlg.all.setCheckState(QtCore.Qt.Checked)
else:
dlg.all.setCheckState(QtCore.Qt.Unchecked)
ok = dlg.exec_()
if not ok:
return []
return dlg.selected
return []
@property
def PropertyTypes(self):
return [
"Acceleration",
"Angle",
"Area",
"Bool",
"Color",
"Direction",
"Distance",
"Enumeration",
"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",
"Rotation",
"Speed",
"String",
"StringList",
"Vector",
"VectorList",
"VectorDistance",
"Volume"]
def getAllProperties(self, obj, includeViewProps = False, blacklist=[]):
"""get all the properties that we might want to copy or set"""
props = [prop for prop in obj.PropertiesList if not prop in blacklist]
if includeViewProps:
viewProps = [f"(view) {prop}" for prop in obj.ViewObject.PropertiesList if not prop in blacklist]
else:
viewProps = []
return props + viewProps
def getDynamicProperties(self, obj):
"""get the list of the dynamic properties of obj"""
props = [p for p in obj.PropertiesList if self.isDynamic(obj,p)]
return props
def getGroup(self, obj, prop):
"""return the name of the group this property is in"""
if not obj:
return None
if not prop in obj.PropertiesList:
return None
return obj.getGroupOfProperty(prop)
def getGroups(self,obj,skipList=[]):
"""get the groups of obj, skipping those in skipList"""
props = [p for p in obj.PropertiesList if obj.getPropertyStatus(p) == [21]]
groups = []
for prop in props:
group = obj.getGroupOfProperty(prop)
if group and not group in groups and not group in skipList:
groups.append(group)
return groups
def isDynamic(self,obj,prop):
"""checks whether prop is a dynamic property and not a built-in property
of obj"""
if prop == "DynamicData":
return False
isSo = False
try:
oldGroup = obj.getGroupOfProperty(prop)
obj.setGroupOfProperty(prop,"test")
obj.setGroupOfProperty(prop,oldGroup)
isSo = True
except:
isSo = False
return isSo
def isDDObject(self, obj):
"""checks if this is a DynamicData object"""
return hasattr(obj, "DynamicData")
def isUnit(self, name):
"""check if name is a reserved keyword for units, such as T or k"""
#if parsing quantity succeeds, it means this name is a reserved keyword
try:
FreeCAD.Units.parseQuantity(name)
return True
except:
return False
def isValidName(self, obj, name):
isUnit = self.isUnit(name)
return name == self.fixName(obj, name) and not self.isUnit(name)
def getNewPropertyNameCandidate(self, obj, candidate):
"""arguments: (obj, candidate) Takes candidate as a starting point and finds a new unique name based on it
Example: candidate = "Length23" and there already exists in obj a "Length23",
so this function would try Length24, Length25, etc. until a new unique name is found"""
if not hasattr(obj, candidate) and not self.isUnit(candidate):
return candidate
# Use regular expression to extract base name and number
match = re.match(r'^(.*?)(\d*)$', candidate)
base_name, number_suffix = match.groups() if match else (candidate, '')
idx = int(number_suffix) if number_suffix else 1
if self.isUnit(base_name):
base_name = f"{base_name}_"
while hasattr(obj, f"{base_name}{idx}"):
idx += 1
new_candidate = f"{base_name}{idx}"
return new_candidate
def fixName(self, obj, name):
"""fixes a name so it can be a valid property name"""
pattern = re.compile(r'^\d') #can't begin with a number
pattern2 = re.compile(r'[^0-9a-zA-Z]') #no non-alphanumerics
REPLACEMENTS = {
" ": "_",
".": "_",
"ä": "ae",
"ö": "oe",
"ü": "ue",
"Ä": "Ae",
"Ö": "Oe",
"Ü": "Ue",
"ß": "ss",
"'": ""
}
new_name = name
for k,v in REPLACEMENTS.items():
new_name = new_name.replace(k, v)
if pattern.match(new_name):
new_name = f"_{new_name}"
new_name = re.sub(pattern2, '_', new_name) #replace with _'s
if self.isUnit(new_name):
new_name = self.getNewPropertyNameCandidate(obj, new_name)
return new_name
#######################################################################################
# Keep Toolbar active even after leaving workbench
class DynamicDataSettingsCommandClass(DynamicDataBaseCommandClass):
"""Settings, currently only whether to keep toolbar after leaving workbench"""
global mostRecentTypes
class DynamicDataSettingsDlg(QtGui.QDialog):
pg = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/DynamicData")
def __init__(self):
super(DynamicDataSettingsCommandClass.DynamicDataSettingsDlg, self).__init__(Gui.getMainWindow())
self.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
self.setAttribute(QtCore.Qt.WA_WindowPropagation, True)
self.form = Gui.PySideUic.loadUi(uiPath + "/dynamicdataprefs.ui")
self.setWindowTitle(self.form.windowTitle()+" v."+__version__)
self.setWindowIcon(QtGui.QIcon("Resources/icons/Settings.svg"))
lay = QtGui.QVBoxLayout(self)
lay.addWidget(self.form)
self.setLayout(lay)
self.form.KeepToolbar.setChecked(self.pg.GetBool('KeepToolbar', True))
self.form.CondensedToolbar.setChecked(self.pg.GetBool('CondensedToolbar', True))
self.form.SupportViewObjectProperties.setChecked(self.pg.GetBool('SupportViewObjectProperties', False))
self.form.AddToActiveContainer.setChecked(self.pg.GetBool('AddToActiveContainer', False))
self.form.CheckForUpdates.setChecked(self.pg.GetBool('CheckForUpdates', True))
self.form.AddToFreeCADPreferences.setChecked(self.pg.GetBool("AddToFreeCADPreferences",True))
self.form.mruLength.setValue(self.pg.GetInt('mruLength', 5))
def closeEvent(self, event):
self.pg.SetBool('KeepToolbar', self.form.KeepToolbar.isChecked())
self.pg.SetBool('CondensedToolbar', self.form.CondensedToolbar.isChecked())
self.pg.SetBool('SupportViewObjectProperties', self.form.SupportViewObjectProperties.isChecked())
self.pg.SetBool('AddToActiveContainer', self.form.AddToActiveContainer.isChecked())
self.pg.SetBool('CheckForUpdates', self.form.CheckForUpdates.isChecked())
self.pg.SetBool('AddToFreeCADPreferences',self.form.AddToFreeCADPreferences.isChecked())
self.pg.SetInt('mruLength', self.form.mruLength.value())
super(DynamicDataSettingsCommandClass.DynamicDataSettingsDlg, self).closeEvent(event)
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):
dlg = self.DynamicDataSettingsDlg()
dlg.open()
def IsActive(self):
return True
#Gui.addCommand("DynamicDataKeepToolbar", DynamicDataKeepToolbarCommandClass())
####################################################################################
# Create the dynamic data container object
class DynamicDataCreateObjectCommandClass(DynamicDataBaseCommandClass):
"""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")
a.addProperty("App::PropertyStringList","DynamicData").DynamicData=self.getHelp()
setattr(a.ViewObject,'DisplayMode',['0']) #avoid enumeration -1 warning
doc.commitTransaction()
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]
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"+__version__+") workbench.",
"This is a simple container object built",
"for holding custom properties."
]
#Gui.addCommand("DynamicDataCreateObject", DynamicDataCreateObjectCommandClass())
####################################################################################
# Create or edit an existing configuration
class DynamicDataCreateConfigurationCommandClass(DynamicDataBaseCommandClass):
"""Create or edit a configuration command"""
class DynamicDataConfigurationDlg(QtGui.QDialog):
def __init__(self,dd):
super(DynamicDataCreateConfigurationCommandClass.DynamicDataConfigurationDlg, self).__init__(Gui.getMainWindow())
self.setAttribute(QtCore.Qt.WA_WindowPropagation, True)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
self.setWindowTitle(f"DynamicData v{__version__} Configuration Editor")
self.setWindowIcon(QtGui.QIcon("Resources/icons/DynamicDataCreateConfiguration.svg"))
self.dd = dd
self.configuration = {}
self.curLineEdit = None #used only in event filter and handleCtrlTab()
hasConfig = self.getConfigurationFromObject()
lay = QtGui.QVBoxLayout(self)
self.setLayout(lay)
self.nameRow = QtGui.QHBoxLayout()
lay.addLayout(self.nameRow)
self.configurationNameLabel = QtGui.QLabel("Configuration name:")
self.nameRow.addWidget(self.configurationNameLabel)
self.configurationName = QtGui.QLineEdit()
self.configurationName.setToolTip(\
"Configuration name will be the name given to \n\
the Enumeration property created and to the Group \n\
all the properties go into.")
self.configurationName.setText(self.configuration["name"])
self.configurationName.selectAll()
self.configurationName.textChanged.connect(self.updateDict)
self.nameRow.addWidget(self.configurationName)
self.enumCountLabel = QtGui.QLabel("Enum count:")
self.enumCount = QtGui.QSpinBox()
self.enumCount.setMinimum(2)
self.enumCount.setMaximum(100)
self.enumCount.setSingleStep(1)
self.enumCount.setValue(self.configuration["enumCount"])
self.enumCount.valueChanged.connect(self.updateDict)
self.enumCount.setToolTip( \
"This is the number of configuration options you \n\
will have, for example: small, medium, large would \n\
be 3.")
self.nameRow.addWidget(self.enumCountLabel)
self.nameRow.addWidget(self.enumCount)
self.variableCountLabel = QtGui.QLabel("Variable count:")
self.nameRow.addWidget(self.variableCountLabel)
self.variableCount = QtGui.QSpinBox()
self.variableCount.setMinimum(2)
self.variableCount.setMaximum(100)
self.variableCount.setSingleStep(1)
self.variableCount.setValue(self.configuration["variableCount"])
self.variableCount.valueChanged.connect(self.updateDict)
self.variableCount.setToolTip( \
"This is the number of variables you will have \n\
in the configuration. For example, if you want \n\
Height, Width, and Length, enter 3 here.")
self.nameRow.addWidget(self.variableCount)
self.grid_scroller = QtGui.QScrollArea()
self.gridLayout = QtGui.QGridLayout()
lay.addWidget(self.grid_scroller)
#lay.addLayout(self.gridLayout)
self.gridWidget= QtGui.QWidget()
self.gridWidget.setLayout(self.gridLayout)
self.grid_scroller.setWidget(self.gridWidget)
self.grid_scroller.setWidgetResizable(True)
self.setupGrid()
self.buttonLayout = QtGui.QHBoxLayout()
lay.addLayout(self.buttonLayout)
self.buttons = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok.__or__(QtGui.QDialogButtonBox.Cancel),\
QtCore.Qt.Horizontal, self)
self.buttons.accepted.connect(self.accept)
self.buttons.rejected.connect(self.reject)
self.helpCheckBox = QtGui.QCheckBox("Show help")
self.helpCheckBox.setChecked(False)
self.helpCheckBox.clicked.connect(self.showHelp)
self.buttonLayout.addWidget(self.helpCheckBox)
self.buttonLayout.addWidget(self.buttons)
self.helpLabel = QtGui.QLabel("Help goes here.")
self.setupHelpText()
self.scroll_area = QtGui.QScrollArea()
lay.addWidget(self.scroll_area)
self.scroll_area.setWidget(self.helpLabel)
self.scroll_area.setVisible(False)
if hasConfig:
self.fillUpLineEdits()
def setupHelpText(self):
txt = """\
A configuration is a set of properties that work together to allow you to set multiple
properties by selecting the configuration you want in an enumeration property. The
enumeration property is at the heart of the configuration. The Configuration name: field
will be the name of this enumeration property. It will also be the name of the group that
the variable properties go into and the name of another group + the word "Lists" that the
list properties will go into.
For example, if the name of the configuration is "Configuration" then you will have a group
named "Configuration" and inside that group an Enumeration property also named "Configuration".
Plus, you will have another group named "Configuration Lists" and inside that group will be a
number of FloatList properties, one for each variable you have. If you have these 3 variables:
"Height", "Width", and "Length", then in the Configuration group you will have 3 Float properties
of the same name and in the Configration List group there will be "Height List", "Width List",
and "Length List", all FloatList types.
We have 3 different property types: 1) the enumeration property that serves as the configuration
selector; 2) the variable properties (whose names are in the left column, e.g. Height, or Radius);
and 3) the list properties that hold the values the variable properties index into based on which
configuration has been selected. All variable properties are of type Float and all list properties
are of type FloatList. (You can replace them with Integer or String property types if you like
after building the configuration by deleting them and adding new properties with the same name,
but if you use the configuration editor to edit the configuration later they will be replaced
again with Float and FloatList types.)
Enum count is how many enums we have in this configuration. The default is 5, which are "Extra
Small", "Small", "Medium", "Large", and "Extra Large". "Select size" is not really an enum, but
it will go into the enumeration as a default message to the user. Edit this so it makes sense
for the enums you are using. Edit all of these enums by changing their text. You can remove some
by reducing the Enum count, which can be anywhere from 2 to 100. You must have at least 2 enums
in the configuration. Note: when you reduct Enum count or Variable count you lose those rows or
columns, including any data contained in the cells, even if you increase the count afterwards.
When you increase the count you get another row or column with generic names like Variable5 or
Enum7.
Enter the values in the cells that you want for each enum and variable. In the example default
configuration you have Height, for example. If you want the Height for the Extra Small enum to
be 2, enter 2 in the cell that aligns with Height and Extra Small. Any cells left blank will be
filled with the value from the first cell in that row, or 0.0 if it is also blank.
Note: when the "Select size" enum is selected in the enumeration property all of the variable
values will be the value from the first enum, so that it won't break your model until you can
select one of the enums. Select size is actually an additional extra set of values added to the
ends of the List properties. You can manually edit these later if you want different defaults.
Your manually edited defaults will not be changed by the editor unless you also change the
number of enums during the edit.
You may apply a configuration to an existing object, such as a Part::Cylinder, and if your variable
names are the same as existing properties, those properties will be incorporated into the configuration.
You may have multiple configurations in the same object, but if you do so you should ensure none of
the variable are the same or else there will be a conflict and the new properties will overwrite the
existing ones. It is recommended to only have 1 configuration per object.
Variable count is how many variables to have in the configuration. By default we have 3. These are:
"Height", "Length", and "Radius". This are likely not to be the names you will want for your
configuration. They are just there as placeholders to serve as examples in the default configuration.
You can add more or remove some by changing the Variable count value.
If you click Cancel your changes will be discarded. If you click OK your configuration will be added
to the selected object. ANY EXISTING PROPERTIES of the same names WILL BE REPLACED. But have no fear,
you can use Undo to revert all your changes to the selected object.
"""
self.helpLabel.setText(txt)
def showHelp(self):
self.scroll_area.setVisible(self.helpCheckBox.isChecked())
def eventFilter(self, obj, event):
if event.type() == QtGui.QKeyEvent.KeyPress:
if bool(event.modifiers() & QtCore.Qt.ControlModifier and event.key() == QtCore.Qt.Key_Tab):
self.curLineEdit = obj
self.handleCtrlTab(False)
return True # Event handled
elif bool(event.modifiers() & QtCore.Qt.ControlModifier and event.key() == QtCore.Qt.Key_Backtab):
self.curLineEdit = obj
self.handleCtrlTab(True)
return True # Event handled
return super().eventFilter(obj, event)
def handleCtrlTab(self, bShift = False):
row,col = self.getRowColFromObjectName(self.curLineEdit.objectName())
objName = f"{row + 1}_{col}" if not bShift else f"{row - 1}_{col}"
next = self.getLineEditFromConfiguration(objName, bCreate = False)
if not next:
return
else:
next.setFocus()
def getLineEditFromConfiguration(self, objName, bCreate = True):
"""get the line edit objName from dictionary if it exists, else created it"""
lineEdit = None
for name,obj in self.configuration["lineEdits"].items():
if name == objName:
lineEdit = obj
break
if not lineEdit and bCreate:
lineEdit = QtGui.QLineEdit()
lineEdit.setObjectName(objName)
lineEdit.installEventFilter(self)
lineEdit.setToolTip("Tab -> next column\nCtrl+Tab -> next row\nCtrl+Shift+Tab ->previous row\nShift+Tab -> previous column")
elif not bCreate and not lineEdit:
return None
self.configuration["lineEdits"][objName] = lineEdit
return lineEdit
def addToGrid(self, lineEdit, row, col):
"""add the LineEdit to the grid at row, col"""
def trigger(objName):
self.lineEditTextChanged(objName)
self.gridLayout.addWidget(lineEdit, row, col)
label = ""
if row == 0:
try:
label = self.configuration["enums"][col]
except:
label = f"Enum{col}"
self.configuration["enums"].append(f"Enum{col}")
elif col == 0:
try:
label = self.configuration["variables"][row-1]
except:
self.configuration["variables"].append(f"Variable{row}")
label = f"Variable{row}"
lineEdit.setText(label)
lineEdit.textChanged.connect(lambda text,name=lineEdit.objectName(): trigger(name))
self.gridLayout.addWidget(lineEdit,row,col)
self.update()
FreeCADGui.updateGui()
def updateTabOrders(self):
"""update the tab orders when adding/removing lineEdit to/from grid"""
def custom_sort(s):
# Split the string into parts
parts = s.split('_')
# Convert the parts to integers
x = int(parts[0])
y = int(parts[1])
# Combine them using a formula
return x * 100 + y
names = {}
for name,obj in self.configuration["lineEdits"].items():
names[name] = obj.objectName()
names = sorted(names, key=custom_sort)
edits = [self.configuration["lineEdits"][name] for name in names]
for ii in range(len(edits)-1):
self.setTabOrder(edits[ii], edits[ii+1])
def removeFromGrid(self, le):
"""remove the line edit from the grid and from the dictionary"""
if le.objectName() in self.configuration["lineEdits"].keys():
val = self.configuration["lineEdits"].pop(le.objectName())
row,col = self.getRowColFromObjectName(le.objectName())
widget = self.gridLayout.itemAtPosition(row,col)
if widget:
widget.widget().deleteLater()
self.update()
FreeCADGui.updateGui()
def setupGrid(self):
"""setup the grid based on the values in self.configuration dictionary"""
for row in range(self.configuration["variableCount"]+1):
for col in range(self.configuration["enumCount"]+1):
lineEdit = self.getLineEditFromConfiguration(f"{row}_{col}")
self.addToGrid(lineEdit, row, col)
def lineEditTextChanged(self, lineEditObjectName):
lineEdit = self.getLineEditFromConfiguration(lineEditObjectName)
row,col = self.getRowColFromObjectName(lineEditObjectName)
if row == 0:
self.configuration["enums"][col] = lineEdit.text()
elif col == 0:
self.configuration["variables"][row-1] = lineEdit.text()
def getRowColFromObjectName(self, objName):
"""returns a tuple (row,col) gotten from the line edit object name
which is always in the form of row_col"""
row,col = objName.split("_")
row = int(row)
col = int(col)
return (row,col)
def isOutOfBounds(self, lineEdit):
"""check if this line edit object needs to be removed from the grid
by comparing its row,col to enum count and variable count"""
row,col = self.getRowColFromObjectName(lineEdit.objectName())
enums = self.enumCount.value()
variables = self.variableCount.value()
if col > enums:
return True
if row > variables:
return True
return False
def updateDict(self):
"""called only when the enum count or variable count changes
in which cases we need to update the grid of line edits
updates the dictionary (self.configuration) based on values in form"""
self.configuration["name"] = self.configurationName.text()
self.configuration["enumCount"] = self.enumCount.value()
self.configuration["variableCount"] = self.variableCount.value()
lineEditsToRemove = [le for le in self.configuration["lineEdits"].values() if self.isOutOfBounds(le)]
for le in lineEditsToRemove:
row,col = self.getRowColFromObjectName(le.objectName())
if row == 0:
self.configuration["enums"].pop()
if col == 0:
self.configuration["variables"].pop()
self.removeFromGrid(le)
# if lineEditsToRemove:
# return
# now we need to see if we need to add any rows or columns
numRows = len(self.configuration["variables"])
numCols = len(self.configuration["enums"])
enums = self.enumCount.value()
variables = self.variableCount.value()
while numCols < enums + 1:
#need to add a new column, so for each row we add one
for row in range(numRows+1):
lineEdit = self.getLineEditFromConfiguration(f"{row}_{numCols}")
self.addToGrid(lineEdit, row, numCols)
numCols = len(self.configuration["enums"])
while numRows < variables:
#need to a new row, so for each column we add one
for col in range(numCols):
lineEdit = self.getLineEditFromConfiguration(f"{numRows+1}_{col}")
self.addToGrid(lineEdit, numRows+1, col)
numRows = len(self.configuration["variables"])
self.updateTabOrders()
def getRowValues(self,row):
"""get the line edit values in row as a list"""
ret = []
for col,enum in enumerate(self.configuration["enums"]):
objName = f"{row+1}_{col+1}"
lineEdit = self.getLineEditFromConfiguration(objName)
val = 0
try:
val = float(lineEdit.text())
except:
if lineEdit.text():
FreeCAD.Console.PrintWarning(f"Couldn't convert to float: {lineEdit.text()} row,col = {row},{col}\n")
else:
#take value from first cell in row and use that for default
firstCell = self.getLineEditFromConfiguration(f"{row+1}_{1}")
try:
val = float(firstCell.text())
except:
val = 0
ret.append(val)
return ret
def setConfiguration(self):
"""setup the configuration"""
dd = self.dd
name = self.configuration["name"]
if hasattr(dd,name):
try:
dd.removeProperty(name)
except:
FreeCAD.Console.PrintWarning(f"Unable to remove property: {name}\n")
if not hasattr(dd,name):
dd.addProperty("App::PropertyEnumeration",name,name,"Configuration enumeration")
setattr(dd,name,self.configuration["enums"])
for row,var in enumerate(self.configuration["variables"]):
if hasattr(dd,f"{var}List"):
try:
dd.removeProperty(f"{var}List")
FreeCAD.Console.PrintMessage(f"Removed property {var}List\n")
except:
FreeCAD.Console.PrintWarning(f"Unable to remove property: {var}List\n")
if not hasattr(dd,f"{var}List"):
dd.addProperty("App::PropertyFloatList",f"{var}List",f"{name}Lists",f"List property for {var}")
FreeCAD.Console.PrintMessage(f"Added property {var}List\n")
setattr(dd,f"{var}List", self.getRowValues(row))
if hasattr(dd,var):
try:
dd.removeProperty(var)
FreeCAD.Console.PrintMessage(f"Removed property {var}\n")
except:
FreeCAD.Console.PrintWarning(f"Unable to remove property: {var}\n")
if not hasattr(dd,var):
dd.addProperty("App::PropertyFloat",var,name,"Property to link to")
FreeCAD.Console.PrintMessage(f"Added property {var}\n")
dd.setExpression(var,f"{dd.Label}.<<{dd.Label}>>.{var}List[<<{dd.Label}>>.{name}-1]")
def getConfigurationFromObject(self):
"""return True if we imported one from an object, else False if this is a new configuration"""
dd = self.dd
ignored = ["MapMode"]
props = [prop for prop in dd.PropertiesList if "Enumeration" in dd.getTypeIdOfProperty(prop) and prop not in ignored]
if len(props) >= 1:
default_item = 0
props = ["New configuration"] + props
prop, ok = QtGui.QInputDialog.getItem(self, "Select configuration", \
"Choose an enumeration to edit or create a new one\n (Cancel for a new default configuration)",\
props, default_item, editable=False)
if not ok or prop == props[0]:
self.makeDefaultConfiguration()
return False
else:
self.importConfiguration(prop)
return True
else: #no existing enumerations
self.makeDefaultConfiguration()
return False
def importConfiguration(self,prop):
"""imports the configuration from the object where prop is the name of the enumeration"""
self.configuration["name"] = prop
self.configuration["enums"] = self.dd.getEnumerationsOfProperty(prop)
vars = [prop2 for prop2 in self.dd.PropertiesList if hasattr(self.dd,f"{prop2}List")]
#lists = [prop for prop in dd.PropertiesList if hasattr(dd,prop[:-4])] #drop List from end of property name
self.configuration["variables"] = vars
self.configuration["lineEdits"] = {}
self.configuration["enumCount"] = len(self.configuration["enums"])-1
self.configuration["variableCount"] = len(vars)
def makeDefaultConfiguration(self):
self.configuration["name"] = "Configuration"
self.configuration["enumCount"] = 5
self.configuration["variableCount"] = 3
self.configuration["enums"] = ["Select size","Extra Small","Small","Medium",\
"Large","Extra Large"]
self.configuration["variables"] = ["Length", "Height", "Radius"]
self.configuration["lineEdits"] = {}
def fillUpLineEdits(self):
"""called from __init__() only if dd object has a configuration already,
so we are going to fill in the Line Edits from that data"""
#look for List properties
for var in self.configuration["variables"]:
lists = [prop for prop in self.dd.PropertiesList if prop == f"{var}List"]
for ls in lists:
values = getattr(self.dd, ls) #e.g. HeightList = [10,20,30], now values = [10,20,30]
row = self.configuration["variables"].index(var)
for col,val in enumerate(values):
lineEdit = self.getLineEditFromConfiguration(f"{row+1}_{col+1}")
lineEdit.setText(str(round(val,6)))
def accept(self):
self.dd.Document.openTransaction("Create/Edit Configuration")
self.setConfiguration()
self.dd.Document.commitTransaction()
super().accept()
def reject(self):
super().reject()
def GetResources(self):
return {'Pixmap' : os.path.join( iconPath , 'DynamicDataCreateConfiguration.svg'),
'MenuText': "Create/Edit Con&figuration",
'Accel' : "Ctrl+Shift+D,F",
'ToolTip' : "Create or edit an existing configuration in the selected object"}
def __init__(self):
self.props = []
self.obj = None
def Activated(self):
doc = FreeCAD.ActiveDocument
dlg = self.DynamicDataConfigurationDlg(self.obj) #self.obj is the selected object
dlg.props = self.props
dlg.exec_()
doc.recompute()
return
def IsActive(self):
if not FreeCAD.ActiveDocument:
return False
selection = Gui.Selection.getSelection()
if len(selection) == 1:
self.obj = selection[0]
return True
#where nothing is selected and there is only one dd object, use that object
if len(selection) == 0:
dds = [obj for obj in FreeCAD.ActiveDocument.Objects if hasattr(obj,"DynamicData")]
if len(dds) == 1:
self.obj = dds[0]
return True
return False
#Gui.addCommand("DynamicDataCreateConfiguration", DynamicDataCreateConfigurationCommandClass())
####################################################################################
# Edit an existing Enumeration property
class DynamicDataEditEnumerationCommandClass(DynamicDataBaseCommandClass):
"""Edit Enumeration command"""
class DynamicDataEnumerationDlg(QtGui.QDialog):
def __init__(self,dd,props):
super(DynamicDataEditEnumerationCommandClass.DynamicDataEnumerationDlg, self).__init__(Gui.getMainWindow())
self.dd = dd
self.ok = False
self.props = props
self.items = []
self.enumerations = {}
self.setupEnumerations()
self.setAttribute(QtCore.Qt.WA_WindowPropagation, True)
self.setWindowTitle(f"DynamicData v{__version__} Enumeration Editor")
lay = QtGui.QVBoxLayout(self)
self.setLayout(lay)
self.propertiesLabel = QtGui.QLabel("Enumeration Properties:")
self.propertiesListBox = QtGui.QListWidget(self)
for prop in self.props:
item = QtGui.QListWidgetItem(prop)
self.items.append(item)
self.propertiesListBox.addItem(item)
self.propertiesListBox.setSelectionMode(QtGui.QListWidget.SingleSelection)
self.propertiesListBox.itemClicked.connect(self.handlePropertiesListBoxItemClicked)
if self.items:
self.propertiesListBox.setCurrentItem(self.items[0])
lay.addWidget(self.propertiesLabel)
lay.addWidget(self.propertiesListBox)
self.textEditLabel = QtGui.QLabel("Edit the selected property by typing here:")
lay.addWidget(self.textEditLabel)
self.textEdit = QtGui.QPlainTextEdit()
self.textEdit.textChanged.connect(self.textChanged)
lay.addWidget(self.textEdit)
self.buttons = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok.__or__(QtGui.QDialogButtonBox.Cancel),\
QtCore.Qt.Horizontal, self)
self.buttons.accepted.connect(self.accept)
self.buttons.rejected.connect(self.reject)
lay.addWidget(self.buttons)
self.setupTextEdit()
def handlePropertiesListBoxItemClicked(self, item):
"""a new enumeration property was selected, so set the QPlainTextEdit"""
self.updateTextEdit()
def textChanged(self):
"""The QPlainTextEdit changed, so update enums"""
self.updateEnumerations()
def setupEnumerations(self):
"""setup enums from the dd object enumerations"""
for prop in self.props:
if not prop in self.enumerations:
self.enumerations[prop] = self.dd.getEnumerationsOfProperty(prop)
def updateEnumerations(self):
"""update enums from QPlainTextEdit"""
prop = self.getCurrentProp()
self.enumerations[prop] = self.getTextEditStrings()
def getCurrentProp(self):
return self.props[self.propertiesListBox.currentRow()]
def setupTextEdit(self):
"""puts the text into the QPlainTextEdit from the dd object enumeration properties"""
if self.props:
prop = self.props[self.propertiesListBox.currentRow()]
enums = self.dd.getEnumerationsOfProperty(prop)
textString = "\n".join(enums)
self.textEdit.setPlainText(textString)
def updateTextEdit(self):
"""update the QPlainTextEdit from enums"""
prop = self.props[self.propertiesListBox.currentRow()]
enums = self.enumerations[prop]
textString = "\n".join(enums)
self.textEdit.setPlainText(textString)
def getTextEditStrings(self):
"""return the text edit contents as a list of strings"""
txt = self.textEdit.toPlainText()
split_text = txt.split("\n")
return split_text
def accept(self):
self.ok = True
super().accept()
def reject(self):
super().reject()
def GetResources(self):
return {'Pixmap' : os.path.join( iconPath , 'DynamicDataEditEnumerations.svg'),
'MenuText': "&Edit Enumerations",
'Accel' : "Ctrl+Shift+D,E",
'ToolTip' : "Edit properties of type Enumeration in selected object"}
def __init__(self):
self.props = []
self.obj = None
def Activated(self):
doc = FreeCAD.ActiveDocument
if not self.props:
FreeCAD.Console.PrintError("DynamicData: Error, no property of type \
Enumeration to edit. Create one first, and then try again.\n")
return
dlg = self.DynamicDataEnumerationDlg(self.obj, self.props) #the dd object
dlg.props = self.props
dlg.exec_()
if dlg.ok:
doc.openTransaction("Edit Enumeration")