LegacyProfileReader.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. class LegacyProfileReader(ProfileReader):
  16. """A plugin that reads profile data from legacy Cura versions.
  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. """
  20. def __init__(self):
  21. """Initialises the legacy profile reader.
  22. This does nothing since the only other function is basically stateless.
  23. """
  24. super().__init__()
  25. def prepareDefaults(self, json: Dict[str, Dict[str, str]]) -> Dict[str, str]:
  26. """Prepares the default values of all legacy settings.
  27. These are loaded from the Dictionary of Doom.
  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. """
  32. defaults = {}
  33. if "defaults" in json:
  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. def prepareLocals(self, config_parser, config_section, defaults):
  38. """Prepares the local variables that can be used in evaluation of computing
  39. new setting values from the old ones.
  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. :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. """
  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. def read(self, file_name):
  56. """Reads a legacy Cura profile from a file and returns it.
  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, None is returned.
  60. """
  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. container_registry = ContainerRegistry.getInstance()
  72. profile_id = container_registry.uniqueName("Imported Legacy Profile")
  73. input_parser = configparser.ConfigParser(interpolation = None)
  74. try:
  75. input_parser.read([file_name]) # 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 input_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", encoding = "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(input_parser, section, defaults) #Gets the settings from the legacy profile.
  99. # Serialised format into version 4.5. Do NOT upgrade this, let the version upgrader handle it.
  100. output_parser = configparser.ConfigParser(interpolation = None)
  101. output_parser.add_section("general")
  102. output_parser.add_section("metadata")
  103. output_parser.add_section("values")
  104. if "translation" not in dict_of_doom:
  105. Logger.log("e", "Dictionary of Doom has no translation. Is it the correct JSON file?")
  106. return None
  107. current_printer_definition = global_container_stack.definition
  108. quality_definition = current_printer_definition.getMetaDataEntry("quality_definition")
  109. if not quality_definition:
  110. quality_definition = current_printer_definition.getId()
  111. output_parser["general"]["definition"] = quality_definition
  112. for new_setting in dict_of_doom["translation"]: # Evaluate all new settings that would get a value from the translations.
  113. old_setting_expression = dict_of_doom["translation"][new_setting]
  114. compiled = compile(old_setting_expression, new_setting, "eval")
  115. try:
  116. new_value = eval(compiled, {"math": math}, legacy_settings) # Pass the legacy settings as local variables to allow access to in the evaluation.
  117. value_using_defaults = eval(compiled, {"math": math}, defaults) #Evaluate again using only the default values to try to see if they are default.
  118. except Exception: # Probably some setting name that was missing or something else that went wrong in the ini file.
  119. Logger.log("w", "Setting " + new_setting + " could not be set because the evaluation failed. Something is probably missing from the imported legacy profile.")
  120. continue
  121. definitions = current_printer_definition.findDefinitions(key = new_setting)
  122. if definitions:
  123. 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.
  124. output_parser["values"][new_setting] = str(new_value) # Store the setting in the profile!
  125. if len(output_parser["values"]) == 0:
  126. Logger.log("i", "A legacy profile was imported but everything evaluates to the defaults, creating an empty profile.")
  127. output_parser["general"]["version"] = "4"
  128. output_parser["general"]["name"] = profile_id
  129. output_parser["metadata"]["type"] = "quality_changes"
  130. output_parser["metadata"]["quality_type"] = "normal" # Don't know what quality_type it is based on, so use "normal" by default.
  131. output_parser["metadata"]["position"] = "0" # We only support single extrusion.
  132. output_parser["metadata"]["setting_version"] = "5" # What the dictionary of doom is made for.
  133. # Serialise in order to perform the version upgrade.
  134. stream = io.StringIO()
  135. output_parser.write(stream)
  136. data = stream.getvalue()
  137. profile = InstanceContainer(profile_id)
  138. profile.deserialize(data, file_name) # Also performs the version upgrade.
  139. profile.setDirty(True)
  140. #We need to return one extruder stack and one global stack.
  141. global_container_id = container_registry.uniqueName("Global Imported Legacy Profile")
  142. # We duplicate the extruder profile into the global stack.
  143. # This may introduce some settings that are global in the extruder stack and some settings that are per-extruder in the global stack.
  144. # We don't care about that. The engine will ignore them anyway.
  145. global_profile = profile.duplicate(new_id = global_container_id, new_name = profile_id) #Needs to have the same name as the extruder profile.
  146. del global_profile.getMetaData()["position"] # Has no position because it's global.
  147. global_profile.setDirty(True)
  148. profile_definition = "fdmprinter"
  149. from UM.Util import parseBool
  150. if parseBool(global_container_stack.getMetaDataEntry("has_machine_quality", "False")):
  151. profile_definition = global_container_stack.getMetaDataEntry("quality_definition")
  152. if not profile_definition:
  153. profile_definition = global_container_stack.definition.getId()
  154. global_profile.setDefinition(profile_definition)
  155. return [global_profile]