GCodeGzWriter.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import gzip
  4. from io import StringIO, BufferedIOBase #To write the g-code to a temporary buffer, and for typing.
  5. from typing import List
  6. from UM.Logger import Logger
  7. from UM.Mesh.MeshWriter import MeshWriter #The class we're extending/implementing.
  8. from UM.PluginRegistry import PluginRegistry
  9. from UM.Scene.SceneNode import SceneNode #For typing.
  10. ## A file writer that writes gzipped g-code.
  11. #
  12. # If you're zipping g-code, you might as well use gzip!
  13. class GCodeGzWriter(MeshWriter):
  14. ## Writes the gzipped g-code to a stream.
  15. #
  16. # Note that even though the function accepts a collection of nodes, the
  17. # entire scene is always written to the file since it is not possible to
  18. # separate the g-code for just specific nodes.
  19. #
  20. # \param stream The stream to write the gzipped g-code to.
  21. # \param nodes This is ignored.
  22. # \param mode Additional information on what type of stream to use. This
  23. # must always be binary mode.
  24. # \return Whether the write was successful.
  25. def write(self, stream: BufferedIOBase, nodes: List[SceneNode], mode = MeshWriter.OutputMode.BinaryMode) -> bool:
  26. if mode != MeshWriter.OutputMode.BinaryMode:
  27. Logger.log("e", "GCodeGzWriter does not support text mode.")
  28. return False
  29. #Get the g-code from the g-code writer.
  30. gcode_textio = StringIO() #We have to convert the g-code into bytes.
  31. success = PluginRegistry.getInstance().getPluginObject("GCodeWriter").write(gcode_textio, None)
  32. if not success: #Writing the g-code failed. Then I can also not write the gzipped g-code.
  33. return False
  34. result = gzip.compress(gcode_textio.getvalue().encode("utf-8"))
  35. stream.write(result)
  36. return True