UFPWriter.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from typing import cast, List, Dict
  4. from Charon.VirtualFile import VirtualFile # To open UFP files.
  5. from Charon.OpenMode import OpenMode # To indicate that we want to write to UFP files.
  6. from Charon.filetypes.OpenPackagingConvention import OPCError
  7. from io import StringIO # For converting g-code to bytes.
  8. from PyQt6.QtCore import QBuffer
  9. from UM.Logger import Logger
  10. from UM.Mesh.MeshWriter import MeshWriter # The writer we need to implement.
  11. from UM.MimeTypeDatabase import MimeTypeDatabase, MimeType
  12. from UM.PluginRegistry import PluginRegistry # To get the g-code writer.
  13. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  14. from cura.CuraApplication import CuraApplication
  15. from cura.CuraPackageManager import CuraPackageManager
  16. from cura.Utils.Threading import call_on_qt_thread
  17. from UM.i18n import i18nCatalog
  18. METADATA_OBJECTS_PATH = "metadata/objects"
  19. METADATA_MATERIALS_PATH = "metadata/packages"
  20. catalog = i18nCatalog("cura")
  21. class UFPWriter(MeshWriter):
  22. def __init__(self):
  23. super().__init__(add_to_recent_files = False)
  24. MimeTypeDatabase.addMimeType(
  25. MimeType(
  26. name = "application/x-ufp",
  27. comment = "Ultimaker Format Package",
  28. suffixes = ["ufp"]
  29. )
  30. )
  31. # This needs to be called on the main thread (Qt thread) because the serialization of material containers can
  32. # trigger loading other containers. Because those loaded containers are QtObjects, they must be created on the
  33. # Qt thread. The File read/write operations right now are executed on separated threads because they are scheduled
  34. # by the Job class.
  35. @call_on_qt_thread
  36. def write(self, stream, nodes, mode = MeshWriter.OutputMode.BinaryMode):
  37. archive = VirtualFile()
  38. archive.openStream(stream, "application/x-ufp", OpenMode.WriteOnly)
  39. try:
  40. self._writeMetadata(archive)
  41. # Store the g-code from the scene.
  42. archive.addContentType(extension = "gcode", mime_type = "text/x-gcode")
  43. except EnvironmentError as e:
  44. error_msg = catalog.i18nc("@info:error", "Can't write to UFP file:") + " " + str(e)
  45. self.setInformation(error_msg)
  46. Logger.error(error_msg)
  47. return False
  48. gcode_textio = StringIO() # We have to convert the g-code into bytes.
  49. gcode_writer = cast(MeshWriter, PluginRegistry.getInstance().getPluginObject("GCodeWriter"))
  50. success = gcode_writer.write(gcode_textio, None)
  51. if not success: # Writing the g-code failed. Then I can also not write the gzipped g-code.
  52. self.setInformation(gcode_writer.getInformation())
  53. return False
  54. try:
  55. gcode = archive.getStream("/3D/model.gcode")
  56. gcode.write(gcode_textio.getvalue().encode("UTF-8"))
  57. archive.addRelation(virtual_path = "/3D/model.gcode", relation_type = "http://schemas.ultimaker.org/package/2018/relationships/gcode")
  58. except EnvironmentError as e:
  59. error_msg = catalog.i18nc("@info:error", "Can't write to UFP file:") + " " + str(e)
  60. self.setInformation(error_msg)
  61. Logger.error(error_msg)
  62. return False
  63. # Attempt to store the thumbnail, if any:
  64. backend = CuraApplication.getInstance().getBackend()
  65. snapshot = None if getattr(backend, "getLatestSnapshot", None) is None else backend.getLatestSnapshot()
  66. if snapshot:
  67. try:
  68. archive.addContentType(extension = "png", mime_type = "image/png")
  69. thumbnail = archive.getStream("/Metadata/thumbnail.png")
  70. thumbnail_buffer = QBuffer()
  71. thumbnail_buffer.open(QBuffer.OpenModeFlag.ReadWrite)
  72. snapshot.save(thumbnail_buffer, "PNG")
  73. thumbnail.write(thumbnail_buffer.data())
  74. archive.addRelation(virtual_path = "/Metadata/thumbnail.png",
  75. relation_type = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail",
  76. origin = "/3D/model.gcode")
  77. except EnvironmentError as e:
  78. error_msg = catalog.i18nc("@info:error", "Can't write to UFP file:") + " " + str(e)
  79. self.setInformation(error_msg)
  80. Logger.error(error_msg)
  81. return False
  82. else:
  83. Logger.log("w", "Thumbnail not created, cannot save it")
  84. # Store the material.
  85. application = CuraApplication.getInstance()
  86. machine_manager = application.getMachineManager()
  87. container_registry = application.getContainerRegistry()
  88. global_stack = machine_manager.activeMachine
  89. material_extension = "xml.fdm_material"
  90. material_mime_type = "application/x-ultimaker-material-profile"
  91. try:
  92. archive.addContentType(extension = material_extension, mime_type = material_mime_type)
  93. except OPCError:
  94. Logger.log("w", "The material extension: %s was already added", material_extension)
  95. added_materials = []
  96. for extruder_stack in global_stack.extruderList:
  97. material = extruder_stack.material
  98. try:
  99. material_file_name = material.getMetaData()["base_file"] + ".xml.fdm_material"
  100. except KeyError:
  101. Logger.log("w", "Unable to get base_file for the material %s", material.getId())
  102. continue
  103. material_file_name = "/Materials/" + material_file_name
  104. # The same material should not be added again.
  105. if material_file_name in added_materials:
  106. continue
  107. material_root_id = material.getMetaDataEntry("base_file")
  108. material_root_query = container_registry.findContainers(id = material_root_id)
  109. if not material_root_query:
  110. Logger.log("e", "Cannot find material container with root id {root_id}".format(root_id = material_root_id))
  111. return False
  112. material_container = material_root_query[0]
  113. try:
  114. serialized_material = material_container.serialize()
  115. except NotImplementedError:
  116. Logger.log("e", "Unable serialize material container with root id: %s", material_root_id)
  117. return False
  118. try:
  119. material_file = archive.getStream(material_file_name)
  120. material_file.write(serialized_material.encode("UTF-8"))
  121. archive.addRelation(virtual_path = material_file_name,
  122. relation_type = "http://schemas.ultimaker.org/package/2018/relationships/material",
  123. origin = "/3D/model.gcode")
  124. except EnvironmentError as e:
  125. error_msg = catalog.i18nc("@info:error", "Can't write to UFP file:") + " " + str(e)
  126. self.setInformation(error_msg)
  127. Logger.error(error_msg)
  128. return False
  129. added_materials.append(material_file_name)
  130. try:
  131. archive.close()
  132. except EnvironmentError as e:
  133. error_msg = catalog.i18nc("@info:error", "Can't write to UFP file:") + " " + str(e)
  134. self.setInformation(error_msg)
  135. Logger.error(error_msg)
  136. return False
  137. return True
  138. @staticmethod
  139. def _writeMetadata(archive: VirtualFile):
  140. material_metadata = UFPWriter._getMaterialPackageMetadata()
  141. object_metadata = UFPWriter._getObjectMetadata()
  142. data = {METADATA_MATERIALS_PATH: material_metadata,
  143. METADATA_OBJECTS_PATH: object_metadata}
  144. archive.setMetadata(data)
  145. @staticmethod
  146. def _getObjectMetadata() -> List[Dict[str, str]]:
  147. """Get object metadata to write for a Node.
  148. :return: List of object metadata dictionaries.
  149. """
  150. metadata = []
  151. objects_model = CuraApplication.getInstance().getObjectsModel()
  152. for item in objects_model.items:
  153. for node in DepthFirstIterator(item["node"]):
  154. if node.getMeshData() is not None and not node.callDecoration("isNonPrintingMesh"):
  155. metadata.extend({"name": node.getName()})
  156. return metadata
  157. @staticmethod
  158. def _getMaterialPackageMetadata() -> List[Dict[str, str]]:
  159. """Get metadata for installed materials in active extruder stack, this does not include bundled materials.
  160. :return: List of material metadata dictionaries.
  161. """
  162. metadata = []
  163. package_manager = cast(CuraPackageManager, CuraApplication.getInstance().getPackageManager())
  164. for extruder in CuraApplication.getInstance().getExtruderManager().getActiveExtruderStacks():
  165. if not extruder.isEnabled:
  166. # Don't export materials not in use
  167. continue
  168. package_id = package_manager.getMaterialFilePackageId(extruder.material.getFileName(), extruder.material.getMetaDataEntry("GUID"))
  169. package_data = package_manager.getInstalledPackageInfo(package_id)
  170. if not package_data or package_data.get("is_bundled"):
  171. continue
  172. material_metadata = {"id": package_id,
  173. "display_name": package_data.get("display_name"),
  174. "website": package_data.get("website"),
  175. "package_version": package_data.get("package_version"),
  176. "sdk_version_semver": package_data.get("package_version_semver")}
  177. metadata.append(material_metadata)
  178. return metadata