XmlMaterialProfile.py 55 KB

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