XmlMaterialProfile.py 63 KB

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