XmlMaterialProfile.py 61 KB

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