GCodeGzWriter.py 2.2 KB

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