XmlMaterialProfile.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. # Copyright (c) 2017 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. import copy
  4. import io
  5. from typing import Optional
  6. import xml.etree.ElementTree as ET
  7. from UM.Resources import Resources
  8. from UM.Logger import Logger
  9. from UM.Util import parseBool
  10. from cura.CuraApplication import CuraApplication
  11. import UM.Dictionary
  12. from UM.Settings.InstanceContainer import InstanceContainer, InvalidInstanceError
  13. from UM.Settings.ContainerRegistry import ContainerRegistry
  14. ## Handles serializing and deserializing material containers from an XML file
  15. class XmlMaterialProfile(InstanceContainer):
  16. def __init__(self, container_id, *args, **kwargs):
  17. super().__init__(container_id, *args, **kwargs)
  18. self._inherited_files = []
  19. ## Translates the version number in the XML files to the setting_version
  20. # metadata entry.
  21. #
  22. # Since the two may increment independently we need a way to say which
  23. # versions of the XML specification are compatible with our setting data
  24. # version numbers.
  25. #
  26. # \param xml_version: The version number found in an XML file.
  27. # \return The corresponding setting_version.
  28. def xmlVersionToSettingVersion(self, xml_version: str) -> int:
  29. if xml_version == "1.3":
  30. return 1
  31. return 0 #Older than 1.3.
  32. def getInheritedFiles(self):
  33. return self._inherited_files
  34. ## Overridden from InstanceContainer
  35. def setReadOnly(self, read_only):
  36. super().setReadOnly(read_only)
  37. basefile = self.getMetaDataEntry("base_file", self._id) # if basefile is self.id, this is a basefile.
  38. for container in ContainerRegistry.getInstance().findInstanceContainers(base_file = basefile):
  39. container._read_only = read_only # prevent loop instead of calling setReadOnly
  40. ## Overridden from InstanceContainer
  41. # set the meta data for all machine / variant combinations
  42. def setMetaDataEntry(self, key, value):
  43. if self.isReadOnly():
  44. return
  45. if self.getMetaDataEntry(key, None) == value:
  46. # Prevent recursion caused by for loop.
  47. return
  48. super().setMetaDataEntry(key, value)
  49. basefile = self.getMetaDataEntry("base_file", self._id) #if basefile is self.id, this is a basefile.
  50. # Update all containers that share GUID and basefile
  51. for container in ContainerRegistry.getInstance().findInstanceContainers(base_file = basefile):
  52. container.setMetaDataEntry(key, value)
  53. ## Overridden from InstanceContainer, similar to setMetaDataEntry.
  54. # without this function the setName would only set the name of the specific nozzle / material / machine combination container
  55. # The function is a bit tricky. It will not set the name of all containers if it has the correct name itself.
  56. def setName(self, new_name):
  57. if self.isReadOnly():
  58. return
  59. # Not only is this faster, it also prevents a major loop that causes a stack overflow.
  60. if self.getName() == new_name:
  61. return
  62. super().setName(new_name)
  63. basefile = self.getMetaDataEntry("base_file", self._id) # if basefile is self.id, this is a basefile.
  64. # Update the basefile as well, this is actually what we're trying to do
  65. # Update all containers that share GUID and basefile
  66. containers = ContainerRegistry.getInstance().findInstanceContainers(base_file = basefile)
  67. for container in containers:
  68. container.setName(new_name)
  69. ## Overridden from InstanceContainer, to set dirty to base file as well.
  70. def setDirty(self, dirty):
  71. super().setDirty(dirty)
  72. base_file = self.getMetaDataEntry("base_file", None)
  73. if base_file is not None and base_file != self._id:
  74. containers = ContainerRegistry.getInstance().findContainers(id=base_file)
  75. if containers:
  76. base_container = containers[0]
  77. if not base_container.isReadOnly():
  78. base_container.setDirty(dirty)
  79. ## Overridden from InstanceContainer
  80. # def setProperty(self, key, property_name, property_value, container = None):
  81. # if self.isReadOnly():
  82. # return
  83. #
  84. # super().setProperty(key, property_name, property_value)
  85. #
  86. # basefile = self.getMetaDataEntry("base_file", self._id) #if basefile is self.id, this is a basefile.
  87. # for container in UM.Settings.ContainerRegistry.ContainerRegistry.getInstance().findInstanceContainers(base_file = basefile):
  88. # if not container.isReadOnly():
  89. # container.setDirty(True)
  90. ## Overridden from InstanceContainer
  91. # base file: global settings + supported machines
  92. # machine / variant combination: only changes for itself.
  93. def serialize(self):
  94. registry = ContainerRegistry.getInstance()
  95. base_file = self.getMetaDataEntry("base_file", "")
  96. if base_file and self.id != base_file:
  97. # Since we create an instance of XmlMaterialProfile for each machine and nozzle in the profile,
  98. # we should only serialize the "base" material definition, since that can then take care of
  99. # serializing the machine/nozzle specific profiles.
  100. raise NotImplementedError("Ignoring serializing non-root XML materials, the data is contained in the base material")
  101. builder = ET.TreeBuilder()
  102. root = builder.start("fdmmaterial", { "xmlns": "http://www.ultimaker.com/material"})
  103. ## Begin Metadata Block
  104. builder.start("metadata")
  105. metadata = copy.deepcopy(self.getMetaData())
  106. properties = metadata.pop("properties", {})
  107. # Metadata properties that should not be serialized.
  108. metadata.pop("status", "")
  109. metadata.pop("variant", "")
  110. metadata.pop("type", "")
  111. metadata.pop("base_file", "")
  112. metadata.pop("approximate_diameter", "")
  113. ## Begin Name Block
  114. builder.start("name")
  115. builder.start("brand")
  116. builder.data(metadata.pop("brand", ""))
  117. builder.end("brand")
  118. builder.start("material")
  119. builder.data(metadata.pop("material", ""))
  120. builder.end("material")
  121. builder.start("color")
  122. builder.data(metadata.pop("color_name", ""))
  123. builder.end("color")
  124. builder.start("label")
  125. builder.data(self._name)
  126. builder.end("label")
  127. builder.end("name")
  128. ## End Name Block
  129. for key, value in metadata.items():
  130. builder.start(key)
  131. if value is not None: #Nones get handled well by the builder.
  132. #Otherwise the builder always expects a string.
  133. #Deserialize expects the stringified version.
  134. value = str(value)
  135. builder.data(value)
  136. builder.end(key)
  137. builder.end("metadata")
  138. ## End Metadata Block
  139. ## Begin Properties Block
  140. builder.start("properties")
  141. for key, value in properties.items():
  142. builder.start(key)
  143. builder.data(value)
  144. builder.end(key)
  145. builder.end("properties")
  146. ## End Properties Block
  147. ## Begin Settings Block
  148. builder.start("settings")
  149. if self.getDefinition().id == "fdmprinter":
  150. for instance in self.findInstances():
  151. self._addSettingElement(builder, instance)
  152. machine_container_map = {}
  153. machine_nozzle_map = {}
  154. all_containers = registry.findInstanceContainers(GUID = self.getMetaDataEntry("GUID"), base_file = self._id)
  155. for container in all_containers:
  156. definition_id = container.getDefinition().id
  157. if definition_id == "fdmprinter":
  158. continue
  159. if definition_id not in machine_container_map:
  160. machine_container_map[definition_id] = container
  161. if definition_id not in machine_nozzle_map:
  162. machine_nozzle_map[definition_id] = {}
  163. variant = container.getMetaDataEntry("variant")
  164. if variant:
  165. machine_nozzle_map[definition_id][variant] = container
  166. continue
  167. machine_container_map[definition_id] = container
  168. for definition_id, container in machine_container_map.items():
  169. definition = container.getDefinition()
  170. try:
  171. product = UM.Dictionary.findKey(self.__product_id_map, definition_id)
  172. except ValueError:
  173. # An unknown product id; export it anyway
  174. product = definition_id
  175. builder.start("machine")
  176. builder.start("machine_identifier", { "manufacturer": definition.getMetaDataEntry("manufacturer", ""), "product": product})
  177. builder.end("machine_identifier")
  178. for instance in container.findInstances():
  179. if self.getDefinition().id == "fdmprinter" and self.getInstance(instance.definition.key) and self.getProperty(instance.definition.key, "value") == instance.value:
  180. # If the settings match that of the base profile, just skip since we inherit the base profile.
  181. continue
  182. self._addSettingElement(builder, instance)
  183. # Find all hotend sub-profiles corresponding to this material and machine and add them to this profile.
  184. for hotend_id, hotend in machine_nozzle_map[definition_id].items():
  185. variant_containers = registry.findInstanceContainers(id = hotend.getMetaDataEntry("variant"))
  186. if not variant_containers:
  187. continue
  188. builder.start("hotend", {"id": variant_containers[0].getName()})
  189. # Compatible is a special case, as it's added as a meta data entry (instead of an instance).
  190. compatible = hotend.getMetaDataEntry("compatible")
  191. if compatible is not None:
  192. builder.start("setting", {"key": "hardware compatible"})
  193. if compatible:
  194. builder.data("yes")
  195. else:
  196. builder.data("no")
  197. builder.end("setting")
  198. for instance in hotend.findInstances():
  199. if container.getInstance(instance.definition.key) and container.getProperty(instance.definition.key, "value") == instance.value:
  200. # If the settings match that of the machine profile, just skip since we inherit the machine profile.
  201. continue
  202. self._addSettingElement(builder, instance)
  203. builder.end("hotend")
  204. builder.end("machine")
  205. builder.end("settings")
  206. ## End Settings Block
  207. builder.end("fdmmaterial")
  208. root = builder.close()
  209. _indent(root)
  210. stream = io.BytesIO()
  211. tree = ET.ElementTree(root)
  212. # this makes sure that the XML header states encoding="utf-8"
  213. tree.write(stream, encoding="utf-8", xml_declaration=True)
  214. return stream.getvalue().decode('utf-8')
  215. # Recursively resolve loading inherited files
  216. def _resolveInheritance(self, file_name):
  217. xml = self._loadFile(file_name)
  218. inherits = xml.find("./um:inherits", self.__namespaces)
  219. if inherits is not None:
  220. inherited = self._resolveInheritance(inherits.text)
  221. xml = self._mergeXML(inherited, xml)
  222. return xml
  223. def _loadFile(self, file_name):
  224. path = Resources.getPath(CuraApplication.getInstance().ResourceTypes.MaterialInstanceContainer, file_name + ".xml.fdm_material")
  225. with open(path, encoding="utf-8") as f:
  226. contents = f.read()
  227. self._inherited_files.append(path)
  228. return ET.fromstring(contents)
  229. # The XML material profile can have specific settings for machines.
  230. # Some machines share profiles, so they are only created once.
  231. # This function duplicates those elements so that each machine tag only has one identifier.
  232. def _expandMachinesXML(self, element):
  233. settings_element = element.find("./um:settings", self.__namespaces)
  234. machines = settings_element.iterfind("./um:machine", self.__namespaces)
  235. machines_to_add = []
  236. machines_to_remove = []
  237. for machine in machines:
  238. identifiers = list(machine.iterfind("./um:machine_identifier", self.__namespaces))
  239. has_multiple_identifiers = len(identifiers) > 1
  240. if has_multiple_identifiers:
  241. # Multiple identifiers found. We need to create a new machine element and copy all it's settings there.
  242. for identifier in identifiers:
  243. new_machine = copy.deepcopy(machine)
  244. # Create list of identifiers that need to be removed from the copied element.
  245. other_identifiers = [self._createKey(other_identifier) for other_identifier in identifiers if other_identifier is not identifier]
  246. # As we can only remove by exact object reference, we need to look through the identifiers of copied machine.
  247. new_machine_identifiers = list(new_machine.iterfind("./um:machine_identifier", self.__namespaces))
  248. for new_machine_identifier in new_machine_identifiers:
  249. key = self._createKey(new_machine_identifier)
  250. # Key was in identifiers to remove, so this element needs to be purged
  251. if key in other_identifiers:
  252. new_machine.remove(new_machine_identifier)
  253. machines_to_add.append(new_machine)
  254. machines_to_remove.append(machine)
  255. else:
  256. pass # Machine only has one identifier. Nothing to do.
  257. # Remove & add all required machines.
  258. for machine_to_remove in machines_to_remove:
  259. settings_element.remove(machine_to_remove)
  260. for machine_to_add in machines_to_add:
  261. settings_element.append(machine_to_add)
  262. return element
  263. def _mergeXML(self, first, second):
  264. result = copy.deepcopy(first)
  265. self._combineElement(self._expandMachinesXML(result), self._expandMachinesXML(second))
  266. return result
  267. def _createKey(self, element):
  268. key = element.tag.split("}")[-1]
  269. if "key" in element.attrib:
  270. key += " key:" + element.attrib["key"]
  271. if "manufacturer" in element.attrib:
  272. key += " manufacturer:" + element.attrib["manufacturer"]
  273. if "product" in element.attrib:
  274. key += " product:" + element.attrib["product"]
  275. if key == "machine":
  276. for item in element:
  277. if "machine_identifier" in item.tag:
  278. key += " " + item.attrib["product"]
  279. return key
  280. # Recursively merges XML elements. Updates either the text or children if another element is found in first.
  281. # If it does not exist, copies it from second.
  282. def _combineElement(self, first, second):
  283. # Create a mapping from tag name to element.
  284. mapping = {}
  285. for element in first:
  286. key = self._createKey(element)
  287. mapping[key] = element
  288. for element in second:
  289. key = self._createKey(element)
  290. if len(element): # Check if element has children.
  291. try:
  292. if "setting" in element.tag and not "settings" in element.tag:
  293. # Setting can have points in it. In that case, delete all values and override them.
  294. for child in list(mapping[key]):
  295. mapping[key].remove(child)
  296. for child in element:
  297. mapping[key].append(child)
  298. else:
  299. self._combineElement(mapping[key], element) # Multiple elements, handle those.
  300. except KeyError:
  301. mapping[key] = element
  302. first.append(element)
  303. else:
  304. try:
  305. mapping[key].text = element.text
  306. except KeyError: # Not in the mapping, so simply add it
  307. mapping[key] = element
  308. first.append(element)
  309. def clearData(self):
  310. self._metadata = {}
  311. self._name = ""
  312. self._definition = None
  313. self._instances = {}
  314. self._read_only = False
  315. self._dirty = False
  316. self._path = ""
  317. def getConfigurationTypeFromSerialized(self, serialized: str) -> Optional[str]:
  318. return "material"
  319. def getVersionFromSerialized(self, serialized: str) -> Optional[int]:
  320. version = None
  321. data = ET.fromstring(serialized)
  322. metadata = data.iterfind("./um:metadata/*", self.__namespaces)
  323. for entry in metadata:
  324. tag_name = _tag_without_namespace(entry)
  325. if tag_name == "version":
  326. try:
  327. version = int(entry.text)
  328. except Exception as e:
  329. raise InvalidInstanceError("Invalid version string '%s': %s" % (entry.text, e))
  330. break
  331. if version is None:
  332. raise InvalidInstanceError("Missing version in metadata")
  333. return version
  334. ## Overridden from InstanceContainer
  335. def deserialize(self, serialized):
  336. # update the serialized data first
  337. from UM.Settings.Interfaces import ContainerInterface
  338. serialized = ContainerInterface.deserialize(self, serialized)
  339. data = ET.fromstring(serialized)
  340. # Reset previous metadata
  341. self.clearData() # Ensure any previous data is gone.
  342. meta_data = {}
  343. meta_data["type"] = "material"
  344. meta_data["base_file"] = self.id
  345. meta_data["status"] = "unknown" # TODO: Add material verfication
  346. inherits = data.find("./um:inherits", self.__namespaces)
  347. if inherits is not None:
  348. inherited = self._resolveInheritance(inherits.text)
  349. data = self._mergeXML(inherited, data)
  350. if "version" in data.attrib:
  351. meta_data["setting_version"] = self.xmlVersionToSettingVersion(data.attrib["version"])
  352. else:
  353. meta_data["setting_version"] = self.xmlVersionToSettingVersion("1.2") #1.2 and lower didn't have that version number there yet.
  354. metadata = data.iterfind("./um:metadata/*", self.__namespaces)
  355. for entry in metadata:
  356. tag_name = _tag_without_namespace(entry)
  357. if tag_name == "name":
  358. brand = entry.find("./um:brand", self.__namespaces)
  359. material = entry.find("./um:material", self.__namespaces)
  360. color = entry.find("./um:color", self.__namespaces)
  361. label = entry.find("./um:label", self.__namespaces)
  362. if label is not None:
  363. self._name = label.text
  364. else:
  365. self._name = self._profile_name(material.text, color.text)
  366. meta_data["brand"] = brand.text
  367. meta_data["material"] = material.text
  368. meta_data["color_name"] = color.text
  369. continue
  370. meta_data[tag_name] = entry.text
  371. if "description" not in meta_data:
  372. meta_data["description"] = ""
  373. if "adhesion_info" not in meta_data:
  374. meta_data["adhesion_info"] = ""
  375. property_values = {}
  376. properties = data.iterfind("./um:properties/*", self.__namespaces)
  377. for entry in properties:
  378. tag_name = _tag_without_namespace(entry)
  379. property_values[tag_name] = entry.text
  380. meta_data["approximate_diameter"] = round(float(property_values.get("diameter", 2.85))) # In mm
  381. meta_data["properties"] = property_values
  382. self.setDefinition(ContainerRegistry.getInstance().findDefinitionContainers(id = "fdmprinter")[0])
  383. global_compatibility = True
  384. global_setting_values = {}
  385. settings = data.iterfind("./um:settings/um:setting", self.__namespaces)
  386. for entry in settings:
  387. key = entry.get("key")
  388. if key in self.__material_property_setting_map:
  389. global_setting_values[self.__material_property_setting_map[key]] = entry.text
  390. elif key in self.__unmapped_settings:
  391. if key == "hardware compatible":
  392. global_compatibility = parseBool(entry.text)
  393. else:
  394. Logger.log("d", "Unsupported material setting %s", key)
  395. self._cached_values = global_setting_values
  396. meta_data["compatible"] = global_compatibility
  397. self.setMetaData(meta_data)
  398. self._dirty = False
  399. machines = data.iterfind("./um:settings/um:machine", self.__namespaces)
  400. for machine in machines:
  401. machine_compatibility = global_compatibility
  402. machine_setting_values = {}
  403. settings = machine.iterfind("./um:setting", self.__namespaces)
  404. for entry in settings:
  405. key = entry.get("key")
  406. if key in self.__material_property_setting_map:
  407. machine_setting_values[self.__material_property_setting_map[key]] = entry.text
  408. elif key in self.__unmapped_settings:
  409. if key == "hardware compatible":
  410. machine_compatibility = parseBool(entry.text)
  411. else:
  412. Logger.log("d", "Unsupported material setting %s", key)
  413. cached_machine_setting_properties = global_setting_values.copy()
  414. cached_machine_setting_properties.update(machine_setting_values)
  415. identifiers = machine.iterfind("./um:machine_identifier", self.__namespaces)
  416. for identifier in identifiers:
  417. machine_id = self.__product_id_map.get(identifier.get("product"), None)
  418. if machine_id is None:
  419. # Lets try again with some naive heuristics.
  420. machine_id = identifier.get("product").replace(" ", "").lower()
  421. definitions = ContainerRegistry.getInstance().findDefinitionContainers(id = machine_id)
  422. if not definitions:
  423. Logger.log("w", "No definition found for machine ID %s", machine_id)
  424. continue
  425. definition = definitions[0]
  426. if machine_compatibility:
  427. new_material_id = self.id + "_" + machine_id
  428. new_material = XmlMaterialProfile(new_material_id)
  429. # Update the private directly, as we want to prevent the lookup that is done when using setName
  430. new_material._name = self.getName()
  431. new_material.setMetaData(copy.deepcopy(self.getMetaData()))
  432. new_material.setDefinition(definition)
  433. # Don't use setMetadata, as that overrides it for all materials with same base file
  434. new_material.getMetaData()["compatible"] = machine_compatibility
  435. new_material.setCachedValues(cached_machine_setting_properties)
  436. new_material._dirty = False
  437. ContainerRegistry.getInstance().addContainer(new_material)
  438. hotends = machine.iterfind("./um:hotend", self.__namespaces)
  439. for hotend in hotends:
  440. hotend_id = hotend.get("id")
  441. if hotend_id is None:
  442. continue
  443. variant_containers = ContainerRegistry.getInstance().findInstanceContainers(id = hotend_id)
  444. if not variant_containers:
  445. # It is not really properly defined what "ID" is so also search for variants by name.
  446. variant_containers = ContainerRegistry.getInstance().findInstanceContainers(definition = definition.id, name = hotend_id)
  447. if not variant_containers:
  448. Logger.log("d", "No variants found with ID or name %s for machine %s", hotend_id, definition.id)
  449. continue
  450. hotend_compatibility = machine_compatibility
  451. hotend_setting_values = {}
  452. settings = hotend.iterfind("./um:setting", self.__namespaces)
  453. for entry in settings:
  454. key = entry.get("key")
  455. if key in self.__material_property_setting_map:
  456. hotend_setting_values[self.__material_property_setting_map[key]] = entry.text
  457. elif key in self.__unmapped_settings:
  458. if key == "hardware compatible":
  459. hotend_compatibility = parseBool(entry.text)
  460. else:
  461. Logger.log("d", "Unsupported material setting %s", key)
  462. new_hotend_id = self.id + "_" + machine_id + "_" + hotend_id.replace(" ", "_")
  463. new_hotend_material = XmlMaterialProfile(new_hotend_id)
  464. # Update the private directly, as we want to prevent the lookup that is done when using setName
  465. new_hotend_material._name = self.getName()
  466. new_hotend_material.setMetaData(copy.deepcopy(self.getMetaData()))
  467. new_hotend_material.setDefinition(definition)
  468. new_hotend_material.addMetaDataEntry("variant", variant_containers[0].id)
  469. # Don't use setMetadata, as that overrides it for all materials with same base file
  470. new_hotend_material.getMetaData()["compatible"] = hotend_compatibility
  471. cached_hotend_setting_properties = cached_machine_setting_properties.copy()
  472. cached_hotend_setting_properties.update(hotend_setting_values)
  473. new_hotend_material.setCachedValues(cached_hotend_setting_properties)
  474. new_hotend_material._dirty = False
  475. ContainerRegistry.getInstance().addContainer(new_hotend_material)
  476. def _addSettingElement(self, builder, instance):
  477. try:
  478. key = UM.Dictionary.findKey(self.__material_property_setting_map, instance.definition.key)
  479. except ValueError:
  480. return
  481. builder.start("setting", { "key": key })
  482. builder.data(str(instance.value))
  483. builder.end("setting")
  484. def _profile_name(self, material_name, color_name):
  485. if color_name != "Generic":
  486. return "%s %s" % (color_name, material_name)
  487. else:
  488. return material_name
  489. # Map XML file setting names to internal names
  490. __material_property_setting_map = {
  491. "print temperature": "default_material_print_temperature",
  492. "heated bed temperature": "material_bed_temperature",
  493. "standby temperature": "material_standby_temperature",
  494. "processing temperature graph": "material_flow_temp_graph",
  495. "print cooling": "cool_fan_speed",
  496. "retraction amount": "retraction_amount",
  497. "retraction speed": "retraction_speed"
  498. }
  499. __unmapped_settings = [
  500. "hardware compatible"
  501. ]
  502. # Map XML file product names to internal ids
  503. # TODO: Move this to definition's metadata
  504. __product_id_map = {
  505. "Ultimaker 3": "ultimaker3",
  506. "Ultimaker 3 Extended": "ultimaker3_extended",
  507. "Ultimaker 2": "ultimaker2",
  508. "Ultimaker 2+": "ultimaker2_plus",
  509. "Ultimaker 2 Go": "ultimaker2_go",
  510. "Ultimaker 2 Extended": "ultimaker2_extended",
  511. "Ultimaker 2 Extended+": "ultimaker2_extended_plus",
  512. "Ultimaker Original": "ultimaker_original",
  513. "Ultimaker Original+": "ultimaker_original_plus",
  514. "IMADE3D JellyBOX": "imade3d_jellybox"
  515. }
  516. # Map of recognised namespaces with a proper prefix.
  517. __namespaces = {
  518. "um": "http://www.ultimaker.com/material"
  519. }
  520. ## Helper function for pretty-printing XML because ETree is stupid
  521. def _indent(elem, level = 0):
  522. i = "\n" + level * " "
  523. if len(elem):
  524. if not elem.text or not elem.text.strip():
  525. elem.text = i + " "
  526. if not elem.tail or not elem.tail.strip():
  527. elem.tail = i
  528. for elem in elem:
  529. _indent(elem, level + 1)
  530. if not elem.tail or not elem.tail.strip():
  531. elem.tail = i
  532. else:
  533. if level and (not elem.tail or not elem.tail.strip()):
  534. elem.tail = i
  535. # The namespace is prepended to the tag name but between {}.
  536. # We are only interested in the actual tag name, so discard everything
  537. # before the last }
  538. def _tag_without_namespace(element):
  539. return element.tag[element.tag.rfind("}") + 1:]