XmlMaterialProfile.py 50 KB

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