LegacyProfileReader.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  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.DefinitionContainer import DefinitionContainer #For getting the current machine's defaults.
  11. from UM.Settings.InstanceContainer import InstanceContainer #The new profile to make.
  12. from cura.ProfileReader import ProfileReader #The plug-in type to implement.
  13. ## A plugin that reads profile data from legacy Cura versions.
  14. #
  15. # It reads a profile from an .ini file, and performs some translations on it.
  16. # Not all translations are correct, mind you, but it is a best effort.
  17. class LegacyProfileReader(ProfileReader):
  18. ## Initialises the legacy profile reader.
  19. #
  20. # This does nothing since the only other function is basically stateless.
  21. def __init__(self):
  22. super().__init__()
  23. ## Prepares the default values of all legacy settings.
  24. #
  25. # These are loaded from the Dictionary of Doom.
  26. #
  27. # \param json The JSON file to load the default setting values from. This
  28. # should not be a URL but a pre-loaded JSON handle.
  29. # \return A dictionary of the default values of the legacy Cura version.
  30. def prepareDefaults(self, json):
  31. defaults = {}
  32. for key in json["defaults"]: #We have to copy over all defaults from the JSON handle to a normal dict.
  33. defaults[key] = json["defaults"][key]
  34. return defaults
  35. ## Prepares the local variables that can be used in evaluation of computing
  36. # new setting values from the old ones.
  37. #
  38. # This fills a dictionary with all settings from the legacy Cura version
  39. # and their values, so that they can be used in evaluating the new setting
  40. # values as Python code.
  41. #
  42. # \param config_parser The ConfigParser that finds the settings in the
  43. # legacy profile.
  44. # \param config_section The section in the profile where the settings
  45. # should be found.
  46. # \param defaults The default values for all settings in the legacy Cura.
  47. # \return A set of local variables, one for each setting in the legacy
  48. # profile.
  49. def prepareLocals(self, config_parser, config_section, defaults):
  50. copied_locals = defaults.copy() #Don't edit the original!
  51. for option in config_parser.options(config_section):
  52. copied_locals[option] = config_parser.get(config_section, option)
  53. return copied_locals
  54. ## Reads a legacy Cura profile from a file and returns it.
  55. #
  56. # \param file_name The file to read the legacy Cura profile from.
  57. # \return The legacy Cura profile that was in the file, if any. If the
  58. # file could not be read or didn't contain a valid profile, \code None
  59. # \endcode is returned.
  60. def read(self, file_name):
  61. if file_name.split(".")[-1] != "ini":
  62. return None
  63. Logger.log("i", "Importing legacy profile from file " + file_name + ".")
  64. profile = InstanceContainer("Imported Legacy Profile") #Create an empty profile.
  65. parser = configparser.ConfigParser(interpolation = None)
  66. try:
  67. with open(file_name) as f:
  68. parser.readfp(f) #Parse the INI file.
  69. except Exception as e:
  70. Logger.log("e", "Unable to open legacy profile %s: %s", file_name, str(e))
  71. return None
  72. #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".
  73. #Since importing multiple machine profiles is out of scope, just import the first section we find.
  74. section = ""
  75. for found_section in parser.sections():
  76. if found_section.startswith("profile"):
  77. section = found_section
  78. break
  79. if not section: #No section starting with "profile" was found. Probably not a proper INI file.
  80. return None
  81. try:
  82. with open(os.path.join(PluginRegistry.getInstance().getPluginPath("LegacyProfileReader"), "DictionaryOfDoom.json"), "r", -1, "utf-8") as f:
  83. dict_of_doom = json.load(f) #Parse the Dictionary of Doom.
  84. except IOError as e:
  85. Logger.log("e", "Could not open DictionaryOfDoom.json for reading: %s", str(e))
  86. return None
  87. except Exception as e:
  88. Logger.log("e", "Could not parse DictionaryOfDoom.json: %s", str(e))
  89. return None
  90. defaults = self.prepareDefaults(dict_of_doom)
  91. legacy_settings = self.prepareLocals(parser, section, defaults) #Gets the settings from the legacy profile.
  92. #Check the target version in the Dictionary of Doom with this application version.
  93. if "target_version" not in dict_of_doom:
  94. Logger.log("e", "Dictionary of Doom has no target version. Is it the correct JSON file?")
  95. return None
  96. if InstanceContainer.Version != dict_of_doom["target_version"]:
  97. Logger.log("e", "Dictionary of Doom of legacy profile reader (version %s) is not in sync with the current instance container version (version %s)!", dict_of_doom["target_version"], str(InstanceContainer.Version))
  98. return None
  99. if "translation" not in dict_of_doom:
  100. Logger.log("e", "Dictionary of Doom has no translation. Is it the correct JSON file?")
  101. return None
  102. current_printer_definition = Application.getInstance().getGlobalContainerStack().getBottom()
  103. profile.setDefinition(current_printer_definition)
  104. for new_setting in dict_of_doom["translation"]: #Evaluate all new settings that would get a value from the translations.
  105. old_setting_expression = dict_of_doom["translation"][new_setting]
  106. compiled = compile(old_setting_expression, new_setting, "eval")
  107. try:
  108. new_value = eval(compiled, {"math": math}, legacy_settings) #Pass the legacy settings as local variables to allow access to in the evaluation.
  109. value_using_defaults = eval(compiled, {"math": math}, defaults) #Evaluate again using only the default values to try to see if they are default.
  110. except Exception: #Probably some setting name that was missing or something else that went wrong in the ini file.
  111. Logger.log("w", "Setting " + new_setting + " could not be set because the evaluation failed. Something is probably missing from the imported legacy profile.")
  112. continue
  113. definitions = current_printer_definition.findDefinitions(key = new_setting)
  114. if definitions:
  115. if new_value != value_using_defaults and definitions[0].default_value != new_value: # Not equal to the default in the new Cura OR the default in the legacy Cura.
  116. profile.setProperty(new_setting, "value", new_value) # Store the setting in the profile!
  117. if len(profile.getAllKeys()) == 0:
  118. Logger.log("i", "A legacy profile was imported but everything evaluates to the defaults, creating an empty profile.")
  119. profile.setDirty(True)
  120. profile.addMetaDataEntry("type", "quality")
  121. return profile