XmlMaterialProfile.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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._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. containers_to_add = []
  343. # update the serialized data first
  344. from UM.Settings.Interfaces import ContainerInterface
  345. serialized = ContainerInterface.deserialize(self, serialized)
  346. try:
  347. data = ET.fromstring(serialized)
  348. except:
  349. Logger.logException("e", "An exception occured while parsing the material profile")
  350. return
  351. # Reset previous metadata
  352. self.clearData() # Ensure any previous data is gone.
  353. meta_data = {}
  354. meta_data["type"] = "material"
  355. meta_data["base_file"] = self.id
  356. meta_data["status"] = "unknown" # TODO: Add material verification
  357. common_setting_values = {}
  358. inherits = data.find("./um:inherits", self.__namespaces)
  359. if inherits is not None:
  360. inherited = self._resolveInheritance(inherits.text)
  361. data = self._mergeXML(inherited, data)
  362. # set setting_version in metadata
  363. if "version" in data.attrib:
  364. meta_data["setting_version"] = self.xmlVersionToSettingVersion(data.attrib["version"])
  365. else:
  366. meta_data["setting_version"] = self.xmlVersionToSettingVersion("1.2") #1.2 and lower didn't have that version number there yet.
  367. metadata = data.iterfind("./um:metadata/*", self.__namespaces)
  368. for entry in metadata:
  369. tag_name = _tag_without_namespace(entry)
  370. if tag_name == "name":
  371. brand = entry.find("./um:brand", self.__namespaces)
  372. material = entry.find("./um:material", self.__namespaces)
  373. color = entry.find("./um:color", self.__namespaces)
  374. label = entry.find("./um:label", self.__namespaces)
  375. if label is not None:
  376. self._name = label.text
  377. else:
  378. self._name = self._profile_name(material.text, color.text)
  379. meta_data["brand"] = brand.text
  380. meta_data["material"] = material.text
  381. meta_data["color_name"] = color.text
  382. continue
  383. # setting_version is derived from the "version" tag in the schema earlier, so don't set it here
  384. if tag_name == "setting_version":
  385. continue
  386. meta_data[tag_name] = entry.text
  387. if tag_name in self.__material_metadata_setting_map:
  388. common_setting_values[self.__material_metadata_setting_map[tag_name]] = entry.text
  389. if "description" not in meta_data:
  390. meta_data["description"] = ""
  391. if "adhesion_info" not in meta_data:
  392. meta_data["adhesion_info"] = ""
  393. property_values = {}
  394. properties = data.iterfind("./um:properties/*", self.__namespaces)
  395. for entry in properties:
  396. tag_name = _tag_without_namespace(entry)
  397. property_values[tag_name] = entry.text
  398. if tag_name in self.__material_properties_setting_map:
  399. common_setting_values[self.__material_properties_setting_map[tag_name]] = entry.text
  400. meta_data["approximate_diameter"] = str(round(float(property_values.get("diameter", 2.85)))) # In mm
  401. meta_data["properties"] = property_values
  402. self.setDefinition(ContainerRegistry.getInstance().findDefinitionContainers(id = "fdmprinter")[0])
  403. common_compatibility = True
  404. settings = data.iterfind("./um:settings/um:setting", self.__namespaces)
  405. for entry in settings:
  406. key = entry.get("key")
  407. if key in self.__material_settings_setting_map:
  408. common_setting_values[self.__material_settings_setting_map[key]] = entry.text
  409. elif key in self.__unmapped_settings:
  410. if key == "hardware compatible":
  411. common_compatibility = self._parseCompatibleValue(entry.text)
  412. else:
  413. Logger.log("d", "Unsupported material setting %s", key)
  414. self._cached_values = common_setting_values # from InstanceContainer ancestor
  415. meta_data["compatible"] = common_compatibility
  416. self.setMetaData(meta_data)
  417. self._dirty = False
  418. machines = data.iterfind("./um:settings/um:machine", self.__namespaces)
  419. for machine in machines:
  420. machine_compatibility = common_compatibility
  421. machine_setting_values = {}
  422. settings = machine.iterfind("./um:setting", self.__namespaces)
  423. for entry in settings:
  424. key = entry.get("key")
  425. if key in self.__material_settings_setting_map:
  426. machine_setting_values[self.__material_settings_setting_map[key]] = entry.text
  427. elif key in self.__unmapped_settings:
  428. if key == "hardware compatible":
  429. machine_compatibility = self._parseCompatibleValue(entry.text)
  430. else:
  431. Logger.log("d", "Unsupported material setting %s", key)
  432. cached_machine_setting_properties = common_setting_values.copy()
  433. cached_machine_setting_properties.update(machine_setting_values)
  434. identifiers = machine.iterfind("./um:machine_identifier", self.__namespaces)
  435. for identifier in identifiers:
  436. machine_id = self.__product_id_map.get(identifier.get("product"), None)
  437. if machine_id is None:
  438. # Lets try again with some naive heuristics.
  439. machine_id = identifier.get("product").replace(" ", "").lower()
  440. definitions = ContainerRegistry.getInstance().findDefinitionContainers(id = machine_id)
  441. if not definitions:
  442. Logger.log("w", "No definition found for machine ID %s", machine_id)
  443. continue
  444. definition = definitions[0]
  445. 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.
  446. if machine_compatibility:
  447. new_material_id = self.id + "_" + machine_id
  448. # The child or derived material container may already exist. This can happen when a material in a
  449. # project file and the a material in Cura have the same ID.
  450. # In the case if a derived material already exists, override that material container because if
  451. # the data in the parent material has been changed, the derived ones should be updated too.
  452. found_materials = ContainerRegistry.getInstance().findInstanceContainers(id = new_material_id)
  453. is_new_material = False
  454. if found_materials:
  455. new_material = found_materials[0]
  456. else:
  457. new_material = XmlMaterialProfile(new_material_id)
  458. is_new_material = True
  459. # Update the private directly, as we want to prevent the lookup that is done when using setName
  460. new_material._name = self.getName()
  461. new_material.setMetaData(copy.deepcopy(self.getMetaData()))
  462. new_material.setDefinition(definition)
  463. # Don't use setMetadata, as that overrides it for all materials with same base file
  464. new_material.getMetaData()["compatible"] = machine_compatibility
  465. new_material.getMetaData()["machine_manufacturer"] = machine_manufacturer
  466. new_material.setCachedValues(cached_machine_setting_properties)
  467. new_material._dirty = False
  468. if is_new_material:
  469. containers_to_add.append(new_material)
  470. hotends = machine.iterfind("./um:hotend", self.__namespaces)
  471. for hotend in hotends:
  472. hotend_id = hotend.get("id")
  473. if hotend_id is None:
  474. continue
  475. variant_containers = ContainerRegistry.getInstance().findInstanceContainers(id = hotend_id)
  476. if not variant_containers:
  477. # It is not really properly defined what "ID" is so also search for variants by name.
  478. variant_containers = ContainerRegistry.getInstance().findInstanceContainers(definition = definition.id, name = hotend_id)
  479. if not variant_containers:
  480. #Logger.log("d", "No variants found with ID or name %s for machine %s", hotend_id, definition.id)
  481. continue
  482. hotend_compatibility = machine_compatibility
  483. hotend_setting_values = {}
  484. settings = hotend.iterfind("./um:setting", self.__namespaces)
  485. for entry in settings:
  486. key = entry.get("key")
  487. if key in self.__material_settings_setting_map:
  488. hotend_setting_values[self.__material_settings_setting_map[key]] = entry.text
  489. elif key in self.__unmapped_settings:
  490. if key == "hardware compatible":
  491. hotend_compatibility = self._parseCompatibleValue(entry.text)
  492. else:
  493. Logger.log("d", "Unsupported material setting %s", key)
  494. new_hotend_id = self.id + "_" + machine_id + "_" + hotend_id.replace(" ", "_")
  495. # Same as machine compatibility, keep the derived material containers consistent with the parent
  496. # material
  497. found_materials = ContainerRegistry.getInstance().findInstanceContainers(id = new_hotend_id)
  498. is_new_material = False
  499. if found_materials:
  500. new_hotend_material = found_materials[0]
  501. else:
  502. new_hotend_material = XmlMaterialProfile(new_hotend_id)
  503. is_new_material = True
  504. # Update the private directly, as we want to prevent the lookup that is done when using setName
  505. new_hotend_material._name = self.getName()
  506. new_hotend_material.setMetaData(copy.deepcopy(self.getMetaData()))
  507. new_hotend_material.setDefinition(definition)
  508. new_hotend_material.addMetaDataEntry("variant", variant_containers[0].id)
  509. # Don't use setMetadata, as that overrides it for all materials with same base file
  510. new_hotend_material.getMetaData()["compatible"] = hotend_compatibility
  511. new_hotend_material.getMetaData()["machine_manufacturer"] = machine_manufacturer
  512. cached_hotend_setting_properties = cached_machine_setting_properties.copy()
  513. cached_hotend_setting_properties.update(hotend_setting_values)
  514. new_hotend_material.setCachedValues(cached_hotend_setting_properties)
  515. new_hotend_material._dirty = False
  516. if is_new_material:
  517. containers_to_add.append(new_hotend_material)
  518. for container_to_add in containers_to_add:
  519. ContainerRegistry.getInstance().addContainer(container_to_add)
  520. def _addSettingElement(self, builder, instance):
  521. try:
  522. key = UM.Dictionary.findKey(self.__material_settings_setting_map, instance.definition.key)
  523. except ValueError:
  524. return
  525. builder.start("setting", { "key": key })
  526. builder.data(str(instance.value))
  527. builder.end("setting")
  528. def _profile_name(self, material_name, color_name):
  529. if color_name != "Generic":
  530. return "%s %s" % (color_name, material_name)
  531. else:
  532. return material_name
  533. ## Parse the value of the "material compatible" property.
  534. def _parseCompatibleValue(self, value: str):
  535. return value in {"yes", "unknown"}
  536. # Map XML file setting names to internal names
  537. __material_settings_setting_map = {
  538. "print temperature": "default_material_print_temperature",
  539. "heated bed temperature": "material_bed_temperature",
  540. "standby temperature": "material_standby_temperature",
  541. "processing temperature graph": "material_flow_temp_graph",
  542. "print cooling": "cool_fan_speed",
  543. "retraction amount": "retraction_amount",
  544. "retraction speed": "retraction_speed"
  545. }
  546. __unmapped_settings = [
  547. "hardware compatible"
  548. ]
  549. __material_properties_setting_map = {
  550. "diameter": "material_diameter"
  551. }
  552. __material_metadata_setting_map = {
  553. "GUID": "material_guid"
  554. }
  555. # Map XML file product names to internal ids
  556. # TODO: Move this to definition's metadata
  557. __product_id_map = {
  558. "Ultimaker 3": "ultimaker3",
  559. "Ultimaker 3 Extended": "ultimaker3_extended",
  560. "Ultimaker 2": "ultimaker2",
  561. "Ultimaker 2+": "ultimaker2_plus",
  562. "Ultimaker 2 Go": "ultimaker2_go",
  563. "Ultimaker 2 Extended": "ultimaker2_extended",
  564. "Ultimaker 2 Extended+": "ultimaker2_extended_plus",
  565. "Ultimaker Original": "ultimaker_original",
  566. "Ultimaker Original+": "ultimaker_original_plus",
  567. "IMADE3D JellyBOX": "imade3d_jellybox"
  568. }
  569. # Map of recognised namespaces with a proper prefix.
  570. __namespaces = {
  571. "um": "http://www.ultimaker.com/material"
  572. }
  573. ## Helper function for pretty-printing XML because ETree is stupid
  574. def _indent(elem, level = 0):
  575. i = "\n" + level * " "
  576. if len(elem):
  577. if not elem.text or not elem.text.strip():
  578. elem.text = i + " "
  579. if not elem.tail or not elem.tail.strip():
  580. elem.tail = i
  581. for elem in elem:
  582. _indent(elem, level + 1)
  583. if not elem.tail or not elem.tail.strip():
  584. elem.tail = i
  585. else:
  586. if level and (not elem.tail or not elem.tail.strip()):
  587. elem.tail = i
  588. # The namespace is prepended to the tag name but between {}.
  589. # We are only interested in the actual tag name, so discard everything
  590. # before the last }
  591. def _tag_without_namespace(element):
  592. return element.tag[element.tag.rfind("}") + 1:]