GCodeReader.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. # Copyright (c) 2015 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. from UM.Mesh.MeshReader import MeshReader
  4. ## A class that reads profile data from g-code files.
  5. #
  6. # It reads the profile data from g-code files and stores the profile as a new
  7. # profile, and then immediately activates that profile.
  8. # This class currently does not process the rest of the g-code in any way.
  9. class GCodeReader(MeshReader):
  10. ## Initialises the g-code reader as a mesh reader.
  11. def __init__(self):
  12. super().__init__()
  13. ## Reads a g-code file, loading the profile from it.
  14. def read(self, file_name):
  15. version = 1 #IF YOU CHANGE THIS FUNCTION IN A WAY THAT BREAKS REVERSE COMPATIBILITY, INCREMENT THIS VERSION NUMBER!
  16. prefix = ";SETTING_" + str(version) + " "
  17. #Loading all settings from the file. They are all at the end, but Python has no reverse seek any more since Python3. TODO: Consider moving settings to the start?
  18. serialised = "" #Will be filled with the serialised profile.
  19. try:
  20. with open(file_name) as f:
  21. for line in f:
  22. if line.startswith(prefix):
  23. serialised += line[len(prefix):] #Remove the prefix from the line, and add it to the rest.
  24. except IOError as e:
  25. Logger.log("e", "Unable to open file %s for reading: %s", file_name, str(e))
  26. #Unescape the serialised profile.
  27. escape_characters = { #Which special characters (keys) are replaced by what escape character (values).
  28. #Note: The keys are regex strings. Values are not.
  29. "\\\\": "\\", #The escape character.
  30. "\\n": "\n", #Newlines. They break off the comment.
  31. "\\r": "\r" #Carriage return. Windows users may need this for visualisation in their editors.
  32. }
  33. escape_characters = dict((re.escape(key), value) for key, value in escape_characters.items())
  34. pattern = re.compile("|".join(escape_characters.keys()))
  35. serialised = pattern.sub(lambda m: escape_characters[re.escape(m.group(0))], serialised) #Perform the replacement with a regular expression.
  36. #Apply the changes to the current profile.
  37. profile = Application.getInstance().getMachineManager().getActiveProfile()
  38. profile.unserialise(serialised)