XmlMaterialProfile.py 61 KB

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