XmlMaterialProfile.py 43 KB

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