XmlMaterialProfile.py 46 KB

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