XmlMaterialProfile.py 61 KB

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