UFPWriter.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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 UM.Scene.SceneNode import SceneNode
  15. from cura.CuraApplication import CuraApplication
  16. from cura.Utils.Threading import call_on_qt_thread
  17. from UM.i18n import i18nCatalog
  18. METADATA_OBJECTS_PATH = "metadata/objects"
  19. catalog = i18nCatalog("cura")
  20. class UFPWriter(MeshWriter):
  21. def __init__(self):
  22. super().__init__(add_to_recent_files = False)
  23. MimeTypeDatabase.addMimeType(
  24. MimeType(
  25. name = "application/x-ufp",
  26. comment = "Ultimaker Format Package",
  27. suffixes = ["ufp"]
  28. )
  29. )
  30. # This needs to be called on the main thread (Qt thread) because the serialization of material containers can
  31. # trigger loading other containers. Because those loaded containers are QtObjects, they must be created on the
  32. # Qt thread. The File read/write operations right now are executed on separated threads because they are scheduled
  33. # by the Job class.
  34. @call_on_qt_thread
  35. def write(self, stream, nodes, mode = MeshWriter.OutputMode.BinaryMode):
  36. archive = VirtualFile()
  37. archive.openStream(stream, "application/x-ufp", OpenMode.WriteOnly)
  38. try:
  39. self._writeObjectList(archive)
  40. # Store the g-code from the scene.
  41. archive.addContentType(extension = "gcode", mime_type = "text/x-gcode")
  42. except EnvironmentError as e:
  43. error_msg = catalog.i18nc("@info:error", "Can't write to UFP file:") + " " + str(e)
  44. self.setInformation(error_msg)
  45. Logger.error(error_msg)
  46. return False
  47. gcode_textio = StringIO() # We have to convert the g-code into bytes.
  48. gcode_writer = cast(MeshWriter, PluginRegistry.getInstance().getPluginObject("GCodeWriter"))
  49. success = gcode_writer.write(gcode_textio, None)
  50. if not success: # Writing the g-code failed. Then I can also not write the gzipped g-code.
  51. self.setInformation(gcode_writer.getInformation())
  52. return False
  53. try:
  54. gcode = archive.getStream("/3D/model.gcode")
  55. gcode.write(gcode_textio.getvalue().encode("UTF-8"))
  56. archive.addRelation(virtual_path = "/3D/model.gcode", relation_type = "http://schemas.ultimaker.org/package/2018/relationships/gcode")
  57. except EnvironmentError as e:
  58. error_msg = catalog.i18nc("@info:error", "Can't write to UFP file:") + " " + str(e)
  59. self.setInformation(error_msg)
  60. Logger.error(error_msg)
  61. return False
  62. # Attempt to store the thumbnail, if any:
  63. backend = CuraApplication.getInstance().getBackend()
  64. snapshot = None if getattr(backend, "getLatestSnapshot", None) is None else backend.getLatestSnapshot()
  65. if snapshot:
  66. try:
  67. archive.addContentType(extension = "png", mime_type = "image/png")
  68. thumbnail = archive.getStream("/Metadata/thumbnail.png")
  69. thumbnail_buffer = QBuffer()
  70. thumbnail_buffer.open(QBuffer.OpenModeFlag.ReadWrite)
  71. snapshot.save(thumbnail_buffer, "PNG")
  72. thumbnail.write(thumbnail_buffer.data())
  73. archive.addRelation(virtual_path = "/Metadata/thumbnail.png",
  74. relation_type = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail",
  75. origin = "/3D/model.gcode")
  76. except EnvironmentError as e:
  77. error_msg = catalog.i18nc("@info:error", "Can't write to UFP file:") + " " + str(e)
  78. self.setInformation(error_msg)
  79. Logger.error(error_msg)
  80. return False
  81. else:
  82. Logger.log("w", "Thumbnail not created, cannot save it")
  83. # Store the material.
  84. application = CuraApplication.getInstance()
  85. machine_manager = application.getMachineManager()
  86. container_registry = application.getContainerRegistry()
  87. global_stack = machine_manager.activeMachine
  88. material_extension = "xml.fdm_material"
  89. material_mime_type = "application/x-ultimaker-material-profile"
  90. try:
  91. archive.addContentType(extension = material_extension, mime_type = material_mime_type)
  92. except OPCError:
  93. Logger.log("w", "The material extension: %s was already added", material_extension)
  94. added_materials = []
  95. for extruder_stack in global_stack.extruderList:
  96. material = extruder_stack.material
  97. try:
  98. material_file_name = material.getMetaData()["base_file"] + ".xml.fdm_material"
  99. except KeyError:
  100. Logger.log("w", "Unable to get base_file for the material %s", material.getId())
  101. continue
  102. material_file_name = "/Materials/" + material_file_name
  103. # The same material should not be added again.
  104. if material_file_name in added_materials:
  105. continue
  106. material_root_id = material.getMetaDataEntry("base_file")
  107. material_root_query = container_registry.findContainers(id = material_root_id)
  108. if not material_root_query:
  109. Logger.log("e", "Cannot find material container with root id {root_id}".format(root_id = material_root_id))
  110. return False
  111. material_container = material_root_query[0]
  112. try:
  113. serialized_material = material_container.serialize()
  114. except NotImplementedError:
  115. Logger.log("e", "Unable serialize material container with root id: %s", material_root_id)
  116. return False
  117. try:
  118. material_file = archive.getStream(material_file_name)
  119. material_file.write(serialized_material.encode("UTF-8"))
  120. archive.addRelation(virtual_path = material_file_name,
  121. relation_type = "http://schemas.ultimaker.org/package/2018/relationships/material",
  122. origin = "/3D/model.gcode")
  123. except EnvironmentError as e:
  124. error_msg = catalog.i18nc("@info:error", "Can't write to UFP file:") + " " + str(e)
  125. self.setInformation(error_msg)
  126. Logger.error(error_msg)
  127. return False
  128. added_materials.append(material_file_name)
  129. try:
  130. archive.close()
  131. except EnvironmentError as e:
  132. error_msg = catalog.i18nc("@info:error", "Can't write to UFP file:") + " " + str(e)
  133. self.setInformation(error_msg)
  134. Logger.error(error_msg)
  135. return False
  136. return True
  137. @staticmethod
  138. def _writeObjectList(archive):
  139. """Write a json list of object names to the METADATA_OBJECTS_PATH metadata field
  140. To retrieve, use: `archive.getMetadata(METADATA_OBJECTS_PATH)`
  141. """
  142. objects_model = CuraApplication.getInstance().getObjectsModel()
  143. object_metas = []
  144. for item in objects_model.items:
  145. object_metas.extend(UFPWriter._getObjectMetadata(item["node"]))
  146. data = {METADATA_OBJECTS_PATH: object_metas}
  147. archive.setMetadata(data)
  148. @staticmethod
  149. def _getObjectMetadata(node: SceneNode) -> List[Dict[str, str]]:
  150. """Get object metadata to write for a Node.
  151. :return: List of object metadata dictionaries.
  152. Might contain > 1 element in case of a group node.
  153. Might be empty in case of nonPrintingMesh
  154. """
  155. return [{"name": item.getName()}
  156. for item in DepthFirstIterator(node)
  157. if item.getMeshData() is not None and not item.callDecoration("isNonPrintingMesh")]