GCodeReader.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # Copyright (c) 2017 Aleph Objects, Inc.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from UM.FileHandler.FileReader import FileReader
  4. from UM.Mesh.MeshReader import MeshReader
  5. from UM.i18n import i18nCatalog
  6. from UM.Preferences import Preferences
  7. catalog = i18nCatalog("cura")
  8. from . import MarlinFlavorParser, RepRapFlavorParser
  9. # Class for loading and parsing G-code files
  10. class GCodeReader(MeshReader):
  11. _flavor_default = "Marlin"
  12. _flavor_keyword = ";FLAVOR:"
  13. _flavor_readers_dict = {"RepRap" : RepRapFlavorParser.RepRapFlavorParser(),
  14. "Marlin" : MarlinFlavorParser.MarlinFlavorParser()}
  15. def __init__(self):
  16. super(GCodeReader, self).__init__()
  17. self._supported_extensions = [".gcode", ".g"]
  18. self._flavor_reader = None
  19. Preferences.getInstance().addPreference("gcodereader/show_caution", True)
  20. def preReadFromStream(self, stream, *args, **kwargs):
  21. for line in stream.split("\n"):
  22. if line[:len(self._flavor_keyword)] == self._flavor_keyword:
  23. try:
  24. self._flavor_reader = self._flavor_readers_dict[line[len(self._flavor_keyword):].rstrip()]
  25. return FileReader.PreReadResult.accepted
  26. except:
  27. # If there is no entry in the dictionary for this flavor, just skip and select the by-default flavor
  28. break
  29. # If no flavor is found in the GCode, then we use the by-default
  30. self._flavor_reader = self._flavor_readers_dict[self._flavor_default]
  31. return FileReader.PreReadResult.accepted
  32. # PreRead is used to get the correct flavor. If not, Marlin is set by default
  33. def preRead(self, file_name, *args, **kwargs):
  34. with open(file_name, "r", encoding = "utf-8") as file:
  35. file_data = file.read()
  36. return self.preReadFromStream(file_data, args, kwargs)
  37. def readFromStream(self, stream):
  38. return self._flavor_reader.processGCodeStream(stream)
  39. def read(self, file_name):
  40. with open(file_name, "r", encoding = "utf-8") as file:
  41. file_data = file.read()
  42. return self.readFromStream(file_data)