LegacyProfileReader.py 8.0 KB

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