XmlMaterialProfile.py 63 KB

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