XmlMaterialProfile.py 61 KB

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