XmlMaterialProfile.py 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  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. name.replace(" ", ""),
  871. name.replace(" ", "_")
  872. }
  873. id_list = list(id_list)
  874. return id_list
  875. @classmethod
  876. def getProductIdMap(cls) -> Dict[str, List[str]]:
  877. """Gets a mapping from product names in the XML files to their definition IDs.
  878. This loads the mapping from a file.
  879. """
  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. @staticmethod
  889. def _parseCompatibleValue(value: str):
  890. """Parse the value of the "material compatible" property."""
  891. return value in {"yes", "unknown"}
  892. def __str__(self):
  893. """Small string representation for debugging."""
  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. "build volume temperature": "build_volume_temperature",
  908. "anti ooze retract position": "material_anti_ooze_retracted_position",
  909. "anti ooze retract speed": "material_anti_ooze_retraction_speed",
  910. "break preparation position": "material_break_preparation_retracted_position",
  911. "break preparation speed": "material_break_preparation_speed",
  912. "break preparation temperature": "material_break_preparation_temperature",
  913. "break position": "material_break_retracted_position",
  914. "flush purge speed": "material_flush_purge_speed",
  915. "flush purge length": "material_flush_purge_length",
  916. "end of filament purge speed": "material_end_of_filament_purge_speed",
  917. "end of filament purge length": "material_end_of_filament_purge_length",
  918. "maximum park duration": "material_maximum_park_duration",
  919. "no load move factor": "material_no_load_move_factor",
  920. "break speed": "material_break_speed",
  921. "break temperature": "material_break_temperature"
  922. } # type: Dict[str, str]
  923. __unmapped_settings = [
  924. "hardware compatible",
  925. "hardware recommended"
  926. ]
  927. __material_properties_setting_map = {
  928. "diameter": "material_diameter"
  929. }
  930. __material_metadata_setting_map = {
  931. "GUID": "material_guid"
  932. }
  933. # Map of recognised namespaces with a proper prefix.
  934. __namespaces = {
  935. "um": "http://www.ultimaker.com/material",
  936. "cura": "http://www.ultimaker.com/cura"
  937. }
  938. def _indent(elem, level = 0):
  939. """Helper function for pretty-printing XML because ETree is stupid"""
  940. i = "\n" + level * " "
  941. if len(elem):
  942. if not elem.text or not elem.text.strip():
  943. elem.text = i + " "
  944. if not elem.tail or not elem.tail.strip():
  945. elem.tail = i
  946. for elem in elem:
  947. _indent(elem, level + 1)
  948. if not elem.tail or not elem.tail.strip():
  949. elem.tail = i
  950. else:
  951. if level and (not elem.tail or not elem.tail.strip()):
  952. elem.tail = i
  953. # The namespace is prepended to the tag name but between {}.
  954. # We are only interested in the actual tag name, so discard everything
  955. # before the last }
  956. def _tag_without_namespace(element):
  957. return element.tag[element.tag.rfind("}") + 1:]