XmlMaterialProfile.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  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. definition = definitions[0]
  446. 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.
  447. if machine_compatibility:
  448. new_material_id = self.getId() + "_" + machine_id
  449. # The child or derived material container may already exist. This can happen when a material in a
  450. # project file and the a material in Cura have the same ID.
  451. # In the case if a derived material already exists, override that material container because if
  452. # the data in the parent material has been changed, the derived ones should be updated too.
  453. if ContainerRegistry.getInstance().isLoaded(new_material_id):
  454. new_material = ContainerRegistry.getInstance().findContainers(id = new_material_id)[0]
  455. is_new_material = False
  456. else:
  457. new_material = XmlMaterialProfile(new_material_id)
  458. is_new_material = True
  459. new_material.setMetaData(copy.deepcopy(self.getMetaData()))
  460. new_material.getMetaData()["id"] = new_material_id
  461. new_material.getMetaData()["name"] = self.getName()
  462. new_material.setDefinition(machine_id)
  463. # Don't use setMetadata, as that overrides it for all materials with same base file
  464. new_material.getMetaData()["compatible"] = machine_compatibility
  465. new_material.getMetaData()["machine_manufacturer"] = machine_manufacturer
  466. new_material.getMetaData()["definition"] = machine_id
  467. new_material.setCachedValues(cached_machine_setting_properties)
  468. new_material._dirty = False
  469. if is_new_material:
  470. containers_to_add.append(new_material)
  471. # Find the buildplates compatibility
  472. buildplates = machine.iterfind("./um:buildplate", self.__namespaces)
  473. buildplate_map = {}
  474. buildplate_map["buildplate_compatible"] = {}
  475. buildplate_map["buildplate_recommended"] = {}
  476. for buildplate in buildplates:
  477. buildplate_id = buildplate.get("id")
  478. if buildplate_id is None:
  479. continue
  480. variant_containers = ContainerRegistry.getInstance().findInstanceContainersMetadata(
  481. id = buildplate_id)
  482. if not variant_containers:
  483. # It is not really properly defined what "ID" is so also search for variants by name.
  484. variant_containers = ContainerRegistry.getInstance().findInstanceContainersMetadata(
  485. definition = machine_id, name = buildplate_id)
  486. if not variant_containers:
  487. continue
  488. buildplate_compatibility = machine_compatibility
  489. buildplate_recommended = machine_compatibility
  490. settings = buildplate.iterfind("./um:setting", self.__namespaces)
  491. for entry in settings:
  492. key = entry.get("key")
  493. if key in self.__unmapped_settings:
  494. if key == "hardware compatible":
  495. buildplate_compatibility = self._parseCompatibleValue(entry.text)
  496. elif key == "hardware recommended":
  497. buildplate_recommended = self._parseCompatibleValue(entry.text)
  498. else:
  499. Logger.log("d", "Unsupported material setting %s", key)
  500. buildplate_map["buildplate_compatible"][buildplate_id] = buildplate_compatibility
  501. buildplate_map["buildplate_recommended"][buildplate_id] = buildplate_recommended
  502. hotends = machine.iterfind("./um:hotend", self.__namespaces)
  503. for hotend in hotends:
  504. hotend_id = hotend.get("id")
  505. if hotend_id is None:
  506. continue
  507. variant_containers = ContainerRegistry.getInstance().findInstanceContainersMetadata(id = hotend_id)
  508. if not variant_containers:
  509. # It is not really properly defined what "ID" is so also search for variants by name.
  510. variant_containers = ContainerRegistry.getInstance().findInstanceContainersMetadata(definition = machine_id, name = hotend_id)
  511. if not variant_containers:
  512. continue
  513. hotend_compatibility = machine_compatibility
  514. hotend_setting_values = {}
  515. settings = hotend.iterfind("./um:setting", self.__namespaces)
  516. for entry in settings:
  517. key = entry.get("key")
  518. if key in self.__material_settings_setting_map:
  519. hotend_setting_values[self.__material_settings_setting_map[key]] = entry.text
  520. elif key in self.__unmapped_settings:
  521. if key == "hardware compatible":
  522. hotend_compatibility = self._parseCompatibleValue(entry.text)
  523. else:
  524. Logger.log("d", "Unsupported material setting %s", key)
  525. new_hotend_id = self.getId() + "_" + machine_id + "_" + hotend_id.replace(" ", "_")
  526. # Same as machine compatibility, keep the derived material containers consistent with the parent material
  527. if ContainerRegistry.getInstance().isLoaded(new_hotend_id):
  528. new_hotend_material = ContainerRegistry.getInstance().findContainers(id = new_hotend_id)[0]
  529. is_new_material = False
  530. else:
  531. new_hotend_material = XmlMaterialProfile(new_hotend_id)
  532. is_new_material = True
  533. new_hotend_material.setMetaData(copy.deepcopy(self.getMetaData()))
  534. new_hotend_material.getMetaData()["id"] = new_hotend_id
  535. new_hotend_material.getMetaData()["name"] = self.getName()
  536. new_hotend_material.getMetaData()["variant"] = variant_containers[0]["id"]
  537. new_hotend_material.setDefinition(machine_id)
  538. # Don't use setMetadata, as that overrides it for all materials with same base file
  539. new_hotend_material.getMetaData()["compatible"] = hotend_compatibility
  540. new_hotend_material.getMetaData()["machine_manufacturer"] = machine_manufacturer
  541. new_hotend_material.getMetaData()["definition"] = machine_id
  542. if buildplate_map["buildplate_compatible"]:
  543. new_hotend_material.getMetaData()["buildplate_compatible"] = buildplate_map["buildplate_compatible"]
  544. new_hotend_material.getMetaData()["buildplate_recommended"] = buildplate_map["buildplate_recommended"]
  545. cached_hotend_setting_properties = cached_machine_setting_properties.copy()
  546. cached_hotend_setting_properties.update(hotend_setting_values)
  547. new_hotend_material.setCachedValues(cached_hotend_setting_properties)
  548. new_hotend_material._dirty = False
  549. if is_new_material:
  550. containers_to_add.append(new_hotend_material)
  551. # there is only one ID for a machine. Once we have reached here, it means we have already found
  552. # a workable ID for that machine, so there is no need to continue
  553. break
  554. for container_to_add in containers_to_add:
  555. ContainerRegistry.getInstance().addContainer(container_to_add)
  556. @classmethod
  557. def deserializeMetadata(cls, serialized: str, container_id: str) -> List[Dict[str, Any]]:
  558. result_metadata = [] #All the metadata that we found except the base (because the base is returned).
  559. #Update the serialized data to the latest version.
  560. serialized = cls._updateSerialized(serialized)
  561. base_metadata = {
  562. "type": "material",
  563. "status": "unknown", #TODO: Add material verification.
  564. "container_type": XmlMaterialProfile,
  565. "id": container_id,
  566. "base_file": container_id
  567. }
  568. try:
  569. data = ET.fromstring(serialized)
  570. except:
  571. Logger.logException("e", "An exception occurred while parsing the material profile")
  572. return []
  573. #TODO: Implement the <inherits> tag. It's unused at the moment though.
  574. if "version" in data.attrib:
  575. base_metadata["setting_version"] = cls.xmlVersionToSettingVersion(data.attrib["version"])
  576. else:
  577. base_metadata["setting_version"] = cls.xmlVersionToSettingVersion("1.2") #1.2 and lower didn't have that version number there yet.
  578. for entry in data.iterfind("./um:metadata/*", cls.__namespaces):
  579. tag_name = _tag_without_namespace(entry)
  580. if tag_name == "name":
  581. brand = entry.find("./um:brand", cls.__namespaces)
  582. material = entry.find("./um:material", cls.__namespaces)
  583. color = entry.find("./um:color", cls.__namespaces)
  584. label = entry.find("./um:label", cls.__namespaces)
  585. if label is not None:
  586. base_metadata["name"] = label.text
  587. else:
  588. base_metadata["name"] = cls._profile_name(material.text, color.text)
  589. base_metadata["brand"] = brand.text
  590. base_metadata["material"] = material.text
  591. base_metadata["color_name"] = color.text
  592. continue
  593. #Setting_version is derived from the "version" tag in the schema earlier, so don't set it here.
  594. if tag_name == "setting_version":
  595. continue
  596. base_metadata[tag_name] = entry.text
  597. if "description" not in base_metadata:
  598. base_metadata["description"] = ""
  599. if "adhesion_info" not in base_metadata:
  600. base_metadata["adhesion_info"] = ""
  601. property_values = {}
  602. properties = data.iterfind("./um:properties/*", cls.__namespaces)
  603. for entry in properties:
  604. tag_name = _tag_without_namespace(entry)
  605. property_values[tag_name] = entry.text
  606. base_metadata["approximate_diameter"] = str(round(float(property_values.get("diameter", 2.85)))) # In mm
  607. base_metadata["properties"] = property_values
  608. base_metadata["definition"] = "fdmprinter"
  609. compatible_entries = data.iterfind("./um:settings/um:setting[@key='hardware compatible']", cls.__namespaces)
  610. try:
  611. common_compatibility = cls._parseCompatibleValue(next(compatible_entries).text)
  612. except StopIteration: #No 'hardware compatible' setting.
  613. common_compatibility = True
  614. base_metadata["compatible"] = common_compatibility
  615. result_metadata.append(base_metadata)
  616. # Map machine human-readable names to IDs
  617. product_id_map = cls.getProductIdMap()
  618. for machine in data.iterfind("./um:settings/um:machine", cls.__namespaces):
  619. machine_compatibility = common_compatibility
  620. for entry in machine.iterfind("./um:setting", cls.__namespaces):
  621. key = entry.get("key")
  622. if key == "hardware compatible":
  623. machine_compatibility = cls._parseCompatibleValue(entry.text)
  624. for identifier in machine.iterfind("./um:machine_identifier", cls.__namespaces):
  625. machine_id_list = product_id_map.get(identifier.get("product"), [])
  626. if not machine_id_list:
  627. machine_id_list = cls.getPossibleDefinitionIDsFromName(identifier.get("product"))
  628. for machine_id in machine_id_list:
  629. definition_metadata = ContainerRegistry.getInstance().findDefinitionContainersMetadata(id = machine_id)
  630. if not definition_metadata:
  631. Logger.log("w", "No definition found for machine ID %s", machine_id)
  632. continue
  633. definition_metadata = definition_metadata[0]
  634. 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.
  635. if machine_compatibility:
  636. new_material_id = container_id + "_" + machine_id
  637. # The child or derived material container may already exist. This can happen when a material in a
  638. # project file and the a material in Cura have the same ID.
  639. # In the case if a derived material already exists, override that material container because if
  640. # the data in the parent material has been changed, the derived ones should be updated too.
  641. found_materials = ContainerRegistry.getInstance().findInstanceContainersMetadata(id = new_material_id)
  642. if found_materials:
  643. new_material_metadata = found_materials[0]
  644. else:
  645. new_material_metadata = {}
  646. new_material_metadata.update(base_metadata)
  647. new_material_metadata["id"] = new_material_id
  648. new_material_metadata["compatible"] = machine_compatibility
  649. new_material_metadata["machine_manufacturer"] = machine_manufacturer
  650. new_material_metadata["definition"] = machine_id
  651. if len(found_materials) == 0: #This is a new material.
  652. result_metadata.append(new_material_metadata)
  653. buildplates = machine.iterfind("./um:buildplate", cls.__namespaces)
  654. buildplate_map = {}
  655. buildplate_map["buildplate_compatible"] = {}
  656. buildplate_map["buildplate_recommended"] = {}
  657. for buildplate in buildplates:
  658. buildplate_id = buildplate.get("id")
  659. if buildplate_id is None:
  660. continue
  661. variant_containers = ContainerRegistry.getInstance().findInstanceContainersMetadata(id = buildplate_id)
  662. if not variant_containers:
  663. # It is not really properly defined what "ID" is so also search for variants by name.
  664. variant_containers = ContainerRegistry.getInstance().findInstanceContainersMetadata(definition = machine_id, name = buildplate_id)
  665. if not variant_containers:
  666. continue
  667. settings = buildplate.iterfind("./um:setting", cls.__namespaces)
  668. for entry in settings:
  669. key = entry.get("key")
  670. if key == "hardware compatible":
  671. buildplate_compatibility = cls._parseCompatibleValue(entry.text)
  672. elif key == "hardware recommended":
  673. buildplate_recommended = cls._parseCompatibleValue(entry.text)
  674. buildplate_map["buildplate_compatible"][buildplate_id] = buildplate_map["buildplate_compatible"]
  675. buildplate_map["buildplate_recommended"][buildplate_id] = buildplate_map["buildplate_recommended"]
  676. for hotend in machine.iterfind("./um:hotend", cls.__namespaces):
  677. hotend_id = hotend.get("id")
  678. if hotend_id is None:
  679. continue
  680. variant_containers = ContainerRegistry.getInstance().findInstanceContainersMetadata(id = hotend_id)
  681. if not variant_containers:
  682. # It is not really properly defined what "ID" is so also search for variants by name.
  683. variant_containers = ContainerRegistry.getInstance().findInstanceContainersMetadata(definition = machine_id, name = hotend_id)
  684. hotend_compatibility = machine_compatibility
  685. for entry in hotend.iterfind("./um:setting", cls.__namespaces):
  686. key = entry.get("key")
  687. if key == "hardware compatible":
  688. hotend_compatibility = cls._parseCompatibleValue(entry.text)
  689. new_hotend_id = container_id + "_" + machine_id + "_" + hotend_id.replace(" ", "_")
  690. # Same as machine compatibility, keep the derived material containers consistent with the parent material
  691. found_materials = ContainerRegistry.getInstance().findInstanceContainersMetadata(id = new_hotend_id)
  692. if found_materials:
  693. new_hotend_material_metadata = found_materials[0]
  694. else:
  695. new_hotend_material_metadata = {}
  696. new_hotend_material_metadata.update(base_metadata)
  697. if variant_containers:
  698. new_hotend_material_metadata["variant"] = variant_containers[0]["id"]
  699. else:
  700. new_hotend_material_metadata["variant"] = hotend_id
  701. _with_missing_variants.append(new_hotend_material_metadata)
  702. new_hotend_material_metadata["compatible"] = hotend_compatibility
  703. new_hotend_material_metadata["machine_manufacturer"] = machine_manufacturer
  704. new_hotend_material_metadata["id"] = new_hotend_id
  705. new_hotend_material_metadata["definition"] = machine_id
  706. if buildplate_map["buildplate_compatible"]:
  707. new_hotend_material_metadata["buildplate_compatible"] = buildplate_map["buildplate_compatible"]
  708. new_hotend_material_metadata["buildplate_recommended"] = buildplate_map["buildplate_recommended"]
  709. if len(found_materials) == 0:
  710. result_metadata.append(new_hotend_material_metadata)
  711. # there is only one ID for a machine. Once we have reached here, it means we have already found
  712. # a workable ID for that machine, so there is no need to continue
  713. break
  714. return result_metadata
  715. def _addSettingElement(self, builder, instance):
  716. try:
  717. key = UM.Dictionary.findKey(self.__material_settings_setting_map, instance.definition.key)
  718. except ValueError:
  719. return
  720. builder.start("setting", { "key": key })
  721. builder.data(str(instance.value))
  722. builder.end("setting")
  723. @classmethod
  724. def _profile_name(cls, material_name, color_name):
  725. if color_name != "Generic":
  726. return "%s %s" % (color_name, material_name)
  727. else:
  728. return material_name
  729. @classmethod
  730. def getPossibleDefinitionIDsFromName(cls, name):
  731. name_parts = name.lower().split(" ")
  732. merged_name_parts = []
  733. for part in name_parts:
  734. if len(part) == 0:
  735. continue
  736. if len(merged_name_parts) == 0:
  737. merged_name_parts.append(part)
  738. continue
  739. if part.isdigit():
  740. # for names with digit(s) such as Ultimaker 3 Extended, we generate an ID like
  741. # "ultimaker3_extended", ignoring the space between "Ultimaker" and "3".
  742. merged_name_parts[-1] = merged_name_parts[-1] + part
  743. else:
  744. merged_name_parts.append(part)
  745. id_list = [name.lower().replace(" ", ""), # simply removing all spaces
  746. name.lower().replace(" ", "_"), # simply replacing all spaces with underscores
  747. "_".join(merged_name_parts),
  748. ]
  749. return id_list
  750. ## Gets a mapping from product names in the XML files to their definition
  751. # IDs.
  752. #
  753. # This loads the mapping from a file.
  754. @classmethod
  755. def getProductIdMap(cls) -> Dict[str, List[str]]:
  756. product_to_id_file = os.path.join(os.path.dirname(sys.modules[cls.__module__].__file__), "product_to_id.json")
  757. with open(product_to_id_file) as f:
  758. product_to_id_map = json.load(f)
  759. product_to_id_map = {key: [value] for key, value in product_to_id_map.items()}
  760. return product_to_id_map
  761. ## Parse the value of the "material compatible" property.
  762. @classmethod
  763. def _parseCompatibleValue(cls, value: str):
  764. return value in {"yes", "unknown"}
  765. ## Small string representation for debugging.
  766. def __str__(self):
  767. return "<XmlMaterialProfile '{my_id}' ('{name}') from base file '{base_file}'>".format(my_id = self.getId(), name = self.getName(), base_file = self.getMetaDataEntry("base_file"))
  768. # Map XML file setting names to internal names
  769. __material_settings_setting_map = {
  770. "print temperature": "default_material_print_temperature",
  771. "heated bed temperature": "default_material_bed_temperature",
  772. "standby temperature": "material_standby_temperature",
  773. "processing temperature graph": "material_flow_temp_graph",
  774. "print cooling": "cool_fan_speed",
  775. "retraction amount": "retraction_amount",
  776. "retraction speed": "retraction_speed",
  777. "adhesion tendency": "material_adhesion_tendency",
  778. "surface energy": "material_surface_energy"
  779. }
  780. __unmapped_settings = [
  781. "hardware compatible",
  782. "hardware recommended"
  783. ]
  784. __material_properties_setting_map = {
  785. "diameter": "material_diameter"
  786. }
  787. __material_metadata_setting_map = {
  788. "GUID": "material_guid"
  789. }
  790. # Map of recognised namespaces with a proper prefix.
  791. __namespaces = {
  792. "um": "http://www.ultimaker.com/material"
  793. }
  794. ## Helper function for pretty-printing XML because ETree is stupid
  795. def _indent(elem, level = 0):
  796. i = "\n" + level * " "
  797. if len(elem):
  798. if not elem.text or not elem.text.strip():
  799. elem.text = i + " "
  800. if not elem.tail or not elem.tail.strip():
  801. elem.tail = i
  802. for elem in elem:
  803. _indent(elem, level + 1)
  804. if not elem.tail or not elem.tail.strip():
  805. elem.tail = i
  806. else:
  807. if level and (not elem.tail or not elem.tail.strip()):
  808. elem.tail = i
  809. # The namespace is prepended to the tag name but between {}.
  810. # We are only interested in the actual tag name, so discard everything
  811. # before the last }
  812. def _tag_without_namespace(element):
  813. return element.tag[element.tag.rfind("}") + 1:]
  814. #While loading XML profiles, some of these profiles don't know what variant
  815. #they belong to. We'd like to search by the machine ID and the variant's
  816. #name, but we don't know the variant's ID. Not all variants have been loaded
  817. #yet so we can't run a filter on the name and machine. The ID is unknown
  818. #so we can't lazily load the variant either. So we have to wait until all
  819. #the rest is loaded properly and then assign the correct variant to the
  820. #material files that were missing it.
  821. _with_missing_variants = []
  822. def _fillMissingVariants():
  823. registry = ContainerRegistry.getInstance()
  824. for variant_metadata in _with_missing_variants:
  825. variants = registry.findContainersMetadata(definition = variant_metadata["definition"], name = variant_metadata["variant"])
  826. if not variants:
  827. Logger.log("w", "Could not find variant for variant-specific material {material_id}.".format(material_id = variant_metadata["id"]))
  828. continue
  829. variant_metadata["variant"] = variants[0]["id"]
  830. ContainerRegistry.allMetadataLoaded.connect(_fillMissingVariants)