XmlMaterialProfile.py 27 KB

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