XmlMaterialProfile.py 51 KB

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