XmlMaterialProfile.py 48 KB

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