XmlMaterialProfile.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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. from typing import List, Optional
  6. import xml.etree.ElementTree as ET
  7. from UM.Resources import Resources
  8. from UM.Logger import Logger
  9. from cura.CuraApplication import CuraApplication
  10. import UM.Dictionary
  11. from UM.Settings.InstanceContainer import InstanceContainer
  12. from UM.Settings.ContainerRegistry import ContainerRegistry
  13. ## Handles serializing and deserializing material containers from an XML file
  14. class XmlMaterialProfile(InstanceContainer):
  15. CurrentFdmMaterialVersion = "1.3"
  16. Version = 1
  17. def __init__(self, container_id, *args, **kwargs):
  18. super().__init__(container_id, *args, **kwargs)
  19. self._inherited_files = []
  20. ## Translates the version number in the XML files to the setting_version
  21. # metadata entry.
  22. #
  23. # Since the two may increment independently we need a way to say which
  24. # versions of the XML specification are compatible with our setting data
  25. # version numbers.
  26. #
  27. # \param xml_version: The version number found in an XML file.
  28. # \return The corresponding setting_version.
  29. @classmethod
  30. def xmlVersionToSettingVersion(cls, xml_version: str) -> int:
  31. if xml_version == "1.3":
  32. return CuraApplication.SettingVersion
  33. return 0 #Older than 1.3.
  34. def getInheritedFiles(self):
  35. return self._inherited_files
  36. ## Overridden from InstanceContainer
  37. def setReadOnly(self, read_only):
  38. super().setReadOnly(read_only)
  39. basefile = self.getMetaDataEntry("base_file", self._id) # if basefile is self.id, this is a basefile.
  40. for container in ContainerRegistry.getInstance().findInstanceContainers(base_file = basefile):
  41. container._read_only = read_only # prevent loop instead of calling setReadOnly
  42. ## Overridden from InstanceContainer
  43. # set the meta data for all machine / variant combinations
  44. def setMetaDataEntry(self, key, value):
  45. if self.isReadOnly():
  46. return
  47. super().setMetaDataEntry(key, value)
  48. basefile = self.getMetaDataEntry("base_file", self._id) #if basefile is self.id, this is a basefile.
  49. # Update all containers that share basefile
  50. for container in ContainerRegistry.getInstance().findInstanceContainers(base_file = basefile):
  51. if container.getMetaDataEntry(key, None) != value: # Prevent recursion
  52. container.setMetaDataEntry(key, value)
  53. ## Overridden from InstanceContainer, similar to setMetaDataEntry.
  54. # without this function the setName would only set the name of the specific nozzle / material / machine combination container
  55. # The function is a bit tricky. It will not set the name of all containers if it has the correct name itself.
  56. def setName(self, new_name):
  57. if self.isReadOnly():
  58. return
  59. # Not only is this faster, it also prevents a major loop that causes a stack overflow.
  60. if self.getName() == new_name:
  61. return
  62. super().setName(new_name)
  63. basefile = self.getMetaDataEntry("base_file", self._id) # if basefile is self.id, this is a basefile.
  64. # Update the basefile as well, this is actually what we're trying to do
  65. # Update all containers that share GUID and basefile
  66. containers = ContainerRegistry.getInstance().findInstanceContainers(base_file = basefile)
  67. for container in containers:
  68. container.setName(new_name)
  69. ## Overridden from InstanceContainer, to set dirty to base file as well.
  70. def setDirty(self, dirty):
  71. super().setDirty(dirty)
  72. base_file = self.getMetaDataEntry("base_file", None)
  73. if base_file is not None and base_file != self._id:
  74. containers = ContainerRegistry.getInstance().findContainers(id=base_file)
  75. if containers:
  76. base_container = containers[0]
  77. if not base_container.isReadOnly():
  78. base_container.setDirty(dirty)
  79. ## Overridden from InstanceContainer
  80. # def setProperty(self, key, property_name, property_value, container = None):
  81. # if self.isReadOnly():
  82. # return
  83. #
  84. # super().setProperty(key, property_name, property_value)
  85. #
  86. # basefile = self.getMetaDataEntry("base_file", self._id) #if basefile is self.id, this is a basefile.
  87. # for container in UM.Settings.ContainerRegistry.ContainerRegistry.getInstance().findInstanceContainers(base_file = basefile):
  88. # if not container.isReadOnly():
  89. # container.setDirty(True)
  90. ## Overridden from InstanceContainer
  91. # base file: common settings + supported machines
  92. # machine / variant combination: only changes for itself.
  93. def serialize(self, ignored_metadata_keys: Optional[List] = None):
  94. registry = ContainerRegistry.getInstance()
  95. base_file = self.getMetaDataEntry("base_file", "")
  96. if base_file and self.id != base_file:
  97. # Since we create an instance of XmlMaterialProfile for each machine and nozzle in the profile,
  98. # we should only serialize the "base" material definition, since that can then take care of
  99. # serializing the machine/nozzle specific profiles.
  100. raise NotImplementedError("Ignoring serializing non-root XML materials, the data is contained in the base material")
  101. builder = ET.TreeBuilder()
  102. root = builder.start("fdmmaterial",
  103. {"xmlns": "http://www.ultimaker.com/material",
  104. "version": self.CurrentFdmMaterialVersion})
  105. ## Begin Metadata Block
  106. builder.start("metadata")
  107. metadata = copy.deepcopy(self.getMetaData())
  108. # setting_version is derived from the "version" tag in the schema, so don't serialize it into a file
  109. if ignored_metadata_keys is None:
  110. ignored_metadata_keys = []
  111. ignored_metadata_keys = ignored_metadata_keys + ["setting_version"]
  112. # remove the keys that we want to ignore in the metadata
  113. for key in ignored_metadata_keys:
  114. if key in metadata:
  115. del metadata[key]
  116. properties = metadata.pop("properties", {})
  117. # Metadata properties that should not be serialized.
  118. metadata.pop("status", "")
  119. metadata.pop("variant", "")
  120. metadata.pop("type", "")
  121. metadata.pop("base_file", "")
  122. metadata.pop("approximate_diameter", "")
  123. ## Begin Name Block
  124. builder.start("name")
  125. builder.start("brand")
  126. builder.data(metadata.pop("brand", ""))
  127. builder.end("brand")
  128. builder.start("material")
  129. builder.data(metadata.pop("material", ""))
  130. builder.end("material")
  131. builder.start("color")
  132. builder.data(metadata.pop("color_name", ""))
  133. builder.end("color")
  134. builder.start("label")
  135. builder.data(self._name)
  136. builder.end("label")
  137. builder.end("name")
  138. ## End Name Block
  139. for key, value in metadata.items():
  140. builder.start(key)
  141. if value is not None: #Nones get handled well by the builder.
  142. #Otherwise the builder always expects a string.
  143. #Deserialize expects the stringified version.
  144. value = str(value)
  145. builder.data(value)
  146. builder.end(key)
  147. builder.end("metadata")
  148. ## End Metadata Block
  149. ## Begin Properties Block
  150. builder.start("properties")
  151. for key, value in properties.items():
  152. builder.start(key)
  153. builder.data(value)
  154. builder.end(key)
  155. builder.end("properties")
  156. ## End Properties Block
  157. ## Begin Settings Block
  158. builder.start("settings")
  159. if self.getDefinition().id == "fdmprinter":
  160. for instance in self.findInstances():
  161. self._addSettingElement(builder, instance)
  162. machine_container_map = {}
  163. machine_nozzle_map = {}
  164. all_containers = registry.findInstanceContainers(GUID = self.getMetaDataEntry("GUID"), base_file = self._id)
  165. for container in all_containers:
  166. definition_id = container.getDefinition().id
  167. if definition_id == "fdmprinter":
  168. continue
  169. if definition_id not in machine_container_map:
  170. machine_container_map[definition_id] = container
  171. if definition_id not in machine_nozzle_map:
  172. machine_nozzle_map[definition_id] = {}
  173. variant = container.getMetaDataEntry("variant")
  174. if variant:
  175. machine_nozzle_map[definition_id][variant] = container
  176. continue
  177. machine_container_map[definition_id] = container
  178. # Map machine human-readable names to IDs
  179. product_id_map = {}
  180. for container in registry.findDefinitionContainers(type = "machine"):
  181. product_id_map[container.getName()] = container.getId()
  182. for definition_id, container in machine_container_map.items():
  183. definition = container.getDefinition()
  184. try:
  185. product = UM.Dictionary.findKey(product_id_map, definition_id)
  186. except ValueError:
  187. # An unknown product id; export it anyway
  188. product = definition_id
  189. builder.start("machine")
  190. builder.start("machine_identifier", {
  191. "manufacturer": container.getMetaDataEntry("machine_manufacturer", definition.getMetaDataEntry("manufacturer", "Unknown")),
  192. "product": product
  193. })
  194. builder.end("machine_identifier")
  195. for instance in container.findInstances():
  196. if self.getDefinition().id == "fdmprinter" and self.getInstance(instance.definition.key) and self.getProperty(instance.definition.key, "value") == instance.value:
  197. # If the settings match that of the base profile, just skip since we inherit the base profile.
  198. continue
  199. self._addSettingElement(builder, instance)
  200. # Find all hotend sub-profiles corresponding to this material and machine and add them to this profile.
  201. for hotend_id, hotend in machine_nozzle_map[definition_id].items():
  202. variant_containers = registry.findInstanceContainers(id = hotend.getMetaDataEntry("variant"))
  203. if not variant_containers:
  204. continue
  205. builder.start("hotend", {"id": variant_containers[0].getName()})
  206. # Compatible is a special case, as it's added as a meta data entry (instead of an instance).
  207. compatible = hotend.getMetaDataEntry("compatible")
  208. if compatible is not None:
  209. builder.start("setting", {"key": "hardware compatible"})
  210. if compatible:
  211. builder.data("yes")
  212. else:
  213. builder.data("no")
  214. builder.end("setting")
  215. for instance in hotend.findInstances():
  216. if container.getInstance(instance.definition.key) and container.getProperty(instance.definition.key, "value") == instance.value:
  217. # If the settings match that of the machine profile, just skip since we inherit the machine profile.
  218. continue
  219. self._addSettingElement(builder, instance)
  220. builder.end("hotend")
  221. builder.end("machine")
  222. builder.end("settings")
  223. ## End Settings Block
  224. builder.end("fdmmaterial")
  225. root = builder.close()
  226. _indent(root)
  227. stream = io.BytesIO()
  228. tree = ET.ElementTree(root)
  229. # this makes sure that the XML header states encoding="utf-8"
  230. tree.write(stream, encoding="utf-8", xml_declaration=True)
  231. return stream.getvalue().decode('utf-8')
  232. # Recursively resolve loading inherited files
  233. def _resolveInheritance(self, file_name):
  234. xml = self._loadFile(file_name)
  235. inherits = xml.find("./um:inherits", self.__namespaces)
  236. if inherits is not None:
  237. inherited = self._resolveInheritance(inherits.text)
  238. xml = self._mergeXML(inherited, xml)
  239. return xml
  240. def _loadFile(self, file_name):
  241. path = Resources.getPath(CuraApplication.getInstance().ResourceTypes.MaterialInstanceContainer, file_name + ".xml.fdm_material")
  242. with open(path, encoding="utf-8") as f:
  243. contents = f.read()
  244. self._inherited_files.append(path)
  245. return ET.fromstring(contents)
  246. # The XML material profile can have specific settings for machines.
  247. # Some machines share profiles, so they are only created once.
  248. # This function duplicates those elements so that each machine tag only has one identifier.
  249. def _expandMachinesXML(self, element):
  250. settings_element = element.find("./um:settings", self.__namespaces)
  251. machines = settings_element.iterfind("./um:machine", self.__namespaces)
  252. machines_to_add = []
  253. machines_to_remove = []
  254. for machine in machines:
  255. identifiers = list(machine.iterfind("./um:machine_identifier", self.__namespaces))
  256. has_multiple_identifiers = len(identifiers) > 1
  257. if has_multiple_identifiers:
  258. # Multiple identifiers found. We need to create a new machine element and copy all it's settings there.
  259. for identifier in identifiers:
  260. new_machine = copy.deepcopy(machine)
  261. # Create list of identifiers that need to be removed from the copied element.
  262. other_identifiers = [self._createKey(other_identifier) for other_identifier in identifiers if other_identifier is not identifier]
  263. # As we can only remove by exact object reference, we need to look through the identifiers of copied machine.
  264. new_machine_identifiers = list(new_machine.iterfind("./um:machine_identifier", self.__namespaces))
  265. for new_machine_identifier in new_machine_identifiers:
  266. key = self._createKey(new_machine_identifier)
  267. # Key was in identifiers to remove, so this element needs to be purged
  268. if key in other_identifiers:
  269. new_machine.remove(new_machine_identifier)
  270. machines_to_add.append(new_machine)
  271. machines_to_remove.append(machine)
  272. else:
  273. pass # Machine only has one identifier. Nothing to do.
  274. # Remove & add all required machines.
  275. for machine_to_remove in machines_to_remove:
  276. settings_element.remove(machine_to_remove)
  277. for machine_to_add in machines_to_add:
  278. settings_element.append(machine_to_add)
  279. return element
  280. def _mergeXML(self, first, second):
  281. result = copy.deepcopy(first)
  282. self._combineElement(self._expandMachinesXML(result), self._expandMachinesXML(second))
  283. return result
  284. def _createKey(self, element):
  285. key = element.tag.split("}")[-1]
  286. if "key" in element.attrib:
  287. key += " key:" + element.attrib["key"]
  288. if "manufacturer" in element.attrib:
  289. key += " manufacturer:" + element.attrib["manufacturer"]
  290. if "product" in element.attrib:
  291. key += " product:" + element.attrib["product"]
  292. if key == "machine":
  293. for item in element:
  294. if "machine_identifier" in item.tag:
  295. key += " " + item.attrib["product"]
  296. return key
  297. # Recursively merges XML elements. Updates either the text or children if another element is found in first.
  298. # If it does not exist, copies it from second.
  299. def _combineElement(self, first, second):
  300. # Create a mapping from tag name to element.
  301. mapping = {}
  302. for element in first:
  303. key = self._createKey(element)
  304. mapping[key] = element
  305. for element in second:
  306. key = self._createKey(element)
  307. if len(element): # Check if element has children.
  308. try:
  309. if "setting" in element.tag and not "settings" in element.tag:
  310. # Setting can have points in it. In that case, delete all values and override them.
  311. for child in list(mapping[key]):
  312. mapping[key].remove(child)
  313. for child in element:
  314. mapping[key].append(child)
  315. else:
  316. self._combineElement(mapping[key], element) # Multiple elements, handle those.
  317. except KeyError:
  318. mapping[key] = element
  319. first.append(element)
  320. else:
  321. try:
  322. mapping[key].text = element.text
  323. except KeyError: # Not in the mapping, so simply add it
  324. mapping[key] = element
  325. first.append(element)
  326. def clearData(self):
  327. self._metadata = {}
  328. self._name = ""
  329. self._definition = None
  330. self._instances = {}
  331. self._read_only = False
  332. self._dirty = False
  333. self._path = ""
  334. def getConfigurationTypeFromSerialized(self, serialized: str) -> Optional[str]:
  335. return "materials"
  336. @classmethod
  337. def getVersionFromSerialized(cls, serialized: str) -> Optional[int]:
  338. data = ET.fromstring(serialized)
  339. version = XmlMaterialProfile.Version
  340. # get setting version
  341. if "version" in data.attrib:
  342. setting_version = XmlMaterialProfile.xmlVersionToSettingVersion(data.attrib["version"])
  343. else:
  344. setting_version = XmlMaterialProfile.xmlVersionToSettingVersion("1.2")
  345. return version * 1000000 + setting_version
  346. ## Overridden from InstanceContainer
  347. def deserialize(self, serialized, file_name = None):
  348. containers_to_add = []
  349. # update the serialized data first
  350. from UM.Settings.Interfaces import ContainerInterface
  351. serialized = ContainerInterface.deserialize(self, serialized, file_name)
  352. try:
  353. data = ET.fromstring(serialized)
  354. except:
  355. Logger.logException("e", "An exception occured while parsing the material profile")
  356. return
  357. # Reset previous metadata
  358. self.clearData() # Ensure any previous data is gone.
  359. meta_data = {}
  360. meta_data["type"] = "material"
  361. meta_data["base_file"] = self.id
  362. meta_data["status"] = "unknown" # TODO: Add material verification
  363. common_setting_values = {}
  364. inherits = data.find("./um:inherits", self.__namespaces)
  365. if inherits is not None:
  366. inherited = self._resolveInheritance(inherits.text)
  367. data = self._mergeXML(inherited, data)
  368. # set setting_version in metadata
  369. if "version" in data.attrib:
  370. meta_data["setting_version"] = self.xmlVersionToSettingVersion(data.attrib["version"])
  371. else:
  372. meta_data["setting_version"] = self.xmlVersionToSettingVersion("1.2") #1.2 and lower didn't have that version number there yet.
  373. metadata = data.iterfind("./um:metadata/*", self.__namespaces)
  374. for entry in metadata:
  375. tag_name = _tag_without_namespace(entry)
  376. if tag_name == "name":
  377. brand = entry.find("./um:brand", self.__namespaces)
  378. material = entry.find("./um:material", self.__namespaces)
  379. color = entry.find("./um:color", self.__namespaces)
  380. label = entry.find("./um:label", self.__namespaces)
  381. if label is not None:
  382. self._name = label.text
  383. else:
  384. self._name = self._profile_name(material.text, color.text)
  385. meta_data["brand"] = brand.text
  386. meta_data["material"] = material.text
  387. meta_data["color_name"] = color.text
  388. continue
  389. # setting_version is derived from the "version" tag in the schema earlier, so don't set it here
  390. if tag_name == "setting_version":
  391. continue
  392. meta_data[tag_name] = entry.text
  393. if tag_name in self.__material_metadata_setting_map:
  394. common_setting_values[self.__material_metadata_setting_map[tag_name]] = entry.text
  395. if "description" not in meta_data:
  396. meta_data["description"] = ""
  397. if "adhesion_info" not in meta_data:
  398. meta_data["adhesion_info"] = ""
  399. property_values = {}
  400. properties = data.iterfind("./um:properties/*", self.__namespaces)
  401. for entry in properties:
  402. tag_name = _tag_without_namespace(entry)
  403. property_values[tag_name] = entry.text
  404. if tag_name in self.__material_properties_setting_map:
  405. common_setting_values[self.__material_properties_setting_map[tag_name]] = entry.text
  406. meta_data["approximate_diameter"] = str(round(float(property_values.get("diameter", 2.85)))) # In mm
  407. meta_data["properties"] = property_values
  408. self.setDefinition(ContainerRegistry.getInstance().findDefinitionContainers(id = "fdmprinter")[0])
  409. common_compatibility = True
  410. settings = data.iterfind("./um:settings/um:setting", self.__namespaces)
  411. for entry in settings:
  412. key = entry.get("key")
  413. if key in self.__material_settings_setting_map:
  414. common_setting_values[self.__material_settings_setting_map[key]] = entry.text
  415. elif key in self.__unmapped_settings:
  416. if key == "hardware compatible":
  417. common_compatibility = self._parseCompatibleValue(entry.text)
  418. self._cached_values = common_setting_values # from InstanceContainer ancestor
  419. meta_data["compatible"] = common_compatibility
  420. self.setMetaData(meta_data)
  421. self._dirty = False
  422. # Map machine human-readable names to IDs
  423. product_id_map = {}
  424. for container in ContainerRegistry.getInstance().findDefinitionContainers(type = "machine"):
  425. product_id_map[container.getName()] = container.getId()
  426. machines = data.iterfind("./um:settings/um:machine", self.__namespaces)
  427. for machine in machines:
  428. machine_compatibility = common_compatibility
  429. machine_setting_values = {}
  430. settings = machine.iterfind("./um:setting", self.__namespaces)
  431. for entry in settings:
  432. key = entry.get("key")
  433. if key in self.__material_settings_setting_map:
  434. machine_setting_values[self.__material_settings_setting_map[key]] = entry.text
  435. elif key in self.__unmapped_settings:
  436. if key == "hardware compatible":
  437. machine_compatibility = self._parseCompatibleValue(entry.text)
  438. else:
  439. Logger.log("d", "Unsupported material setting %s", key)
  440. cached_machine_setting_properties = common_setting_values.copy()
  441. cached_machine_setting_properties.update(machine_setting_values)
  442. identifiers = machine.iterfind("./um:machine_identifier", self.__namespaces)
  443. for identifier in identifiers:
  444. machine_id = product_id_map.get(identifier.get("product"), None)
  445. if machine_id is None:
  446. # Lets try again with some naive heuristics.
  447. machine_id = identifier.get("product").replace(" ", "").lower()
  448. definitions = ContainerRegistry.getInstance().findDefinitionContainers(id = machine_id)
  449. if not definitions:
  450. # Logger.log("w", "No definition found for machine ID %s", machine_id)
  451. continue
  452. definition = definitions[0]
  453. machine_manufacturer = identifier.get("manufacturer", definition.getMetaDataEntry("manufacturer", "Unknown")) #If the XML material doesn't specify a manufacturer, use the one in the actual printer definition.
  454. if machine_compatibility:
  455. new_material_id = self.id + "_" + machine_id
  456. # The child or derived material container may already exist. This can happen when a material in a
  457. # project file and the a material in Cura have the same ID.
  458. # In the case if a derived material already exists, override that material container because if
  459. # the data in the parent material has been changed, the derived ones should be updated too.
  460. found_materials = ContainerRegistry.getInstance().findInstanceContainers(id = new_material_id)
  461. is_new_material = False
  462. if found_materials:
  463. new_material = found_materials[0]
  464. else:
  465. new_material = XmlMaterialProfile(new_material_id)
  466. is_new_material = True
  467. # Update the private directly, as we want to prevent the lookup that is done when using setName
  468. new_material._name = self.getName()
  469. new_material.setMetaData(copy.deepcopy(self.getMetaData()))
  470. new_material.setDefinition(definition)
  471. # Don't use setMetadata, as that overrides it for all materials with same base file
  472. new_material.getMetaData()["compatible"] = machine_compatibility
  473. new_material.getMetaData()["machine_manufacturer"] = machine_manufacturer
  474. new_material.setCachedValues(cached_machine_setting_properties)
  475. new_material._dirty = False
  476. if is_new_material:
  477. containers_to_add.append(new_material)
  478. hotends = machine.iterfind("./um:hotend", self.__namespaces)
  479. for hotend in hotends:
  480. hotend_id = hotend.get("id")
  481. if hotend_id is None:
  482. continue
  483. variant_containers = ContainerRegistry.getInstance().findInstanceContainers(id = hotend_id)
  484. if not variant_containers:
  485. # It is not really properly defined what "ID" is so also search for variants by name.
  486. variant_containers = ContainerRegistry.getInstance().findInstanceContainers(definition = definition.id, name = hotend_id)
  487. if not variant_containers:
  488. #Logger.log("d", "No variants found with ID or name %s for machine %s", hotend_id, definition.id)
  489. continue
  490. hotend_compatibility = machine_compatibility
  491. hotend_setting_values = {}
  492. settings = hotend.iterfind("./um:setting", self.__namespaces)
  493. for entry in settings:
  494. key = entry.get("key")
  495. if key in self.__material_settings_setting_map:
  496. hotend_setting_values[self.__material_settings_setting_map[key]] = entry.text
  497. elif key in self.__unmapped_settings:
  498. if key == "hardware compatible":
  499. hotend_compatibility = self._parseCompatibleValue(entry.text)
  500. else:
  501. Logger.log("d", "Unsupported material setting %s", key)
  502. new_hotend_id = self.id + "_" + machine_id + "_" + hotend_id.replace(" ", "_")
  503. # Same as machine compatibility, keep the derived material containers consistent with the parent
  504. # material
  505. found_materials = ContainerRegistry.getInstance().findInstanceContainers(id = new_hotend_id)
  506. is_new_material = False
  507. if found_materials:
  508. new_hotend_material = found_materials[0]
  509. else:
  510. new_hotend_material = XmlMaterialProfile(new_hotend_id)
  511. is_new_material = True
  512. # Update the private directly, as we want to prevent the lookup that is done when using setName
  513. new_hotend_material._name = self.getName()
  514. new_hotend_material.setMetaData(copy.deepcopy(self.getMetaData()))
  515. new_hotend_material.setDefinition(definition)
  516. new_hotend_material.addMetaDataEntry("variant", variant_containers[0].id)
  517. # Don't use setMetadata, as that overrides it for all materials with same base file
  518. new_hotend_material.getMetaData()["compatible"] = hotend_compatibility
  519. new_hotend_material.getMetaData()["machine_manufacturer"] = machine_manufacturer
  520. cached_hotend_setting_properties = cached_machine_setting_properties.copy()
  521. cached_hotend_setting_properties.update(hotend_setting_values)
  522. new_hotend_material.setCachedValues(cached_hotend_setting_properties)
  523. new_hotend_material._dirty = False
  524. if is_new_material:
  525. containers_to_add.append(new_hotend_material)
  526. for container_to_add in containers_to_add:
  527. ContainerRegistry.getInstance().addContainer(container_to_add)
  528. def _addSettingElement(self, builder, instance):
  529. try:
  530. key = UM.Dictionary.findKey(self.__material_settings_setting_map, instance.definition.key)
  531. except ValueError:
  532. return
  533. builder.start("setting", { "key": key })
  534. builder.data(str(instance.value))
  535. builder.end("setting")
  536. def _profile_name(self, material_name, color_name):
  537. if color_name != "Generic":
  538. return "%s %s" % (color_name, material_name)
  539. else:
  540. return material_name
  541. ## Parse the value of the "material compatible" property.
  542. def _parseCompatibleValue(self, value: str):
  543. return value in {"yes", "unknown"}
  544. # Map XML file setting names to internal names
  545. __material_settings_setting_map = {
  546. "print temperature": "default_material_print_temperature",
  547. "heated bed temperature": "material_bed_temperature",
  548. "standby temperature": "material_standby_temperature",
  549. "processing temperature graph": "material_flow_temp_graph",
  550. "print cooling": "cool_fan_speed",
  551. "retraction amount": "retraction_amount",
  552. "retraction speed": "retraction_speed",
  553. "adhesion tendency": "material_adhesion_tendency",
  554. "surface energy": "material_surface_energy"
  555. }
  556. __unmapped_settings = [
  557. "hardware compatible"
  558. ]
  559. __material_properties_setting_map = {
  560. "diameter": "material_diameter"
  561. }
  562. __material_metadata_setting_map = {
  563. "GUID": "material_guid"
  564. }
  565. # Map of recognised namespaces with a proper prefix.
  566. __namespaces = {
  567. "um": "http://www.ultimaker.com/material"
  568. }
  569. ## Helper function for pretty-printing XML because ETree is stupid
  570. def _indent(elem, level = 0):
  571. i = "\n" + level * " "
  572. if len(elem):
  573. if not elem.text or not elem.text.strip():
  574. elem.text = i + " "
  575. if not elem.tail or not elem.tail.strip():
  576. elem.tail = i
  577. for elem in elem:
  578. _indent(elem, level + 1)
  579. if not elem.tail or not elem.tail.strip():
  580. elem.tail = i
  581. else:
  582. if level and (not elem.tail or not elem.tail.strip()):
  583. elem.tail = i
  584. # The namespace is prepended to the tag name but between {}.
  585. # We are only interested in the actual tag name, so discard everything
  586. # before the last }
  587. def _tag_without_namespace(element):
  588. return element.tag[element.tag.rfind("}") + 1:]