ThreeMFWorkspaceReader.py 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from configparser import ConfigParser
  4. import zipfile
  5. import os
  6. from typing import List, Tuple
  7. import xml.etree.ElementTree as ET
  8. from UM.Workspace.WorkspaceReader import WorkspaceReader
  9. from UM.Application import Application
  10. from UM.Logger import Logger
  11. from UM.Message import Message
  12. from UM.i18n import i18nCatalog
  13. from UM.Signal import postponeSignals, CompressTechnique
  14. from UM.Settings.ContainerFormatError import ContainerFormatError
  15. from UM.Settings.ContainerStack import ContainerStack
  16. from UM.Settings.DefinitionContainer import DefinitionContainer
  17. from UM.Settings.InstanceContainer import InstanceContainer
  18. from UM.Settings.ContainerRegistry import ContainerRegistry
  19. from UM.MimeTypeDatabase import MimeTypeDatabase, MimeType
  20. from UM.Job import Job
  21. from UM.Preferences import Preferences
  22. from cura.Settings.CuraStackBuilder import CuraStackBuilder
  23. from cura.Settings.ExtruderStack import ExtruderStack
  24. from cura.Settings.GlobalStack import GlobalStack
  25. from cura.Settings.CuraContainerStack import _ContainerIndexes
  26. from cura.CuraApplication import CuraApplication
  27. from cura.Utils.Threading import call_on_qt_thread
  28. from .WorkspaceDialog import WorkspaceDialog
  29. i18n_catalog = i18nCatalog("cura")
  30. class ContainerInfo:
  31. def __init__(self, file_name: str, serialized: str, parser: ConfigParser):
  32. self.file_name = file_name
  33. self.serialized = serialized
  34. self.parser = parser
  35. self.container = None
  36. self.definition_id = None
  37. class QualityChangesInfo:
  38. def __init__(self):
  39. self.name = None
  40. self.global_info = None
  41. self.extruder_info_dict = {}
  42. class MachineInfo:
  43. def __init__(self):
  44. self.container_id = None
  45. self.name = None
  46. self.definition_id = None
  47. self.quality_type = None
  48. self.custom_quality_name = None
  49. self.quality_changes_info = None
  50. self.variant_info = None
  51. self.definition_changes_info = None
  52. self.user_changes_info = None
  53. self.extruder_info_dict = {}
  54. class ExtruderInfo:
  55. def __init__(self):
  56. self.position = None
  57. self.enabled = True
  58. self.variant_info = None
  59. self.root_material_id = None
  60. self.definition_changes_info = None
  61. self.user_changes_info = None
  62. ## Base implementation for reading 3MF workspace files.
  63. class ThreeMFWorkspaceReader(WorkspaceReader):
  64. def __init__(self):
  65. super().__init__()
  66. MimeTypeDatabase.addMimeType(
  67. MimeType(
  68. name="application/x-curaproject+xml",
  69. comment="Cura Project File",
  70. suffixes=["curaproject.3mf"]
  71. )
  72. )
  73. self._supported_extensions = [".3mf"]
  74. self._dialog = WorkspaceDialog()
  75. self._3mf_mesh_reader = None
  76. self._container_registry = ContainerRegistry.getInstance()
  77. # suffixes registered with the MineTypes don't start with a dot '.'
  78. self._definition_container_suffix = "." + ContainerRegistry.getMimeTypeForContainer(DefinitionContainer).preferredSuffix
  79. self._material_container_suffix = None # We have to wait until all other plugins are loaded before we can set it
  80. self._instance_container_suffix = "." + ContainerRegistry.getMimeTypeForContainer(InstanceContainer).preferredSuffix
  81. self._container_stack_suffix = "." + ContainerRegistry.getMimeTypeForContainer(ContainerStack).preferredSuffix
  82. self._extruder_stack_suffix = "." + ContainerRegistry.getMimeTypeForContainer(ExtruderStack).preferredSuffix
  83. self._global_stack_suffix = "." + ContainerRegistry.getMimeTypeForContainer(GlobalStack).preferredSuffix
  84. # Certain instance container types are ignored because we make the assumption that only we make those types
  85. # of containers. They are:
  86. # - quality
  87. # - variant
  88. self._ignored_instance_container_types = {"quality", "variant"}
  89. self._resolve_strategies = {}
  90. self._id_mapping = {}
  91. # In Cura 2.5 and 2.6, the empty profiles used to have those long names
  92. self._old_empty_profile_id_dict = {"empty_%s" % k: "empty" for k in ["material", "variant"]}
  93. self._is_same_machine_type = False
  94. self._old_new_materials = {}
  95. self._materials_to_select = {}
  96. self._machine_info = None
  97. def _clearState(self):
  98. self._is_same_machine_type = False
  99. self._id_mapping = {}
  100. self._old_new_materials = {}
  101. self._materials_to_select = {}
  102. self._machine_info = None
  103. ## Get a unique name based on the old_id. This is different from directly calling the registry in that it caches results.
  104. # This has nothing to do with speed, but with getting consistent new naming for instances & objects.
  105. def getNewId(self, old_id):
  106. if old_id not in self._id_mapping:
  107. self._id_mapping[old_id] = self._container_registry.uniqueName(old_id)
  108. return self._id_mapping[old_id]
  109. ## Separates the given file list into a list of GlobalStack files and a list of ExtruderStack files.
  110. #
  111. # In old versions, extruder stack files have the same suffix as container stack files ".stack.cfg".
  112. #
  113. def _determineGlobalAndExtruderStackFiles(self, project_file_name: str, file_list: List[str]) -> Tuple[str, List[str]]:
  114. archive = zipfile.ZipFile(project_file_name, "r")
  115. global_stack_file_list = [name for name in file_list if name.endswith(self._global_stack_suffix)]
  116. extruder_stack_file_list = [name for name in file_list if name.endswith(self._extruder_stack_suffix)]
  117. # separate container stack files and extruder stack files
  118. files_to_determine = [name for name in file_list if name.endswith(self._container_stack_suffix)]
  119. for file_name in files_to_determine:
  120. # FIXME: HACK!
  121. # We need to know the type of the stack file, but we can only know it if we deserialize it.
  122. # The default ContainerStack.deserialize() will connect signals, which is not desired in this case.
  123. # Since we know that the stack files are INI files, so we directly use the ConfigParser to parse them.
  124. serialized = archive.open(file_name).read().decode("utf-8")
  125. stack_config = ConfigParser(interpolation = None)
  126. stack_config.read_string(serialized)
  127. # sanity check
  128. if not stack_config.has_option("metadata", "type"):
  129. Logger.log("e", "%s in %s doesn't seem to be valid stack file", file_name, project_file_name)
  130. continue
  131. stack_type = stack_config.get("metadata", "type")
  132. if stack_type == "extruder_train":
  133. extruder_stack_file_list.append(file_name)
  134. elif stack_type == "machine":
  135. global_stack_file_list.append(file_name)
  136. else:
  137. Logger.log("w", "Unknown container stack type '%s' from %s in %s",
  138. stack_type, file_name, project_file_name)
  139. if len(global_stack_file_list) > 1:
  140. Logger.log("e", "More than one global stack file found: [{file_list}]".format(file_list = global_stack_file_list))
  141. #But we can recover by just getting the first global stack file.
  142. if len(global_stack_file_list) == 0:
  143. Logger.log("e", "No global stack file found!")
  144. raise FileNotFoundError("No global stack file found!")
  145. return global_stack_file_list[0], extruder_stack_file_list
  146. ## read some info so we can make decisions
  147. # \param file_name
  148. # \param show_dialog In case we use preRead() to check if a file is a valid project file, we don't want to show a dialog.
  149. def preRead(self, file_name, show_dialog=True, *args, **kwargs):
  150. self._clearState()
  151. self._3mf_mesh_reader = Application.getInstance().getMeshFileHandler().getReaderForFile(file_name)
  152. if self._3mf_mesh_reader and self._3mf_mesh_reader.preRead(file_name) == WorkspaceReader.PreReadResult.accepted:
  153. pass
  154. else:
  155. Logger.log("w", "Could not find reader that was able to read the scene data for 3MF workspace")
  156. return WorkspaceReader.PreReadResult.failed
  157. self._machine_info = MachineInfo()
  158. machine_type = ""
  159. variant_type_name = i18n_catalog.i18nc("@label", "Nozzle")
  160. # Check if there are any conflicts, so we can ask the user.
  161. archive = zipfile.ZipFile(file_name, "r")
  162. cura_file_names = [name for name in archive.namelist() if name.startswith("Cura/")]
  163. resolve_strategy_keys = ["machine", "material", "quality_changes"]
  164. self._resolve_strategies = {k: None for k in resolve_strategy_keys}
  165. containers_found_dict = {k: False for k in resolve_strategy_keys}
  166. #
  167. # Read definition containers
  168. #
  169. machine_definition_id = None
  170. machine_definition_container_count = 0
  171. extruder_definition_container_count = 0
  172. definition_container_files = [name for name in cura_file_names if name.endswith(self._definition_container_suffix)]
  173. for definition_container_file in definition_container_files:
  174. container_id = self._stripFileToId(definition_container_file)
  175. definitions = self._container_registry.findDefinitionContainersMetadata(id = container_id)
  176. serialized = archive.open(definition_container_file).read().decode("utf-8")
  177. if not definitions:
  178. definition_container = DefinitionContainer.deserializeMetadata(serialized, container_id)[0]
  179. else:
  180. definition_container = definitions[0]
  181. definition_container_type = definition_container.get("type")
  182. if definition_container_type == "machine":
  183. machine_definition_id = container_id
  184. machine_type = definition_container["name"]
  185. variant_type_name = definition_container.get("variants_name", variant_type_name)
  186. machine_definition_container_count += 1
  187. elif definition_container_type == "extruder":
  188. extruder_definition_container_count += 1
  189. else:
  190. Logger.log("w", "Unknown definition container type %s for %s",
  191. definition_container_type, definition_container_file)
  192. Job.yieldThread()
  193. if machine_definition_container_count != 1:
  194. return WorkspaceReader.PreReadResult.failed # Not a workspace file but ordinary 3MF.
  195. material_labels = []
  196. material_conflict = False
  197. xml_material_profile = self._getXmlProfileClass()
  198. reverse_material_id_dict = {}
  199. if self._material_container_suffix is None:
  200. self._material_container_suffix = ContainerRegistry.getMimeTypeForContainer(xml_material_profile).preferredSuffix
  201. if xml_material_profile:
  202. material_container_files = [name for name in cura_file_names if name.endswith(self._material_container_suffix)]
  203. for material_container_file in material_container_files:
  204. container_id = self._stripFileToId(material_container_file)
  205. serialized = archive.open(material_container_file).read().decode("utf-8")
  206. metadata_list = xml_material_profile.deserializeMetadata(serialized, container_id)
  207. reverse_map = {metadata["id"]: container_id for metadata in metadata_list}
  208. reverse_material_id_dict.update(reverse_map)
  209. material_labels.append(self._getMaterialLabelFromSerialized(serialized))
  210. if self._container_registry.findContainersMetadata(id = container_id): #This material already exists.
  211. containers_found_dict["material"] = True
  212. if not self._container_registry.isReadOnly(container_id): # Only non readonly materials can be in conflict
  213. material_conflict = True
  214. Job.yieldThread()
  215. # Check if any quality_changes instance container is in conflict.
  216. instance_container_files = [name for name in cura_file_names if name.endswith(self._instance_container_suffix)]
  217. quality_name = ""
  218. custom_quality_name = ""
  219. num_settings_overriden_by_quality_changes = 0 # How many settings are changed by the quality changes
  220. num_user_settings = 0
  221. quality_changes_conflict = False
  222. self._machine_info.quality_changes_info = QualityChangesInfo()
  223. quality_changes_info_list = []
  224. instance_container_info_dict = {} # id -> parser
  225. for instance_container_file_name in instance_container_files:
  226. container_id = self._stripFileToId(instance_container_file_name)
  227. serialized = archive.open(instance_container_file_name).read().decode("utf-8")
  228. # Qualities and variants don't have upgrades, so don't upgrade them
  229. parser = ConfigParser(interpolation = None)
  230. parser.read_string(serialized)
  231. container_type = parser["metadata"]["type"]
  232. if container_type not in ("quality", "variant"):
  233. serialized = InstanceContainer._updateSerialized(serialized, instance_container_file_name)
  234. parser = ConfigParser(interpolation = None)
  235. parser.read_string(serialized)
  236. container_info = ContainerInfo(instance_container_file_name, serialized, parser)
  237. instance_container_info_dict[container_id] = container_info
  238. container_type = parser["metadata"]["type"]
  239. if container_type == "quality_changes":
  240. quality_changes_info_list.append(container_info)
  241. if not parser.has_option("metadata", "position"):
  242. self._machine_info.quality_changes_info.name = parser["general"]["name"]
  243. self._machine_info.quality_changes_info.global_info = container_info
  244. else:
  245. position = parser["metadata"]["position"]
  246. self._machine_info.quality_changes_info.extruder_info_dict[position] = container_info
  247. custom_quality_name = parser["general"]["name"]
  248. values = parser["values"] if parser.has_section("values") else dict()
  249. num_settings_overriden_by_quality_changes += len(values)
  250. # Check if quality changes already exists.
  251. quality_changes = self._container_registry.findInstanceContainers(id = container_id)
  252. if quality_changes:
  253. containers_found_dict["quality_changes"] = True
  254. # Check if there really is a conflict by comparing the values
  255. instance_container = InstanceContainer(container_id)
  256. try:
  257. instance_container.deserialize(serialized, file_name = instance_container_file_name)
  258. except ContainerFormatError:
  259. Logger.logException("e", "Failed to deserialize InstanceContainer %s from project file %s",
  260. instance_container_file_name, file_name)
  261. return ThreeMFWorkspaceReader.PreReadResult.failed
  262. if quality_changes[0] != instance_container:
  263. quality_changes_conflict = True
  264. elif container_type == "quality":
  265. if not quality_name:
  266. quality_name = parser["general"]["name"]
  267. elif container_type == "user":
  268. num_user_settings += len(parser["values"])
  269. elif container_type in self._ignored_instance_container_types:
  270. # Ignore certain instance container types
  271. Logger.log("w", "Ignoring instance container [%s] with type [%s]", container_id, container_type)
  272. continue
  273. Job.yieldThread()
  274. if self._machine_info.quality_changes_info.global_info is None:
  275. self._machine_info.quality_changes_info = None
  276. # Load ContainerStack files and ExtruderStack files
  277. try:
  278. global_stack_file, extruder_stack_files = self._determineGlobalAndExtruderStackFiles(
  279. file_name, cura_file_names)
  280. except FileNotFoundError:
  281. return WorkspaceReader.PreReadResult.failed
  282. machine_conflict = False
  283. # Because there can be cases as follows:
  284. # - the global stack exists but some/all of the extruder stacks DON'T exist
  285. # - the global stack DOESN'T exist but some/all of the extruder stacks exist
  286. # To simplify this, only check if the global stack exists or not
  287. global_stack_id = self._stripFileToId(global_stack_file)
  288. serialized = archive.open(global_stack_file).read().decode("utf-8")
  289. machine_name = self._getMachineNameFromSerializedStack(serialized)
  290. stacks = self._container_registry.findContainerStacks(name = machine_name, type = "machine")
  291. self._is_same_machine_type = True
  292. existing_global_stack = None
  293. if stacks:
  294. global_stack = stacks[0]
  295. existing_global_stack = global_stack
  296. containers_found_dict["machine"] = True
  297. # Check if there are any changes at all in any of the container stacks.
  298. id_list = self._getContainerIdListFromSerialized(serialized)
  299. for index, container_id in enumerate(id_list):
  300. # take into account the old empty container IDs
  301. container_id = self._old_empty_profile_id_dict.get(container_id, container_id)
  302. if global_stack.getContainer(index).getId() != container_id:
  303. machine_conflict = True
  304. break
  305. self._is_same_machine_type = global_stack.definition.getId() == machine_definition_id
  306. # Get quality type
  307. parser = ConfigParser(interpolation = None)
  308. parser.read_string(serialized)
  309. quality_container_id = parser["containers"][str(_ContainerIndexes.Quality)]
  310. quality_type = "empty_quality"
  311. if quality_container_id not in ("empty", "empty_quality"):
  312. quality_type = instance_container_info_dict[quality_container_id].parser["metadata"]["quality_type"]
  313. # Get machine info
  314. serialized = archive.open(global_stack_file).read().decode("utf-8")
  315. serialized = GlobalStack._updateSerialized(serialized, global_stack_file)
  316. parser = ConfigParser(interpolation = None)
  317. parser.read_string(serialized)
  318. definition_changes_id = parser["containers"][str(_ContainerIndexes.DefinitionChanges)]
  319. if definition_changes_id not in ("empty", "empty_definition_changes"):
  320. self._machine_info.definition_changes_info = instance_container_info_dict[definition_changes_id]
  321. user_changes_id = parser["containers"][str(_ContainerIndexes.UserChanges)]
  322. if user_changes_id not in ("empty", "empty_user_changes"):
  323. self._machine_info.user_changes_info = instance_container_info_dict[user_changes_id]
  324. # Also check variant and material in case it doesn't have extruder stacks
  325. if not extruder_stack_files:
  326. position = "0"
  327. extruder_info = ExtruderInfo()
  328. extruder_info.position = position
  329. variant_id = parser["containers"][str(_ContainerIndexes.Variant)]
  330. material_id = parser["containers"][str(_ContainerIndexes.Material)]
  331. if variant_id not in ("empty", "empty_variant"):
  332. extruder_info.variant_info = instance_container_info_dict[variant_id]
  333. if material_id not in ("empty", "empty_material"):
  334. root_material_id = reverse_material_id_dict[material_id]
  335. extruder_info.root_material_id = root_material_id
  336. self._machine_info.extruder_info_dict[position] = extruder_info
  337. else:
  338. variant_id = parser["containers"][str(_ContainerIndexes.Variant)]
  339. if variant_id not in ("empty", "empty_variant"):
  340. self._machine_info.variant_info = instance_container_info_dict[variant_id]
  341. Job.yieldThread()
  342. # if the global stack is found, we check if there are conflicts in the extruder stacks
  343. for extruder_stack_file in extruder_stack_files:
  344. serialized = archive.open(extruder_stack_file).read().decode("utf-8")
  345. serialized = ExtruderStack._updateSerialized(serialized, extruder_stack_file)
  346. parser = ConfigParser(interpolation = None)
  347. parser.read_string(serialized)
  348. # The check should be done for the extruder stack that's associated with the existing global stack,
  349. # and those extruder stacks may have different IDs.
  350. # So we check according to the positions
  351. position = parser["metadata"]["position"]
  352. variant_id = parser["containers"][str(_ContainerIndexes.Variant)]
  353. material_id = parser["containers"][str(_ContainerIndexes.Material)]
  354. extruder_info = ExtruderInfo()
  355. extruder_info.position = position
  356. if parser.has_option("metadata", "enabled"):
  357. extruder_info.enabled = parser["metadata"]["enabled"]
  358. if variant_id not in ("empty", "empty_variant"):
  359. extruder_info.variant_info = instance_container_info_dict[variant_id]
  360. if material_id not in ("empty", "empty_material"):
  361. root_material_id = reverse_material_id_dict[material_id]
  362. extruder_info.root_material_id = root_material_id
  363. definition_changes_id = parser["containers"][str(_ContainerIndexes.DefinitionChanges)]
  364. if definition_changes_id not in ("empty", "empty_definition_changes"):
  365. extruder_info.definition_changes_info = instance_container_info_dict[definition_changes_id]
  366. user_changes_id = parser["containers"][str(_ContainerIndexes.UserChanges)]
  367. if user_changes_id not in ("empty", "empty_user_changes"):
  368. extruder_info.user_changes_info = instance_container_info_dict[user_changes_id]
  369. self._machine_info.extruder_info_dict[position] = extruder_info
  370. if not machine_conflict and containers_found_dict["machine"]:
  371. if position not in global_stack.extruders:
  372. continue
  373. existing_extruder_stack = global_stack.extruders[position]
  374. # check if there are any changes at all in any of the container stacks.
  375. id_list = self._getContainerIdListFromSerialized(serialized)
  376. for index, container_id in enumerate(id_list):
  377. # take into account the old empty container IDs
  378. container_id = self._old_empty_profile_id_dict.get(container_id, container_id)
  379. if existing_extruder_stack.getContainer(index).getId() != container_id:
  380. machine_conflict = True
  381. break
  382. num_visible_settings = 0
  383. try:
  384. temp_preferences = Preferences()
  385. serialized = archive.open("Cura/preferences.cfg").read().decode("utf-8")
  386. temp_preferences.deserialize(serialized)
  387. visible_settings_string = temp_preferences.getValue("general/visible_settings")
  388. has_visible_settings_string = visible_settings_string is not None
  389. if visible_settings_string is not None:
  390. num_visible_settings = len(visible_settings_string.split(";"))
  391. active_mode = temp_preferences.getValue("cura/active_mode")
  392. if not active_mode:
  393. active_mode = Application.getInstance().getPreferences().getValue("cura/active_mode")
  394. except KeyError:
  395. # If there is no preferences file, it's not a workspace, so notify user of failure.
  396. Logger.log("w", "File %s is not a valid workspace.", file_name)
  397. return WorkspaceReader.PreReadResult.failed
  398. # Check if the machine definition exists. If not, indicate failure because we do not import definition files.
  399. def_results = self._container_registry.findDefinitionContainersMetadata(id = machine_definition_id)
  400. if not def_results:
  401. message = Message(i18n_catalog.i18nc("@info:status Don't translate the XML tags <filename> or <message>!",
  402. "Project file <filename>{0}</filename> contains an unknown machine type"
  403. " <message>{1}</message>. Cannot import the machine."
  404. " Models will be imported instead.", file_name, machine_definition_id),
  405. title = i18n_catalog.i18nc("@info:title", "Open Project File"))
  406. message.show()
  407. Logger.log("i", "Could unknown machine definition %s in project file %s, cannot import it.",
  408. self._machine_info.definition_id, file_name)
  409. return WorkspaceReader.PreReadResult.failed
  410. # In case we use preRead() to check if a file is a valid project file, we don't want to show a dialog.
  411. if not show_dialog:
  412. return WorkspaceReader.PreReadResult.accepted
  413. # prepare data for the dialog
  414. num_extruders = extruder_definition_container_count
  415. if num_extruders == 0:
  416. num_extruders = 1 # No extruder stacks found, which means there is one extruder
  417. extruders = num_extruders * [""]
  418. quality_name = custom_quality_name if custom_quality_name else quality_name
  419. self._machine_info.container_id = global_stack_id
  420. self._machine_info.name = machine_name
  421. self._machine_info.definition_id = machine_definition_id
  422. self._machine_info.quality_type = quality_type
  423. self._machine_info.custom_quality_name = quality_name
  424. if machine_conflict and not self._is_same_machine_type:
  425. machine_conflict = False
  426. is_printer_group = False
  427. if machine_conflict:
  428. group_name = existing_global_stack.getMetaDataEntry("connect_group_name")
  429. if group_name is not None:
  430. is_printer_group = True
  431. machine_name = group_name
  432. # Show the dialog, informing the user what is about to happen.
  433. self._dialog.setMachineConflict(machine_conflict)
  434. self._dialog.setIsPrinterGroup(is_printer_group)
  435. self._dialog.setQualityChangesConflict(quality_changes_conflict)
  436. self._dialog.setMaterialConflict(material_conflict)
  437. self._dialog.setHasVisibleSettingsField(has_visible_settings_string)
  438. self._dialog.setNumVisibleSettings(num_visible_settings)
  439. self._dialog.setQualityName(quality_name)
  440. self._dialog.setQualityType(quality_type)
  441. self._dialog.setNumSettingsOverridenByQualityChanges(num_settings_overriden_by_quality_changes)
  442. self._dialog.setNumUserSettings(num_user_settings)
  443. self._dialog.setActiveMode(active_mode)
  444. self._dialog.setMachineName(machine_name)
  445. self._dialog.setMaterialLabels(material_labels)
  446. self._dialog.setMachineType(machine_type)
  447. self._dialog.setExtruders(extruders)
  448. self._dialog.setVariantType(variant_type_name)
  449. self._dialog.setHasObjectsOnPlate(Application.getInstance().platformActivity)
  450. self._dialog.show()
  451. # Block until the dialog is closed.
  452. self._dialog.waitForClose()
  453. if self._dialog.getResult() == {}:
  454. return WorkspaceReader.PreReadResult.cancelled
  455. self._resolve_strategies = self._dialog.getResult()
  456. #
  457. # There can be 3 resolve strategies coming from the dialog:
  458. # - new: create a new container
  459. # - override: override the existing container
  460. # - None: There is no conflict, which means containers with the same IDs may or may not be there already.
  461. # If there is an existing container, there is no conflict between them, and default to "override"
  462. # If there is no existing container, default to "new"
  463. #
  464. # Default values
  465. for key, strategy in self._resolve_strategies.items():
  466. if key not in containers_found_dict or strategy is not None:
  467. continue
  468. self._resolve_strategies[key] = "override" if containers_found_dict[key] else "new"
  469. return WorkspaceReader.PreReadResult.accepted
  470. ## Read the project file
  471. # Add all the definitions / materials / quality changes that do not exist yet. Then it loads
  472. # all the stacks into the container registry. In some cases it will reuse the container for the global stack.
  473. # It handles old style project files containing .stack.cfg as well as new style project files
  474. # containing global.cfg / extruder.cfg
  475. #
  476. # \param file_name
  477. @call_on_qt_thread
  478. def read(self, file_name):
  479. container_registry = ContainerRegistry.getInstance()
  480. signals = [container_registry.containerAdded,
  481. container_registry.containerRemoved,
  482. container_registry.containerMetaDataChanged]
  483. #
  484. # We now have different managers updating their lookup tables upon container changes. It is critical to make
  485. # sure that the managers have a complete set of data when they update.
  486. #
  487. # In project loading, lots of the container-related signals are loosely emitted, which can create timing gaps
  488. # for incomplete data update or other kinds of issues to happen.
  489. #
  490. # To avoid this, we postpone all signals so they don't get emitted immediately. But, please also be aware that,
  491. # because of this, do not expect to have the latest data in the lookup tables in project loading.
  492. #
  493. with postponeSignals(*signals, compress = CompressTechnique.NoCompression):
  494. return self._read(file_name)
  495. def _read(self, file_name):
  496. application = CuraApplication.getInstance()
  497. material_manager = application.getMaterialManager()
  498. archive = zipfile.ZipFile(file_name, "r")
  499. cura_file_names = [name for name in archive.namelist() if name.startswith("Cura/")]
  500. # Create a shadow copy of the preferences (we don't want all of the preferences, but we do want to re-use its
  501. # parsing code.
  502. temp_preferences = Preferences()
  503. serialized = archive.open("Cura/preferences.cfg").read().decode("utf-8")
  504. temp_preferences.deserialize(serialized)
  505. # Copy a number of settings from the temp preferences to the global
  506. global_preferences = application.getInstance().getPreferences()
  507. visible_settings = temp_preferences.getValue("general/visible_settings")
  508. if visible_settings is None:
  509. Logger.log("w", "Workspace did not contain visible settings. Leaving visibility unchanged")
  510. else:
  511. global_preferences.setValue("general/visible_settings", visible_settings)
  512. global_preferences.setValue("cura/active_setting_visibility_preset", "custom")
  513. categories_expanded = temp_preferences.getValue("cura/categories_expanded")
  514. if categories_expanded is None:
  515. Logger.log("w", "Workspace did not contain expanded categories. Leaving them unchanged")
  516. else:
  517. global_preferences.setValue("cura/categories_expanded", categories_expanded)
  518. application.expandedCategoriesChanged.emit() # Notify the GUI of the change
  519. # If a machine with the same name is of a different type, always create a new one.
  520. if not self._is_same_machine_type or self._resolve_strategies["machine"] != "override":
  521. # We need to create a new machine
  522. machine_name = self._container_registry.uniqueName(self._machine_info.name)
  523. global_stack = CuraStackBuilder.createMachine(machine_name, self._machine_info.definition_id)
  524. if global_stack: #Only switch if creating the machine was successful.
  525. extruder_stack_dict = global_stack.extruders
  526. self._container_registry.addContainer(global_stack)
  527. else:
  528. # Find the machine
  529. global_stack = self._container_registry.findContainerStacks(name = self._machine_info.name, type = "machine")[0]
  530. extruder_stacks = self._container_registry.findContainerStacks(machine = global_stack.getId(),
  531. type = "extruder_train")
  532. extruder_stack_dict = {stack.getMetaDataEntry("position"): stack for stack in extruder_stacks}
  533. Logger.log("d", "Workspace loading is checking definitions...")
  534. # Get all the definition files & check if they exist. If not, add them.
  535. definition_container_files = [name for name in cura_file_names if name.endswith(self._definition_container_suffix)]
  536. for definition_container_file in definition_container_files:
  537. container_id = self._stripFileToId(definition_container_file)
  538. definitions = self._container_registry.findDefinitionContainersMetadata(id = container_id)
  539. if not definitions:
  540. definition_container = DefinitionContainer(container_id)
  541. try:
  542. definition_container.deserialize(archive.open(definition_container_file).read().decode("utf-8"),
  543. file_name = definition_container_file)
  544. except ContainerFormatError:
  545. # We cannot just skip the definition file because everything else later will just break if the
  546. # machine definition cannot be found.
  547. Logger.logException("e", "Failed to deserialize definition file %s in project file %s",
  548. definition_container_file, file_name)
  549. definition_container = self._container_registry.findDefinitionContainers(id = "fdmprinter")[0] #Fall back to defaults.
  550. self._container_registry.addContainer(definition_container)
  551. Job.yieldThread()
  552. Logger.log("d", "Workspace loading is checking materials...")
  553. # Get all the material files and check if they exist. If not, add them.
  554. xml_material_profile = self._getXmlProfileClass()
  555. if self._material_container_suffix is None:
  556. self._material_container_suffix = ContainerRegistry.getMimeTypeForContainer(xml_material_profile).suffixes[0]
  557. if xml_material_profile:
  558. material_container_files = [name for name in cura_file_names if name.endswith(self._material_container_suffix)]
  559. for material_container_file in material_container_files:
  560. to_deserialize_material = False
  561. container_id = self._stripFileToId(material_container_file)
  562. need_new_name = False
  563. materials = self._container_registry.findInstanceContainers(id = container_id)
  564. if not materials:
  565. # No material found, deserialize this material later and add it
  566. to_deserialize_material = True
  567. else:
  568. material_container = materials[0]
  569. old_material_root_id = material_container.getMetaDataEntry("base_file")
  570. if not self._container_registry.isReadOnly(old_material_root_id): # Only create new materials if they are not read only.
  571. to_deserialize_material = True
  572. if self._resolve_strategies["material"] == "override":
  573. # Remove the old materials and then deserialize the one from the project
  574. root_material_id = material_container.getMetaDataEntry("base_file")
  575. material_manager.removeMaterialByRootId(root_material_id)
  576. elif self._resolve_strategies["material"] == "new":
  577. # Note that we *must* deserialize it with a new ID, as multiple containers will be
  578. # auto created & added.
  579. container_id = self.getNewId(container_id)
  580. self._old_new_materials[old_material_root_id] = container_id
  581. need_new_name = True
  582. if to_deserialize_material:
  583. material_container = xml_material_profile(container_id)
  584. try:
  585. material_container.deserialize(archive.open(material_container_file).read().decode("utf-8"),
  586. file_name = container_id + "." + self._material_container_suffix)
  587. except ContainerFormatError:
  588. Logger.logException("e", "Failed to deserialize material file %s in project file %s",
  589. material_container_file, file_name)
  590. continue
  591. if need_new_name:
  592. new_name = ContainerRegistry.getInstance().uniqueName(material_container.getName())
  593. material_container.setName(new_name)
  594. material_container.setDirty(True)
  595. self._container_registry.addContainer(material_container)
  596. Job.yieldThread()
  597. # Handle quality changes if any
  598. self._processQualityChanges(global_stack)
  599. # Prepare the machine
  600. self._applyChangesToMachine(global_stack, extruder_stack_dict)
  601. Logger.log("d", "Workspace loading is notifying rest of the code of changes...")
  602. # Actually change the active machine.
  603. #
  604. # This is scheduled for later is because it depends on the Variant/Material/Qualitiy Managers to have the latest
  605. # data, but those managers will only update upon a container/container metadata changed signal. Because this
  606. # function is running on the main thread (Qt thread), although those "changed" signals have been emitted, but
  607. # they won't take effect until this function is done.
  608. # To solve this, we schedule _updateActiveMachine() for later so it will have the latest data.
  609. self._updateActiveMachine(global_stack)
  610. # Load all the nodes / mesh data of the workspace
  611. nodes = self._3mf_mesh_reader.read(file_name)
  612. if nodes is None:
  613. nodes = []
  614. base_file_name = os.path.basename(file_name)
  615. if base_file_name.endswith(".curaproject.3mf"):
  616. base_file_name = base_file_name[:base_file_name.rfind(".curaproject.3mf")]
  617. self.setWorkspaceName(base_file_name)
  618. return nodes
  619. def _processQualityChanges(self, global_stack):
  620. if self._machine_info.quality_changes_info is None:
  621. return
  622. application = CuraApplication.getInstance()
  623. quality_manager = application.getQualityManager()
  624. # If we have custom profiles, load them
  625. quality_changes_name = self._machine_info.quality_changes_info.name
  626. if self._machine_info.quality_changes_info is not None:
  627. Logger.log("i", "Loading custom profile [%s] from project file",
  628. self._machine_info.quality_changes_info.name)
  629. # Get the correct extruder definition IDs for quality changes
  630. from cura.Machines.QualityManager import getMachineDefinitionIDForQualitySearch
  631. machine_definition_id_for_quality = getMachineDefinitionIDForQualitySearch(global_stack.definition)
  632. machine_definition_for_quality = self._container_registry.findDefinitionContainers(id = machine_definition_id_for_quality)[0]
  633. quality_changes_info = self._machine_info.quality_changes_info
  634. quality_changes_quality_type = quality_changes_info.global_info.parser["metadata"]["quality_type"]
  635. quality_changes_name = quality_changes_info.name
  636. create_new = self._resolve_strategies.get("quality_changes") != "override"
  637. if create_new:
  638. container_info_dict = {None: self._machine_info.quality_changes_info.global_info}
  639. container_info_dict.update(quality_changes_info.extruder_info_dict)
  640. quality_changes_name = self._container_registry.uniqueName(quality_changes_name)
  641. for position, container_info in container_info_dict.items():
  642. extruder_stack = None
  643. if position is not None:
  644. extruder_stack = global_stack.extruders[position]
  645. container = quality_manager._createQualityChanges(quality_changes_quality_type,
  646. quality_changes_name,
  647. global_stack, extruder_stack)
  648. container_info.container = container
  649. container.setDirty(True)
  650. self._container_registry.addContainer(container)
  651. Logger.log("d", "Created new quality changes container [%s]", container.getId())
  652. else:
  653. # Find the existing containers
  654. quality_changes_containers = self._container_registry.findInstanceContainers(name = quality_changes_name,
  655. type = "quality_changes")
  656. for container in quality_changes_containers:
  657. extruder_position = container.getMetaDataEntry("position")
  658. if extruder_position is None:
  659. quality_changes_info.global_info.container = container
  660. else:
  661. if extruder_position not in quality_changes_info.extruder_info_dict:
  662. quality_changes_info.extruder_info_dict[extruder_position] = ContainerInfo(None, None, None)
  663. container_info = quality_changes_info.extruder_info_dict[extruder_position]
  664. container_info.container = container
  665. # If there is no quality changes for any extruder, create one.
  666. if not quality_changes_info.extruder_info_dict:
  667. container_info = ContainerInfo(None, None, None)
  668. quality_changes_info.extruder_info_dict["0"] = container_info
  669. extruder_stack = global_stack.extruders["0"]
  670. container = quality_manager._createQualityChanges(quality_changes_quality_type, quality_changes_name,
  671. global_stack, extruder_stack)
  672. container_info.container = container
  673. container.setDirty(True)
  674. self._container_registry.addContainer(container)
  675. Logger.log("d", "Created new quality changes container [%s]", container.getId())
  676. # Clear all existing containers
  677. quality_changes_info.global_info.container.clear()
  678. for container_info in quality_changes_info.extruder_info_dict.values():
  679. container_info.container.clear()
  680. # Loop over everything and override the existing containers
  681. global_info = quality_changes_info.global_info
  682. global_info.container.clear() # Clear all
  683. for key, value in global_info.parser["values"].items():
  684. if not machine_definition_for_quality.getProperty(key, "settable_per_extruder"):
  685. global_info.container.setProperty(key, "value", value)
  686. else:
  687. quality_changes_info.extruder_info_dict["0"].container.setProperty(key, "value", value)
  688. for position, container_info in quality_changes_info.extruder_info_dict.items():
  689. if container_info.parser is None:
  690. continue
  691. if container_info.container is None:
  692. extruder_stack = global_stack.extruders[position]
  693. container = quality_manager._createQualityChanges(quality_changes_quality_type, quality_changes_name,
  694. global_stack, extruder_stack)
  695. container_info.container = container
  696. for key, value in container_info.parser["values"].items():
  697. container_info.container.setProperty(key, "value", value)
  698. self._machine_info.quality_changes_info.name = quality_changes_name
  699. def _clearStack(self, stack):
  700. application = CuraApplication.getInstance()
  701. stack.definitionChanges.clear()
  702. stack.variant = application.empty_variant_container
  703. stack.material = application.empty_material_container
  704. stack.quality = application.empty_quality_container
  705. stack.qualityChanges = application.empty_quality_changes_container
  706. stack.userChanges.clear()
  707. def _applyDefinitionChanges(self, global_stack, extruder_stack_dict):
  708. values_to_set_for_extruders = {}
  709. if self._machine_info.definition_changes_info is not None:
  710. parser = self._machine_info.definition_changes_info.parser
  711. for key, value in parser["values"].items():
  712. if global_stack.getProperty(key, "settable_per_extruder"):
  713. values_to_set_for_extruders[key] = value
  714. else:
  715. global_stack.definitionChanges.setProperty(key, "value", value)
  716. for position, extruder_stack in extruder_stack_dict.items():
  717. if position not in self._machine_info.extruder_info_dict:
  718. continue
  719. extruder_info = self._machine_info.extruder_info_dict[position]
  720. if extruder_info.definition_changes_info is None:
  721. continue
  722. parser = extruder_info.definition_changes_info.parser
  723. for key, value in values_to_set_for_extruders.items():
  724. extruder_stack.definitionChanges.setProperty(key, "value", value)
  725. if parser is not None:
  726. for key, value in parser["values"].items():
  727. extruder_stack.definitionChanges.setProperty(key, "value", value)
  728. def _applyUserChanges(self, global_stack, extruder_stack_dict):
  729. values_to_set_for_extruder_0 = {}
  730. if self._machine_info.user_changes_info is not None:
  731. parser = self._machine_info.user_changes_info.parser
  732. for key, value in parser["values"].items():
  733. if global_stack.getProperty(key, "settable_per_extruder"):
  734. values_to_set_for_extruder_0[key] = value
  735. else:
  736. global_stack.userChanges.setProperty(key, "value", value)
  737. for position, extruder_stack in extruder_stack_dict.items():
  738. if position not in self._machine_info.extruder_info_dict:
  739. continue
  740. extruder_info = self._machine_info.extruder_info_dict[position]
  741. if extruder_info.user_changes_info is not None:
  742. parser = self._machine_info.extruder_info_dict[position].user_changes_info.parser
  743. if position == "0":
  744. for key, value in values_to_set_for_extruder_0.items():
  745. extruder_stack.userChanges.setProperty(key, "value", value)
  746. if parser is not None:
  747. for key, value in parser["values"].items():
  748. extruder_stack.userChanges.setProperty(key, "value", value)
  749. def _applyVariants(self, global_stack, extruder_stack_dict):
  750. application = CuraApplication.getInstance()
  751. variant_manager = application.getVariantManager()
  752. if self._machine_info.variant_info is not None:
  753. parser = self._machine_info.variant_info.parser
  754. variant_name = parser["general"]["name"]
  755. from cura.Machines.VariantManager import VariantType
  756. variant_type = VariantType.BUILD_PLATE
  757. node = variant_manager.getVariantNode(global_stack.definition.getId(), variant_name, variant_type)
  758. if node is not None and node.getContainer() is not None:
  759. global_stack.variant = node.getContainer()
  760. for position, extruder_stack in extruder_stack_dict.items():
  761. if position not in self._machine_info.extruder_info_dict:
  762. continue
  763. extruder_info = self._machine_info.extruder_info_dict[position]
  764. if extruder_info.variant_info is None:
  765. continue
  766. parser = extruder_info.variant_info.parser
  767. variant_name = parser["general"]["name"]
  768. from cura.Machines.VariantManager import VariantType
  769. variant_type = VariantType.NOZZLE
  770. node = variant_manager.getVariantNode(global_stack.definition.getId(), variant_name, variant_type)
  771. if node is not None and node.getContainer() is not None:
  772. extruder_stack.variant = node.getContainer()
  773. def _applyMaterials(self, global_stack, extruder_stack_dict):
  774. application = CuraApplication.getInstance()
  775. material_manager = application.getMaterialManager()
  776. # Force update lookup tables first
  777. material_manager.initialize()
  778. for position, extruder_stack in extruder_stack_dict.items():
  779. if position not in self._machine_info.extruder_info_dict:
  780. continue
  781. extruder_info = self._machine_info.extruder_info_dict[position]
  782. if extruder_info.root_material_id is None:
  783. continue
  784. root_material_id = extruder_info.root_material_id
  785. root_material_id = self._old_new_materials.get(root_material_id, root_material_id)
  786. # get material diameter of this extruder
  787. machine_material_diameter = extruder_stack.materialDiameter
  788. material_node = material_manager.getMaterialNode(global_stack.definition.getId(),
  789. extruder_stack.variant.getName(),
  790. machine_material_diameter,
  791. root_material_id)
  792. if material_node is not None and material_node.getContainer() is not None:
  793. extruder_stack.material = material_node.getContainer()
  794. def _applyChangesToMachine(self, global_stack, extruder_stack_dict):
  795. # Clear all first
  796. self._clearStack(global_stack)
  797. for extruder_stack in extruder_stack_dict.values():
  798. self._clearStack(extruder_stack)
  799. self._applyDefinitionChanges(global_stack, extruder_stack_dict)
  800. self._applyUserChanges(global_stack, extruder_stack_dict)
  801. self._applyVariants(global_stack, extruder_stack_dict)
  802. self._applyMaterials(global_stack, extruder_stack_dict)
  803. # prepare the quality to select
  804. self._quality_changes_to_apply = None
  805. self._quality_type_to_apply = None
  806. if self._machine_info.quality_changes_info is not None:
  807. self._quality_changes_to_apply = self._machine_info.quality_changes_info.name
  808. else:
  809. self._quality_type_to_apply = self._machine_info.quality_type
  810. # Set enabled/disabled for extruders
  811. for position, extruder_stack in extruder_stack_dict.items():
  812. extruder_info = self._machine_info.extruder_info_dict.get(position)
  813. if not extruder_info:
  814. continue
  815. if "enabled" not in extruder_stack.getMetaData():
  816. extruder_stack.addMetaDataEntry("enabled", "True")
  817. extruder_stack.setMetaDataEntry("enabled", str(extruder_info.enabled))
  818. def _updateActiveMachine(self, global_stack):
  819. # Actually change the active machine.
  820. machine_manager = Application.getInstance().getMachineManager()
  821. material_manager = Application.getInstance().getMaterialManager()
  822. quality_manager = Application.getInstance().getQualityManager()
  823. # Force update the lookup maps first
  824. material_manager.initialize()
  825. quality_manager.initialize()
  826. machine_manager.setActiveMachine(global_stack.getId())
  827. if self._quality_changes_to_apply:
  828. quality_changes_group_dict = quality_manager.getQualityChangesGroups(global_stack)
  829. if self._quality_changes_to_apply not in quality_changes_group_dict:
  830. Logger.log("e", "Could not find quality_changes [%s]", self._quality_changes_to_apply)
  831. return
  832. quality_changes_group = quality_changes_group_dict[self._quality_changes_to_apply]
  833. machine_manager.setQualityChangesGroup(quality_changes_group, no_dialog = True)
  834. else:
  835. self._quality_type_to_apply = self._quality_type_to_apply.lower()
  836. quality_group_dict = quality_manager.getQualityGroups(global_stack)
  837. if self._quality_type_to_apply in quality_group_dict:
  838. quality_group = quality_group_dict[self._quality_type_to_apply]
  839. else:
  840. Logger.log("i", "Could not find quality type [%s], switch to default", self._quality_type_to_apply)
  841. preferred_quality_type = global_stack.getMetaDataEntry("preferred_quality_type")
  842. quality_group_dict = quality_manager.getQualityGroups(global_stack)
  843. quality_group = quality_group_dict.get(preferred_quality_type)
  844. if quality_group is None:
  845. Logger.log("e", "Could not get preferred quality type [%s]", preferred_quality_type)
  846. if quality_group is not None:
  847. machine_manager.setQualityGroup(quality_group, no_dialog = True)
  848. # Notify everything/one that is to notify about changes.
  849. global_stack.containersChanged.emit(global_stack.getTop())
  850. def _stripFileToId(self, file):
  851. mime_type = MimeTypeDatabase.getMimeTypeForFile(file)
  852. file = mime_type.stripExtension(file)
  853. return file.replace("Cura/", "")
  854. def _getXmlProfileClass(self):
  855. return self._container_registry.getContainerForMimeType(MimeTypeDatabase.getMimeType("application/x-ultimaker-material-profile"))
  856. ## Get the list of ID's of all containers in a container stack by partially parsing it's serialized data.
  857. def _getContainerIdListFromSerialized(self, serialized):
  858. parser = ConfigParser(interpolation=None, empty_lines_in_values=False)
  859. parser.read_string(serialized)
  860. container_ids = []
  861. if "containers" in parser:
  862. for index, container_id in parser.items("containers"):
  863. container_ids.append(container_id)
  864. elif parser.has_option("general", "containers"):
  865. container_string = parser["general"].get("containers", "")
  866. container_list = container_string.split(",")
  867. container_ids = [container_id for container_id in container_list if container_id != ""]
  868. # HACK: there used to be 6 containers numbering from 0 to 5 in a stack,
  869. # now we have 7: index 5 becomes "definition_changes"
  870. if len(container_ids) == 6:
  871. # Hack; We used to not save the definition changes. Fix this.
  872. container_ids.insert(5, "empty")
  873. return container_ids
  874. def _getMachineNameFromSerializedStack(self, serialized):
  875. parser = ConfigParser(interpolation=None, empty_lines_in_values=False)
  876. parser.read_string(serialized)
  877. return parser["general"].get("name", "")
  878. def _getMaterialLabelFromSerialized(self, serialized):
  879. data = ET.fromstring(serialized)
  880. metadata = data.iterfind("./um:metadata/um:name/um:label", {"um": "http://www.ultimaker.com/material"})
  881. for entry in metadata:
  882. return entry.text