LegacyProfileReader.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. # Copyright (c) 2018 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 typing import Dict
  9. from UM.Application import Application # To get the machine manager to create the new profile in.
  10. from UM.Logger import Logger # Logging errors.
  11. from UM.PluginRegistry import PluginRegistry # For getting the path to this plugin's directory.
  12. from UM.Settings.ContainerRegistry import ContainerRegistry #To create unique profile IDs.
  13. from UM.Settings.InstanceContainer import InstanceContainer # The new profile to make.
  14. from cura.ReaderWriters.ProfileReader import ProfileReader # The plug-in type to implement.
  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: Dict[str, Dict[str, str]]) -> Dict[str, str]:
  33. defaults = {}
  34. if "defaults" in json:
  35. for key in json["defaults"]: # We have to copy over all defaults from the JSON handle to a normal dict.
  36. defaults[key] = json["defaults"][key]
  37. return defaults
  38. ## Prepares the local variables that can be used in evaluation of computing
  39. # new setting values from the old ones.
  40. #
  41. # This fills a dictionary with all settings from the legacy Cura version
  42. # and their values, so that they can be used in evaluating the new setting
  43. # values as Python code.
  44. #
  45. # \param config_parser The ConfigParser that finds the settings in the
  46. # legacy profile.
  47. # \param config_section The section in the profile where the settings
  48. # should be found.
  49. # \param defaults The default values for all settings in the legacy Cura.
  50. # \return A set of local variables, one for each setting in the legacy
  51. # profile.
  52. def prepareLocals(self, config_parser, config_section, defaults):
  53. copied_locals = defaults.copy() # Don't edit the original!
  54. for option in config_parser.options(config_section):
  55. copied_locals[option] = config_parser.get(config_section, option)
  56. return copied_locals
  57. ## Reads a legacy Cura profile from a file and returns it.
  58. #
  59. # \param file_name The file to read the legacy Cura profile from.
  60. # \return The legacy Cura profile that was in the file, if any. If the
  61. # file could not be read or didn't contain a valid profile, \code None
  62. # \endcode is returned.
  63. def read(self, file_name):
  64. if file_name.split(".")[-1] != "ini":
  65. return None
  66. global_container_stack = Application.getInstance().getGlobalContainerStack()
  67. if not global_container_stack:
  68. return None
  69. multi_extrusion = global_container_stack.getProperty("machine_extruder_count", "value") > 1
  70. if multi_extrusion:
  71. Logger.log("e", "Unable to import legacy profile %s. Multi extrusion is not supported", file_name)
  72. raise Exception("Unable to import legacy profile. Multi extrusion is not supported")
  73. Logger.log("i", "Importing legacy profile from file " + file_name + ".")
  74. container_registry = ContainerRegistry.getInstance()
  75. profile_id = container_registry.uniqueName("Imported Legacy Profile")
  76. input_parser = configparser.ConfigParser(interpolation = None)
  77. try:
  78. input_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 input_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", encoding = "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(input_parser, section, defaults) #Gets the settings from the legacy profile.
  102. # Serialised format into version 4.5. Do NOT upgrade this, let the version upgrader handle it.
  103. output_parser = configparser.ConfigParser(interpolation = None)
  104. output_parser.add_section("general")
  105. output_parser.add_section("metadata")
  106. output_parser.add_section("values")
  107. if "translation" not in dict_of_doom:
  108. Logger.log("e", "Dictionary of Doom has no translation. Is it the correct JSON file?")
  109. return None
  110. current_printer_definition = global_container_stack.definition
  111. quality_definition = current_printer_definition.getMetaDataEntry("quality_definition")
  112. if not quality_definition:
  113. quality_definition = current_printer_definition.getId()
  114. output_parser["general"]["definition"] = quality_definition
  115. for new_setting in dict_of_doom["translation"]: # Evaluate all new settings that would get a value from the translations.
  116. old_setting_expression = dict_of_doom["translation"][new_setting]
  117. compiled = compile(old_setting_expression, new_setting, "eval")
  118. try:
  119. new_value = eval(compiled, {"math": math}, legacy_settings) # Pass the legacy settings as local variables to allow access to in the evaluation.
  120. value_using_defaults = eval(compiled, {"math": math}, defaults) #Evaluate again using only the default values to try to see if they are default.
  121. except Exception: # Probably some setting name that was missing or something else that went wrong in the ini file.
  122. Logger.log("w", "Setting " + new_setting + " could not be set because the evaluation failed. Something is probably missing from the imported legacy profile.")
  123. continue
  124. definitions = current_printer_definition.findDefinitions(key = new_setting)
  125. if definitions:
  126. 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.
  127. output_parser["values"][new_setting] = str(new_value) # Store the setting in the profile!
  128. if len(output_parser["values"]) == 0:
  129. Logger.log("i", "A legacy profile was imported but everything evaluates to the defaults, creating an empty profile.")
  130. output_parser["general"]["version"] = "4"
  131. output_parser["general"]["name"] = profile_id
  132. output_parser["metadata"]["type"] = "quality_changes"
  133. output_parser["metadata"]["quality_type"] = "normal" # Don't know what quality_type it is based on, so use "normal" by default.
  134. output_parser["metadata"]["position"] = "0" # We only support single extrusion.
  135. output_parser["metadata"]["setting_version"] = "5" # What the dictionary of doom is made for.
  136. # Serialise in order to perform the version upgrade.
  137. stream = io.StringIO()
  138. output_parser.write(stream)
  139. data = stream.getvalue()
  140. profile = InstanceContainer(profile_id)
  141. profile.deserialize(data) # Also performs the version upgrade.
  142. profile.setDirty(True)
  143. #We need to return one extruder stack and one global stack.
  144. global_container_id = container_registry.uniqueName("Global Imported Legacy Profile")
  145. # We duplicate the extruder profile into the global stack.
  146. # This may introduce some settings that are global in the extruder stack and some settings that are per-extruder in the global stack.
  147. # We don't care about that. The engine will ignore them anyway.
  148. global_profile = profile.duplicate(new_id = global_container_id, new_name = profile_id) #Needs to have the same name as the extruder profile.
  149. del global_profile.getMetaData()["position"] # Has no position because it's global.
  150. global_profile.setDirty(True)
  151. profile_definition = "fdmprinter"
  152. from UM.Util import parseBool
  153. if parseBool(global_container_stack.getMetaDataEntry("has_machine_quality", "False")):
  154. profile_definition = global_container_stack.getMetaDataEntry("quality_definition")
  155. if not profile_definition:
  156. profile_definition = global_container_stack.definition.getId()
  157. global_profile.setDefinition(profile_definition)
  158. return [global_profile]