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