XmlMaterialProfile.py 31 KB

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