XmlMaterialProfile.py 49 KB

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