XmlMaterialProfile.py 57 KB

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