LegacyProfileReader.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. # Copyright (c) 2017 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 io
  5. import json # For reading the Dictionary of Doom.
  6. import math # For mathematical operations included in the Dictionary of Doom.
  7. import os.path # For concatenating the path to the plugin and the relative path to the Dictionary of Doom.
  8. from UM.Application import Application # To get the machine manager to create the new profile in.
  9. from UM.Logger import Logger # Logging errors.
  10. from UM.PluginRegistry import PluginRegistry # For getting the path to this plugin's directory.
  11. from UM.Settings.ContainerRegistry import ContainerRegistry #To create unique profile IDs.
  12. from UM.Settings.InstanceContainer import InstanceContainer # The new profile to make.
  13. from cura.ProfileReader import ProfileReader # The plug-in type to implement.
  14. from cura.Settings.ExtruderManager import ExtruderManager #To get the current extruder definition.
  15. ## A plugin that reads profile data from legacy Cura versions.
  16. #
  17. # It reads a profile from an .ini file, and performs some translations on it.
  18. # Not all translations are correct, mind you, but it is a best effort.
  19. class LegacyProfileReader(ProfileReader):
  20. ## Initialises the legacy profile reader.
  21. #
  22. # This does nothing since the only other function is basically stateless.
  23. def __init__(self):
  24. super().__init__()
  25. ## Prepares the default values of all legacy settings.
  26. #
  27. # These are loaded from the Dictionary of Doom.
  28. #
  29. # \param json The JSON file to load the default setting values from. This
  30. # should not be a URL but a pre-loaded JSON handle.
  31. # \return A dictionary of the default values of the legacy Cura version.
  32. def prepareDefaults(self, json):
  33. defaults = {}
  34. for key in json["defaults"]: # We have to copy over all defaults from the JSON handle to a normal dict.
  35. defaults[key] = json["defaults"][key]
  36. return defaults
  37. ## Prepares the local variables that can be used in evaluation of computing
  38. # new setting values from the old ones.
  39. #
  40. # This fills a dictionary with all settings from the legacy Cura version
  41. # and their values, so that they can be used in evaluating the new setting
  42. # values as Python code.
  43. #
  44. # \param config_parser The ConfigParser that finds the settings in the
  45. # legacy profile.
  46. # \param config_section The section in the profile where the settings
  47. # should be found.
  48. # \param defaults The default values for all settings in the legacy Cura.
  49. # \return A set of local variables, one for each setting in the legacy
  50. # profile.
  51. def prepareLocals(self, config_parser, config_section, defaults):
  52. copied_locals = defaults.copy() # Don't edit the original!
  53. for option in config_parser.options(config_section):
  54. copied_locals[option] = config_parser.get(config_section, option)
  55. return copied_locals
  56. ## Reads a legacy Cura profile from a file and returns it.
  57. #
  58. # \param file_name The file to read the legacy Cura profile from.
  59. # \return The legacy Cura profile that was in the file, if any. If the
  60. # file could not be read or didn't contain a valid profile, \code None
  61. # \endcode is returned.
  62. def read(self, file_name):
  63. if file_name.split(".")[-1] != "ini":
  64. return None
  65. global_container_stack = Application.getInstance().getGlobalContainerStack()
  66. if not global_container_stack:
  67. return None
  68. multi_extrusion = global_container_stack.getProperty("machine_extruder_count", "value") > 1
  69. if multi_extrusion:
  70. Logger.log("e", "Unable to import legacy profile %s. Multi extrusion is not supported", file_name)
  71. raise Exception("Unable to import legacy profile. Multi extrusion is not supported")
  72. Logger.log("i", "Importing legacy profile from file " + file_name + ".")
  73. container_registry = ContainerRegistry.getInstance()
  74. profile_id = container_registry.uniqueName("Imported Legacy Profile")
  75. profile = InstanceContainer(profile_id) # Create an empty profile.
  76. parser = configparser.ConfigParser(interpolation = None)
  77. try:
  78. parser.read([file_name]) # Parse the INI file.
  79. except Exception as e:
  80. Logger.log("e", "Unable to open legacy profile %s: %s", file_name, str(e))
  81. return None
  82. # 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".
  83. # Since importing multiple machine profiles is out of scope, just import the first section we find.
  84. section = ""
  85. for found_section in parser.sections():
  86. if found_section.startswith("profile"):
  87. section = found_section
  88. break
  89. if not section: # No section starting with "profile" was found. Probably not a proper INI file.
  90. return None
  91. try:
  92. with open(os.path.join(PluginRegistry.getInstance().getPluginPath("LegacyProfileReader"), "DictionaryOfDoom.json"), "r", -1, "utf-8") as f:
  93. dict_of_doom = json.load(f) # Parse the Dictionary of Doom.
  94. except IOError as e:
  95. Logger.log("e", "Could not open DictionaryOfDoom.json for reading: %s", str(e))
  96. return None
  97. except Exception as e:
  98. Logger.log("e", "Could not parse DictionaryOfDoom.json: %s", str(e))
  99. return None
  100. defaults = self.prepareDefaults(dict_of_doom)
  101. legacy_settings = self.prepareLocals(parser, section, defaults) #Gets the settings from the legacy profile.
  102. #Check the target version in the Dictionary of Doom with this application version.
  103. if "target_version" not in dict_of_doom:
  104. Logger.log("e", "Dictionary of Doom has no target version. Is it the correct JSON file?")
  105. return None
  106. if InstanceContainer.Version != dict_of_doom["target_version"]:
  107. 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))
  108. return None
  109. if "translation" not in dict_of_doom:
  110. Logger.log("e", "Dictionary of Doom has no translation. Is it the correct JSON file?")
  111. return None
  112. current_printer_definition = global_container_stack.definition
  113. quality_definition = current_printer_definition.getMetaDataEntry("quality_definition")
  114. if not quality_definition:
  115. quality_definition = current_printer_definition.getId()
  116. profile.setDefinition(quality_definition)
  117. for new_setting in dict_of_doom["translation"]: # Evaluate all new settings that would get a value from the translations.
  118. old_setting_expression = dict_of_doom["translation"][new_setting]
  119. compiled = compile(old_setting_expression, new_setting, "eval")
  120. try:
  121. new_value = eval(compiled, {"math": math}, legacy_settings) # Pass the legacy settings as local variables to allow access to in the evaluation.
  122. value_using_defaults = eval(compiled, {"math": math}, defaults) #Evaluate again using only the default values to try to see if they are default.
  123. except Exception: # Probably some setting name that was missing or something else that went wrong in the ini file.
  124. Logger.log("w", "Setting " + new_setting + " could not be set because the evaluation failed. Something is probably missing from the imported legacy profile.")
  125. continue
  126. definitions = current_printer_definition.findDefinitions(key = new_setting)
  127. if definitions:
  128. 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.
  129. profile.setProperty(new_setting, "value", new_value) # Store the setting in the profile!
  130. if len(profile.getAllKeys()) == 0:
  131. Logger.log("i", "A legacy profile was imported but everything evaluates to the defaults, creating an empty profile.")
  132. profile.addMetaDataEntry("type", "profile")
  133. # don't know what quality_type it is based on, so use "normal" by default
  134. profile.addMetaDataEntry("quality_type", "normal")
  135. profile.setName(profile_id)
  136. profile.setDirty(True)
  137. #Serialise and deserialise in order to perform the version upgrade.
  138. parser = configparser.ConfigParser(interpolation=None)
  139. data = profile.serialize()
  140. parser.read_string(data)
  141. parser["general"]["version"] = "1"
  142. if parser.has_section("values"):
  143. parser["settings"] = parser["values"]
  144. del parser["values"]
  145. stream = io.StringIO()
  146. parser.write(stream)
  147. data = stream.getvalue()
  148. profile.deserialize(data)
  149. # The definition can get reset to fdmprinter during the deserialization's upgrade. Here we set the definition
  150. # again.
  151. profile.setDefinition(quality_definition)
  152. #We need to return one extruder stack and one global stack.
  153. global_container_id = container_registry.uniqueName("Global Imported Legacy Profile")
  154. global_profile = profile.duplicate(new_id = global_container_id, new_name = profile_id) #Needs to have the same name as the extruder profile.
  155. global_profile.setDirty(True)
  156. profile_definition = "fdmprinter"
  157. from UM.Util import parseBool
  158. if parseBool(global_container_stack.getMetaDataEntry("has_machine_quality", "False")):
  159. profile_definition = global_container_stack.getMetaDataEntry("quality_definition")
  160. if not profile_definition:
  161. profile_definition = global_container_stack.definition.getId()
  162. global_profile.setDefinition(profile_definition)
  163. return [global_profile]