GCodeGzWriter.py 2.2 KB

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