XmlMaterialProfile.py 50 KB

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