XmlMaterialProfile.py 57 KB

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