LegacyProfileReader.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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. global_container_stack = Application.getInstance().getGlobalContainerStack()
  64. if not global_container_stack:
  65. return None
  66. multi_extrusion = global_container_stack.getProperty("machine_extruder_count", "value") > 1
  67. if multi_extrusion:
  68. Logger.log("e", "Unable to import legacy profile %s. Multi extrusion is not supported", file_name)
  69. raise Exception("Unable to import legacy profile. Multi extrusion is not supported")
  70. Logger.log("i", "Importing legacy profile from file " + file_name + ".")
  71. profile = InstanceContainer("Imported Legacy Profile") # Create an empty profile.
  72. parser = configparser.ConfigParser(interpolation = None)
  73. try:
  74. with open(file_name) as f:
  75. parser.readfp(f) #Parse the INI file.
  76. except Exception as e:
  77. Logger.log("e", "Unable to open legacy profile %s: %s", file_name, str(e))
  78. return None
  79. #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".
  80. #Since importing multiple machine profiles is out of scope, just import the first section we find.
  81. section = ""
  82. for found_section in parser.sections():
  83. if found_section.startswith("profile"):
  84. section = found_section
  85. break
  86. if not section: #No section starting with "profile" was found. Probably not a proper INI file.
  87. return None
  88. try:
  89. with open(os.path.join(PluginRegistry.getInstance().getPluginPath("LegacyProfileReader"), "DictionaryOfDoom.json"), "r", -1, "utf-8") as f:
  90. dict_of_doom = json.load(f) #Parse the Dictionary of Doom.
  91. except IOError as e:
  92. Logger.log("e", "Could not open DictionaryOfDoom.json for reading: %s", str(e))
  93. return None
  94. except Exception as e:
  95. Logger.log("e", "Could not parse DictionaryOfDoom.json: %s", str(e))
  96. return None
  97. defaults = self.prepareDefaults(dict_of_doom)
  98. legacy_settings = self.prepareLocals(parser, section, defaults) #Gets the settings from the legacy profile.
  99. #Check the target version in the Dictionary of Doom with this application version.
  100. if "target_version" not in dict_of_doom:
  101. Logger.log("e", "Dictionary of Doom has no target version. Is it the correct JSON file?")
  102. return None
  103. if InstanceContainer.Version != dict_of_doom["target_version"]:
  104. 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))
  105. return None
  106. if "translation" not in dict_of_doom:
  107. Logger.log("e", "Dictionary of Doom has no translation. Is it the correct JSON file?")
  108. return None
  109. current_printer_definition = global_container_stack.getBottom()
  110. profile.setDefinition(current_printer_definition)
  111. for new_setting in dict_of_doom["translation"]: #Evaluate all new settings that would get a value from the translations.
  112. old_setting_expression = dict_of_doom["translation"][new_setting]
  113. compiled = compile(old_setting_expression, new_setting, "eval")
  114. try:
  115. new_value = eval(compiled, {"math": math}, legacy_settings) #Pass the legacy settings as local variables to allow access to in the evaluation.
  116. value_using_defaults = eval(compiled, {"math": math}, defaults) #Evaluate again using only the default values to try to see if they are default.
  117. except Exception: #Probably some setting name that was missing or something else that went wrong in the ini file.
  118. Logger.log("w", "Setting " + new_setting + " could not be set because the evaluation failed. Something is probably missing from the imported legacy profile.")
  119. continue
  120. definitions = current_printer_definition.findDefinitions(key = new_setting)
  121. if definitions:
  122. 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.
  123. profile.setProperty(new_setting, "value", new_value) # Store the setting in the profile!
  124. if len(profile.getAllKeys()) == 0:
  125. Logger.log("i", "A legacy profile was imported but everything evaluates to the defaults, creating an empty profile.")
  126. profile.setDirty(True)
  127. profile.addMetaDataEntry("type", "quality_changes")
  128. profile.addMetaDataEntry("quality_type", "normal")
  129. return profile