GCodeGzWriter.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 cast, 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. from UM.i18n import i18nCatalog
  11. catalog = i18nCatalog("cura")
  12. ## A file writer that writes gzipped g-code.
  13. #
  14. # If you're zipping g-code, you might as well use gzip!
  15. class GCodeGzWriter(MeshWriter):
  16. ## Writes the gzipped g-code to a stream.
  17. #
  18. # Note that even though the function accepts a collection of nodes, the
  19. # entire scene is always written to the file since it is not possible to
  20. # separate the g-code for just specific nodes.
  21. #
  22. # \param stream The stream to write the gzipped g-code to.
  23. # \param nodes This is ignored.
  24. # \param mode Additional information on what type of stream to use. This
  25. # must always be binary mode.
  26. # \return Whether the write was successful.
  27. def write(self, stream: BufferedIOBase, nodes: List[SceneNode], mode = MeshWriter.OutputMode.BinaryMode) -> bool:
  28. if mode != MeshWriter.OutputMode.BinaryMode:
  29. Logger.log("e", "GCodeGzWriter does not support text mode.")
  30. self.setInformation(catalog.i18nc("@error:not supported", "GCodeGzWriter does not support text mode."))
  31. return False
  32. #Get the g-code from the g-code writer.
  33. gcode_textio = StringIO() #We have to convert the g-code into bytes.
  34. gcode_writer = cast(MeshWriter, PluginRegistry.getInstance().getPluginObject("GCodeWriter"))
  35. success = gcode_writer.write(gcode_textio, None)
  36. if not success: #Writing the g-code failed. Then I can also not write the gzipped g-code.
  37. self.setInformation(gcode_writer.getInformation())
  38. return False
  39. result = gzip.compress(gcode_textio.getvalue().encode("utf-8"))
  40. stream.write(result)
  41. return True