UFPWriter.py 7.1 KB

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