XmlMaterialProfile.py 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import copy
  4. import io
  5. import json # To parse the product-to-id mapping file.
  6. import os.path # To find the product-to-id mapping.
  7. from typing import Any, Dict, List, Optional, Tuple, cast, Set
  8. import xml.etree.ElementTree as ET
  9. from UM.PluginRegistry import PluginRegistry
  10. from UM.Resources import Resources
  11. from UM.Logger import Logger
  12. import UM.Dictionary
  13. from UM.Settings.InstanceContainer import InstanceContainer
  14. from UM.Settings.ContainerRegistry import ContainerRegistry
  15. from UM.ConfigurationErrorMessage import ConfigurationErrorMessage
  16. from cura.CuraApplication import CuraApplication
  17. from cura.PrinterOutput.FormatMaps import FormatMaps
  18. from cura.Machines.VariantType import VariantType
  19. try:
  20. from .XmlMaterialValidator import XmlMaterialValidator
  21. except (ImportError, SystemError):
  22. import XmlMaterialValidator # type: ignore # This fixes the tests not being able to import.
  23. class XmlMaterialProfile(InstanceContainer):
  24. """Handles serializing and deserializing material containers from an XML file"""
  25. CurrentFdmMaterialVersion = "1.3"
  26. Version = 1
  27. def __init__(self, container_id, *args, **kwargs):
  28. super().__init__(container_id, *args, **kwargs)
  29. self._inherited_files = []
  30. @staticmethod
  31. def xmlVersionToSettingVersion(xml_version: str) -> int:
  32. """Translates the version number in the XML files to the setting_version metadata entry.
  33. Since the two may increment independently we need a way to say which
  34. versions of the XML specification are compatible with our setting data
  35. version numbers.
  36. :param xml_version: The version number found in an XML file.
  37. :return: The corresponding setting_version.
  38. """
  39. if xml_version == "1.3":
  40. return CuraApplication.SettingVersion
  41. return 0 # Older than 1.3.
  42. def getInheritedFiles(self):
  43. return self._inherited_files
  44. def setMetaDataEntry(self, key, value, apply_to_all = True):
  45. """set the meta data for all machine / variant combinations
  46. The "apply_to_all" flag indicates whether this piece of metadata should be applied to all material containers
  47. or just this specific container.
  48. For example, when you change the material name, you want to apply it to all its derived containers, but for
  49. some specific settings, they should only be applied to a machine/variant-specific container.
  50. Overridden from InstanceContainer
  51. """
  52. registry = ContainerRegistry.getInstance()
  53. if registry.isReadOnly(self.getId()):
  54. Logger.log("w", "Can't change metadata {key} of material {material_id} because it's read-only.".format(key = key, material_id = self.getId()))
  55. return
  56. # Some metadata such as diameter should also be instantiated to be a setting. Go though all values for the
  57. # "properties" field and apply the new values to SettingInstances as well.
  58. new_setting_values_dict = {}
  59. if key == "properties":
  60. for k, v in value.items():
  61. if k in self.__material_properties_setting_map:
  62. new_setting_values_dict[self.__material_properties_setting_map[k]] = v
  63. if not apply_to_all: # Historical: If you only want to modify THIS container. We only used that to prevent recursion but with the below code that's no longer necessary.
  64. # CURA-6920: This is an optimization, but it also fixes the problem that you can only set metadata for a
  65. # material container that can be found in the container registry.
  66. container_query = [self]
  67. else:
  68. container_query = registry.findContainers(base_file = self.getMetaDataEntry("base_file"))
  69. for container in container_query:
  70. if key not in container.getMetaData() or container.getMetaData()[key] != value:
  71. container.getMetaData()[key] = value
  72. container.setDirty(True)
  73. container.metaDataChanged.emit(container)
  74. for k, v in new_setting_values_dict.items():
  75. self.setProperty(k, "value", v)
  76. def setName(self, new_name):
  77. """Overridden from InstanceContainer, similar to setMetaDataEntry.
  78. without this function the setName would only set the name of the specific nozzle / material / machine combination container
  79. The function is a bit tricky. It will not set the name of all containers if it has the correct name itself.
  80. """
  81. registry = ContainerRegistry.getInstance()
  82. if registry.isReadOnly(self.getId()):
  83. return
  84. # Not only is this faster, it also prevents a major loop that causes a stack overflow.
  85. if self.getName() == new_name:
  86. return
  87. super().setName(new_name)
  88. basefile = self.getMetaDataEntry("base_file", self.getId()) # if basefile is self.getId, this is a basefile.
  89. # Update the basefile as well, this is actually what we're trying to do
  90. # Update all containers that share GUID and basefile
  91. containers = registry.findInstanceContainers(base_file = basefile)
  92. for container in containers:
  93. container.setName(new_name)
  94. def setDirty(self, dirty):
  95. """Overridden from InstanceContainer, to set dirty to base file as well."""
  96. super().setDirty(dirty)
  97. base_file = self.getMetaDataEntry("base_file", None)
  98. registry = ContainerRegistry.getInstance()
  99. if base_file is not None and base_file != self.getId() and not registry.isReadOnly(base_file):
  100. containers = registry.findContainers(id = base_file)
  101. if containers:
  102. containers[0].setDirty(dirty)
  103. def serialize(self, ignored_metadata_keys: Optional[Set[str]] = None):
  104. """Overridden from InstanceContainer
  105. base file: common settings + supported machines
  106. machine / variant combination: only changes for itself.
  107. """
  108. registry = ContainerRegistry.getInstance()
  109. base_file = self.getMetaDataEntry("base_file", "")
  110. if base_file and self.getId() != base_file:
  111. # Since we create an instance of XmlMaterialProfile for each machine and nozzle in the profile,
  112. # we should only serialize the "base" material definition, since that can then take care of
  113. # serializing the machine/nozzle specific profiles.
  114. raise NotImplementedError("Ignoring serializing non-root XML materials, the data is contained in the base material")
  115. builder = ET.TreeBuilder()
  116. root = builder.start("fdmmaterial",
  117. {"xmlns": "http://www.ultimaker.com/material",
  118. "xmlns:cura": "http://www.ultimaker.com/cura",
  119. "version": self.CurrentFdmMaterialVersion})
  120. ## Begin Metadata Block
  121. builder.start("metadata", {}) # type: ignore
  122. metadata = copy.deepcopy(self.getMetaData())
  123. # Get the to reserialize keys from the metadata before they are deleted.
  124. reserialize_settings = copy.deepcopy(metadata["reserialize_settings"])
  125. # setting_version is derived from the "version" tag in the schema, so don't serialize it into a file
  126. if ignored_metadata_keys is None:
  127. ignored_metadata_keys = set()
  128. ignored_metadata_keys |= {"setting_version", "definition", "status", "variant", "type", "base_file", "approximate_diameter", "id", "container_type", "name", "compatible", "reserialize_settings"}
  129. # remove the keys that we want to ignore in the metadata
  130. for key in ignored_metadata_keys:
  131. if key in metadata:
  132. del metadata[key]
  133. properties = metadata.pop("properties", {})
  134. ## Begin Name Block
  135. builder.start("name", {}) # type: ignore
  136. builder.start("brand", {}) # type: ignore
  137. builder.data(metadata.pop("brand", ""))
  138. builder.end("brand")
  139. builder.start("material", {}) # type: ignore
  140. builder.data(metadata.pop("material", ""))
  141. builder.end("material")
  142. builder.start("color", {}) # type: ignore
  143. builder.data(metadata.pop("color_name", ""))
  144. builder.end("color")
  145. builder.start("label", {}) # type: ignore
  146. builder.data(self.getName())
  147. builder.end("label")
  148. builder.end("name")
  149. ## End Name Block
  150. for key, value in metadata.items():
  151. key_to_use = key
  152. if key in self._metadata_tags_that_have_cura_namespace:
  153. key_to_use = "cura:" + key_to_use
  154. builder.start(key_to_use, {}) # type: ignore
  155. if value is not None: #Nones get handled well by the builder.
  156. #Otherwise the builder always expects a string.
  157. #Deserialize expects the stringified version.
  158. value = str(value)
  159. builder.data(value)
  160. builder.end(key_to_use)
  161. builder.end("metadata")
  162. ## End Metadata Block
  163. ## Begin Properties Block
  164. builder.start("properties", {}) # type: ignore
  165. for key, value in properties.items():
  166. builder.start(key, {}) # type: ignore
  167. builder.data(value)
  168. builder.end(key)
  169. builder.end("properties")
  170. ## End Properties Block
  171. ## Begin Settings Block
  172. builder.start("settings", {}) # type: ignore
  173. if self.getMetaDataEntry("definition") == "fdmprinter":
  174. for instance in self.findInstances():
  175. self._addSettingElement(builder, instance)
  176. machine_container_map = {} # type: Dict[str, InstanceContainer]
  177. machine_variant_map = {} # type: Dict[str, Dict[str, Any]]
  178. root_material_id = self.getMetaDataEntry("base_file") # if basefile is self.getId, this is a basefile.
  179. all_containers = registry.findInstanceContainers(base_file = root_material_id)
  180. for container in all_containers:
  181. definition_id = container.getMetaDataEntry("definition")
  182. if definition_id == "fdmprinter":
  183. continue
  184. if definition_id not in machine_container_map:
  185. machine_container_map[definition_id] = container
  186. if definition_id not in machine_variant_map:
  187. machine_variant_map[definition_id] = {}
  188. variant_name = container.getMetaDataEntry("variant_name")
  189. if not variant_name:
  190. machine_container_map[definition_id] = container
  191. continue
  192. variant_dict = {"variant_type": container.getMetaDataEntry("hardware_type", "nozzle"),
  193. "material_container": container}
  194. machine_variant_map[definition_id][variant_name] = variant_dict
  195. # Map machine human-readable names to IDs
  196. product_id_map = FormatMaps.getProductIdMap()
  197. for definition_id, container in machine_container_map.items():
  198. definition_id = container.getMetaDataEntry("definition")
  199. definition_metadata = registry.findDefinitionContainersMetadata(id = definition_id)[0]
  200. product = definition_id
  201. for product_name, product_id_list in product_id_map.items():
  202. if definition_id in product_id_list:
  203. product = product_name
  204. break
  205. builder.start("machine", {}) # type: ignore
  206. builder.start("machine_identifier", {
  207. "manufacturer": container.getMetaDataEntry("machine_manufacturer",
  208. definition_metadata.get("manufacturer", "Unknown")),
  209. "product": product
  210. })
  211. builder.end("machine_identifier")
  212. for instance in container.findInstances():
  213. if self.getMetaDataEntry("definition") == "fdmprinter" and self.getInstance(instance.definition.key) and self.getProperty(instance.definition.key, "value") == instance.value:
  214. # If the settings match that of the base profile, just skip since we inherit the base profile.
  215. continue
  216. self._addSettingElement(builder, instance)
  217. # Find all hotend sub-profiles corresponding to this material and machine and add them to this profile.
  218. buildplate_dict = {} # type: Dict[str, Any]
  219. for variant_name, variant_dict in machine_variant_map[definition_id].items():
  220. variant_type = VariantType(variant_dict["variant_type"])
  221. if variant_type == VariantType.NOZZLE:
  222. # The hotend identifier is not the containers name, but its "name".
  223. builder.start("hotend", {"id": variant_name})
  224. # Compatible is a special case, as it's added as a meta data entry (instead of an instance).
  225. material_container = variant_dict["material_container"]
  226. compatible = material_container.getMetaDataEntry("compatible")
  227. if compatible is not None:
  228. builder.start("setting", {"key": "hardware compatible"})
  229. if compatible:
  230. builder.data("yes")
  231. else:
  232. builder.data("no")
  233. builder.end("setting")
  234. for instance in material_container.findInstances():
  235. if container.getInstance(instance.definition.key) and container.getProperty(instance.definition.key, "value") == instance.value:
  236. # If the settings match that of the machine profile, just skip since we inherit the machine profile.
  237. continue
  238. self._addSettingElement(builder, instance)
  239. if material_container.getMetaDataEntry("buildplate_compatible") and not buildplate_dict:
  240. buildplate_dict["buildplate_compatible"] = material_container.getMetaDataEntry("buildplate_compatible")
  241. buildplate_dict["buildplate_recommended"] = material_container.getMetaDataEntry("buildplate_recommended")
  242. buildplate_dict["material_container"] = material_container
  243. hotend_reserialize_settings = material_container.getMetaDataEntry("reserialize_settings")
  244. for key, value in hotend_reserialize_settings.items():
  245. builder.start("setting", {"key": key})
  246. builder.data(value)
  247. builder.end("setting")
  248. builder.end("hotend")
  249. if buildplate_dict:
  250. for variant_name in buildplate_dict["buildplate_compatible"]:
  251. builder.start("buildplate", {"id": variant_name})
  252. material_container = buildplate_dict["material_container"]
  253. buildplate_compatible_dict = material_container.getMetaDataEntry("buildplate_compatible")
  254. buildplate_recommended_dict = material_container.getMetaDataEntry("buildplate_recommended")
  255. if buildplate_compatible_dict:
  256. compatible = buildplate_compatible_dict[variant_name]
  257. recommended = buildplate_recommended_dict[variant_name]
  258. builder.start("setting", {"key": "hardware compatible"})
  259. builder.data("yes" if compatible else "no")
  260. builder.end("setting")
  261. builder.start("setting", {"key": "hardware recommended"})
  262. builder.data("yes" if recommended else "no")
  263. builder.end("setting")
  264. buildplate_reserialize_settings = material_container.getMetaDataEntry("reserialize_settings")
  265. for key, value in buildplate_reserialize_settings.items():
  266. builder.start("setting", {"key": key})
  267. builder.data(value)
  268. builder.end("setting")
  269. builder.end("buildplate")
  270. machine_reserialize_settings = container.getMetaDataEntry("reserialize_settings")
  271. for key, value in machine_reserialize_settings.items():
  272. builder.start("setting", {"key": key})
  273. builder.data(value)
  274. builder.end("setting")
  275. builder.end("machine")
  276. for key, value in reserialize_settings.items():
  277. builder.start("setting", {"key": key})
  278. builder.data(value)
  279. builder.end("setting")
  280. builder.end("settings")
  281. ## End Settings Block
  282. builder.end("fdmmaterial")
  283. root = builder.close()
  284. _indent(root)
  285. stream = io.BytesIO()
  286. tree = ET.ElementTree(root)
  287. # this makes sure that the XML header states encoding="utf-8"
  288. tree.write(stream, encoding = "utf-8", xml_declaration = True)
  289. return stream.getvalue().decode("utf-8")
  290. def getFileName(self) -> str:
  291. return (self.getMetaDataEntry("base_file") + ".xml.fdm_material").replace(" ", "+")
  292. # Recursively resolve loading inherited files
  293. def _resolveInheritance(self, file_name):
  294. xml = self._loadFile(file_name)
  295. inherits = xml.find("./um:inherits", self.__namespaces)
  296. if inherits is not None:
  297. inherited = self._resolveInheritance(inherits.text)
  298. xml = self._mergeXML(inherited, xml)
  299. return xml
  300. def _loadFile(self, file_name):
  301. path = Resources.getPath(CuraApplication.getInstance().ResourceTypes.MaterialInstanceContainer, file_name + ".xml.fdm_material")
  302. with open(path, encoding = "utf-8") as f:
  303. contents = f.read()
  304. self._inherited_files.append(path)
  305. return ET.fromstring(contents)
  306. # The XML material profile can have specific settings for machines.
  307. # Some machines share profiles, so they are only created once.
  308. # This function duplicates those elements so that each machine tag only has one identifier.
  309. def _expandMachinesXML(self, element):
  310. settings_element = element.find("./um:settings", self.__namespaces)
  311. machines = settings_element.iterfind("./um:machine", self.__namespaces)
  312. machines_to_add = []
  313. machines_to_remove = []
  314. for machine in machines:
  315. identifiers = list(machine.iterfind("./um:machine_identifier", self.__namespaces))
  316. has_multiple_identifiers = len(identifiers) > 1
  317. if has_multiple_identifiers:
  318. # Multiple identifiers found. We need to create a new machine element and copy all it's settings there.
  319. for identifier in identifiers:
  320. new_machine = copy.deepcopy(machine)
  321. # Create list of identifiers that need to be removed from the copied element.
  322. other_identifiers = [self._createKey(other_identifier) for other_identifier in identifiers if other_identifier is not identifier]
  323. # As we can only remove by exact object reference, we need to look through the identifiers of copied machine.
  324. new_machine_identifiers = list(new_machine.iterfind("./um:machine_identifier", self.__namespaces))
  325. for new_machine_identifier in new_machine_identifiers:
  326. key = self._createKey(new_machine_identifier)
  327. # Key was in identifiers to remove, so this element needs to be purged
  328. if key in other_identifiers:
  329. new_machine.remove(new_machine_identifier)
  330. machines_to_add.append(new_machine)
  331. machines_to_remove.append(machine)
  332. else:
  333. pass # Machine only has one identifier. Nothing to do.
  334. # Remove & add all required machines.
  335. for machine_to_remove in machines_to_remove:
  336. settings_element.remove(machine_to_remove)
  337. for machine_to_add in machines_to_add:
  338. settings_element.append(machine_to_add)
  339. return element
  340. def _mergeXML(self, first, second):
  341. result = copy.deepcopy(first)
  342. self._combineElement(self._expandMachinesXML(result), self._expandMachinesXML(second))
  343. return result
  344. @staticmethod
  345. def _createKey(element):
  346. key = element.tag.split("}")[-1]
  347. if "key" in element.attrib:
  348. key += " key:" + element.attrib["key"]
  349. if "manufacturer" in element.attrib:
  350. key += " manufacturer:" + element.attrib["manufacturer"]
  351. if "product" in element.attrib:
  352. key += " product:" + element.attrib["product"]
  353. if key == "machine":
  354. for item in element:
  355. if "machine_identifier" in item.tag:
  356. key += " " + item.attrib["product"]
  357. return key
  358. # Recursively merges XML elements. Updates either the text or children if another element is found in first.
  359. # If it does not exist, copies it from second.
  360. @staticmethod
  361. def _combineElement(first, second):
  362. # Create a mapping from tag name to element.
  363. mapping = {}
  364. for element in first:
  365. key = XmlMaterialProfile._createKey(element)
  366. mapping[key] = element
  367. for element in second:
  368. key = XmlMaterialProfile._createKey(element)
  369. if len(element): # Check if element has children.
  370. try:
  371. if "setting" in element.tag and not "settings" in element.tag:
  372. # Setting can have points in it. In that case, delete all values and override them.
  373. for child in list(mapping[key]):
  374. mapping[key].remove(child)
  375. for child in element:
  376. mapping[key].append(child)
  377. else:
  378. XmlMaterialProfile._combineElement(mapping[key], element) # Multiple elements, handle those.
  379. except KeyError:
  380. mapping[key] = element
  381. first.append(element)
  382. else:
  383. try:
  384. mapping[key].text = element.text
  385. except KeyError: # Not in the mapping, so simply add it
  386. mapping[key] = element
  387. first.append(element)
  388. def clearData(self):
  389. self._metadata = {
  390. "id": self.getId(),
  391. "name": ""
  392. }
  393. self._definition = None
  394. self._instances = {}
  395. self._read_only = False
  396. self._dirty = False
  397. self._path = ""
  398. @classmethod
  399. def getConfigurationTypeFromSerialized(cls, serialized: str) -> Optional[str]:
  400. return "materials"
  401. @classmethod
  402. def getVersionFromSerialized(cls, serialized: str) -> int:
  403. data = ET.fromstring(serialized)
  404. version = XmlMaterialProfile.Version
  405. # get setting version
  406. if "version" in data.attrib:
  407. setting_version = cls.xmlVersionToSettingVersion(data.attrib["version"])
  408. else:
  409. setting_version = cls.xmlVersionToSettingVersion("1.2")
  410. return version * 1000000 + setting_version
  411. @classmethod
  412. def getMetadataFromSerialized(cls, serialized: str, property_name: str) -> str:
  413. data = ET.fromstring(serialized)
  414. metadata = data.find("./um:metadata", cls.__namespaces)
  415. property = metadata.find("./um:" + property_name, cls.__namespaces)
  416. # This is a necessary property != None check, xml library overrides __bool__ to return False in cases when Element is not None.
  417. return property.text if property != None else ""
  418. def deserialize(self, serialized, file_name = None):
  419. """Overridden from InstanceContainer"""
  420. containers_to_add = []
  421. # update the serialized data first
  422. from UM.Settings.Interfaces import ContainerInterface
  423. serialized = ContainerInterface.deserialize(self, serialized, file_name)
  424. try:
  425. data = ET.fromstring(serialized)
  426. except:
  427. Logger.logException("e", "An exception occurred while parsing the material profile")
  428. return
  429. # Reset previous metadata
  430. old_id = self.getId()
  431. self.clearData() # Ensure any previous data is gone.
  432. meta_data = {}
  433. meta_data["type"] = "material"
  434. meta_data["base_file"] = self.getId()
  435. meta_data["status"] = "unknown" # TODO: Add material verification
  436. meta_data["id"] = old_id
  437. meta_data["container_type"] = XmlMaterialProfile
  438. meta_data["reserialize_settings"] = {}
  439. common_setting_values = {}
  440. inherits = data.find("./um:inherits", self.__namespaces)
  441. if inherits is not None:
  442. inherited = self._resolveInheritance(inherits.text)
  443. data = self._mergeXML(inherited, data)
  444. # set setting_version in metadata
  445. if "version" in data.attrib:
  446. meta_data["setting_version"] = self.xmlVersionToSettingVersion(data.attrib["version"])
  447. else:
  448. meta_data["setting_version"] = self.xmlVersionToSettingVersion("1.2") #1.2 and lower didn't have that version number there yet.
  449. meta_data["name"] = "Unknown Material" #In case the name tag is missing.
  450. for entry in data.iterfind("./um:metadata/*", self.__namespaces):
  451. tag_name = _tag_without_namespace(entry)
  452. if tag_name == "name":
  453. brand = entry.find("./um:brand", self.__namespaces)
  454. material = entry.find("./um:material", self.__namespaces)
  455. color = entry.find("./um:color", self.__namespaces)
  456. label = entry.find("./um:label", self.__namespaces)
  457. if label is not None and label.text is not None:
  458. meta_data["name"] = label.text
  459. else:
  460. meta_data["name"] = self._profile_name(material.text, color.text)
  461. meta_data["brand"] = brand.text if brand.text is not None else "Unknown Brand"
  462. meta_data["material"] = material.text if material.text is not None else "Unknown Type"
  463. meta_data["color_name"] = color.text if color.text is not None else "Unknown Color"
  464. continue
  465. # setting_version is derived from the "version" tag in the schema earlier, so don't set it here
  466. if tag_name == "setting_version":
  467. continue
  468. meta_data[tag_name] = entry.text
  469. for tag_name, value in meta_data.items():
  470. if tag_name in self.__material_metadata_setting_map:
  471. common_setting_values[self.__material_metadata_setting_map[tag_name]] = value
  472. if "description" not in meta_data:
  473. meta_data["description"] = ""
  474. if "adhesion_info" not in meta_data:
  475. meta_data["adhesion_info"] = ""
  476. validation_message = XmlMaterialValidator.validateMaterialMetaData(meta_data)
  477. if validation_message is not None:
  478. ConfigurationErrorMessage.getInstance().addFaultyContainers(self.getId())
  479. Logger.log("e", "Not a valid material profile: {message}".format(message = validation_message))
  480. return
  481. property_values = {}
  482. properties = data.iterfind("./um:properties/*", self.__namespaces)
  483. for entry in properties:
  484. tag_name = _tag_without_namespace(entry)
  485. property_values[tag_name] = entry.text
  486. if tag_name in self.__material_properties_setting_map:
  487. common_setting_values[self.__material_properties_setting_map[tag_name]] = entry.text
  488. meta_data["approximate_diameter"] = str(round(float(property_values.get("diameter", 2.85)))) # In mm
  489. meta_data["properties"] = property_values
  490. meta_data["definition"] = "fdmprinter"
  491. common_compatibility = True
  492. settings = data.iterfind("./um:settings/um:setting", self.__namespaces)
  493. for entry in settings:
  494. key = entry.get("key")
  495. if key in self.__material_settings_setting_map:
  496. if key == "processing temperature graph": #This setting has no setting text but subtags.
  497. graph_nodes = entry.iterfind("./um:point", self.__namespaces)
  498. graph_points = []
  499. for graph_node in graph_nodes:
  500. flow = float(graph_node.get("flow"))
  501. temperature = float(graph_node.get("temperature"))
  502. graph_points.append([flow, temperature])
  503. common_setting_values[self.__material_settings_setting_map[key]] = str(graph_points)
  504. else:
  505. common_setting_values[self.__material_settings_setting_map[key]] = entry.text
  506. elif key in self.__unmapped_settings:
  507. if key == "hardware compatible":
  508. common_compatibility = self._parseCompatibleValue(entry.text)
  509. elif key in self.__keep_serialized_settings:
  510. meta_data["reserialize_settings"][key] = entry.text
  511. # Add namespaced Cura-specific settings
  512. settings = data.iterfind("./um:settings/cura:setting", self.__namespaces)
  513. for entry in settings:
  514. value = entry.text
  515. if value.lower() == "yes":
  516. value = True
  517. elif value.lower() == "no":
  518. value = False
  519. key = entry.get("key")
  520. common_setting_values[key] = value
  521. self._cached_values = common_setting_values # from InstanceContainer ancestor
  522. meta_data["compatible"] = common_compatibility
  523. self.setMetaData(meta_data)
  524. self._dirty = False
  525. # Map machine human-readable names to IDs
  526. product_id_map = FormatMaps.getProductIdMap()
  527. machines = data.iterfind("./um:settings/um:machine", self.__namespaces)
  528. for machine in machines:
  529. machine_compatibility = common_compatibility
  530. machine_setting_values = {}
  531. settings = machine.iterfind("./um:setting", self.__namespaces)
  532. machine_reserialize_settings = {}
  533. for entry in settings:
  534. key = entry.get("key")
  535. if key in self.__material_settings_setting_map:
  536. if key == "processing temperature graph": #This setting has no setting text but subtags.
  537. graph_nodes = entry.iterfind("./um:point", self.__namespaces)
  538. graph_points = []
  539. for graph_node in graph_nodes:
  540. flow = float(graph_node.get("flow"))
  541. temperature = float(graph_node.get("temperature"))
  542. graph_points.append([flow, temperature])
  543. machine_setting_values[self.__material_settings_setting_map[key]] = str(graph_points)
  544. else:
  545. machine_setting_values[self.__material_settings_setting_map[key]] = entry.text
  546. elif key in self.__unmapped_settings:
  547. if key == "hardware compatible":
  548. machine_compatibility = self._parseCompatibleValue(entry.text)
  549. elif key in self.__keep_serialized_settings:
  550. machine_reserialize_settings[key] = entry.text
  551. else:
  552. Logger.log("d", "Unsupported material setting %s", key)
  553. # Add namespaced Cura-specific settings
  554. settings = machine.iterfind("./cura:setting", self.__namespaces)
  555. for entry in settings:
  556. value = entry.text
  557. if value.lower() == "yes":
  558. value = True
  559. elif value.lower() == "no":
  560. value = False
  561. key = entry.get("key")
  562. machine_setting_values[key] = value
  563. cached_machine_setting_properties = common_setting_values.copy()
  564. cached_machine_setting_properties.update(machine_setting_values)
  565. identifiers = machine.iterfind("./um:machine_identifier", self.__namespaces)
  566. for identifier in identifiers:
  567. machine_id_list = product_id_map.get(identifier.get("product"), [])
  568. if not machine_id_list:
  569. machine_id_list = self.getPossibleDefinitionIDsFromName(identifier.get("product"))
  570. for machine_id in machine_id_list:
  571. definitions = ContainerRegistry.getInstance().findDefinitionContainersMetadata(id = machine_id)
  572. if not definitions:
  573. continue
  574. definition = definitions[0]
  575. machine_manufacturer = identifier.get("manufacturer", definition.get("manufacturer", "Unknown")) #If the XML material doesn't specify a manufacturer, use the one in the actual printer definition.
  576. # Always create the instance of the material even if it is not compatible, otherwise it will never
  577. # show as incompatible if the material profile doesn't define hotends in the machine - CURA-5444
  578. new_material_id = self.getId() + "_" + machine_id
  579. # The child or derived material container may already exist. This can happen when a material in a
  580. # project file and the a material in Cura have the same ID.
  581. # In the case if a derived material already exists, override that material container because if
  582. # the data in the parent material has been changed, the derived ones should be updated too.
  583. if ContainerRegistry.getInstance().isLoaded(new_material_id):
  584. new_material = ContainerRegistry.getInstance().findContainers(id = new_material_id)[0]
  585. is_new_material = False
  586. else:
  587. new_material = XmlMaterialProfile(new_material_id)
  588. is_new_material = True
  589. new_material.setMetaData(copy.deepcopy(self.getMetaData()))
  590. new_material.getMetaData()["id"] = new_material_id
  591. new_material.getMetaData()["name"] = self.getName()
  592. new_material.setDefinition(machine_id)
  593. # Don't use setMetadata, as that overrides it for all materials with same base file
  594. new_material.getMetaData()["compatible"] = machine_compatibility
  595. new_material.getMetaData()["machine_manufacturer"] = machine_manufacturer
  596. new_material.getMetaData()["definition"] = machine_id
  597. new_material.getMetaData()["reserialize_settings"] = machine_reserialize_settings
  598. new_material.setCachedValues(cached_machine_setting_properties)
  599. new_material._dirty = False
  600. if is_new_material:
  601. containers_to_add.append(new_material)
  602. hotends = machine.iterfind("./um:hotend", self.__namespaces)
  603. for hotend in hotends:
  604. # The "id" field for hotends in material profiles is actually name
  605. hotend_name = hotend.get("id")
  606. if hotend_name is None:
  607. continue
  608. hotend_mapped_settings, hotend_unmapped_settings, hotend_reserialize_settings = self._getSettingsDictForNode(hotend)
  609. hotend_compatibility = hotend_unmapped_settings.get("hardware compatible", machine_compatibility)
  610. # Generate container ID for the hotend-specific material container
  611. new_hotend_specific_material_id = self.getId() + "_" + machine_id + "_" + hotend_name.replace(" ", "_")
  612. # Same as machine compatibility, keep the derived material containers consistent with the parent material
  613. if ContainerRegistry.getInstance().isLoaded(new_hotend_specific_material_id):
  614. new_hotend_material = ContainerRegistry.getInstance().findContainers(id = new_hotend_specific_material_id)[0]
  615. is_new_material = False
  616. else:
  617. new_hotend_material = XmlMaterialProfile(new_hotend_specific_material_id)
  618. is_new_material = True
  619. new_hotend_material.setMetaData(copy.deepcopy(self.getMetaData()))
  620. new_hotend_material.getMetaData()["id"] = new_hotend_specific_material_id
  621. new_hotend_material.getMetaData()["name"] = self.getName()
  622. new_hotend_material.getMetaData()["variant_name"] = hotend_name
  623. new_hotend_material.setDefinition(machine_id)
  624. # Don't use setMetadata, as that overrides it for all materials with same base file
  625. new_hotend_material.getMetaData()["compatible"] = hotend_compatibility
  626. new_hotend_material.getMetaData()["machine_manufacturer"] = machine_manufacturer
  627. new_hotend_material.getMetaData()["definition"] = machine_id
  628. new_hotend_material.getMetaData()["reserialize_settings"] = hotend_reserialize_settings
  629. cached_hotend_setting_properties = cached_machine_setting_properties.copy()
  630. cached_hotend_setting_properties.update(hotend_mapped_settings)
  631. new_hotend_material.setCachedValues(cached_hotend_setting_properties)
  632. new_hotend_material._dirty = False
  633. if is_new_material:
  634. if ContainerRegistry.getInstance().isReadOnly(self.getId()):
  635. ContainerRegistry.getInstance().setExplicitReadOnly(new_hotend_material.getId())
  636. containers_to_add.append(new_hotend_material)
  637. # there is only one ID for a machine. Once we have reached here, it means we have already found
  638. # a workable ID for that machine, so there is no need to continue
  639. break
  640. for container_to_add in containers_to_add:
  641. ContainerRegistry.getInstance().addContainer(container_to_add)
  642. @classmethod
  643. def _getSettingsDictForNode(cls, node) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any]]:
  644. node_mapped_settings_dict: Dict[str, Any] = dict()
  645. node_unmapped_settings_dict: Dict[str, Any] = dict()
  646. node_reserialize_settings_dict: Dict[str, Any] = dict()
  647. # Fetch settings in the "um" namespace
  648. um_settings = node.iterfind("./um:setting", cls.__namespaces)
  649. for um_setting_entry in um_settings:
  650. setting_key = um_setting_entry.get("key")
  651. # Mapped settings
  652. if setting_key in cls.__material_settings_setting_map:
  653. if setting_key == "processing temperature graph": # This setting has no setting text but subtags.
  654. graph_nodes = um_setting_entry.iterfind("./um:point", cls.__namespaces)
  655. graph_points = []
  656. for graph_node in graph_nodes:
  657. flow = float(graph_node.get("flow"))
  658. temperature = float(graph_node.get("temperature"))
  659. graph_points.append([flow, temperature])
  660. node_mapped_settings_dict[cls.__material_settings_setting_map[setting_key]] = str(
  661. graph_points)
  662. else:
  663. node_mapped_settings_dict[cls.__material_settings_setting_map[setting_key]] = um_setting_entry.text
  664. # Unmapped settings
  665. elif setting_key in cls.__unmapped_settings:
  666. if setting_key in ("hardware compatible", "hardware recommended"):
  667. node_unmapped_settings_dict[setting_key] = cls._parseCompatibleValue(um_setting_entry.text)
  668. # Settings unused by Cura itself, but which need reserialization since they might be important to others.
  669. elif setting_key in cls.__keep_serialized_settings:
  670. node_reserialize_settings_dict[setting_key] = um_setting_entry.text
  671. # Unknown settings
  672. else:
  673. Logger.log("w", "Unsupported material setting %s", setting_key)
  674. # Fetch settings in the "cura" namespace
  675. cura_settings = node.iterfind("./cura:setting", cls.__namespaces)
  676. for cura_setting_entry in cura_settings:
  677. value = cura_setting_entry.text
  678. if value.lower() == "yes":
  679. value = True
  680. elif value.lower() == "no":
  681. value = False
  682. key = cura_setting_entry.get("key")
  683. # Cura settings are all mapped
  684. node_mapped_settings_dict[key] = value
  685. return node_mapped_settings_dict, node_unmapped_settings_dict, node_reserialize_settings_dict
  686. @classmethod
  687. def deserializeMetadata(cls, serialized: str, container_id: str) -> List[Dict[str, Any]]:
  688. result_metadata = [] #All the metadata that we found except the base (because the base is returned).
  689. #Update the serialized data to the latest version.
  690. serialized = cls._updateSerialized(serialized)
  691. base_metadata = {
  692. "type": "material",
  693. "status": "unknown", #TODO: Add material verification.
  694. "container_type": XmlMaterialProfile,
  695. "id": container_id,
  696. "base_file": container_id
  697. }
  698. try:
  699. data = ET.fromstring(serialized)
  700. except:
  701. Logger.logException("e", "An exception occurred while parsing the material profile")
  702. return []
  703. #TODO: Implement the <inherits> tag. It's unused at the moment though.
  704. if "version" in data.attrib:
  705. base_metadata["setting_version"] = cls.xmlVersionToSettingVersion(data.attrib["version"])
  706. else:
  707. base_metadata["setting_version"] = cls.xmlVersionToSettingVersion("1.2") #1.2 and lower didn't have that version number there yet.
  708. for entry in data.iterfind("./um:metadata/*", cls.__namespaces):
  709. tag_name = _tag_without_namespace(entry)
  710. if tag_name == "name":
  711. brand = entry.find("./um:brand", cls.__namespaces)
  712. material = entry.find("./um:material", cls.__namespaces)
  713. color = entry.find("./um:color", cls.__namespaces)
  714. label = entry.find("./um:label", cls.__namespaces)
  715. if label is not None and label.text is not None:
  716. base_metadata["name"] = label.text
  717. else:
  718. if material is not None and color is not None:
  719. base_metadata["name"] = cls._profile_name(material.text, color.text)
  720. else:
  721. base_metadata["name"] = "Unknown Material"
  722. base_metadata["brand"] = brand.text if brand is not None and brand.text is not None else "Unknown Brand"
  723. base_metadata["material"] = material.text if material is not None and material.text is not None else "Unknown Type"
  724. base_metadata["color_name"] = color.text if color is not None and color.text is not None else "Unknown Color"
  725. continue
  726. #Setting_version is derived from the "version" tag in the schema earlier, so don't set it here.
  727. if tag_name == "setting_version":
  728. continue
  729. base_metadata[tag_name] = entry.text
  730. if "description" not in base_metadata:
  731. base_metadata["description"] = ""
  732. if "adhesion_info" not in base_metadata:
  733. base_metadata["adhesion_info"] = ""
  734. property_values = {}
  735. properties = data.iterfind("./um:properties/*", cls.__namespaces)
  736. for entry in properties:
  737. tag_name = _tag_without_namespace(entry)
  738. property_values[tag_name] = entry.text
  739. base_metadata["approximate_diameter"] = str(round(float(cast(float, property_values.get("diameter", 2.85))))) # In mm
  740. base_metadata["properties"] = property_values
  741. base_metadata["definition"] = "fdmprinter"
  742. # Certain materials are loaded but should not be visible / selectable to the user.
  743. base_metadata["visible"] = not base_metadata.get("abstract_color", False)
  744. compatible_entries = data.iterfind("./um:settings/um:setting[@key='hardware compatible']", cls.__namespaces)
  745. try:
  746. common_compatibility = cls._parseCompatibleValue(next(compatible_entries).text) # type: ignore
  747. except StopIteration: #No 'hardware compatible' setting.
  748. common_compatibility = True
  749. base_metadata["compatible"] = common_compatibility
  750. result_metadata.append(base_metadata)
  751. # Map machine human-readable names to IDs
  752. product_id_map = FormatMaps.getProductIdMap()
  753. for machine in data.iterfind("./um:settings/um:machine", cls.__namespaces):
  754. machine_compatibility = common_compatibility
  755. for entry in machine.iterfind("./um:setting[@key='hardware compatible']", cls.__namespaces):
  756. if entry.text is not None:
  757. machine_compatibility = cls._parseCompatibleValue(entry.text)
  758. for identifier in machine.iterfind("./um:machine_identifier", cls.__namespaces):
  759. machine_id_list = product_id_map.get(identifier.get("product", ""), [])
  760. if not machine_id_list:
  761. machine_id_list = cls.getPossibleDefinitionIDsFromName(identifier.get("product"))
  762. for machine_id in machine_id_list:
  763. definition_metadatas = ContainerRegistry.getInstance().findDefinitionContainersMetadata(id = machine_id)
  764. if not definition_metadatas:
  765. continue
  766. definition_metadata = definition_metadatas[0]
  767. machine_manufacturer = identifier.get("manufacturer", definition_metadata.get("manufacturer", "Unknown")) #If the XML material doesn't specify a manufacturer, use the one in the actual printer definition.
  768. # Always create the instance of the material even if it is not compatible, otherwise it will never
  769. # show as incompatible if the material profile doesn't define hotends in the machine - CURA-5444
  770. new_material_id = container_id + "_" + machine_id
  771. # Do not look for existing container/container metadata with the same ID although they may exist.
  772. # In project loading and perhaps some other places, we only want to get information (metadata)
  773. # from a file without changing the current state of the system. If we overwrite the existing
  774. # metadata here, deserializeMetadata() will not be safe for retrieving information.
  775. new_material_metadata = {}
  776. new_material_metadata.update(base_metadata)
  777. new_material_metadata["id"] = new_material_id
  778. new_material_metadata["compatible"] = machine_compatibility
  779. new_material_metadata["machine_manufacturer"] = machine_manufacturer
  780. new_material_metadata["definition"] = machine_id
  781. result_metadata.append(new_material_metadata)
  782. buildplates = machine.iterfind("./um:buildplate", cls.__namespaces)
  783. buildplate_map = {} # type: Dict[str, Dict[str, bool]]
  784. buildplate_map["buildplate_compatible"] = {}
  785. buildplate_map["buildplate_recommended"] = {}
  786. for buildplate in buildplates:
  787. buildplate_id = buildplate.get("id")
  788. if buildplate_id is None:
  789. continue
  790. variant_metadata = ContainerRegistry.getInstance().findInstanceContainersMetadata(id = buildplate_id)
  791. if not variant_metadata:
  792. # It is not really properly defined what "ID" is so also search for variants by name.
  793. variant_metadata = ContainerRegistry.getInstance().findInstanceContainersMetadata(definition = machine_id, name = buildplate_id)
  794. if not variant_metadata:
  795. continue
  796. settings = buildplate.iterfind("./um:setting", cls.__namespaces)
  797. buildplate_compatibility = True
  798. buildplate_recommended = True
  799. for entry in settings:
  800. key = entry.get("key")
  801. if entry.text is not None:
  802. if key == "hardware compatible":
  803. buildplate_compatibility = cls._parseCompatibleValue(entry.text)
  804. elif key == "hardware recommended":
  805. buildplate_recommended = cls._parseCompatibleValue(entry.text)
  806. buildplate_map["buildplate_compatible"][buildplate_id] = buildplate_compatibility
  807. buildplate_map["buildplate_recommended"][buildplate_id] = buildplate_recommended
  808. for hotend in machine.iterfind("./um:hotend", cls.__namespaces):
  809. hotend_name = hotend.get("id")
  810. if hotend_name is None:
  811. continue
  812. hotend_compatibility = machine_compatibility
  813. for entry in hotend.iterfind("./um:setting[@key='hardware compatible']", cls.__namespaces):
  814. if entry.text is not None:
  815. hotend_compatibility = cls._parseCompatibleValue(entry.text)
  816. new_hotend_specific_material_id = container_id + "_" + machine_id + "_" + hotend_name.replace(" ", "_")
  817. # Same as above, do not overwrite existing metadata.
  818. new_hotend_material_metadata = {}
  819. new_hotend_material_metadata.update(base_metadata)
  820. new_hotend_material_metadata["variant_name"] = hotend_name
  821. new_hotend_material_metadata["compatible"] = hotend_compatibility
  822. new_hotend_material_metadata["machine_manufacturer"] = machine_manufacturer
  823. new_hotend_material_metadata["id"] = new_hotend_specific_material_id
  824. new_hotend_material_metadata["definition"] = machine_id
  825. if buildplate_map["buildplate_compatible"]:
  826. new_hotend_material_metadata["buildplate_compatible"] = buildplate_map["buildplate_compatible"]
  827. new_hotend_material_metadata["buildplate_recommended"] = buildplate_map["buildplate_recommended"]
  828. result_metadata.append(new_hotend_material_metadata)
  829. #
  830. # Buildplates in Hotends
  831. #
  832. buildplates = hotend.iterfind("./um:buildplate", cls.__namespaces)
  833. for buildplate in buildplates:
  834. # The "id" field for buildplate in material profiles is actually name
  835. buildplate_name = buildplate.get("id")
  836. if buildplate_name is None:
  837. continue
  838. buildplate_mapped_settings, buildplate_unmapped_settings, buildplate_reserialize_settings = cls._getSettingsDictForNode(buildplate)
  839. buildplate_compatibility = buildplate_unmapped_settings.get("hardware compatible",
  840. buildplate_map["buildplate_compatible"])
  841. buildplate_recommended = buildplate_unmapped_settings.get("hardware recommended",
  842. buildplate_map["buildplate_recommended"])
  843. # Generate container ID for the hotend-and-buildplate-specific material container
  844. new_hotend_and_buildplate_specific_material_id = new_hotend_specific_material_id + "_" + buildplate_name.replace(
  845. " ", "_")
  846. new_hotend_and_buildplate_material_metadata = {}
  847. new_hotend_and_buildplate_material_metadata.update(new_hotend_material_metadata)
  848. new_hotend_and_buildplate_material_metadata["id"] = new_hotend_and_buildplate_specific_material_id
  849. new_hotend_and_buildplate_material_metadata["buildplate_name"] = buildplate_name
  850. new_hotend_and_buildplate_material_metadata["compatible"] = buildplate_compatibility
  851. new_hotend_and_buildplate_material_metadata["buildplate_compatible"] = buildplate_compatibility
  852. new_hotend_and_buildplate_material_metadata["buildplate_recommended"] = buildplate_recommended
  853. new_hotend_and_buildplate_material_metadata["reserialize_settings"] = buildplate_reserialize_settings
  854. result_metadata.append(new_hotend_and_buildplate_material_metadata)
  855. # there is only one ID for a machine. Once we have reached here, it means we have already found
  856. # a workable ID for that machine, so there is no need to continue
  857. break
  858. return result_metadata
  859. def _addSettingElement(self, builder, instance):
  860. key = instance.definition.key
  861. if key in self.__material_settings_setting_map.values():
  862. # Setting has a key in the standard namespace
  863. key = UM.Dictionary.findKey(self.__material_settings_setting_map, instance.definition.key)
  864. tag_name = "setting"
  865. if key == "processing temperature graph": #The Processing Temperature Graph has its own little structure that we need to implement separately.
  866. builder.start(tag_name, {"key": key})
  867. graph_str = str(instance.value)
  868. graph = graph_str.replace("[", "").replace("]", "").split(", ") #Crude parsing of this list: Flatten the list by removing all brackets, then split on ", ". Safe to eval attacks though!
  869. graph = [graph[i:i + 2] for i in range(0, len(graph) - 1, 2)] #Convert to 2D array.
  870. for point in graph:
  871. builder.start("point", {"flow": point[0], "temperature": point[1]})
  872. builder.end("point")
  873. builder.end(tag_name)
  874. return
  875. elif key not in self.__material_properties_setting_map.values() and key not in self.__material_metadata_setting_map.values():
  876. # Setting is not in the standard namespace, and not a material property (eg diameter) or metadata (eg GUID)
  877. tag_name = "cura:setting"
  878. else:
  879. # Skip material properties (eg diameter) or metadata (eg GUID)
  880. return
  881. truth_map = { True: "yes", False: "no" }
  882. if tag_name != "cura:setting" and instance.value in truth_map:
  883. data = truth_map[instance.value]
  884. else:
  885. data = str(instance.value)
  886. builder.start(tag_name, { "key": key })
  887. builder.data(data)
  888. builder.end(tag_name)
  889. @staticmethod
  890. def _profile_name(material_name, color_name):
  891. if material_name is None:
  892. return "Unknown Material"
  893. if color_name != "Generic":
  894. return "%s %s" % (color_name, material_name)
  895. else:
  896. return material_name
  897. @staticmethod
  898. def getPossibleDefinitionIDsFromName(name):
  899. name_parts = name.lower().split(" ")
  900. merged_name_parts = []
  901. for part in name_parts:
  902. if len(part) == 0:
  903. continue
  904. if len(merged_name_parts) == 0:
  905. merged_name_parts.append(part)
  906. continue
  907. if part.isdigit():
  908. # for names with digit(s) such as Ultimaker 3 Extended, we generate an ID like
  909. # "ultimaker3_extended", ignoring the space between "Ultimaker" and "3".
  910. merged_name_parts[-1] = merged_name_parts[-1] + part
  911. else:
  912. merged_name_parts.append(part)
  913. id_list = {name.lower().replace(" ", ""), # simply removing all spaces
  914. name.lower().replace(" ", "_"), # simply replacing all spaces with underscores
  915. "_".join(merged_name_parts),
  916. name.replace(" ", ""),
  917. name.replace(" ", "_")
  918. }
  919. id_list = list(id_list)
  920. return id_list
  921. @staticmethod
  922. def _parseCompatibleValue(value: str):
  923. """Parse the value of the "material compatible" property."""
  924. return value in {"yes", "unknown"}
  925. def __str__(self):
  926. """Small string representation for debugging."""
  927. return "<XmlMaterialProfile '{my_id}' ('{name}') from base file '{base_file}'>".format(my_id = self.getId(), name = self.getName(), base_file = self.getMetaDataEntry("base_file"))
  928. _metadata_tags_that_have_cura_namespace = {"pva_compatible", "breakaway_compatible"}
  929. # Map XML file setting names to internal names
  930. __material_settings_setting_map = {
  931. "print temperature": "default_material_print_temperature",
  932. "heated bed temperature": "default_material_bed_temperature",
  933. "standby temperature": "material_standby_temperature",
  934. "processing temperature graph": "material_flow_temp_graph",
  935. "print cooling": "cool_fan_speed",
  936. "retraction amount": "retraction_amount",
  937. "retraction speed": "retraction_speed",
  938. "adhesion tendency": "material_adhesion_tendency",
  939. "surface energy": "material_surface_energy",
  940. "build volume temperature": "build_volume_temperature",
  941. "anti ooze retract position": "material_anti_ooze_retracted_position",
  942. "anti ooze retract speed": "material_anti_ooze_retraction_speed",
  943. "break preparation position": "material_break_preparation_retracted_position",
  944. "break preparation speed": "material_break_preparation_speed",
  945. "break preparation temperature": "material_break_preparation_temperature",
  946. "break position": "material_break_retracted_position",
  947. "flush purge speed": "material_flush_purge_speed",
  948. "flush purge length": "material_flush_purge_length",
  949. "end of filament purge speed": "material_end_of_filament_purge_speed",
  950. "end of filament purge length": "material_end_of_filament_purge_length",
  951. "maximum park duration": "material_maximum_park_duration",
  952. "no load move factor": "material_no_load_move_factor",
  953. "break speed": "material_break_speed",
  954. "break temperature": "material_break_temperature"
  955. } # type: Dict[str, str]
  956. __unmapped_settings = [
  957. "hardware compatible",
  958. "hardware recommended"
  959. ]
  960. __keep_serialized_settings = { # Settings irrelevant to Cura, but that could be present in the files so we must store them and keep them serialized.
  961. "relative extrusion",
  962. "flow sensor detection margin",
  963. "different material purge volume",
  964. "same material purge volume",
  965. "end of print purge volume",
  966. "end of filament purge volume",
  967. "purge anti ooze retract position",
  968. "purge drop retract position",
  969. "purge retract speed",
  970. "purge unretract speed",
  971. "purge anti ooze dwell time",
  972. "purge drop dwell time",
  973. "dwell time before break preparation move",
  974. "pressure release dwell time",
  975. "tainted print core max temperature",
  976. "recommend cleaning after n prints",
  977. "maximum heated bed temperature",
  978. "material bed adhesion temperature",
  979. "maximum heated chamber temperature",
  980. "shrinkage percentage",
  981. "move to die distance",
  982. }
  983. __material_properties_setting_map = {
  984. "diameter": "material_diameter"
  985. }
  986. __material_metadata_setting_map = {
  987. "GUID": "material_guid",
  988. "material": "material_type",
  989. "brand": "material_brand",
  990. }
  991. # Map of recognised namespaces with a proper prefix.
  992. __namespaces = {
  993. "um": "http://www.ultimaker.com/material",
  994. "cura": "http://www.ultimaker.com/cura"
  995. }
  996. def _indent(elem, level = 0):
  997. """Helper function for pretty-printing XML because ETree is stupid"""
  998. i = "\n" + level * " "
  999. if len(elem):
  1000. if not elem.text or not elem.text.strip():
  1001. elem.text = i + " "
  1002. if not elem.tail or not elem.tail.strip():
  1003. elem.tail = i
  1004. for elem in elem:
  1005. _indent(elem, level + 1)
  1006. if not elem.tail or not elem.tail.strip():
  1007. elem.tail = i
  1008. else:
  1009. if level and (not elem.tail or not elem.tail.strip()):
  1010. elem.tail = i
  1011. # The namespace is prepended to the tag name but between {}.
  1012. # We are only interested in the actual tag name, so discard everything
  1013. # before the last }
  1014. def _tag_without_namespace(element):
  1015. return element.tag[element.tag.rfind("}") + 1:]