UFPWriter.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #Copyright (c) 2018 Ultimaker B.V.
  2. #Cura is released under the terms of the LGPLv3 or higher.
  3. from Charon.VirtualFile import VirtualFile #To open UFP files.
  4. from Charon.OpenMode import OpenMode #To indicate that we want to write to UFP files.
  5. from io import StringIO #For converting g-code to bytes.
  6. from UM.Application import Application
  7. from UM.Logger import Logger
  8. from UM.Mesh.MeshWriter import MeshWriter #The writer we need to implement.
  9. from UM.PluginRegistry import PluginRegistry #To get the g-code writer.
  10. from PyQt5.QtCore import QBuffer
  11. from cura.Snapshot import Snapshot
  12. class UFPWriter(MeshWriter):
  13. def __init__(self):
  14. super().__init__()
  15. self._snapshot = None
  16. Application.getInstance().getOutputDeviceManager().writeStarted.connect(self._createSnapshot)
  17. def _createSnapshot(self, *args):
  18. # must be called from the main thread because of OpenGL
  19. Logger.log("d", "Creating thumbnail image...")
  20. self._snapshot = Snapshot.snapshot(width = 300, height = 300)
  21. def write(self, stream, nodes, mode = MeshWriter.OutputMode.BinaryMode):
  22. archive = VirtualFile()
  23. archive.openStream(stream, "application/x-ufp", OpenMode.WriteOnly)
  24. #Store the g-code from the scene.
  25. archive.addContentType(extension = "gcode", mime_type = "text/x-gcode")
  26. gcode_textio = StringIO() #We have to convert the g-code into bytes.
  27. PluginRegistry.getInstance().getPluginObject("GCodeWriter").write(gcode_textio, None)
  28. gcode = archive.getStream("/3D/model.gcode")
  29. gcode.write(gcode_textio.getvalue().encode("UTF-8"))
  30. archive.addRelation(virtual_path = "/3D/model.gcode", relation_type = "http://schemas.ultimaker.org/package/2018/relationships/gcode")
  31. #Store the thumbnail.
  32. if self._snapshot:
  33. archive.addContentType(extension = "png", mime_type = "image/png")
  34. thumbnail = archive.getStream("/Metadata/thumbnail.png")
  35. thumbnail_buffer = QBuffer()
  36. thumbnail_buffer.open(QBuffer.ReadWrite)
  37. thumbnail_image = self._snapshot
  38. thumbnail_image.save(thumbnail_buffer, "PNG")
  39. thumbnail.write(thumbnail_buffer.data())
  40. archive.addRelation(virtual_path = "/Metadata/thumbnail.png", relation_type = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail", origin = "/3D/model.gcode")
  41. else:
  42. Logger.log("d", "Thumbnail not created, cannot save it")
  43. archive.close()
  44. return True