XmlMaterialProfile.py 58 KB

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