XmlMaterialProfile.py 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import copy
  4. import io
  5. import json # To parse the product-to-id mapping file.
  6. import os.path # To find the product-to-id mapping.
  7. from typing import Any, Dict, List, Optional, Tuple, cast, Set
  8. import xml.etree.ElementTree as ET
  9. from UM.PluginRegistry import PluginRegistry
  10. from UM.Resources import Resources
  11. from UM.Logger import Logger
  12. import UM.Dictionary
  13. from UM.Settings.InstanceContainer import InstanceContainer
  14. from UM.Settings.ContainerRegistry import ContainerRegistry
  15. from UM.ConfigurationErrorMessage import ConfigurationErrorMessage
  16. from cura.CuraApplication import CuraApplication
  17. from cura.Machines.VariantType import VariantType
  18. try:
  19. from .XmlMaterialValidator import XmlMaterialValidator
  20. except (ImportError, SystemError):
  21. import XmlMaterialValidator # type: ignore # This fixes the tests not being able to import.
  22. class XmlMaterialProfile(InstanceContainer):
  23. """Handles serializing and deserializing material containers from an XML file"""
  24. CurrentFdmMaterialVersion = "1.3"
  25. Version = 1
  26. def __init__(self, container_id, *args, **kwargs):
  27. super().__init__(container_id, *args, **kwargs)
  28. self._inherited_files = []
  29. @staticmethod
  30. def xmlVersionToSettingVersion(xml_version: str) -> int:
  31. """Translates the version number in the XML files to the setting_version metadata entry.
  32. Since the two may increment independently we need a way to say which
  33. versions of the XML specification are compatible with our setting data
  34. version numbers.
  35. :param xml_version: The version number found in an XML file.
  36. :return: The corresponding setting_version.
  37. """
  38. if xml_version == "1.3":
  39. return CuraApplication.SettingVersion
  40. return 0 # Older than 1.3.
  41. def getInheritedFiles(self):
  42. return self._inherited_files
  43. def setMetaDataEntry(self, key, value, apply_to_all = True):
  44. """set the meta data for all machine / variant combinations
  45. The "apply_to_all" flag indicates whether this piece of metadata should be applied to all material containers
  46. or just this specific container.
  47. For example, when you change the material name, you want to apply it to all its derived containers, but for
  48. some specific settings, they should only be applied to a machine/variant-specific container.
  49. Overridden from InstanceContainer
  50. """
  51. registry = ContainerRegistry.getInstance()
  52. if registry.isReadOnly(self.getId()):
  53. Logger.log("w", "Can't change metadata {key} of material {material_id} because it's read-only.".format(key = key, material_id = self.getId()))
  54. return
  55. # Some metadata such as diameter should also be instantiated to be a setting. Go though all values for the
  56. # "properties" field and apply the new values to SettingInstances as well.
  57. new_setting_values_dict = {}
  58. if key == "properties":
  59. for k, v in value.items():
  60. if k in self.__material_properties_setting_map:
  61. new_setting_values_dict[self.__material_properties_setting_map[k]] = v
  62. if not apply_to_all: # Historical: If you only want to modify THIS container. We only used that to prevent recursion but with the below code that's no longer necessary.
  63. # CURA-6920: This is an optimization, but it also fixes the problem that you can only set metadata for a
  64. # material container that can be found in the container registry.
  65. container_query = [self]
  66. else:
  67. container_query = registry.findContainers(base_file = self.getMetaDataEntry("base_file"))
  68. for container in container_query:
  69. if key not in container.getMetaData() or container.getMetaData()[key] != value:
  70. container.getMetaData()[key] = value
  71. container.setDirty(True)
  72. container.metaDataChanged.emit(container)
  73. for k, v in new_setting_values_dict.items():
  74. self.setProperty(k, "value", v)
  75. def setName(self, new_name):
  76. """Overridden from InstanceContainer, similar to setMetaDataEntry.
  77. without this function the setName would only set the name of the specific nozzle / material / machine combination container
  78. The function is a bit tricky. It will not set the name of all containers if it has the correct name itself.
  79. """
  80. registry = ContainerRegistry.getInstance()
  81. if registry.isReadOnly(self.getId()):
  82. return
  83. # Not only is this faster, it also prevents a major loop that causes a stack overflow.
  84. if self.getName() == new_name:
  85. return
  86. super().setName(new_name)
  87. basefile = self.getMetaDataEntry("base_file", self.getId()) # if basefile is self.getId, this is a basefile.
  88. # Update the basefile as well, this is actually what we're trying to do
  89. # Update all containers that share GUID and basefile
  90. containers = registry.findInstanceContainers(base_file = basefile)
  91. for container in containers:
  92. container.setName(new_name)
  93. def setDirty(self, dirty):
  94. """Overridden from InstanceContainer, to set dirty to base file as well."""
  95. super().setDirty(dirty)
  96. base_file = self.getMetaDataEntry("base_file", None)
  97. registry = ContainerRegistry.getInstance()
  98. if base_file is not None and base_file != self.getId() and not registry.isReadOnly(base_file):
  99. containers = registry.findContainers(id = base_file)
  100. if containers:
  101. containers[0].setDirty(dirty)
  102. def serialize(self, ignored_metadata_keys: Optional[Set[str]] = None):
  103. """Overridden from InstanceContainer
  104. base file: common settings + supported machines
  105. machine / variant combination: only changes for itself.
  106. """
  107. registry = ContainerRegistry.getInstance()
  108. base_file = self.getMetaDataEntry("base_file", "")
  109. if base_file and self.getId() != base_file:
  110. # Since we create an instance of XmlMaterialProfile for each machine and nozzle in the profile,
  111. # we should only serialize the "base" material definition, since that can then take care of
  112. # serializing the machine/nozzle specific profiles.
  113. raise NotImplementedError("Ignoring serializing non-root XML materials, the data is contained in the base material")
  114. builder = ET.TreeBuilder()
  115. root = builder.start("fdmmaterial",
  116. {"xmlns": "http://www.ultimaker.com/material",
  117. "xmlns:cura": "http://www.ultimaker.com/cura",
  118. "version": self.CurrentFdmMaterialVersion})
  119. ## Begin Metadata Block
  120. builder.start("metadata", {}) # type: ignore
  121. metadata = copy.deepcopy(self.getMetaData())
  122. # Get the to reserialize keys from the metadata before they are deleted.
  123. reserialize_settings = copy.deepcopy(metadata["reserialize_settings"])
  124. # setting_version is derived from the "version" tag in the schema, so don't serialize it into a file
  125. if ignored_metadata_keys is None:
  126. ignored_metadata_keys = set()
  127. ignored_metadata_keys |= {"setting_version", "definition", "status", "variant", "type", "base_file", "approximate_diameter", "id", "container_type", "name", "compatible", "reserialize_settings"}
  128. # remove the keys that we want to ignore in the metadata
  129. for key in ignored_metadata_keys:
  130. if key in metadata:
  131. del metadata[key]
  132. properties = metadata.pop("properties", {})
  133. ## Begin Name Block
  134. builder.start("name", {}) # type: ignore
  135. builder.start("brand", {}) # type: ignore
  136. builder.data(metadata.pop("brand", ""))
  137. builder.end("brand")
  138. builder.start("material", {}) # type: ignore
  139. builder.data(metadata.pop("material", ""))
  140. builder.end("material")
  141. builder.start("color", {}) # type: ignore
  142. builder.data(metadata.pop("color_name", ""))
  143. builder.end("color")
  144. builder.start("label", {}) # type: ignore
  145. builder.data(self.getName())
  146. builder.end("label")
  147. builder.end("name")
  148. ## End Name Block
  149. for key, value in metadata.items():
  150. key_to_use = key
  151. if key in self._metadata_tags_that_have_cura_namespace:
  152. key_to_use = "cura:" + key_to_use
  153. builder.start(key_to_use, {}) # type: ignore
  154. if value is not None: #Nones get handled well by the builder.
  155. #Otherwise the builder always expects a string.
  156. #Deserialize expects the stringified version.
  157. value = str(value)
  158. builder.data(value)
  159. builder.end(key_to_use)
  160. builder.end("metadata")
  161. ## End Metadata Block
  162. ## Begin Properties Block
  163. builder.start("properties", {}) # type: ignore
  164. for key, value in properties.items():
  165. builder.start(key, {}) # type: ignore
  166. builder.data(value)
  167. builder.end(key)
  168. builder.end("properties")
  169. ## End Properties Block
  170. ## Begin Settings Block
  171. builder.start("settings", {}) # type: ignore
  172. if self.getMetaDataEntry("definition") == "fdmprinter":
  173. for instance in self.findInstances():
  174. self._addSettingElement(builder, instance)
  175. machine_container_map = {} # type: Dict[str, InstanceContainer]
  176. machine_variant_map = {} # type: Dict[str, Dict[str, Any]]
  177. root_material_id = self.getMetaDataEntry("base_file") # if basefile is self.getId, this is a basefile.
  178. all_containers = registry.findInstanceContainers(base_file = root_material_id)
  179. for container in all_containers:
  180. definition_id = container.getMetaDataEntry("definition")
  181. if definition_id == "fdmprinter":
  182. continue
  183. if definition_id not in machine_container_map:
  184. machine_container_map[definition_id] = container
  185. if definition_id not in machine_variant_map:
  186. machine_variant_map[definition_id] = {}
  187. variant_name = container.getMetaDataEntry("variant_name")
  188. if not variant_name:
  189. machine_container_map[definition_id] = container
  190. continue
  191. variant_dict = {"variant_type": container.getMetaDataEntry("hardware_type", "nozzle"),
  192. "material_container": container}
  193. machine_variant_map[definition_id][variant_name] = variant_dict
  194. # Map machine human-readable names to IDs
  195. product_id_map = self.getProductIdMap()
  196. for definition_id, container in machine_container_map.items():
  197. definition_id = container.getMetaDataEntry("definition")
  198. definition_metadata = registry.findDefinitionContainersMetadata(id = definition_id)[0]
  199. product = definition_id
  200. for product_name, product_id_list in product_id_map.items():
  201. if definition_id in product_id_list:
  202. product = product_name
  203. break
  204. builder.start("machine", {}) # type: ignore
  205. builder.start("machine_identifier", {
  206. "manufacturer": container.getMetaDataEntry("machine_manufacturer",
  207. definition_metadata.get("manufacturer", "Unknown")),
  208. "product": product
  209. })
  210. builder.end("machine_identifier")
  211. for instance in container.findInstances():
  212. if self.getMetaDataEntry("definition") == "fdmprinter" and self.getInstance(instance.definition.key) and self.getProperty(instance.definition.key, "value") == instance.value:
  213. # If the settings match that of the base profile, just skip since we inherit the base profile.
  214. continue
  215. self._addSettingElement(builder, instance)
  216. # Find all hotend sub-profiles corresponding to this material and machine and add them to this profile.
  217. buildplate_dict = {} # type: Dict[str, Any]
  218. for variant_name, variant_dict in machine_variant_map[definition_id].items():
  219. variant_type = VariantType(variant_dict["variant_type"])
  220. if variant_type == VariantType.NOZZLE:
  221. # The hotend identifier is not the containers name, but its "name".
  222. builder.start("hotend", {"id": variant_name})
  223. # Compatible is a special case, as it's added as a meta data entry (instead of an instance).
  224. material_container = variant_dict["material_container"]
  225. compatible = material_container.getMetaDataEntry("compatible")
  226. if compatible is not None:
  227. builder.start("setting", {"key": "hardware compatible"})
  228. if compatible:
  229. builder.data("yes")
  230. else:
  231. builder.data("no")
  232. builder.end("setting")
  233. for instance in material_container.findInstances():
  234. if container.getInstance(instance.definition.key) and container.getProperty(instance.definition.key, "value") == instance.value:
  235. # If the settings match that of the machine profile, just skip since we inherit the machine profile.
  236. continue
  237. self._addSettingElement(builder, instance)
  238. if material_container.getMetaDataEntry("buildplate_compatible") and not buildplate_dict:
  239. buildplate_dict["buildplate_compatible"] = material_container.getMetaDataEntry("buildplate_compatible")
  240. buildplate_dict["buildplate_recommended"] = material_container.getMetaDataEntry("buildplate_recommended")
  241. buildplate_dict["material_container"] = material_container
  242. hotend_reserialize_settings = material_container.getMetaDataEntry("reserialize_settings")
  243. for key, value in hotend_reserialize_settings.items():
  244. builder.start("setting", {"key": key})
  245. builder.data(value)
  246. builder.end("setting")
  247. builder.end("hotend")
  248. if buildplate_dict:
  249. for variant_name in buildplate_dict["buildplate_compatible"]:
  250. builder.start("buildplate", {"id": variant_name})
  251. material_container = buildplate_dict["material_container"]
  252. buildplate_compatible_dict = material_container.getMetaDataEntry("buildplate_compatible")
  253. buildplate_recommended_dict = material_container.getMetaDataEntry("buildplate_recommended")
  254. if buildplate_compatible_dict:
  255. compatible = buildplate_compatible_dict[variant_name]
  256. recommended = buildplate_recommended_dict[variant_name]
  257. builder.start("setting", {"key": "hardware compatible"})
  258. builder.data("yes" if compatible else "no")
  259. builder.end("setting")
  260. builder.start("setting", {"key": "hardware recommended"})
  261. builder.data("yes" if recommended else "no")
  262. builder.end("setting")
  263. buildplate_reserialize_settings = material_container.getMetaDataEntry("reserialize_settings")
  264. for key, value in buildplate_reserialize_settings.items():
  265. builder.start("setting", {"key": key})
  266. builder.data(value)
  267. builder.end("setting")
  268. builder.end("buildplate")
  269. machine_reserialize_settings = container.getMetaDataEntry("reserialize_settings")
  270. for key, value in machine_reserialize_settings.items():
  271. builder.start("setting", {"key": key})
  272. builder.data(value)
  273. builder.end("setting")
  274. builder.end("machine")
  275. for key, value in reserialize_settings.items():
  276. builder.start("setting", {"key": key})
  277. builder.data(value)
  278. builder.end("setting")
  279. builder.end("settings")
  280. ## End Settings Block
  281. builder.end("fdmmaterial")
  282. root = builder.close()
  283. _indent(root)
  284. stream = io.BytesIO()
  285. tree = ET.ElementTree(root)
  286. # this makes sure that the XML header states encoding="utf-8"
  287. tree.write(stream, encoding = "utf-8", xml_declaration = True)
  288. return stream.getvalue().decode("utf-8")
  289. def getFileName(self) -> str:
  290. return (self.getMetaDataEntry("base_file") + ".xml.fdm_material").replace(" ", "+")
  291. # Recursively resolve loading inherited files
  292. def _resolveInheritance(self, file_name):
  293. xml = self._loadFile(file_name)
  294. inherits = xml.find("./um:inherits", self.__namespaces)
  295. if inherits is not None:
  296. inherited = self._resolveInheritance(inherits.text)
  297. xml = self._mergeXML(inherited, xml)
  298. return xml
  299. def _loadFile(self, file_name):
  300. path = Resources.getPath(CuraApplication.getInstance().ResourceTypes.MaterialInstanceContainer, file_name + ".xml.fdm_material")
  301. with open(path, encoding = "utf-8") as f:
  302. contents = f.read()
  303. self._inherited_files.append(path)
  304. return ET.fromstring(contents)
  305. # The XML material profile can have specific settings for machines.
  306. # Some machines share profiles, so they are only created once.
  307. # This function duplicates those elements so that each machine tag only has one identifier.
  308. def _expandMachinesXML(self, element):
  309. settings_element = element.find("./um:settings", self.__namespaces)
  310. machines = settings_element.iterfind("./um:machine", self.__namespaces)
  311. machines_to_add = []
  312. machines_to_remove = []
  313. for machine in machines:
  314. identifiers = list(machine.iterfind("./um:machine_identifier", self.__namespaces))
  315. has_multiple_identifiers = len(identifiers) > 1
  316. if has_multiple_identifiers:
  317. # Multiple identifiers found. We need to create a new machine element and copy all it's settings there.
  318. for identifier in identifiers:
  319. new_machine = copy.deepcopy(machine)
  320. # Create list of identifiers that need to be removed from the copied element.
  321. other_identifiers = [self._createKey(other_identifier) for other_identifier in identifiers if other_identifier is not identifier]
  322. # As we can only remove by exact object reference, we need to look through the identifiers of copied machine.
  323. new_machine_identifiers = list(new_machine.iterfind("./um:machine_identifier", self.__namespaces))
  324. for new_machine_identifier in new_machine_identifiers:
  325. key = self._createKey(new_machine_identifier)
  326. # Key was in identifiers to remove, so this element needs to be purged
  327. if key in other_identifiers:
  328. new_machine.remove(new_machine_identifier)
  329. machines_to_add.append(new_machine)
  330. machines_to_remove.append(machine)
  331. else:
  332. pass # Machine only has one identifier. Nothing to do.
  333. # Remove & add all required machines.
  334. for machine_to_remove in machines_to_remove:
  335. settings_element.remove(machine_to_remove)
  336. for machine_to_add in machines_to_add:
  337. settings_element.append(machine_to_add)
  338. return element
  339. def _mergeXML(self, first, second):
  340. result = copy.deepcopy(first)
  341. self._combineElement(self._expandMachinesXML(result), self._expandMachinesXML(second))
  342. return result
  343. @staticmethod
  344. def _createKey(element):
  345. key = element.tag.split("}")[-1]
  346. if "key" in element.attrib:
  347. key += " key:" + element.attrib["key"]
  348. if "manufacturer" in element.attrib:
  349. key += " manufacturer:" + element.attrib["manufacturer"]
  350. if "product" in element.attrib:
  351. key += " product:" + element.attrib["product"]
  352. if key == "machine":
  353. for item in element:
  354. if "machine_identifier" in item.tag:
  355. key += " " + item.attrib["product"]
  356. return key
  357. # Recursively merges XML elements. Updates either the text or children if another element is found in first.
  358. # If it does not exist, copies it from second.
  359. @staticmethod
  360. def _combineElement(first, second):
  361. # Create a mapping from tag name to element.
  362. mapping = {}
  363. for element in first:
  364. key = XmlMaterialProfile._createKey(element)
  365. mapping[key] = element
  366. for element in second:
  367. key = XmlMaterialProfile._createKey(element)
  368. if len(element): # Check if element has children.
  369. try:
  370. if "setting" in element.tag and not "settings" in element.tag:
  371. # Setting can have points in it. In that case, delete all values and override them.
  372. for child in list(mapping[key]):
  373. mapping[key].remove(child)
  374. for child in element:
  375. mapping[key].append(child)
  376. else:
  377. XmlMaterialProfile._combineElement(mapping[key], element) # Multiple elements, handle those.
  378. except KeyError:
  379. mapping[key] = element
  380. first.append(element)
  381. else:
  382. try:
  383. mapping[key].text = element.text
  384. except KeyError: # Not in the mapping, so simply add it
  385. mapping[key] = element
  386. first.append(element)
  387. def clearData(self):
  388. self._metadata = {
  389. "id": self.getId(),
  390. "name": ""
  391. }
  392. self._definition = None
  393. self._instances = {}
  394. self._read_only = False
  395. self._dirty = False
  396. self._path = ""
  397. @classmethod
  398. def getConfigurationTypeFromSerialized(cls, serialized: str) -> Optional[str]:
  399. return "materials"
  400. @classmethod
  401. def getVersionFromSerialized(cls, serialized: str) -> int:
  402. data = ET.fromstring(serialized)
  403. version = XmlMaterialProfile.Version
  404. # get setting version
  405. if "version" in data.attrib:
  406. setting_version = cls.xmlVersionToSettingVersion(data.attrib["version"])
  407. else:
  408. setting_version = cls.xmlVersionToSettingVersion("1.2")
  409. return version * 1000000 + setting_version
  410. @classmethod
  411. def getMetadataFromSerialized(cls, serialized: str, property_name: str) -> str:
  412. data = ET.fromstring(serialized)
  413. metadata = data.find("./um:metadata", cls.__namespaces)
  414. property = metadata.find("./um:" + property_name, cls.__namespaces)
  415. # This is a necessary property != None check, xml library overrides __bool__ to return False in cases when Element is not None.
  416. return property.text if property != None else ""
  417. def deserialize(self, serialized, file_name = None):
  418. """Overridden from InstanceContainer"""
  419. containers_to_add = []
  420. # update the serialized data first
  421. from UM.Settings.Interfaces import ContainerInterface
  422. serialized = ContainerInterface.deserialize(self, serialized, file_name)
  423. try:
  424. data = ET.fromstring(serialized)
  425. except:
  426. Logger.logException("e", "An exception occurred while parsing the material profile")
  427. return
  428. # Reset previous metadata
  429. old_id = self.getId()
  430. self.clearData() # Ensure any previous data is gone.
  431. meta_data = {}
  432. meta_data["type"] = "material"
  433. meta_data["base_file"] = self.getId()
  434. meta_data["status"] = "unknown" # TODO: Add material verification
  435. meta_data["id"] = old_id
  436. meta_data["container_type"] = XmlMaterialProfile
  437. meta_data["reserialize_settings"] = {}
  438. common_setting_values = {}
  439. inherits = data.find("./um:inherits", self.__namespaces)
  440. if inherits is not None:
  441. inherited = self._resolveInheritance(inherits.text)
  442. data = self._mergeXML(inherited, data)
  443. # set setting_version in metadata
  444. if "version" in data.attrib:
  445. meta_data["setting_version"] = self.xmlVersionToSettingVersion(data.attrib["version"])
  446. else:
  447. meta_data["setting_version"] = self.xmlVersionToSettingVersion("1.2") #1.2 and lower didn't have that version number there yet.
  448. meta_data["name"] = "Unknown Material" #In case the name tag is missing.
  449. for entry in data.iterfind("./um:metadata/*", self.__namespaces):
  450. tag_name = _tag_without_namespace(entry)
  451. if tag_name == "name":
  452. brand = entry.find("./um:brand", self.__namespaces)
  453. material = entry.find("./um:material", self.__namespaces)
  454. color = entry.find("./um:color", self.__namespaces)
  455. label = entry.find("./um:label", self.__namespaces)
  456. if label is not None and label.text is not None:
  457. meta_data["name"] = label.text
  458. else:
  459. meta_data["name"] = self._profile_name(material.text, color.text)
  460. meta_data["brand"] = brand.text if brand.text is not None else "Unknown Brand"
  461. meta_data["material"] = material.text if material.text is not None else "Unknown Type"
  462. meta_data["color_name"] = color.text if color.text is not None else "Unknown Color"
  463. continue
  464. # setting_version is derived from the "version" tag in the schema earlier, so don't set it here
  465. if tag_name == "setting_version":
  466. continue
  467. meta_data[tag_name] = entry.text
  468. for tag_name, value in meta_data.items():
  469. if tag_name in self.__material_metadata_setting_map:
  470. common_setting_values[self.__material_metadata_setting_map[tag_name]] = value
  471. if "description" not in meta_data:
  472. meta_data["description"] = ""
  473. if "adhesion_info" not in meta_data:
  474. meta_data["adhesion_info"] = ""
  475. validation_message = XmlMaterialValidator.validateMaterialMetaData(meta_data)
  476. if validation_message is not None:
  477. ConfigurationErrorMessage.getInstance().addFaultyContainers(self.getId())
  478. Logger.log("e", "Not a valid material profile: {message}".format(message = validation_message))
  479. return
  480. property_values = {}
  481. properties = data.iterfind("./um:properties/*", self.__namespaces)
  482. for entry in properties:
  483. tag_name = _tag_without_namespace(entry)
  484. property_values[tag_name] = entry.text
  485. if tag_name in self.__material_properties_setting_map:
  486. common_setting_values[self.__material_properties_setting_map[tag_name]] = entry.text
  487. meta_data["approximate_diameter"] = str(round(float(property_values.get("diameter", 2.85)))) # In mm
  488. meta_data["properties"] = property_values
  489. meta_data["definition"] = "fdmprinter"
  490. common_compatibility = True
  491. settings = data.iterfind("./um:settings/um:setting", self.__namespaces)
  492. for entry in settings:
  493. key = entry.get("key")
  494. if key in self.__material_settings_setting_map:
  495. if key == "processing temperature graph": #This setting has no setting text but subtags.
  496. graph_nodes = entry.iterfind("./um:point", self.__namespaces)
  497. graph_points = []
  498. for graph_node in graph_nodes:
  499. flow = float(graph_node.get("flow"))
  500. temperature = float(graph_node.get("temperature"))
  501. graph_points.append([flow, temperature])
  502. common_setting_values[self.__material_settings_setting_map[key]] = str(graph_points)
  503. else:
  504. common_setting_values[self.__material_settings_setting_map[key]] = entry.text
  505. elif key in self.__unmapped_settings:
  506. if key == "hardware compatible":
  507. common_compatibility = self._parseCompatibleValue(entry.text)
  508. elif key in self.__keep_serialized_settings:
  509. meta_data["reserialize_settings"][key] = entry.text
  510. # Add namespaced Cura-specific settings
  511. settings = data.iterfind("./um:settings/cura:setting", self.__namespaces)
  512. for entry in settings:
  513. value = entry.text
  514. if value.lower() == "yes":
  515. value = True
  516. elif value.lower() == "no":
  517. value = False
  518. key = entry.get("key")
  519. common_setting_values[key] = value
  520. self._cached_values = common_setting_values # from InstanceContainer ancestor
  521. meta_data["compatible"] = common_compatibility
  522. self.setMetaData(meta_data)
  523. self._dirty = False
  524. # Map machine human-readable names to IDs
  525. product_id_map = self.getProductIdMap()
  526. machines = data.iterfind("./um:settings/um:machine", self.__namespaces)
  527. for machine in machines:
  528. machine_compatibility = common_compatibility
  529. machine_setting_values = {}
  530. settings = machine.iterfind("./um:setting", self.__namespaces)
  531. machine_reserialize_settings = {}
  532. for entry in settings:
  533. key = entry.get("key")
  534. if key in self.__material_settings_setting_map:
  535. if key == "processing temperature graph": #This setting has no setting text but subtags.
  536. graph_nodes = entry.iterfind("./um:point", self.__namespaces)
  537. graph_points = []
  538. for graph_node in graph_nodes:
  539. flow = float(graph_node.get("flow"))
  540. temperature = float(graph_node.get("temperature"))
  541. graph_points.append([flow, temperature])
  542. machine_setting_values[self.__material_settings_setting_map[key]] = str(graph_points)
  543. else:
  544. machine_setting_values[self.__material_settings_setting_map[key]] = entry.text
  545. elif key in self.__unmapped_settings:
  546. if key == "hardware compatible":
  547. machine_compatibility = self._parseCompatibleValue(entry.text)
  548. elif key in self.__keep_serialized_settings:
  549. machine_reserialize_settings[key] = entry.text
  550. else:
  551. Logger.log("d", "Unsupported material setting %s", key)
  552. # Add namespaced Cura-specific settings
  553. settings = machine.iterfind("./cura:setting", self.__namespaces)
  554. for entry in settings:
  555. value = entry.text
  556. if value.lower() == "yes":
  557. value = True
  558. elif value.lower() == "no":
  559. value = False
  560. key = entry.get("key")
  561. machine_setting_values[key] = value
  562. cached_machine_setting_properties = common_setting_values.copy()
  563. cached_machine_setting_properties.update(machine_setting_values)
  564. identifiers = machine.iterfind("./um:machine_identifier", self.__namespaces)
  565. for identifier in identifiers:
  566. machine_id_list = product_id_map.get(identifier.get("product"), [])
  567. if not machine_id_list:
  568. machine_id_list = self.getPossibleDefinitionIDsFromName(identifier.get("product"))
  569. for machine_id in machine_id_list:
  570. definitions = ContainerRegistry.getInstance().findDefinitionContainersMetadata(id = machine_id)
  571. if not definitions:
  572. continue
  573. definition = definitions[0]
  574. machine_manufacturer = identifier.get("manufacturer", definition.get("manufacturer", "Unknown")) #If the XML material doesn't specify a manufacturer, use the one in the actual printer definition.
  575. # Always create the instance of the material even if it is not compatible, otherwise it will never
  576. # show as incompatible if the material profile doesn't define hotends in the machine - CURA-5444
  577. new_material_id = self.getId() + "_" + machine_id
  578. # The child or derived material container may already exist. This can happen when a material in a
  579. # project file and the a material in Cura have the same ID.
  580. # In the case if a derived material already exists, override that material container because if
  581. # the data in the parent material has been changed, the derived ones should be updated too.
  582. if ContainerRegistry.getInstance().isLoaded(new_material_id):
  583. new_material = ContainerRegistry.getInstance().findContainers(id = new_material_id)[0]
  584. is_new_material = False
  585. else:
  586. new_material = XmlMaterialProfile(new_material_id)
  587. is_new_material = True
  588. new_material.setMetaData(copy.deepcopy(self.getMetaData()))
  589. new_material.getMetaData()["id"] = new_material_id
  590. new_material.getMetaData()["name"] = self.getName()
  591. new_material.setDefinition(machine_id)
  592. # Don't use setMetadata, as that overrides it for all materials with same base file
  593. new_material.getMetaData()["compatible"] = machine_compatibility
  594. new_material.getMetaData()["machine_manufacturer"] = machine_manufacturer
  595. new_material.getMetaData()["definition"] = machine_id
  596. new_material.getMetaData()["reserialize_settings"] = machine_reserialize_settings
  597. new_material.setCachedValues(cached_machine_setting_properties)
  598. new_material._dirty = False
  599. if is_new_material:
  600. containers_to_add.append(new_material)
  601. hotends = machine.iterfind("./um:hotend", self.__namespaces)
  602. for hotend in hotends:
  603. # The "id" field for hotends in material profiles is actually name
  604. hotend_name = hotend.get("id")
  605. if hotend_name is None:
  606. continue
  607. hotend_mapped_settings, hotend_unmapped_settings, hotend_reserialize_settings = self._getSettingsDictForNode(hotend)
  608. hotend_compatibility = hotend_unmapped_settings.get("hardware compatible", machine_compatibility)
  609. # Generate container ID for the hotend-specific material container
  610. new_hotend_specific_material_id = self.getId() + "_" + machine_id + "_" + hotend_name.replace(" ", "_")
  611. # Same as machine compatibility, keep the derived material containers consistent with the parent material
  612. if ContainerRegistry.getInstance().isLoaded(new_hotend_specific_material_id):
  613. new_hotend_material = ContainerRegistry.getInstance().findContainers(id = new_hotend_specific_material_id)[0]
  614. is_new_material = False
  615. else:
  616. new_hotend_material = XmlMaterialProfile(new_hotend_specific_material_id)
  617. is_new_material = True
  618. new_hotend_material.setMetaData(copy.deepcopy(self.getMetaData()))
  619. new_hotend_material.getMetaData()["id"] = new_hotend_specific_material_id
  620. new_hotend_material.getMetaData()["name"] = self.getName()
  621. new_hotend_material.getMetaData()["variant_name"] = hotend_name
  622. new_hotend_material.setDefinition(machine_id)
  623. # Don't use setMetadata, as that overrides it for all materials with same base file
  624. new_hotend_material.getMetaData()["compatible"] = hotend_compatibility
  625. new_hotend_material.getMetaData()["machine_manufacturer"] = machine_manufacturer
  626. new_hotend_material.getMetaData()["definition"] = machine_id
  627. new_hotend_material.getMetaData()["reserialize_settings"] = hotend_reserialize_settings
  628. cached_hotend_setting_properties = cached_machine_setting_properties.copy()
  629. cached_hotend_setting_properties.update(hotend_mapped_settings)
  630. new_hotend_material.setCachedValues(cached_hotend_setting_properties)
  631. new_hotend_material._dirty = False
  632. if is_new_material:
  633. if ContainerRegistry.getInstance().isReadOnly(self.getId()):
  634. ContainerRegistry.getInstance().setExplicitReadOnly(new_hotend_material.getId())
  635. containers_to_add.append(new_hotend_material)
  636. # there is only one ID for a machine. Once we have reached here, it means we have already found
  637. # a workable ID for that machine, so there is no need to continue
  638. break
  639. for container_to_add in containers_to_add:
  640. ContainerRegistry.getInstance().addContainer(container_to_add)
  641. @classmethod
  642. def _getSettingsDictForNode(cls, node) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any]]:
  643. node_mapped_settings_dict: Dict[str, Any] = dict()
  644. node_unmapped_settings_dict: Dict[str, Any] = dict()
  645. node_reserialize_settings_dict: Dict[str, Any] = dict()
  646. # Fetch settings in the "um" namespace
  647. um_settings = node.iterfind("./um:setting", cls.__namespaces)
  648. for um_setting_entry in um_settings:
  649. setting_key = um_setting_entry.get("key")
  650. # Mapped settings
  651. if setting_key in cls.__material_settings_setting_map:
  652. if setting_key == "processing temperature graph": # This setting has no setting text but subtags.
  653. graph_nodes = um_setting_entry.iterfind("./um:point", cls.__namespaces)
  654. graph_points = []
  655. for graph_node in graph_nodes:
  656. flow = float(graph_node.get("flow"))
  657. temperature = float(graph_node.get("temperature"))
  658. graph_points.append([flow, temperature])
  659. node_mapped_settings_dict[cls.__material_settings_setting_map[setting_key]] = str(
  660. graph_points)
  661. else:
  662. node_mapped_settings_dict[cls.__material_settings_setting_map[setting_key]] = um_setting_entry.text
  663. # Unmapped settings
  664. elif setting_key in cls.__unmapped_settings:
  665. if setting_key in ("hardware compatible", "hardware recommended"):
  666. node_unmapped_settings_dict[setting_key] = cls._parseCompatibleValue(um_setting_entry.text)
  667. # Settings unused by Cura itself, but which need reserialization since they might be important to others.
  668. elif setting_key in cls.__keep_serialized_settings:
  669. node_reserialize_settings_dict[setting_key] = um_setting_entry.text
  670. # Unknown settings
  671. else:
  672. Logger.log("w", "Unsupported material setting %s", setting_key)
  673. # Fetch settings in the "cura" namespace
  674. cura_settings = node.iterfind("./cura:setting", cls.__namespaces)
  675. for cura_setting_entry in cura_settings:
  676. value = cura_setting_entry.text
  677. if value.lower() == "yes":
  678. value = True
  679. elif value.lower() == "no":
  680. value = False
  681. key = cura_setting_entry.get("key")
  682. # Cura settings are all mapped
  683. node_mapped_settings_dict[key] = value
  684. return node_mapped_settings_dict, node_unmapped_settings_dict, node_reserialize_settings_dict
  685. @classmethod
  686. def deserializeMetadata(cls, serialized: str, container_id: str) -> List[Dict[str, Any]]:
  687. result_metadata = [] #All the metadata that we found except the base (because the base is returned).
  688. #Update the serialized data to the latest version.
  689. serialized = cls._updateSerialized(serialized)
  690. base_metadata = {
  691. "type": "material",
  692. "status": "unknown", #TODO: Add material verification.
  693. "container_type": XmlMaterialProfile,
  694. "id": container_id,
  695. "base_file": container_id
  696. }
  697. try:
  698. data = ET.fromstring(serialized)
  699. except:
  700. Logger.logException("e", "An exception occurred while parsing the material profile")
  701. return []
  702. #TODO: Implement the <inherits> tag. It's unused at the moment though.
  703. if "version" in data.attrib:
  704. base_metadata["setting_version"] = cls.xmlVersionToSettingVersion(data.attrib["version"])
  705. else:
  706. base_metadata["setting_version"] = cls.xmlVersionToSettingVersion("1.2") #1.2 and lower didn't have that version number there yet.
  707. for entry in data.iterfind("./um:metadata/*", cls.__namespaces):
  708. tag_name = _tag_without_namespace(entry)
  709. if tag_name == "name":
  710. brand = entry.find("./um:brand", cls.__namespaces)
  711. material = entry.find("./um:material", cls.__namespaces)
  712. color = entry.find("./um:color", cls.__namespaces)
  713. label = entry.find("./um:label", cls.__namespaces)
  714. if label is not None and label.text is not None:
  715. base_metadata["name"] = label.text
  716. else:
  717. if material is not None and color is not None:
  718. base_metadata["name"] = cls._profile_name(material.text, color.text)
  719. else:
  720. base_metadata["name"] = "Unknown Material"
  721. base_metadata["brand"] = brand.text if brand is not None and brand.text is not None else "Unknown Brand"
  722. base_metadata["material"] = material.text if material is not None and material.text is not None else "Unknown Type"
  723. base_metadata["color_name"] = color.text if color is not None and color.text is not None else "Unknown Color"
  724. continue
  725. #Setting_version is derived from the "version" tag in the schema earlier, so don't set it here.
  726. if tag_name == "setting_version":
  727. continue
  728. base_metadata[tag_name] = entry.text
  729. if "description" not in base_metadata:
  730. base_metadata["description"] = ""
  731. if "adhesion_info" not in base_metadata:
  732. base_metadata["adhesion_info"] = ""
  733. property_values = {}
  734. properties = data.iterfind("./um:properties/*", cls.__namespaces)
  735. for entry in properties:
  736. tag_name = _tag_without_namespace(entry)
  737. property_values[tag_name] = entry.text
  738. base_metadata["approximate_diameter"] = str(round(float(cast(float, property_values.get("diameter", 2.85))))) # In mm
  739. base_metadata["properties"] = property_values
  740. base_metadata["definition"] = "fdmprinter"
  741. # Certain materials are loaded but should not be visible / selectable to the user.
  742. base_metadata["visible"] = not base_metadata.get("abstract_color", False)
  743. compatible_entries = data.iterfind("./um:settings/um:setting[@key='hardware compatible']", cls.__namespaces)
  744. try:
  745. common_compatibility = cls._parseCompatibleValue(next(compatible_entries).text) # type: ignore
  746. except StopIteration: #No 'hardware compatible' setting.
  747. common_compatibility = True
  748. base_metadata["compatible"] = common_compatibility
  749. result_metadata.append(base_metadata)
  750. # Map machine human-readable names to IDs
  751. product_id_map = cls.getProductIdMap()
  752. for machine in data.iterfind("./um:settings/um:machine", cls.__namespaces):
  753. machine_compatibility = common_compatibility
  754. for entry in machine.iterfind("./um:setting[@key='hardware compatible']", cls.__namespaces):
  755. if entry.text is not None:
  756. machine_compatibility = cls._parseCompatibleValue(entry.text)
  757. for identifier in machine.iterfind("./um:machine_identifier", cls.__namespaces):
  758. machine_id_list = product_id_map.get(identifier.get("product", ""), [])
  759. if not machine_id_list:
  760. machine_id_list = cls.getPossibleDefinitionIDsFromName(identifier.get("product"))
  761. for machine_id in machine_id_list:
  762. definition_metadatas = ContainerRegistry.getInstance().findDefinitionContainersMetadata(id = machine_id)
  763. if not definition_metadatas:
  764. continue
  765. definition_metadata = definition_metadatas[0]
  766. machine_manufacturer = identifier.get("manufacturer", definition_metadata.get("manufacturer", "Unknown")) #If the XML material doesn't specify a manufacturer, use the one in the actual printer definition.
  767. # Always create the instance of the material even if it is not compatible, otherwise it will never
  768. # show as incompatible if the material profile doesn't define hotends in the machine - CURA-5444
  769. new_material_id = container_id + "_" + machine_id
  770. # Do not look for existing container/container metadata with the same ID although they may exist.
  771. # In project loading and perhaps some other places, we only want to get information (metadata)
  772. # from a file without changing the current state of the system. If we overwrite the existing
  773. # metadata here, deserializeMetadata() will not be safe for retrieving information.
  774. new_material_metadata = {}
  775. new_material_metadata.update(base_metadata)
  776. new_material_metadata["id"] = new_material_id
  777. new_material_metadata["compatible"] = machine_compatibility
  778. new_material_metadata["machine_manufacturer"] = machine_manufacturer
  779. new_material_metadata["definition"] = machine_id
  780. result_metadata.append(new_material_metadata)
  781. buildplates = machine.iterfind("./um:buildplate", cls.__namespaces)
  782. buildplate_map = {} # type: Dict[str, Dict[str, bool]]
  783. buildplate_map["buildplate_compatible"] = {}
  784. buildplate_map["buildplate_recommended"] = {}
  785. for buildplate in buildplates:
  786. buildplate_id = buildplate.get("id")
  787. if buildplate_id is None:
  788. continue
  789. variant_metadata = ContainerRegistry.getInstance().findInstanceContainersMetadata(id = buildplate_id)
  790. if not variant_metadata:
  791. # It is not really properly defined what "ID" is so also search for variants by name.
  792. variant_metadata = ContainerRegistry.getInstance().findInstanceContainersMetadata(definition = machine_id, name = buildplate_id)
  793. if not variant_metadata:
  794. continue
  795. settings = buildplate.iterfind("./um:setting", cls.__namespaces)
  796. buildplate_compatibility = True
  797. buildplate_recommended = True
  798. for entry in settings:
  799. key = entry.get("key")
  800. if entry.text is not None:
  801. if key == "hardware compatible":
  802. buildplate_compatibility = cls._parseCompatibleValue(entry.text)
  803. elif key == "hardware recommended":
  804. buildplate_recommended = cls._parseCompatibleValue(entry.text)
  805. buildplate_map["buildplate_compatible"][buildplate_id] = buildplate_compatibility
  806. buildplate_map["buildplate_recommended"][buildplate_id] = buildplate_recommended
  807. for hotend in machine.iterfind("./um:hotend", cls.__namespaces):
  808. hotend_name = hotend.get("id")
  809. if hotend_name is None:
  810. continue
  811. hotend_compatibility = machine_compatibility
  812. for entry in hotend.iterfind("./um:setting[@key='hardware compatible']", cls.__namespaces):
  813. if entry.text is not None:
  814. hotend_compatibility = cls._parseCompatibleValue(entry.text)
  815. new_hotend_specific_material_id = container_id + "_" + machine_id + "_" + hotend_name.replace(" ", "_")
  816. # Same as above, do not overwrite existing metadata.
  817. new_hotend_material_metadata = {}
  818. new_hotend_material_metadata.update(base_metadata)
  819. new_hotend_material_metadata["variant_name"] = hotend_name
  820. new_hotend_material_metadata["compatible"] = hotend_compatibility
  821. new_hotend_material_metadata["machine_manufacturer"] = machine_manufacturer
  822. new_hotend_material_metadata["id"] = new_hotend_specific_material_id
  823. new_hotend_material_metadata["definition"] = machine_id
  824. if buildplate_map["buildplate_compatible"]:
  825. new_hotend_material_metadata["buildplate_compatible"] = buildplate_map["buildplate_compatible"]
  826. new_hotend_material_metadata["buildplate_recommended"] = buildplate_map["buildplate_recommended"]
  827. result_metadata.append(new_hotend_material_metadata)
  828. #
  829. # Buildplates in Hotends
  830. #
  831. buildplates = hotend.iterfind("./um:buildplate", cls.__namespaces)
  832. for buildplate in buildplates:
  833. # The "id" field for buildplate in material profiles is actually name
  834. buildplate_name = buildplate.get("id")
  835. if buildplate_name is None:
  836. continue
  837. buildplate_mapped_settings, buildplate_unmapped_settings, buildplate_reserialize_settings = cls._getSettingsDictForNode(buildplate)
  838. buildplate_compatibility = buildplate_unmapped_settings.get("hardware compatible",
  839. buildplate_map["buildplate_compatible"])
  840. buildplate_recommended = buildplate_unmapped_settings.get("hardware recommended",
  841. buildplate_map["buildplate_recommended"])
  842. # Generate container ID for the hotend-and-buildplate-specific material container
  843. new_hotend_and_buildplate_specific_material_id = new_hotend_specific_material_id + "_" + buildplate_name.replace(
  844. " ", "_")
  845. new_hotend_and_buildplate_material_metadata = {}
  846. new_hotend_and_buildplate_material_metadata.update(new_hotend_material_metadata)
  847. new_hotend_and_buildplate_material_metadata["id"] = new_hotend_and_buildplate_specific_material_id
  848. new_hotend_and_buildplate_material_metadata["buildplate_name"] = buildplate_name
  849. new_hotend_and_buildplate_material_metadata["compatible"] = buildplate_compatibility
  850. new_hotend_and_buildplate_material_metadata["buildplate_compatible"] = buildplate_compatibility
  851. new_hotend_and_buildplate_material_metadata["buildplate_recommended"] = buildplate_recommended
  852. new_hotend_and_buildplate_material_metadata["reserialize_settings"] = buildplate_reserialize_settings
  853. result_metadata.append(new_hotend_and_buildplate_material_metadata)
  854. # there is only one ID for a machine. Once we have reached here, it means we have already found
  855. # a workable ID for that machine, so there is no need to continue
  856. break
  857. return result_metadata
  858. def _addSettingElement(self, builder, instance):
  859. key = instance.definition.key
  860. if key in self.__material_settings_setting_map.values():
  861. # Setting has a key in the standard namespace
  862. key = UM.Dictionary.findKey(self.__material_settings_setting_map, instance.definition.key)
  863. tag_name = "setting"
  864. if key == "processing temperature graph": #The Processing Temperature Graph has its own little structure that we need to implement separately.
  865. builder.start(tag_name, {"key": key})
  866. graph_str = str(instance.value)
  867. graph = graph_str.replace("[", "").replace("]", "").split(", ") #Crude parsing of this list: Flatten the list by removing all brackets, then split on ", ". Safe to eval attacks though!
  868. graph = [graph[i:i + 2] for i in range(0, len(graph) - 1, 2)] #Convert to 2D array.
  869. for point in graph:
  870. builder.start("point", {"flow": point[0], "temperature": point[1]})
  871. builder.end("point")
  872. builder.end(tag_name)
  873. return
  874. elif key not in self.__material_properties_setting_map.values() and key not in self.__material_metadata_setting_map.values():
  875. # Setting is not in the standard namespace, and not a material property (eg diameter) or metadata (eg GUID)
  876. tag_name = "cura:setting"
  877. else:
  878. # Skip material properties (eg diameter) or metadata (eg GUID)
  879. return
  880. truth_map = { True: "yes", False: "no" }
  881. if tag_name != "cura:setting" and instance.value in truth_map:
  882. data = truth_map[instance.value]
  883. else:
  884. data = str(instance.value)
  885. builder.start(tag_name, { "key": key })
  886. builder.data(data)
  887. builder.end(tag_name)
  888. @staticmethod
  889. def _profile_name(material_name, color_name):
  890. if material_name is None:
  891. return "Unknown Material"
  892. if color_name != "Generic":
  893. return "%s %s" % (color_name, material_name)
  894. else:
  895. return material_name
  896. @staticmethod
  897. def getPossibleDefinitionIDsFromName(name):
  898. name_parts = name.lower().split(" ")
  899. merged_name_parts = []
  900. for part in name_parts:
  901. if len(part) == 0:
  902. continue
  903. if len(merged_name_parts) == 0:
  904. merged_name_parts.append(part)
  905. continue
  906. if part.isdigit():
  907. # for names with digit(s) such as Ultimaker 3 Extended, we generate an ID like
  908. # "ultimaker3_extended", ignoring the space between "Ultimaker" and "3".
  909. merged_name_parts[-1] = merged_name_parts[-1] + part
  910. else:
  911. merged_name_parts.append(part)
  912. id_list = {name.lower().replace(" ", ""), # simply removing all spaces
  913. name.lower().replace(" ", "_"), # simply replacing all spaces with underscores
  914. "_".join(merged_name_parts),
  915. name.replace(" ", ""),
  916. name.replace(" ", "_")
  917. }
  918. id_list = list(id_list)
  919. return id_list
  920. __product_to_id_map: Optional[Dict[str, List[str]]] = None
  921. @classmethod
  922. def getProductIdMap(cls) -> Dict[str, List[str]]:
  923. """Gets a mapping from product names in the XML files to their definition IDs.
  924. This loads the mapping from a file.
  925. """
  926. if cls.__product_to_id_map is not None:
  927. return cls.__product_to_id_map
  928. plugin_path = cast(str, PluginRegistry.getInstance().getPluginPath("XmlMaterialProfile"))
  929. product_to_id_file = os.path.join(plugin_path, "product_to_id.json")
  930. with open(product_to_id_file, encoding = "utf-8") as f:
  931. contents = ""
  932. for line in f:
  933. contents += line if "#" not in line else "".join([line.replace("#", str(n)) for n in range(1, 12)])
  934. cls.__product_to_id_map = json.loads(contents)
  935. cls.__product_to_id_map = {key: [value] for key, value in cls.__product_to_id_map.items()}
  936. #This also loads "Ultimaker S5" -> "ultimaker_s5" even though that is not strictly necessary with the default to change spaces into underscores.
  937. #However it is not always loaded with that default; this mapping is also used in serialize() without that default.
  938. return cls.__product_to_id_map
  939. @staticmethod
  940. def _parseCompatibleValue(value: str):
  941. """Parse the value of the "material compatible" property."""
  942. return value in {"yes", "unknown"}
  943. def __str__(self):
  944. """Small string representation for debugging."""
  945. return "<XmlMaterialProfile '{my_id}' ('{name}') from base file '{base_file}'>".format(my_id = self.getId(), name = self.getName(), base_file = self.getMetaDataEntry("base_file"))
  946. _metadata_tags_that_have_cura_namespace = {"pva_compatible", "breakaway_compatible"}
  947. # Map XML file setting names to internal names
  948. __material_settings_setting_map = {
  949. "print temperature": "default_material_print_temperature",
  950. "heated bed temperature": "default_material_bed_temperature",
  951. "standby temperature": "material_standby_temperature",
  952. "processing temperature graph": "material_flow_temp_graph",
  953. "print cooling": "cool_fan_speed",
  954. "retraction amount": "retraction_amount",
  955. "retraction speed": "retraction_speed",
  956. "adhesion tendency": "material_adhesion_tendency",
  957. "surface energy": "material_surface_energy",
  958. "build volume temperature": "build_volume_temperature",
  959. "anti ooze retract position": "material_anti_ooze_retracted_position",
  960. "anti ooze retract speed": "material_anti_ooze_retraction_speed",
  961. "break preparation position": "material_break_preparation_retracted_position",
  962. "break preparation speed": "material_break_preparation_speed",
  963. "break preparation temperature": "material_break_preparation_temperature",
  964. "break position": "material_break_retracted_position",
  965. "flush purge speed": "material_flush_purge_speed",
  966. "flush purge length": "material_flush_purge_length",
  967. "end of filament purge speed": "material_end_of_filament_purge_speed",
  968. "end of filament purge length": "material_end_of_filament_purge_length",
  969. "maximum park duration": "material_maximum_park_duration",
  970. "no load move factor": "material_no_load_move_factor",
  971. "break speed": "material_break_speed",
  972. "break temperature": "material_break_temperature"
  973. } # type: Dict[str, str]
  974. __unmapped_settings = [
  975. "hardware compatible",
  976. "hardware recommended"
  977. ]
  978. __keep_serialized_settings = { # Settings irrelevant to Cura, but that could be present in the files so we must store them and keep them serialized.
  979. "relative extrusion",
  980. "flow sensor detection margin",
  981. "different material purge volume",
  982. "same material purge volume",
  983. "end of print purge volume",
  984. "end of filament purge volume",
  985. "purge anti ooze retract position",
  986. "purge drop retract position",
  987. "purge retract speed",
  988. "purge unretract speed",
  989. "purge anti ooze dwell time",
  990. "purge drop dwell time",
  991. "dwell time before break preparation move",
  992. "pressure release dwell time",
  993. "tainted print core max temperature",
  994. "recommend cleaning after n prints",
  995. "maximum heated bed temperature",
  996. "material bed adhesion temperature",
  997. "maximum heated chamber temperature",
  998. "shrinkage percentage",
  999. "move to die distance",
  1000. }
  1001. __material_properties_setting_map = {
  1002. "diameter": "material_diameter"
  1003. }
  1004. __material_metadata_setting_map = {
  1005. "GUID": "material_guid",
  1006. "material": "material_type",
  1007. "brand": "material_brand",
  1008. }
  1009. # Map of recognised namespaces with a proper prefix.
  1010. __namespaces = {
  1011. "um": "http://www.ultimaker.com/material",
  1012. "cura": "http://www.ultimaker.com/cura"
  1013. }
  1014. def _indent(elem, level = 0):
  1015. """Helper function for pretty-printing XML because ETree is stupid"""
  1016. i = "\n" + level * " "
  1017. if len(elem):
  1018. if not elem.text or not elem.text.strip():
  1019. elem.text = i + " "
  1020. if not elem.tail or not elem.tail.strip():
  1021. elem.tail = i
  1022. for elem in elem:
  1023. _indent(elem, level + 1)
  1024. if not elem.tail or not elem.tail.strip():
  1025. elem.tail = i
  1026. else:
  1027. if level and (not elem.tail or not elem.tail.strip()):
  1028. elem.tail = i
  1029. # The namespace is prepended to the tag name but between {}.
  1030. # We are only interested in the actual tag name, so discard everything
  1031. # before the last }
  1032. def _tag_without_namespace(element):
  1033. return element.tag[element.tag.rfind("}") + 1:]