XmlMaterialProfile.py 62 KB

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