ThreeMFWorkspaceReader.py 54 KB

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