CuraProfileReader.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import configparser
  4. from typing import List, Optional, Tuple
  5. from UM.PluginRegistry import PluginRegistry
  6. from UM.Logger import Logger
  7. from UM.Settings.ContainerFormatError import ContainerFormatError
  8. from UM.Settings.InstanceContainer import InstanceContainer # The new profile to make.
  9. from cura.ReaderWriters.ProfileReader import ProfileReader
  10. import zipfile
  11. ## A plugin that reads profile data from Cura profile files.
  12. #
  13. # It reads a profile from a .curaprofile file, and returns it as a profile
  14. # instance.
  15. class CuraProfileReader(ProfileReader):
  16. ## Initialises the cura profile reader.
  17. # This does nothing since the only other function is basically stateless.
  18. def __init__(self) -> None:
  19. super().__init__()
  20. ## Reads a cura profile from a file and returns it.
  21. #
  22. # \param file_name The file to read the cura profile from.
  23. # \return The cura profiles that were in the file, if any. If the file
  24. # could not be read or didn't contain a valid profile, ``None`` is
  25. # returned.
  26. def read(self, file_name: str) -> List[Optional[InstanceContainer]]:
  27. try:
  28. with zipfile.ZipFile(file_name, "r") as archive:
  29. results = [] #type: List[Optional[InstanceContainer]]
  30. for profile_id in archive.namelist():
  31. with archive.open(profile_id) as f:
  32. serialized = f.read()
  33. profile = self._loadProfile(serialized.decode("utf-8"), profile_id)
  34. if profile is not None:
  35. results.append(profile)
  36. return results
  37. except zipfile.BadZipFile:
  38. # It must be an older profile from Cura 2.1.
  39. with open(file_name, encoding = "utf-8") as fhandle:
  40. serialized_bytes = fhandle.read()
  41. return [self._loadProfile(serialized, profile_id) for serialized, profile_id in self._upgradeProfile(serialized_bytes, file_name)]
  42. ## Convert a profile from an old Cura to this Cura if needed.
  43. #
  44. # \param serialized The profile data to convert in the serialized on-disk
  45. # format.
  46. # \param profile_id The name of the profile.
  47. # \return List of serialized profile strings and matching profile names.
  48. def _upgradeProfile(self, serialized: str, profile_id: str) -> List[Tuple[str, str]]:
  49. parser = configparser.ConfigParser(interpolation = None)
  50. parser.read_string(serialized)
  51. if "general" not in parser:
  52. Logger.log("w", "Missing required section 'general'.")
  53. return []
  54. if "version" not in parser["general"]:
  55. Logger.log("w", "Missing required 'version' property")
  56. return []
  57. version = int(parser["general"]["version"])
  58. if InstanceContainer.Version != version:
  59. name = parser["general"]["name"]
  60. return self._upgradeProfileVersion(serialized, name, version)
  61. else:
  62. return [(serialized, profile_id)]
  63. ## Load a profile from a serialized string.
  64. #
  65. # \param serialized The profile data to read.
  66. # \param profile_id The name of the profile.
  67. # \return The profile that was stored in the string.
  68. def _loadProfile(self, serialized: str, profile_id: str) -> Optional[InstanceContainer]:
  69. # Create an empty profile.
  70. profile = InstanceContainer(profile_id)
  71. profile.setMetaDataEntry("type", "quality_changes")
  72. try:
  73. profile.deserialize(serialized)
  74. except ContainerFormatError as e:
  75. Logger.log("e", "Error in the format of a container: %s", str(e))
  76. return None
  77. except Exception as e:
  78. Logger.log("e", "Error while trying to parse profile: %s", str(e))
  79. return None
  80. return profile
  81. ## Upgrade a serialized profile to the current profile format.
  82. #
  83. # \param serialized The profile data to convert.
  84. # \param profile_id The name of the profile.
  85. # \param source_version The profile version of 'serialized'.
  86. # \return List of serialized profile strings and matching profile names.
  87. def _upgradeProfileVersion(self, serialized: str, profile_id: str, source_version: int) -> List[Tuple[str, str]]:
  88. converter_plugins = PluginRegistry.getInstance().getAllMetaData(filter = {"version_upgrade": {} }, active_only = True)
  89. source_format = ("profile", source_version)
  90. profile_convert_funcs = [plugin["version_upgrade"][source_format][2] for plugin in converter_plugins
  91. if source_format in plugin["version_upgrade"] and plugin["version_upgrade"][source_format][1] == InstanceContainer.Version]
  92. if not profile_convert_funcs:
  93. return []
  94. filenames, outputs = profile_convert_funcs[0](serialized, profile_id)
  95. if filenames is None and outputs is None:
  96. return []
  97. return list(zip(outputs, filenames))