LegacyProfileReader.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. # Copyright (c) 2015 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. import configparser #For reading the legacy profile INI files.
  4. import json #For reading the Dictionary of Doom.
  5. import math #For mathematical operations included in the Dictionary of Doom.
  6. import os.path #For concatenating the path to the plugin and the relative path to the Dictionary of Doom.
  7. from UM.Application import Application #To get the machine manager to create the new profile in.
  8. from UM.Logger import Logger #Logging errors.
  9. from UM.PluginRegistry import PluginRegistry #For getting the path to this plugin's directory.
  10. from UM.Settings.Profile import Profile
  11. from UM.Settings.ProfileReader import ProfileReader
  12. ## A plugin that reads profile data from legacy Cura versions.
  13. #
  14. # It reads a profile from an .ini file, and performs some translations on it.
  15. # Not all translations are correct, mind you, but it is a best effort.
  16. class LegacyProfileReader(ProfileReader):
  17. ## Initialises the legacy profile reader.
  18. #
  19. # This does nothing since the only other function is basically stateless.
  20. def __init__(self):
  21. super().__init__()
  22. ## Prepares the local variables that can be used in evaluation of computing
  23. # new setting values from the old ones.
  24. #
  25. # This fills a dictionary with all settings from the legacy Cura version
  26. # and their values, so that they can be used in evaluating the new setting
  27. # values as Python code.
  28. #
  29. # \param config_parser The ConfigParser that finds the settings in the
  30. # legacy profile.
  31. # \param config_section The section in the profile where the settings
  32. # should be found.
  33. # \param json The JSON file to load the default setting values from. This
  34. # should not be an URL but a pre-loaded JSON handle.
  35. # \return A set of local variables, one for each setting in the legacy
  36. # profile.
  37. def prepareLocals(self, config_parser, config_section, json):
  38. locals = {}
  39. for key in json["defaults"]: #We have to copy over all defaults from the JSON handle to a normal dict.
  40. locals[key] = json["defaults"][key]
  41. for option in config_parser.options(config_section):
  42. locals[option] = config_parser.get(config_section, option)
  43. return locals
  44. ## Reads a legacy Cura profile from a file and returns it.
  45. #
  46. # \param file_name The file to read the legacy Cura profile from.
  47. # \return The legacy Cura profile that was in the file, if any. If the
  48. # file could not be read or didn't contain a valid profile, \code None
  49. # \endcode is returned.
  50. def read(self, file_name):
  51. profile = Profile(machine_manager = Application.getInstance().getMachineManager(), read_only = False) #Create an empty profile.
  52. profile.setName("Imported Legacy Profile")
  53. parser = configparser.ConfigParser(interpolation = None)
  54. try:
  55. with open(file_name) as f:
  56. parser.readfp(f) #Parse the INI file.
  57. except Exception as e:
  58. Logger.log("e", "Unable to open legacy profile %s: %s", file_name, str(e))
  59. return None
  60. #Legacy Cura saved the profile under the section "profile_N" where N is the ID of a machine, except when you export in which case it saves it in the section "profile".
  61. #Since importing multiple machine profiles is out of scope, just import the first section we find.
  62. section = ""
  63. for found_section in parser.sections():
  64. if found_section.startswith("profile"):
  65. section = found_section
  66. break
  67. if not section: #No section starting with "profile" was found. Probably not a proper INI file.
  68. return None
  69. try:
  70. with open(os.path.join(PluginRegistry.getInstance().getPluginPath("LegacyProfileReader"), "DictionaryOfDoom.json"), "r", -1, "utf-8") as f:
  71. dict_of_doom = json.load(f) #Parse the Dictionary of Doom.
  72. except IOError as e:
  73. Logger.log("e", "Could not open DictionaryOfDoom.json for reading: %s", str(e))
  74. return None
  75. except Exception as e:
  76. Logger.log("e", "Could not parse DictionaryOfDoom.json: %s", str(e))
  77. return None
  78. legacy_settings = self.prepareLocals(parser, section, dict_of_doom) #Gets the settings from the legacy profile.
  79. #Check the target version in the Dictionary of Doom with this application version.
  80. if "target_version" not in dict_of_doom:
  81. Logger.log("e", "Dictionary of Doom has no target version. Is it the correct JSON file?")
  82. return None
  83. if Profile.ProfileVersion != dict_of_doom["target_version"]:
  84. Logger.log("e", "Dictionary of Doom of legacy profile reader (version %s) is not in sync with the profile version (version %s)!", dict_of_doom["target_version"], str(Profile.ProfileVersion))
  85. return None
  86. if "translation" not in dict_of_doom:
  87. Logger.log("e", "Dictionary of Doom has no translation. Is it the correct JSON file?")
  88. return None
  89. for new_setting in dict_of_doom["translation"]: #Evaluate all new settings that would get a value from the translations.
  90. old_setting_expression = dict_of_doom["translation"][new_setting]
  91. compiled = compile(old_setting_expression, new_setting, "eval")
  92. try:
  93. new_value = eval(compiled, {"math": math}, legacy_settings) #Pass the legacy settings as local variables to allow access to in the evaluation.
  94. except Exception as e: #Probably some setting name that was missing or something else that went wrong in the ini file.
  95. Logger.log("w", "Setting " + new_setting + " could not be set because the evaluation failed. Something is probably missing from the imported legacy profile.")
  96. continue
  97. if profile.getSettingValue(new_setting) != new_value: #Not equal to the default.
  98. profile.setSettingValue(new_setting, new_value) #Store the setting in the profile!
  99. return profile