forked from FreeCAD/FreeCAD
/
MaterialEditor.py
826 lines (653 loc) · 29.3 KB
/
MaterialEditor.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
# ***************************************************************************
# * Copyright (c) 2013 Yorik van Havre <yorik@uncreated.net> *
# * Copyright (c) 2019 Bernd Hahnebach <bernd@bimstatik.org> *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * This program is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
__title__ = "FreeCAD material editor"
__author__ = "Yorik van Havre, Bernd Hahnebach"
__url__ = "http://www.freecadweb.org"
import os
from PySide import QtCore, QtGui, QtSvg
import FreeCAD
import FreeCADGui
# import Material_rc
# is this still needed after the move to card utils???
unicode = str
# ************************************************************************************************
# ************************************************************************************************
class MaterialEditor:
def __init__(self, obj=None, prop=None, material=None, card_path=""):
"""Initializes, optionally with an object name and a material property
name to edit, or directly with a material dictionary."""
self.obj = obj
self.prop = prop
self.material = material
self.customprops = []
self.internalprops = []
self.groups = []
self.directory = FreeCAD.getResourceDir() + "Mod/Material"
self.materials = {}
self.cards = {}
self.icons = {}
self.card_path = card_path
# load the UI file from the same directory as this script
self.widget = FreeCADGui.PySideUic.loadUi(
os.path.dirname(__file__) + os.sep + "materials-editor.ui"
)
self.widget.setWindowIcon(QtGui.QIcon(":/icons/preview-rendered.svg"))
# restore size and position
p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Material")
w = p.GetInt("MaterialEditorWidth", 441)
h = p.GetInt("MaterialEditorHeight", 626)
self.widget.resize(w, h)
# additional UI fixes and tweaks
widget = self.widget
buttonURL = widget.ButtonURL
buttonDeleteProperty = widget.ButtonDeleteProperty
buttonAddProperty = widget.ButtonAddProperty
standardButtons = widget.standardButtons
buttonOpen = widget.ButtonOpen
buttonSave = widget.ButtonSave
comboMaterial = widget.ComboMaterial
treeView = widget.treeView
# create preview svg slots
self.widget.PreviewRender = QtSvg.QSvgWidget(":/icons/preview-rendered.svg")
self.widget.PreviewRender.setMaximumWidth(64)
self.widget.PreviewRender.setMinimumHeight(64)
self.widget.topLayout.addWidget(self.widget.PreviewRender)
self.widget.PreviewVector = QtSvg.QSvgWidget(":/icons/preview-vector.svg")
self.widget.PreviewVector.setMaximumWidth(64)
self.widget.PreviewVector.setMinimumHeight(64)
self.widget.topLayout.addWidget(self.widget.PreviewVector)
self.updatePreviews(mat=material)
buttonURL.setIcon(QtGui.QIcon(":/icons/internet-web-browser.svg"))
buttonDeleteProperty.setEnabled(False)
standardButtons.button(QtGui.QDialogButtonBox.Ok).setAutoDefault(False)
standardButtons.button(QtGui.QDialogButtonBox.Cancel).setAutoDefault(False)
self.updateCardsInCombo()
# TODO allow to enter a custom property by pressing Enter in the lineedit
# currently closes the dialog
standardButtons.rejected.connect(self.reject)
standardButtons.accepted.connect(self.accept)
buttonOpen.clicked.connect(self.openfile)
buttonSave.clicked.connect(self.savefile)
buttonURL.clicked.connect(self.openProductURL)
comboMaterial.currentIndexChanged[int].connect(self.chooseMaterial)
buttonAddProperty.clicked.connect(self.addCustomProperty)
buttonDeleteProperty.clicked.connect(self.deleteCustomProperty)
treeView.clicked.connect(self.onClickTree)
model = QtGui.QStandardItemModel()
treeView.setModel(model)
treeView.setUniformRowHeights(True)
treeView.setItemDelegate(MaterialsDelegate())
# init model
self.implementModel()
# update the editor with the contents of the property, if we have one
d = None
if self.prop and self.obj:
d = FreeCAD.ActiveDocument.getObject(self.obj).getPropertyByName(self.prop)
elif self.material:
d = self.material
if d:
self.updateMatParamsInTree(d)
self.widget.ComboMaterial.setCurrentIndex(0)
# set after tree params to the none material
if self.card_path:
# we need the index of this path
index = self.widget.ComboMaterial.findData(self.card_path)
self.chooseMaterial(index)
# TODO: What if material and card_name was given?
# In such case ATM material is chosen, give some feedback for all those corner cases.
def implementModel(self):
"""implements the model with the material attribute structure."""
p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Material")
widget = self.widget
treeView = widget.treeView
model = treeView.model()
model.setHorizontalHeaderLabels(["Property", "Value", "Type"])
treeView.setColumnWidth(0, 250)
treeView.setColumnWidth(1, 250)
treeView.setColumnHidden(2, True)
from materialtools.cardutils import get_material_template
template_data = get_material_template(True)
for group in template_data:
gg = list(group.keys())[0] # group dict has only one key
top = QtGui.QStandardItem(gg)
model.appendRow([top])
self.groups.append(gg)
for properName in group[gg]:
pp = properName # property name
item = QtGui.QStandardItem(pp)
item.setToolTip(group[gg][properName]["Description"])
self.internalprops.append(pp)
it = QtGui.QStandardItem()
it.setToolTip(group[gg][properName]["Description"])
tt = group[gg][properName]["Type"]
itType = QtGui.QStandardItem(tt)
top.appendRow([item, it, itType])
treeView.setExpanded(top.index(), p.GetBool("TreeExpand"+gg, True))
# top.sortChildren(0)
# treeView.expandAll()
def updateMatParamsInTree(self, data):
"""updates the contents of the editor with the given dictionary
the material property keys where added to the editor already
not known material property keys will be added to the user defined group"""
# print(data)
model = self.widget.treeView.model()
root = model.invisibleRootItem()
for gg in range(root.rowCount() - 1):
group = root.child(gg, 0)
for pp in range(group.rowCount()):
item = group.child(pp, 0)
it = group.child(pp, 1)
kk = self.collapseKey(item.text())
try:
value = data[kk]
it.setText(value)
del data[kk]
except KeyError:
# treat here changes in Material Card Template
# Norm -> StandardCode
if (kk == "Standard Code") and ("Norm" in data) and data["Norm"]:
it.setText(data["Norm"])
del data["Norm"]
it.setText("")
userGroup = root.child(gg + 1, 0)
userGroup.setRowCount(0)
self.customprops = []
for k, i in data.items():
k = self.expandKey(k)
item = QtGui.QStandardItem(k)
it = QtGui.QStandardItem(i)
userGroup.appendRow([item, it])
self.customprops.append(k)
def chooseMaterial(self, index):
if index < 0:
return
self.card_path = self.widget.ComboMaterial.itemData(index)
FreeCAD.Console.PrintMessage(
"choose_material in material editor:\n"
" {}\n".format(self.card_path)
)
if os.path.isfile(self.card_path):
from importFCMat import read
d = read(self.card_path)
self.updateMatParamsInTree(d)
# be careful with reading from materials dict
# the card could be updated the dict not
self.widget.ComboMaterial.setCurrentIndex(index) # set after tree params
else:
FreeCAD.Console.PrintError("material card not found: {}\n".format(self.card_path))
def updateCardsInCombo(self):
"""updates the contents of the materials combo with existing material cards"""
mat_prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Material/Cards")
sort_by_resources = mat_prefs.GetBool("SortByResources", False)
# get all available materials (fill self.materials, self.cards and self.icons)
from materialtools.cardutils import import_materials as getmats
self.materials, self.cards, self.icons = getmats()
card_name_list = [] # [ [card_name, card_path, icon_path], ... ]
if sort_by_resources is True:
for a_path in sorted(self.materials.keys()):
card_name_list.append([self.cards[a_path], a_path, self.icons[a_path]])
else:
card_names_tmp = {}
for path, name in self.cards.items():
card_names_tmp[name] = path
for a_name in sorted(card_names_tmp.keys()):
a_path = card_names_tmp[a_name]
card_name_list.append([a_name, a_path, self.icons[a_path]])
card_name_list.insert(0, [None, "", ""])
for mat in card_name_list:
self.widget.ComboMaterial.addItem(QtGui.QIcon(mat[2]), mat[0], mat[1])
def openProductURL(self):
"""opens the contents of the ProductURL field in an external browser."""
model = self.widget.treeView.model()
item = model.findItems(translate("Material", "Product URL"),
QtCore.Qt.MatchRecursive, 0)[0]
group = item.parent()
it = group.child(item.row(), 1)
url = it.text()
if url:
QtGui.QDesktopServices.openUrl(QtCore.QUrl(url, QtCore.QUrl.TolerantMode))
def accept(self):
""
self.storeSize()
QtGui.QDialog.accept(self.widget)
def reject(self):
""
self.storeSize()
QtGui.QDialog.reject(self.widget)
def storeSize(self):
"stores the widget size"
# store widths
p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Material")
p.SetInt("MaterialEditorWidth", self.widget.width())
p.SetInt("MaterialEditorHeight", self.widget.height())
root = self.widget.treeView.model().invisibleRootItem()
for gg in range(root.rowCount()):
group = root.child(gg)
p.SetBool("TreeExpand"+group.text(), self.widget.treeView.isExpanded(group.index()))
def expandKey(self, key):
"adds spaces before caps in a KeyName"
nk = ""
for ln in key:
if ln.isupper():
if nk:
# this allows for series of caps, such as ProductURL
if not nk[-1].isupper():
nk += " "
nk += ln
return nk
def collapseKey(self, key):
"removes the spaces in a Key Name"
nk = ""
for ln in key:
if ln != " ":
nk += ln
return nk
def addCustomProperty(self, key=None, value=None):
"Adds a custom property to the editor, optionally with a value."
if not key:
key = self.widget.EditProperty.text()
if key:
model = self.widget.treeView.model()
item = model.findItems(key, QtCore.Qt.MatchRecursive, 0)
if not item:
top = model.findItems(translate("Material", "UserDefined"),
QtCore.Qt.MatchExactly, 0)[0]
item = QtGui.QStandardItem(key)
it = QtGui.QStandardItem(value)
top.appendRow([item, it])
self.customprops.append(key)
def deleteCustomProperty(self, key=None):
"""Deletes a custom property from the editor,
or deletes the value of an internal property."""
widget = self.widget
treeView = widget.treeView
model = treeView.model()
buttonDeleteProperty = widget.ButtonDeleteProperty
if not key:
index = treeView.selectedIndexes()[0]
item = model.itemFromIndex(index)
key = item.text()
if key:
item = model.findItems(key, QtCore.Qt.MatchRecursive, 0)
if item:
index = model.indexFromItem(item[0])
topIndex = index.parent()
top = model.itemFromIndex(topIndex)
row = item[0].row()
if key in self.customprops:
top.takeRow(row)
self.customprops.remove(key)
buttonDeleteProperty.setProperty("text", "Delete property")
elif key in self.internalprops:
it = top.child(row, 1)
it.setText("")
buttonDeleteProperty.setProperty("text", "Delete value")
buttonDeleteProperty.setEnabled(False)
def onClickTree(self, index):
"""Checks if the current item is a custom or an internal property,
and enable the delete property or delete value button."""
widget = self.widget
buttonDeleteProperty = widget.ButtonDeleteProperty
treeView = widget.treeView
model = treeView.model()
ind = treeView.selectedIndexes()[0]
item = model.itemFromIndex(ind)
text = item.text()
if text in self.customprops:
buttonDeleteProperty.setEnabled(True)
buttonDeleteProperty.setProperty("text", "Delete property")
elif text in self.internalprops:
indParent = ind.parent()
group = model.itemFromIndex(indParent)
row = item.row()
it = group.child(row, 1)
buttonDeleteProperty.setProperty("text", "Delete value")
if it.text():
buttonDeleteProperty.setEnabled(True)
else:
buttonDeleteProperty.setEnabled(False)
else:
buttonDeleteProperty.setEnabled(False)
buttonDeleteProperty.setProperty("text", "Delete property")
self.updatePreviews()
def getDict(self):
"returns a dictionary from the contents of the editor."
model = self.widget.treeView.model()
if model is None:
return {}
root = model.invisibleRootItem()
d = {}
for gg in range(root.rowCount()):
group = root.child(gg)
for row in range(group.rowCount()):
kk = group.child(row, 0).text()
ii = group.child(row, 1).text()
# TODO the following should be translated back to english
# since text(0) could be translated
matkey = self.collapseKey(str(kk))
matvalue = unicode(ii)
if matvalue or (matkey == "Name"):
# use only keys which are not empty and the name even if empty
d[matkey] = matvalue
# self.outputDict(d)
return d
def outputDict(self, d):
print("MaterialEditor dictionary")
for param in d:
print(" {} : {}".format(param, d[param]))
"""
def setTexture(self, pattern):
"displays a texture preview if needed"
self.widget.PreviewVector.hide()
if pattern:
try:
import DrawingPatterns
except:
print("DrawingPatterns not found")
else:
pattern = DrawingPatterns.buildFileSwatch(pattern, size=96, png=True)
if pattern:
self.widget.PreviewVector.setPixmap(QtGui.QPixmap(pattern))
self.widget.PreviewVector.show()
"""
def updatePreviews(self, mat=None):
"updates the preview images from the content of the editor"
if not mat:
mat = self.getDict()
diffcol = None
highlightcol = None
sectioncol = None
if "DiffuseColor" in mat:
diffcol = mat["DiffuseColor"]
elif "ViewColor" in mat:
diffcol = mat["ViwColor"]
elif "Color" in mat:
diffcol = mat["Color"]
if "SpecularColor" in mat:
highlightcol = mat["SpecularColor"]
if "SectionColor" in mat:
sectioncol = mat["SectionColor"]
if diffcol or highlightcol:
fd = QtCore.QFile(":/icons/preview-rendered.svg")
if fd.open(QtCore.QIODevice.ReadOnly | QtCore.QIODevice.Text):
svg = QtCore.QTextStream(fd).readAll()
fd.close()
if diffcol:
svg = svg.replace("#d3d7cf", self.getColorHash(diffcol, val=255))
svg = svg.replace("#555753", self.getColorHash(diffcol, val=125))
if highlightcol:
svg = svg.replace("#fffffe", self.getColorHash(highlightcol, val=255))
self.widget.PreviewRender.load(QtCore.QByteArray(bytes(svg, encoding="utf8")))
if diffcol or sectioncol:
fd = QtCore.QFile(":/icons/preview-vector.svg")
if fd.open(QtCore.QIODevice.ReadOnly | QtCore.QIODevice.Text):
svg = QtCore.QTextStream(fd).readAll()
fd.close()
if diffcol:
svg = svg.replace("#d3d7cf", self.getColorHash(diffcol, val=255))
svg = svg.replace("#555753", self.getColorHash(diffcol, val=125))
if sectioncol:
svg = svg.replace("#ffffff", self.getColorHash(sectioncol, val=255))
self.widget.PreviewVector.load(QtCore.QByteArray(bytes(svg, encoding="utf8")))
def getColorHash(self, col, val=255):
"returns a '#000000' string from a '(0.1,0.2,0.3)' string"
col = [float(x.strip()) for x in col.strip("()").split(",")]
color = QtGui.QColor(int(col[0]*val), int(col[1]*val), int(col[2]*val))
return color.name()
def openfile(self):
"Opens a FCMat file"
filetuple = QtGui.QFileDialog.getOpenFileName(
QtGui.QApplication.activeWindow(),
"Open FreeCAD Material file",
self.directory,
"*.FCMat"
)
self.card_path = filetuple[0]
index = self.widget.ComboMaterial.findData(self.card_path)
print(index)
# check if card_path is in known path, means it is in combo box already
# if not print message, and give some feedbach that the card parameter are loaded
if os.path.isfile(self.card_path):
if index == -1:
FreeCAD.Console.PrintMessage(
"Card path: {} not found in known cards."
"The material parameter only are loaded.\n"
.format(self.card_path)
)
from importFCMat import read
d = read(self.card_path)
if d:
self.updateMatParamsInTree(d)
self.widget.ComboMaterial.setCurrentIndex(0)
# set combo box to the none material after tree params
else:
self.chooseMaterial(index)
self.directory = os.path.dirname(self.card_path)
def savefile(self):
"Saves a FCMat file."
model = self.widget.treeView.model()
item = model.findItems(translate("Material", "Name"),
QtCore.Qt.MatchRecursive, 0)[0]
group = item.parent()
it = group.child(item.row(), 1)
name = it.text()
if not name:
name = "Material"
filetuple = QtGui.QFileDialog.getSaveFileName(
QtGui.QApplication.activeWindow(),
"Save FreeCAD Material file",
self.directory + "/" + name + ".FCMat",
"*.FCMat"
)
# a tuple of two empty strings returns True, so use the filename directly
filename = filetuple[0]
if filename:
self.directory = os.path.dirname(filename)
# should not be resource dir but user result dir instead
d = self.getDict()
# self.outputDict(d)
if d:
from importFCMat import write
write(filename, d)
self.updateCardsInCombo()
def show(self):
return self.widget.show()
def exec_(self):
return self.widget.exec_()
# ************************************************************************************************
# ************************************************************************************************
class MaterialsDelegate(QtGui.QStyledItemDelegate):
"""provides display and editing facilities for data items from a model."""
def __init__(self):
""
super(MaterialsDelegate, self).__init__()
def createEditor(self, parent, option, index):
"""returns the widget used to change data from the model."""
model = index.model()
column = index.column()
item = model.itemFromIndex(index)
group = item.parent()
if not group:
return
if column == 1:
row = index.row()
PP = group.child(row, 0)
matproperty = PP.text().replace(" ", "") # remove spaces
TT = group.child(row, 2)
if TT:
Type = TT.text()
else:
Type = "String"
VV = group.child(row, 1)
Value = VV.text()
editor = matProperWidget(parent, matproperty, Type, Value)
elif column == 0:
if group.text() == "User defined":
editor = matProperWidget(parent)
else:
return
else:
return
return editor
def setEditorData(self, editor, index):
"""provides the widget with data to manipulate."""
Type = editor.property("Type")
model = index.model()
item = model.itemFromIndex(index)
print("item1={}".format(item.text()))
if Type == "Color":
color = editor.property("color")
color = tuple([v/255.0 for v in color.getRgb()])
item.setText(str(color))
elif Type == "File":
lineEdit = editor.children()[1]
item.setText(lineEdit.text())
else:
super(MaterialsDelegate, self).setEditorData(editor, index)
# ************************************************************************************************
# ************************************************************************************************
def matProperWidget(parent=None, matproperty=None, Type="String", Value=None,
minimum=None, maximum=None, stepsize=None, precision=12):
"""customs widgets for the material stuff."""
# FIXME
# Workaround for problem from here:
# https://forum.freecadweb.org/viewtopic.php?f=18&t=56912&start=20#p516811
# set precision to 12
# Better would be a similar system like used in FEM material task panel
# if the value in the InputField has not changed the data is not changed
# why does the value changes if the user clicks in
# the value and unit should exact stay as it is displayed before the user
# clicks in the field
# the user defined properties are of Type String and thus uses a "Gui::PrefLineEdit"
print(matproperty)
print(Type)
print(Value)
ui = FreeCADGui.UiLoader()
if Type == "String":
widget = ui.createWidget("Gui::PrefLineEdit")
elif Type == "URL":
widget = ui.createWidget("Gui::PrefLineEdit")
elif Type == "File":
widget = ui.createWidget("Gui::FileChooser")
if Value:
lineEdit = widget.children()[1]
lineEdit.setText(Value)
elif Type == "Quantity" or Type == "Float":
widget = ui.createWidget("Gui::InputField")
# print(matproperty)
if hasattr(FreeCAD.Units, matproperty):
unit = getattr(FreeCAD.Units, matproperty)
quantity = FreeCAD.Units.Quantity(1, unit)
widget.setProperty("unit", quantity.getUserPreferred()[2])
else:
FreeCAD.Console.PrintWarning(
"Not known unit for property: {}. Probably the Quantity does not have a unit.\n"
.format(matproperty)
)
# the Gui::InputField is used for Floats too, because of the digits
elif Type == "Integer":
widget = ui.createWidget("Gui::UIntSpinBox")
# elif Type == "Float":
# widget = ui.createWidget("Gui::PrefDoubleSpinBox")
# has only 2 digit precision, but for example RelativePermittivity needs much more
# see material card for Air, thus Workaround
# a "Gui::InputField" without unit is used
elif Type == "Enumerator":
widget = ui.createWidget("Gui::PrefComboBox")
elif Type == "Boolean":
widget = ui.createWidget("Gui::PrefComboBox")
widget.insertItems(0, ["", "False", "True"])
elif Type == "Vector":
widget = ui.createWidget("Gui::PrefLineEdit")
elif Type == "Color":
widget = ui.createWidget("Gui::PrefColorButton")
if Value:
value = string2tuple(Value)
color = QtGui.QColor()
color.setRgb(value[0], value[1], value[2], value[3])
widget.setProperty("color", color)
else:
widget = QtGui.QLineEdit()
if minimum is not None:
widget.setProperty("minimum", minimum)
if maximum is not None:
widget.setProperty("maximum", maximum)
if stepsize is not None:
widget.setProperty("stepsize", stepsize)
if precision is not None:
widget.setProperty("precision", precision)
widget.setProperty("Type", Type)
widget.setParent(parent)
return widget
def string2tuple(string):
"provisionally"
value = string[1:-1]
value = value.split(",")
value = [int(float(v)*255) for v in value]
value = tuple(value)
return value
def translate(context, text):
"translates text"
return text # TODO use Qt translation mechanism here
def openEditor(obj=None, prop=None):
"""openEditor([obj,prop]): opens the editor, optionally with
an object name and material property name to edit"""
editor = MaterialEditor(obj, prop)
editor.exec_()
def editMaterial(material=None, card_path=None):
"""editMaterial(material): opens the editor to edit the contents
of the given material dictionary. Returns the modified material dictionary."""
# if the material editor is opened with this def and the card_path is None
# the combo box with the card name is empty
# this makes sense, because the editor was not opened with a card_path,
# but with material dictionary instead
# TODO: add some text in combo box, may be "custom material data" or "user material data"
# TODO: if card_path is None, all known cards could be checked,
# if one fits exact ALL provided data, this card name could be displayed
editor = MaterialEditor(material=material, card_path=card_path)
result = editor.exec_()
if result:
return editor.getDict()
else:
# on cancel button an empty dict is returned
return {}
# ************************************************************************************************
# ************************************************************************************************
"""
# some examples how to open the material editor in Python:
import MaterialEditor
MaterialEditor.openEditor()
doc = FreeCAD.open(
FreeCAD.ConfigGet("AppHomePath") + "data/examples/FemCalculixCantilever3D.FCStd"
)
import MaterialEditor
MaterialEditor.openEditor("SolidMaterial", "Material")
import MaterialEditor
MaterialEditor.editMaterial({
"Density": "1234.0 kg/m^3",
"Name": "My-Material-Data",
"PoissonRatio": "0.66",
"YoungsModulus": "123456 MPa"
})
import MaterialEditor
MaterialEditor.editMaterial("ABS")
"""