XmlMaterialProfile.py 57 KB

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