XmlMaterialProfile.py 57 KB

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