XmlMaterialProfile.py 47 KB

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