GCodeReader.py 2.5 KB

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