GCodeReader.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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.Application import Application
  7. from UM.MimeTypeDatabase import MimeTypeDatabase, MimeType
  8. catalog = i18nCatalog("cura")
  9. from . import MarlinFlavorParser, RepRapFlavorParser
  10. MimeTypeDatabase.addMimeType(
  11. MimeType(
  12. name = "application/x-cura-gcode-file",
  13. comment = "Cura GCode File",
  14. suffixes = ["gcode", "gcode.gz"]
  15. )
  16. )
  17. # Class for loading and parsing G-code files
  18. class GCodeReader(MeshReader):
  19. _flavor_default = "Marlin"
  20. _flavor_keyword = ";FLAVOR:"
  21. _flavor_readers_dict = {"RepRap" : RepRapFlavorParser.RepRapFlavorParser(),
  22. "Marlin" : MarlinFlavorParser.MarlinFlavorParser()}
  23. def __init__(self, application):
  24. super(GCodeReader, self).__init__(application)
  25. self._supported_extensions = [".gcode", ".g"]
  26. self._flavor_reader = None
  27. Application.getInstance().getPreferences().addPreference("gcodereader/show_caution", True)
  28. def preReadFromStream(self, stream, *args, **kwargs):
  29. for line in stream.split("\n"):
  30. if line[:len(self._flavor_keyword)] == self._flavor_keyword:
  31. try:
  32. self._flavor_reader = self._flavor_readers_dict[line[len(self._flavor_keyword):].rstrip()]
  33. return FileReader.PreReadResult.accepted
  34. except:
  35. # If there is no entry in the dictionary for this flavor, just skip and select the by-default flavor
  36. break
  37. # If no flavor is found in the GCode, then we use the by-default
  38. self._flavor_reader = self._flavor_readers_dict[self._flavor_default]
  39. return FileReader.PreReadResult.accepted
  40. # PreRead is used to get the correct flavor. If not, Marlin is set by default
  41. def preRead(self, file_name, *args, **kwargs):
  42. with open(file_name, "r", encoding = "utf-8") as file:
  43. file_data = file.read()
  44. return self.preReadFromStream(file_data, args, kwargs)
  45. def readFromStream(self, stream):
  46. return self._flavor_reader.processGCodeStream(stream)
  47. def _read(self, file_name):
  48. with open(file_name, "r", encoding = "utf-8") as file:
  49. file_data = file.read()
  50. return self.readFromStream(file_data)