ThreeMFWorkspaceWriter.py 11 KB

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