XmlMaterialProfile.py 31 KB

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