LegacyProfileReader.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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 default values of all legacy settings.
  23. #
  24. # These are loaded from the Dictionary of Doom.
  25. #
  26. # \param json The JSON file to load the default setting values from. This
  27. # should not be a URL but a pre-loaded JSON handle.
  28. # \return A dictionary of the default values of the legacy Cura version.
  29. def prepareDefaults(self, json):
  30. defaults = {}
  31. for key in json["defaults"]: #We have to copy over all defaults from the JSON handle to a normal dict.
  32. defaults[key] = json["defaults"][key]
  33. return defaults
  34. ## Prepares the local variables that can be used in evaluation of computing
  35. # new setting values from the old ones.
  36. #
  37. # This fills a dictionary with all settings from the legacy Cura version
  38. # and their values, so that they can be used in evaluating the new setting
  39. # values as Python code.
  40. #
  41. # \param config_parser The ConfigParser that finds the settings in the
  42. # legacy profile.
  43. # \param config_section The section in the profile where the settings
  44. # should be found.
  45. # \param defaults The default values for all settings in the legacy Cura.
  46. # \return A set of local variables, one for each setting in the legacy
  47. # profile.
  48. def prepareLocals(self, config_parser, config_section, defaults):
  49. locals = defaults.copy() #Don't edit the original!
  50. for option in config_parser.options(config_section):
  51. locals[option] = config_parser.get(config_section, option)
  52. return locals
  53. ## Reads a legacy Cura profile from a file and returns it.
  54. #
  55. # \param file_name The file to read the legacy Cura profile from.
  56. # \return The legacy Cura profile that was in the file, if any. If the
  57. # file could not be read or didn't contain a valid profile, \code None
  58. # \endcode is returned.
  59. def read(self, file_name):
  60. if file_name.split(".")[-1] != "ini":
  61. return None
  62. Logger.log("i", "Importing legacy profile from file " + file_name + ".")
  63. profile = Profile(machine_manager = Application.getInstance().getMachineManager(), read_only = False) #Create an empty profile.
  64. parser = configparser.ConfigParser(interpolation = None)
  65. try:
  66. with open(file_name) as f:
  67. parser.readfp(f) #Parse the INI file.
  68. except Exception as e:
  69. Logger.log("e", "Unable to open legacy profile %s: %s", file_name, str(e))
  70. return None
  71. #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".
  72. #Since importing multiple machine profiles is out of scope, just import the first section we find.
  73. section = ""
  74. for found_section in parser.sections():
  75. if found_section.startswith("profile"):
  76. section = found_section
  77. break
  78. if not section: #No section starting with "profile" was found. Probably not a proper INI file.
  79. return None
  80. try:
  81. with open(os.path.join(PluginRegistry.getInstance().getPluginPath("LegacyProfileReader"), "DictionaryOfDoom.json"), "r", -1, "utf-8") as f:
  82. dict_of_doom = json.load(f) #Parse the Dictionary of Doom.
  83. except IOError as e:
  84. Logger.log("e", "Could not open DictionaryOfDoom.json for reading: %s", str(e))
  85. return None
  86. except Exception as e:
  87. Logger.log("e", "Could not parse DictionaryOfDoom.json: %s", str(e))
  88. return None
  89. defaults = self.prepareDefaults(dict_of_doom)
  90. legacy_settings = self.prepareLocals(parser, section, defaults) #Gets the settings from the legacy profile.
  91. #Check the target version in the Dictionary of Doom with this application version.
  92. if "target_version" not in dict_of_doom:
  93. Logger.log("e", "Dictionary of Doom has no target version. Is it the correct JSON file?")
  94. return None
  95. if Profile.ProfileVersion != dict_of_doom["target_version"]:
  96. 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))
  97. return None
  98. if "translation" not in dict_of_doom:
  99. Logger.log("e", "Dictionary of Doom has no translation. Is it the correct JSON file?")
  100. return None
  101. for new_setting in dict_of_doom["translation"]: #Evaluate all new settings that would get a value from the translations.
  102. old_setting_expression = dict_of_doom["translation"][new_setting]
  103. compiled = compile(old_setting_expression, new_setting, "eval")
  104. try:
  105. new_value = eval(compiled, {"math": math}, legacy_settings) #Pass the legacy settings as local variables to allow access to in the evaluation.
  106. value_using_defaults = eval(compiled, {"math": math}, defaults) #Evaluate again using only the default values to try to see if they are default.
  107. except Exception as e: #Probably some setting name that was missing or something else that went wrong in the ini file.
  108. Logger.log("w", "Setting " + new_setting + " could not be set because the evaluation failed. Something is probably missing from the imported legacy profile.")
  109. continue
  110. if new_value != value_using_defaults and profile.getSettingValue(new_setting) != new_value: #Not equal to the default in the new Cura OR the default in the legacy Cura.
  111. profile.setSettingValue(new_setting, new_value) #Store the setting in the profile!
  112. if len(profile.getChangedSettings()) == 0:
  113. Logger.log("i", "A legacy profile was imported but everything evaluates to the defaults, creating an empty profile.")
  114. return profile