XmlMaterialProfile.py 26 KB

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