XmlMaterialProfile.py 57 KB

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