UFPWriter.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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. catalog = i18nCatalog("cura")
  17. class UFPWriter(MeshWriter):
  18. def __init__(self):
  19. super().__init__(add_to_recent_files = False)
  20. MimeTypeDatabase.addMimeType(
  21. MimeType(
  22. name = "application/x-ufp",
  23. comment = "Ultimaker Format Package",
  24. suffixes = ["ufp"]
  25. )
  26. )
  27. self._snapshot = None
  28. def _createSnapshot(self, *args):
  29. # must be called from the main thread because of OpenGL
  30. Logger.log("d", "Creating thumbnail image...")
  31. try:
  32. self._snapshot = Snapshot.snapshot(width = 300, height = 300)
  33. except Exception:
  34. Logger.logException("w", "Failed to create snapshot image")
  35. self._snapshot = None # Failing to create thumbnail should not fail creation of UFP
  36. # This needs to be called on the main thread (Qt thread) because the serialization of material containers can
  37. # trigger loading other containers. Because those loaded containers are QtObjects, they must be created on the
  38. # Qt thread. The File read/write operations right now are executed on separated threads because they are scheduled
  39. # by the Job class.
  40. @call_on_qt_thread
  41. def write(self, stream, nodes, mode = MeshWriter.OutputMode.BinaryMode):
  42. archive = VirtualFile()
  43. archive.openStream(stream, "application/x-ufp", OpenMode.WriteOnly)
  44. #Store the g-code from the scene.
  45. archive.addContentType(extension = "gcode", mime_type = "text/x-gcode")
  46. gcode_textio = StringIO() #We have to convert the g-code into bytes.
  47. gcode_writer = cast(MeshWriter, PluginRegistry.getInstance().getPluginObject("GCodeWriter"))
  48. success = gcode_writer.write(gcode_textio, None)
  49. if not success: #Writing the g-code failed. Then I can also not write the gzipped g-code.
  50. self.setInformation(gcode_writer.getInformation())
  51. return False
  52. gcode = archive.getStream("/3D/model.gcode")
  53. gcode.write(gcode_textio.getvalue().encode("UTF-8"))
  54. archive.addRelation(virtual_path = "/3D/model.gcode", relation_type = "http://schemas.ultimaker.org/package/2018/relationships/gcode")
  55. self._createSnapshot()
  56. #Store the thumbnail.
  57. if self._snapshot:
  58. archive.addContentType(extension = "png", mime_type = "image/png")
  59. thumbnail = archive.getStream("/Metadata/thumbnail.png")
  60. thumbnail_buffer = QBuffer()
  61. thumbnail_buffer.open(QBuffer.ReadWrite)
  62. thumbnail_image = self._snapshot
  63. thumbnail_image.save(thumbnail_buffer, "PNG")
  64. thumbnail.write(thumbnail_buffer.data())
  65. archive.addRelation(virtual_path = "/Metadata/thumbnail.png", relation_type = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail", origin = "/3D/model.gcode")
  66. else:
  67. Logger.log("d", "Thumbnail not created, cannot save it")
  68. # Store the material.
  69. application = CuraApplication.getInstance()
  70. machine_manager = application.getMachineManager()
  71. container_registry = application.getContainerRegistry()
  72. global_stack = machine_manager.activeMachine
  73. material_extension = "xml.fdm_material"
  74. material_mime_type = "application/x-ultimaker-material-profile"
  75. try:
  76. archive.addContentType(extension = material_extension, mime_type = material_mime_type)
  77. except:
  78. Logger.log("w", "The material extension: %s was already added", material_extension)
  79. added_materials = []
  80. for extruder_stack in global_stack.extruders.values():
  81. material = extruder_stack.material
  82. try:
  83. material_file_name = material.getMetaData()["base_file"] + ".xml.fdm_material"
  84. except KeyError:
  85. Logger.log("w", "Unable to get base_file for the material %s", material.getId())
  86. continue
  87. material_file_name = "/Materials/" + material_file_name
  88. # The same material should not be added again.
  89. if material_file_name in added_materials:
  90. continue
  91. material_root_id = material.getMetaDataEntry("base_file")
  92. material_root_query = container_registry.findContainers(id = material_root_id)
  93. if not material_root_query:
  94. Logger.log("e", "Cannot find material container with root id {root_id}".format(root_id = material_root_id))
  95. return False
  96. material_container = material_root_query[0]
  97. try:
  98. serialized_material = material_container.serialize()
  99. except NotImplementedError:
  100. Logger.log("e", "Unable serialize material container with root id: %s", material_root_id)
  101. return False
  102. material_file = archive.getStream(material_file_name)
  103. material_file.write(serialized_material.encode("UTF-8"))
  104. archive.addRelation(virtual_path = material_file_name,
  105. relation_type = "http://schemas.ultimaker.org/package/2018/relationships/material",
  106. origin = "/3D/model.gcode")
  107. added_materials.append(material_file_name)
  108. try:
  109. archive.close()
  110. except OSError as e:
  111. error_msg = catalog.i18nc("@info:error", "Can't write to UFP file:") + " " + str(e)
  112. self.setInformation(error_msg)
  113. Logger.error(error_msg)
  114. return False
  115. return True