ThreeMFWorkspaceWriter.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. # Copyright (c) 2020 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from typing import Optional
  4. import configparser
  5. from io import StringIO
  6. from threading import Lock
  7. import zipfile
  8. from typing import Dict, Any
  9. from UM.Application import Application
  10. from UM.Logger import Logger
  11. from UM.Preferences import Preferences
  12. from UM.Settings.ContainerRegistry import ContainerRegistry
  13. from UM.Workspace.WorkspaceWriter import WorkspaceWriter
  14. from UM.i18n import i18nCatalog
  15. catalog = i18nCatalog("cura")
  16. from .ThreeMFWriter import ThreeMFWriter
  17. from .SettingsExportModel import SettingsExportModel
  18. from .SettingsExportGroup import SettingsExportGroup
  19. USER_SETTINGS_PATH = "Cura/user-settings.json"
  20. class ThreeMFWorkspaceWriter(WorkspaceWriter):
  21. def __init__(self):
  22. super().__init__()
  23. self._ucp_model: Optional[SettingsExportModel] = None
  24. def setExportModel(self, model: SettingsExportModel) -> None:
  25. if self._ucp_model != model:
  26. self._ucp_model = model
  27. def _write(self, stream, nodes, mode=WorkspaceWriter.OutputMode.BinaryMode):
  28. application = Application.getInstance()
  29. machine_manager = application.getMachineManager()
  30. mesh_writer = application.getMeshFileHandler().getWriter("3MFWriter")
  31. if not mesh_writer: # We need to have the 3mf mesh writer, otherwise we can't save the entire workspace
  32. self.setInformation(catalog.i18nc("@error:zip", "3MF Writer plug-in is corrupt."))
  33. Logger.error("3MF Writer class is unavailable. Can't write workspace.")
  34. return False
  35. global_stack = machine_manager.activeMachine
  36. if global_stack is None:
  37. self.setInformation(
  38. catalog.i18nc("@error", "There is no workspace yet to write. Please add a printer first."))
  39. Logger.error("Tried to write a 3MF workspace before there was a global stack.")
  40. return False
  41. # Indicate that the 3mf mesh writer should not close the archive just yet (we still need to add stuff to it).
  42. mesh_writer.setStoreArchive(True)
  43. if not mesh_writer.write(stream, nodes, mode, self._ucp_model):
  44. self.setInformation(mesh_writer.getInformation())
  45. return False
  46. archive = mesh_writer.getArchive()
  47. if archive is None: # This happens if there was no mesh data to write.
  48. archive = zipfile.ZipFile(stream, "w", compression=zipfile.ZIP_DEFLATED)
  49. try:
  50. # Add global container stack data to the archive.
  51. self._writeContainerToArchive(global_stack, archive)
  52. # Also write all containers in the stack to the file
  53. for container in global_stack.getContainers():
  54. self._writeContainerToArchive(container, archive)
  55. # Check if the machine has extruders and save all that data as well.
  56. for extruder_stack in global_stack.extruderList:
  57. self._writeContainerToArchive(extruder_stack, archive)
  58. for container in extruder_stack.getContainers():
  59. self._writeContainerToArchive(container, archive)
  60. # Write user settings data
  61. if self._ucp_model is not None:
  62. user_settings_data = self._getUserSettings(self._ucp_model)
  63. ThreeMFWriter._storeMetadataJson(user_settings_data, archive, USER_SETTINGS_PATH)
  64. except PermissionError:
  65. self.setInformation(catalog.i18nc("@error:zip", "No permission to write the workspace here."))
  66. Logger.error("No permission to write workspace to this stream.")
  67. return False
  68. # Write preferences to archive
  69. original_preferences = Application.getInstance().getPreferences() # Copy only the preferences that we use to the workspace.
  70. temp_preferences = Preferences()
  71. for preference in {"general/visible_settings", "cura/active_mode", "cura/categories_expanded",
  72. "metadata/setting_version"}:
  73. temp_preferences.addPreference(preference, None)
  74. temp_preferences.setValue(preference, original_preferences.getValue(preference))
  75. preferences_string = StringIO()
  76. temp_preferences.writeToFile(preferences_string)
  77. preferences_file = zipfile.ZipInfo("Cura/preferences.cfg")
  78. try:
  79. archive.writestr(preferences_file, preferences_string.getvalue())
  80. # Save Cura version
  81. version_file = zipfile.ZipInfo("Cura/version.ini")
  82. version_config_parser = configparser.ConfigParser(interpolation=None)
  83. version_config_parser.add_section("versions")
  84. version_config_parser.set("versions", "cura_version", application.getVersion())
  85. version_config_parser.set("versions", "build_type", application.getBuildType())
  86. version_config_parser.set("versions", "is_debug_mode", str(application.getIsDebugMode()))
  87. version_file_string = StringIO()
  88. version_config_parser.write(version_file_string)
  89. archive.writestr(version_file, version_file_string.getvalue())
  90. self._writePluginMetadataToArchive(archive)
  91. # Close the archive & reset states.
  92. archive.close()
  93. except PermissionError:
  94. self.setInformation(catalog.i18nc("@error:zip", "No permission to write the workspace here."))
  95. Logger.error("No permission to write workspace to this stream.")
  96. return False
  97. except EnvironmentError as e:
  98. self.setInformation(catalog.i18nc("@error:zip", str(e)))
  99. Logger.error("EnvironmentError when writing workspace to this stream: {err}".format(err=str(e)))
  100. return False
  101. mesh_writer.setStoreArchive(False)
  102. return True
  103. def write(self, stream, nodes, mode=WorkspaceWriter.OutputMode.BinaryMode):
  104. success = self._write(stream, nodes, mode=WorkspaceWriter.OutputMode.BinaryMode)
  105. self._ucp_model = None
  106. return success
  107. @staticmethod
  108. def _writePluginMetadataToArchive(archive: zipfile.ZipFile) -> None:
  109. file_name_template = "%s/plugin_metadata.json"
  110. for plugin_id, metadata in Application.getInstance().getWorkspaceMetadataStorage().getAllData().items():
  111. file_name = file_name_template % plugin_id
  112. file_in_archive = zipfile.ZipInfo(file_name)
  113. # We have to set the compress type of each file as well (it doesn't keep the type of the entire archive)
  114. file_in_archive.compress_type = zipfile.ZIP_DEFLATED
  115. import json
  116. archive.writestr(file_in_archive, json.dumps(metadata, separators = (", ", ": "), indent = 4, skipkeys = True))
  117. @staticmethod
  118. def _writeContainerToArchive(container, archive):
  119. """Helper function that writes ContainerStacks, InstanceContainers and DefinitionContainers to the archive.
  120. :param container: That follows the :type{ContainerInterface} to archive.
  121. :param archive: The archive to write to.
  122. """
  123. if isinstance(container, type(ContainerRegistry.getInstance().getEmptyInstanceContainer())):
  124. return # Empty file, do nothing.
  125. file_suffix = ContainerRegistry.getMimeTypeForContainer(type(container)).preferredSuffix
  126. # Some containers have a base file, which should then be the file to use.
  127. if "base_file" in container.getMetaData():
  128. base_file = container.getMetaDataEntry("base_file")
  129. if base_file != container.getId():
  130. container = ContainerRegistry.getInstance().findContainers(id = base_file)[0]
  131. file_name = "Cura/%s.%s" % (container.getId(), file_suffix)
  132. try:
  133. if file_name in archive.namelist():
  134. return # File was already saved, no need to do it again. Uranium guarantees unique ID's, so this should hold.
  135. file_in_archive = zipfile.ZipInfo(file_name)
  136. # For some reason we have to set the compress type of each file as well (it doesn't keep the type of the entire archive)
  137. file_in_archive.compress_type = zipfile.ZIP_DEFLATED
  138. # Do not include the network authentication keys
  139. ignore_keys = {
  140. "um_cloud_cluster_id",
  141. "um_network_key",
  142. "um_linked_to_account",
  143. "removal_warning",
  144. "host_guid",
  145. "group_name",
  146. "group_size",
  147. "connection_type",
  148. "capabilities",
  149. "octoprint_api_key",
  150. "is_online",
  151. }
  152. serialized_data = container.serialize(ignored_metadata_keys = ignore_keys)
  153. archive.writestr(file_in_archive, serialized_data)
  154. except (FileNotFoundError, EnvironmentError):
  155. Logger.error("File became inaccessible while writing to it: {archive_filename}".format(archive_filename = archive.fp.name))
  156. return
  157. @staticmethod
  158. def _getUserSettings(model: SettingsExportModel) -> Dict[str, Dict[str, Any]]:
  159. user_settings = {}
  160. for group in model.settingsGroups:
  161. category = ''
  162. if group.category == SettingsExportGroup.Category.Global:
  163. category = 'global'
  164. elif group.category == SettingsExportGroup.Category.Extruder:
  165. category = f"extruder_{group.extruder_index}"
  166. if len(category) > 0:
  167. settings_values = {}
  168. stack = group.stack
  169. for setting in group.settings:
  170. if setting.selected:
  171. settings_values[setting.id] = stack.getProperty(setting.id, "value")
  172. user_settings[category] = settings_values
  173. return user_settings