LegacyProfileReader.py 9.9 KB

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