ThreeMFWorkspaceWriter.py 7.9 KB

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