XmlMaterialProfile.py 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  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. if instance.value is True:
  881. data = "yes"
  882. elif instance.value is False:
  883. data = "no"
  884. else:
  885. data = str(instance.value)
  886. builder.start(tag_name, { "key": key })
  887. builder.data(data)
  888. builder.end(tag_name)
  889. @staticmethod
  890. def _profile_name(material_name, color_name):
  891. if material_name is None:
  892. return "Unknown Material"
  893. if color_name != "Generic":
  894. return "%s %s" % (color_name, material_name)
  895. else:
  896. return material_name
  897. @staticmethod
  898. def getPossibleDefinitionIDsFromName(name):
  899. name_parts = name.lower().split(" ")
  900. merged_name_parts = []
  901. for part in name_parts:
  902. if len(part) == 0:
  903. continue
  904. if len(merged_name_parts) == 0:
  905. merged_name_parts.append(part)
  906. continue
  907. if part.isdigit():
  908. # for names with digit(s) such as Ultimaker 3 Extended, we generate an ID like
  909. # "ultimaker3_extended", ignoring the space between "Ultimaker" and "3".
  910. merged_name_parts[-1] = merged_name_parts[-1] + part
  911. else:
  912. merged_name_parts.append(part)
  913. id_list = {name.lower().replace(" ", ""), # simply removing all spaces
  914. name.lower().replace(" ", "_"), # simply replacing all spaces with underscores
  915. "_".join(merged_name_parts),
  916. name.replace(" ", ""),
  917. name.replace(" ", "_")
  918. }
  919. id_list = list(id_list)
  920. return id_list
  921. __product_to_id_map: Optional[Dict[str, List[str]]] = None
  922. @classmethod
  923. def getProductIdMap(cls) -> Dict[str, List[str]]:
  924. """Gets a mapping from product names in the XML files to their definition IDs.
  925. This loads the mapping from a file.
  926. """
  927. if cls.__product_to_id_map is not None:
  928. return cls.__product_to_id_map
  929. plugin_path = cast(str, PluginRegistry.getInstance().getPluginPath("XmlMaterialProfile"))
  930. product_to_id_file = os.path.join(plugin_path, "product_to_id.json")
  931. with open(product_to_id_file, encoding = "utf-8") as f:
  932. contents = ""
  933. for line in f:
  934. contents += line if "#" not in line else "".join([line.replace("#", str(n)) for n in range(1, 12)])
  935. cls.__product_to_id_map = json.loads(contents)
  936. cls.__product_to_id_map = {key: [value] for key, value in cls.__product_to_id_map.items()}
  937. #This also loads "Ultimaker S5" -> "ultimaker_s5" even though that is not strictly necessary with the default to change spaces into underscores.
  938. #However it is not always loaded with that default; this mapping is also used in serialize() without that default.
  939. return cls.__product_to_id_map
  940. @staticmethod
  941. def _parseCompatibleValue(value: str):
  942. """Parse the value of the "material compatible" property."""
  943. return value in {"yes", "unknown"}
  944. def __str__(self):
  945. """Small string representation for debugging."""
  946. return "<XmlMaterialProfile '{my_id}' ('{name}') from base file '{base_file}'>".format(my_id = self.getId(), name = self.getName(), base_file = self.getMetaDataEntry("base_file"))
  947. _metadata_tags_that_have_cura_namespace = {"pva_compatible", "breakaway_compatible"}
  948. # Map XML file setting names to internal names
  949. __material_settings_setting_map = {
  950. "print temperature": "default_material_print_temperature",
  951. "heated bed temperature": "default_material_bed_temperature",
  952. "standby temperature": "material_standby_temperature",
  953. "processing temperature graph": "material_flow_temp_graph",
  954. "print cooling": "cool_fan_speed",
  955. "retraction amount": "retraction_amount",
  956. "retraction speed": "retraction_speed",
  957. "adhesion tendency": "material_adhesion_tendency",
  958. "surface energy": "material_surface_energy",
  959. "build volume temperature": "build_volume_temperature",
  960. "anti ooze retract position": "material_anti_ooze_retracted_position",
  961. "anti ooze retract speed": "material_anti_ooze_retraction_speed",
  962. "break preparation position": "material_break_preparation_retracted_position",
  963. "break preparation speed": "material_break_preparation_speed",
  964. "break preparation temperature": "material_break_preparation_temperature",
  965. "break position": "material_break_retracted_position",
  966. "flush purge speed": "material_flush_purge_speed",
  967. "flush purge length": "material_flush_purge_length",
  968. "end of filament purge speed": "material_end_of_filament_purge_speed",
  969. "end of filament purge length": "material_end_of_filament_purge_length",
  970. "maximum park duration": "material_maximum_park_duration",
  971. "no load move factor": "material_no_load_move_factor",
  972. "break speed": "material_break_speed",
  973. "break temperature": "material_break_temperature"
  974. } # type: Dict[str, str]
  975. __unmapped_settings = [
  976. "hardware compatible",
  977. "hardware recommended"
  978. ]
  979. __keep_serialized_settings = { # Settings irrelevant to Cura, but that could be present in the files so we must store them and keep them serialized.
  980. "relative extrusion",
  981. "flow sensor detection margin",
  982. "different material purge volume",
  983. "same material purge volume",
  984. "end of print purge volume",
  985. "end of filament purge volume",
  986. "purge anti ooze retract position",
  987. "purge drop retract position",
  988. "purge retract speed",
  989. "purge unretract speed",
  990. "purge anti ooze dwell time",
  991. "purge drop dwell time",
  992. "dwell time before break preparation move",
  993. "pressure release dwell time",
  994. "tainted print core max temperature",
  995. "recommend cleaning after n prints",
  996. "maximum heated bed temperature",
  997. "material bed adhesion temperature",
  998. "maximum heated chamber temperature",
  999. "shrinkage percentage",
  1000. "move to die distance",
  1001. }
  1002. __material_properties_setting_map = {
  1003. "diameter": "material_diameter"
  1004. }
  1005. __material_metadata_setting_map = {
  1006. "GUID": "material_guid",
  1007. "material": "material_type",
  1008. "brand": "material_brand",
  1009. }
  1010. # Map of recognised namespaces with a proper prefix.
  1011. __namespaces = {
  1012. "um": "http://www.ultimaker.com/material",
  1013. "cura": "http://www.ultimaker.com/cura"
  1014. }
  1015. def _indent(elem, level = 0):
  1016. """Helper function for pretty-printing XML because ETree is stupid"""
  1017. i = "\n" + level * " "
  1018. if len(elem):
  1019. if not elem.text or not elem.text.strip():
  1020. elem.text = i + " "
  1021. if not elem.tail or not elem.tail.strip():
  1022. elem.tail = i
  1023. for elem in elem:
  1024. _indent(elem, level + 1)
  1025. if not elem.tail or not elem.tail.strip():
  1026. elem.tail = i
  1027. else:
  1028. if level and (not elem.tail or not elem.tail.strip()):
  1029. elem.tail = i
  1030. # The namespace is prepended to the tag name but between {}.
  1031. # We are only interested in the actual tag name, so discard everything
  1032. # before the last }
  1033. def _tag_without_namespace(element):
  1034. return element.tag[element.tag.rfind("}") + 1:]