UFPWriter.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. #Copyright (c) 2020 Ultimaker B.V.
  2. #Cura is released under the terms of the LGPLv3 or higher.
  3. from typing import cast
  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 UM.Logger import Logger
  8. from UM.Mesh.MeshWriter import MeshWriter #The writer we need to implement.
  9. from UM.MimeTypeDatabase import MimeTypeDatabase, MimeType
  10. from UM.PluginRegistry import PluginRegistry #To get the g-code writer.
  11. from PyQt5.QtCore import QBuffer
  12. from cura.CuraApplication import CuraApplication
  13. from cura.Snapshot import Snapshot
  14. from cura.Utils.Threading import call_on_qt_thread
  15. from UM.i18n import i18nCatalog
  16. METADATA_OBJECTS_PATH = "metadata/objects"
  17. catalog = i18nCatalog("cura")
  18. class UFPWriter(MeshWriter):
  19. def __init__(self):
  20. super().__init__(add_to_recent_files = False)
  21. MimeTypeDatabase.addMimeType(
  22. MimeType(
  23. name = "application/x-ufp",
  24. comment = "Ultimaker Format Package",
  25. suffixes = ["ufp"]
  26. )
  27. )
  28. self._snapshot = None
  29. def _createSnapshot(self, *args):
  30. # must be called from the main thread because of OpenGL
  31. Logger.log("d", "Creating thumbnail image...")
  32. try:
  33. self._snapshot = Snapshot.snapshot(width = 300, height = 300)
  34. except Exception:
  35. Logger.logException("w", "Failed to create snapshot image")
  36. self._snapshot = None # Failing to create thumbnail should not fail creation of UFP
  37. # This needs to be called on the main thread (Qt thread) because the serialization of material containers can
  38. # trigger loading other containers. Because those loaded containers are QtObjects, they must be created on the
  39. # Qt thread. The File read/write operations right now are executed on separated threads because they are scheduled
  40. # by the Job class.
  41. @call_on_qt_thread
  42. def write(self, stream, nodes, mode = MeshWriter.OutputMode.BinaryMode):
  43. archive = VirtualFile()
  44. archive.openStream(stream, "application/x-ufp", OpenMode.WriteOnly)
  45. self._writeObjectList(archive)
  46. #Store the g-code from the scene.
  47. archive.addContentType(extension = "gcode", mime_type = "text/x-gcode")
  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. 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. self._createSnapshot()
  58. #Store the thumbnail.
  59. if self._snapshot:
  60. archive.addContentType(extension = "png", mime_type = "image/png")
  61. thumbnail = archive.getStream("/Metadata/thumbnail.png")
  62. thumbnail_buffer = QBuffer()
  63. thumbnail_buffer.open(QBuffer.ReadWrite)
  64. thumbnail_image = self._snapshot
  65. thumbnail_image.save(thumbnail_buffer, "PNG")
  66. thumbnail.write(thumbnail_buffer.data())
  67. archive.addRelation(virtual_path = "/Metadata/thumbnail.png", relation_type = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail", origin = "/3D/model.gcode")
  68. else:
  69. Logger.log("d", "Thumbnail not created, cannot save it")
  70. # Store the material.
  71. application = CuraApplication.getInstance()
  72. machine_manager = application.getMachineManager()
  73. container_registry = application.getContainerRegistry()
  74. global_stack = machine_manager.activeMachine
  75. material_extension = "xml.fdm_material"
  76. material_mime_type = "application/x-ultimaker-material-profile"
  77. try:
  78. archive.addContentType(extension = material_extension, mime_type = material_mime_type)
  79. except:
  80. Logger.log("w", "The material extension: %s was already added", material_extension)
  81. added_materials = []
  82. for extruder_stack in global_stack.extruderList:
  83. material = extruder_stack.material
  84. try:
  85. material_file_name = material.getMetaData()["base_file"] + ".xml.fdm_material"
  86. except KeyError:
  87. Logger.log("w", "Unable to get base_file for the material %s", material.getId())
  88. continue
  89. material_file_name = "/Materials/" + material_file_name
  90. # The same material should not be added again.
  91. if material_file_name in added_materials:
  92. continue
  93. material_root_id = material.getMetaDataEntry("base_file")
  94. material_root_query = container_registry.findContainers(id = material_root_id)
  95. if not material_root_query:
  96. Logger.log("e", "Cannot find material container with root id {root_id}".format(root_id = material_root_id))
  97. return False
  98. material_container = material_root_query[0]
  99. try:
  100. serialized_material = material_container.serialize()
  101. except NotImplementedError:
  102. Logger.log("e", "Unable serialize material container with root id: %s", material_root_id)
  103. return False
  104. material_file = archive.getStream(material_file_name)
  105. material_file.write(serialized_material.encode("UTF-8"))
  106. archive.addRelation(virtual_path = material_file_name,
  107. relation_type = "http://schemas.ultimaker.org/package/2018/relationships/material",
  108. origin = "/3D/model.gcode")
  109. added_materials.append(material_file_name)
  110. try:
  111. archive.close()
  112. except OSError as e:
  113. error_msg = catalog.i18nc("@info:error", "Can't write to UFP file:") + " " + str(e)
  114. self.setInformation(error_msg)
  115. Logger.error(error_msg)
  116. return False
  117. return True
  118. @staticmethod
  119. def _writeObjectList(archive):
  120. """Write a json list of object names to the METADATA_OBJECTS_PATH metadata field
  121. To retrieve, use: `archive.getMetadata(METADATA_OBJECTS_PATH)`
  122. """
  123. objectsModel = CuraApplication.getInstance().getObjectsModel()
  124. objectMetas = [{"name": item["name"]} for item in objectsModel.items]
  125. data = {METADATA_OBJECTS_PATH: objectMetas}
  126. archive.setMetadata(data)