GCodeReader.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. # PreRead is used to get the correct flavor. If not, Marlin is set by default
  21. def preRead(self, file_name, *args, **kwargs):
  22. with open(file_name, "r", encoding = "utf-8") as file:
  23. for line in file:
  24. if line[:len(self._flavor_keyword)] == self._flavor_keyword:
  25. try:
  26. self._flavor_reader = self._flavor_readers_dict[line[len(self._flavor_keyword):].rstrip()]
  27. return FileReader.PreReadResult.accepted
  28. except:
  29. # If there is no entry in the dictionary for this flavor, just skip and select the by-default flavor
  30. break
  31. # If no flavor is found in the GCode, then we use the by-default
  32. self._flavor_reader = self._flavor_readers_dict[self._flavor_default]
  33. return FileReader.PreReadResult.accepted
  34. def read(self, file_name):
  35. return self._flavor_reader.processGCodeFile(file_name)