XmlMaterialProfile.py 62 KB

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