XmlMaterialProfile.py 57 KB

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