CuraContainerRegistry.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import os
  4. import re
  5. import configparser
  6. from typing import Any, cast, Dict, Optional, List, Union, Tuple
  7. from PyQt6.QtWidgets import QMessageBox
  8. from UM.Decorators import override
  9. from UM.Settings.ContainerFormatError import ContainerFormatError
  10. from UM.Settings.Interfaces import ContainerInterface
  11. from UM.Settings.ContainerRegistry import ContainerRegistry
  12. from UM.Settings.ContainerStack import ContainerStack
  13. from UM.Settings.InstanceContainer import InstanceContainer
  14. from UM.Settings.SettingInstance import SettingInstance
  15. from UM.Logger import Logger
  16. from UM.Message import Message
  17. from UM.Platform import Platform
  18. from UM.PluginRegistry import PluginRegistry # For getting the possible profile writers to write with.
  19. from UM.Resources import Resources
  20. from UM.Util import parseBool
  21. from cura.ReaderWriters.ProfileWriter import ProfileWriter
  22. from . import ExtruderStack
  23. from . import GlobalStack
  24. import cura.CuraApplication
  25. from cura.Settings.cura_empty_instance_containers import empty_quality_container
  26. from cura.Machines.ContainerTree import ContainerTree
  27. from cura.ReaderWriters.ProfileReader import NoProfileException, ProfileReader
  28. from UM.i18n import i18nCatalog
  29. from .DatabaseHandlers.IntentDatabaseHandler import IntentDatabaseHandler
  30. from .DatabaseHandlers.QualityDatabaseHandler import QualityDatabaseHandler
  31. from .DatabaseHandlers.VariantDatabaseHandler import VariantDatabaseHandler
  32. catalog = i18nCatalog("cura")
  33. class CuraContainerRegistry(ContainerRegistry):
  34. def __init__(self, *args, **kwargs):
  35. super().__init__(*args, **kwargs)
  36. # We don't have all the machines loaded in the beginning, so in order to add the missing extruder stack
  37. # for single extrusion machines, we subscribe to the containerAdded signal, and whenever a global stack
  38. # is added, we check to see if an extruder stack needs to be added.
  39. self.containerAdded.connect(self._onContainerAdded)
  40. self._database_handlers["variant"] = VariantDatabaseHandler()
  41. self._database_handlers["quality"] = QualityDatabaseHandler()
  42. self._database_handlers["intent"] = IntentDatabaseHandler()
  43. @override(ContainerRegistry)
  44. def addContainer(self, container: ContainerInterface) -> bool:
  45. """Overridden from ContainerRegistry
  46. Adds a container to the registry.
  47. This will also try to convert a ContainerStack to either Extruder or
  48. Global stack based on metadata information.
  49. """
  50. # Note: Intentional check with type() because we want to ignore subclasses
  51. if type(container) == ContainerStack:
  52. container = self._convertContainerStack(cast(ContainerStack, container))
  53. if isinstance(container, InstanceContainer) and type(container) != type(self.getEmptyInstanceContainer()):
  54. # Check against setting version of the definition.
  55. required_setting_version = cura.CuraApplication.CuraApplication.SettingVersion
  56. actual_setting_version = int(container.getMetaDataEntry("setting_version", default = 0))
  57. if required_setting_version != actual_setting_version:
  58. Logger.log("w", "Instance container {container_id} is outdated. Its setting version is {actual_setting_version} but it should be {required_setting_version}.".format(container_id = container.getId(), actual_setting_version = actual_setting_version, required_setting_version = required_setting_version))
  59. return False # Don't add.
  60. return super().addContainer(container)
  61. def createUniqueName(self, container_type: str, current_name: str, new_name: str, fallback_name: str) -> str:
  62. """Create a name that is not empty and unique
  63. :param container_type: :type{string} Type of the container (machine, quality, ...)
  64. :param current_name: :type{} Current name of the container, which may be an acceptable option
  65. :param new_name: :type{string} Base name, which may not be unique
  66. :param fallback_name: :type{string} Name to use when (stripped) new_name is empty
  67. :return: :type{string} Name that is unique for the specified type and name/id
  68. """
  69. new_name = new_name.strip()
  70. num_check = re.compile(r"(.*?)\s*#\d+$").match(new_name)
  71. if num_check:
  72. new_name = num_check.group(1)
  73. if new_name == "":
  74. new_name = fallback_name
  75. unique_name = new_name
  76. i = 1
  77. # In case we are renaming, the current name of the container is also a valid end-result
  78. while self._containerExists(container_type, unique_name) and unique_name != current_name:
  79. i += 1
  80. unique_name = "%s #%d" % (new_name, i)
  81. return unique_name
  82. def _containerExists(self, container_type: str, container_name: str):
  83. """Check if a container with of a certain type and a certain name or id exists
  84. Both the id and the name are checked, because they may not be the same and it is better if they are both unique
  85. :param container_type: :type{string} Type of the container (machine, quality, ...)
  86. :param container_name: :type{string} Name to check
  87. """
  88. container_class = ContainerStack if "machine" in container_type else InstanceContainer
  89. return self.findContainersMetadata(container_type = container_class, id = container_name, type = container_type, ignore_case = True) or \
  90. self.findContainersMetadata(container_type = container_class, name = container_name, type = container_type)
  91. def exportQualityProfile(self, container_list: List[InstanceContainer], file_name: str, file_type: str) -> bool:
  92. """Exports an profile to a file
  93. :param container_list: :type{list} the containers to export. This is not
  94. necessarily in any order!
  95. :param file_name: :type{str} the full path and filename to export to.
  96. :param file_type: :type{str} the file type with the format "<description> (*.<extension>)"
  97. :return: True if the export succeeded, false otherwise.
  98. """
  99. # Parse the fileType to deduce what plugin can save the file format.
  100. # fileType has the format "<description> (*.<extension>)"
  101. split = file_type.rfind(" (*.") # Find where the description ends and the extension starts.
  102. if split < 0: # Not found. Invalid format.
  103. Logger.log("e", "Invalid file format identifier %s", file_type)
  104. return False
  105. description = file_type[:split]
  106. extension = file_type[split + 4:-1] # Leave out the " (*." and ")".
  107. if not file_name.endswith("." + extension): # Auto-fill the extension if the user did not provide any.
  108. file_name += "." + extension
  109. # On Windows, QML FileDialog properly asks for overwrite confirm, but not on other platforms, so handle those ourself.
  110. if not Platform.isWindows():
  111. if os.path.exists(file_name):
  112. result = QMessageBox.question(None, catalog.i18nc("@title:window", "File Already Exists"),
  113. catalog.i18nc("@label Don't translate the XML tag <filename>!", "The file <filename>{0}</filename> already exists. Are you sure you want to overwrite it?").format(file_name))
  114. if result == QMessageBox.StandardButton.No:
  115. return False
  116. profile_writer = self._findProfileWriter(extension, description)
  117. try:
  118. if profile_writer is None:
  119. raise Exception("Unable to find a profile writer")
  120. success = profile_writer.write(file_name, container_list)
  121. except Exception as e:
  122. Logger.log("e", "Failed to export profile to %s: %s", file_name, str(e))
  123. m = Message(catalog.i18nc("@info:status Don't translate the XML tags <filename> or <message>!",
  124. "Failed to export profile to <filename>{0}</filename>: <message>{1}</message>",
  125. file_name, str(e)),
  126. lifetime = 0,
  127. title = catalog.i18nc("@info:title", "Error"),
  128. message_type = Message.MessageType.ERROR)
  129. m.show()
  130. return False
  131. if not success:
  132. Logger.log("w", "Failed to export profile to %s: Writer plugin reported failure.", file_name)
  133. m = Message(catalog.i18nc("@info:status Don't translate the XML tag <filename>!",
  134. "Failed to export profile to <filename>{0}</filename>: Writer plugin reported failure.",
  135. file_name),
  136. lifetime = 0,
  137. title = catalog.i18nc("@info:title", "Error"),
  138. message_type = Message.MessageType.ERROR)
  139. m.show()
  140. return False
  141. m = Message(catalog.i18nc("@info:status Don't translate the XML tag <filename>!",
  142. "Exported profile to <filename>{0}</filename>",
  143. file_name),
  144. title = catalog.i18nc("@info:title", "Export succeeded"),
  145. message_type = Message.MessageType.POSITIVE)
  146. m.show()
  147. return True
  148. def _findProfileWriter(self, extension: str, description: str) -> Optional[ProfileWriter]:
  149. """Gets the plugin object matching the criteria
  150. :param extension:
  151. :param description:
  152. :return: The plugin object matching the given extension and description.
  153. """
  154. plugin_registry = PluginRegistry.getInstance()
  155. for plugin_id, meta_data in self._getIOPlugins("profile_writer"):
  156. for supported_type in meta_data["profile_writer"]: # All file types this plugin can supposedly write.
  157. supported_extension = supported_type.get("extension", None)
  158. if supported_extension == extension: # This plugin supports a file type with the same extension.
  159. supported_description = supported_type.get("description", None)
  160. if supported_description == description: # The description is also identical. Assume it's the same file type.
  161. return cast(ProfileWriter, plugin_registry.getPluginObject(plugin_id))
  162. return None
  163. def importProfile(self, file_name: str) -> Dict[str, str]:
  164. """Imports a profile from a file
  165. :param file_name: The full path and filename of the profile to import.
  166. :return: Dict with a 'status' key containing the string 'ok', 'warning' or 'error',
  167. and a 'message' key containing a message for the user.
  168. """
  169. Logger.log("d", "Attempting to import profile %s", file_name)
  170. if not file_name:
  171. return { "status": "error", "message": catalog.i18nc("@info:status Don't translate the XML tags <filename>!", "Failed to import profile from <filename>{0}</filename>: {1}", file_name, "Invalid path")}
  172. global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  173. if not global_stack:
  174. return {"status": "error", "message": catalog.i18nc("@info:status Don't translate the XML tags <filename>!", "Can't import profile from <filename>{0}</filename> before a printer is added.", file_name)}
  175. container_tree = ContainerTree.getInstance()
  176. machine_extruders = global_stack.extruderList
  177. plugin_registry = PluginRegistry.getInstance()
  178. extension = file_name.split(".")[-1]
  179. for plugin_id, meta_data in self._getIOPlugins("profile_reader"):
  180. if meta_data["profile_reader"][0]["extension"] != extension:
  181. continue
  182. profile_reader = cast(ProfileReader, plugin_registry.getPluginObject(plugin_id))
  183. try:
  184. profile_or_list = profile_reader.read(file_name) # Try to open the file with the profile reader.
  185. except NoProfileException:
  186. return { "status": "ok", "message": catalog.i18nc("@info:status Don't translate the XML tags <filename>!", "No custom profile to import in file <filename>{0}</filename>", file_name)}
  187. except Exception as e:
  188. # Note that this will fail quickly. That is, if any profile reader throws an exception, it will stop reading. It will only continue reading if the reader returned None.
  189. Logger.log("e", "Failed to import profile from %s: %s while using profile reader. Got exception %s", file_name, profile_reader.getPluginId(), str(e))
  190. return { "status": "error", "message": catalog.i18nc("@info:status Don't translate the XML tags <filename>!", "Failed to import profile from <filename>{0}</filename>:", file_name) + "\n<message>" + str(e) + "</message>"}
  191. if profile_or_list:
  192. # Ensure it is always a list of profiles
  193. if not isinstance(profile_or_list, list):
  194. profile_or_list = [profile_or_list]
  195. # First check if this profile is suitable for this machine
  196. global_profile = None
  197. extruder_profiles = []
  198. if len(profile_or_list) == 1:
  199. global_profile = profile_or_list[0]
  200. else:
  201. for profile in profile_or_list:
  202. if not profile.getMetaDataEntry("position"):
  203. global_profile = profile
  204. else:
  205. extruder_profiles.append(profile)
  206. extruder_profiles = sorted(extruder_profiles, key = lambda x: int(x.getMetaDataEntry("position", default = "0")))
  207. profile_or_list = [global_profile] + extruder_profiles
  208. if not global_profile:
  209. Logger.log("e", "Incorrect profile [%s]. Could not find global profile", file_name)
  210. return { "status": "error",
  211. "message": catalog.i18nc("@info:status Don't translate the XML tags <filename>!", "This profile <filename>{0}</filename> contains incorrect data, could not import it.", file_name)}
  212. profile_definition = global_profile.getMetaDataEntry("definition")
  213. # Make sure we have a profile_definition in the file:
  214. if profile_definition is None:
  215. break
  216. machine_definitions = self.findContainers(id = profile_definition)
  217. if not machine_definitions:
  218. Logger.log("e", "Incorrect profile [%s]. Unknown machine type [%s]", file_name, profile_definition)
  219. return {"status": "error",
  220. "message": catalog.i18nc("@info:status Don't translate the XML tags <filename>!", "This profile <filename>{0}</filename> contains incorrect data, could not import it.", file_name)
  221. }
  222. machine_definition = machine_definitions[0]
  223. # Get the expected machine definition.
  224. # i.e.: We expect gcode for a UM2 Extended to be defined as normal UM2 gcode...
  225. has_machine_quality = parseBool(machine_definition.getMetaDataEntry("has_machine_quality", "false"))
  226. profile_definition = machine_definition.getMetaDataEntry("quality_definition", machine_definition.getId()) if has_machine_quality else "fdmprinter"
  227. expected_machine_definition = container_tree.machines[global_stack.definition.getId()].quality_definition
  228. # And check if the profile_definition matches either one (showing error if not):
  229. if profile_definition != expected_machine_definition:
  230. Logger.log("d", "Profile {file_name} is for machine {profile_definition}, but the current active machine is {expected_machine_definition}. Changing profile's definition.".format(file_name = file_name, profile_definition = profile_definition, expected_machine_definition = expected_machine_definition))
  231. global_profile.setMetaDataEntry("definition", expected_machine_definition)
  232. for extruder_profile in extruder_profiles:
  233. extruder_profile.setMetaDataEntry("definition", expected_machine_definition)
  234. quality_name = global_profile.getName()
  235. quality_type = global_profile.getMetaDataEntry("quality_type")
  236. name_seed = os.path.splitext(os.path.basename(file_name))[0]
  237. new_name = self.uniqueName(name_seed)
  238. # Ensure it is always a list of profiles
  239. if type(profile_or_list) is not list:
  240. profile_or_list = [profile_or_list]
  241. # Make sure that there are also extruder stacks' quality_changes, not just one for the global stack
  242. if len(profile_or_list) == 1:
  243. global_profile = profile_or_list[0]
  244. extruder_profiles = []
  245. for idx, extruder in enumerate(global_stack.extruderList):
  246. profile_id = ContainerRegistry.getInstance().uniqueName(global_stack.getId() + "_extruder_" + str(idx + 1))
  247. profile = InstanceContainer(profile_id)
  248. profile.setName(quality_name)
  249. profile.setMetaDataEntry("setting_version", cura.CuraApplication.CuraApplication.SettingVersion)
  250. profile.setMetaDataEntry("type", "quality_changes")
  251. profile.setMetaDataEntry("definition", expected_machine_definition)
  252. profile.setMetaDataEntry("quality_type", quality_type)
  253. profile.setDirty(True)
  254. if idx == 0:
  255. # Move all per-extruder settings to the first extruder's quality_changes
  256. for qc_setting_key in global_profile.getAllKeys():
  257. settable_per_extruder = global_stack.getProperty(qc_setting_key, "settable_per_extruder")
  258. if settable_per_extruder:
  259. setting_value = global_profile.getProperty(qc_setting_key, "value")
  260. setting_definition = global_stack.getSettingDefinition(qc_setting_key)
  261. if setting_definition is not None:
  262. new_instance = SettingInstance(setting_definition, profile)
  263. new_instance.setProperty("value", setting_value)
  264. new_instance.resetState() # Ensure that the state is not seen as a user state.
  265. profile.addInstance(new_instance)
  266. profile.setDirty(True)
  267. global_profile.removeInstance(qc_setting_key, postpone_emit = True)
  268. extruder_profiles.append(profile)
  269. for profile in extruder_profiles:
  270. profile_or_list.append(profile)
  271. # Import all profiles
  272. profile_ids_added = [] # type: List[str]
  273. additional_message = None
  274. for profile_index, profile in enumerate(profile_or_list):
  275. if profile_index == 0:
  276. # This is assumed to be the global profile
  277. profile_id = (cast(ContainerInterface, global_stack.getBottom()).getId() + "_" + name_seed).lower().replace(" ", "_")
  278. elif profile_index < len(machine_extruders) + 1:
  279. # This is assumed to be an extruder profile
  280. extruder_id = machine_extruders[profile_index - 1].definition.getId()
  281. extruder_position = str(profile_index - 1)
  282. if not profile.getMetaDataEntry("position"):
  283. profile.setMetaDataEntry("position", extruder_position)
  284. else:
  285. profile.setMetaDataEntry("position", extruder_position)
  286. profile_id = (extruder_id + "_" + name_seed).lower().replace(" ", "_")
  287. else: # More extruders in the imported file than in the machine.
  288. continue # Delete the additional profiles.
  289. configuration_successful, message = self._configureProfile(profile, profile_id, new_name, expected_machine_definition)
  290. if configuration_successful:
  291. additional_message = message
  292. else:
  293. # Remove any profiles that were added.
  294. for profile_id in profile_ids_added + [profile.getId()]:
  295. self.removeContainer(profile_id)
  296. if not message:
  297. message = ""
  298. return {"status": "error", "message": catalog.i18nc(
  299. "@info:status Don't translate the XML tag <filename>!",
  300. "Failed to import profile from <filename>{0}</filename>:",
  301. file_name) + " " + message}
  302. profile_ids_added.append(profile.getId())
  303. result_status = "ok"
  304. success_message = catalog.i18nc("@info:status", "Successfully imported profile {0}.", profile_or_list[0].getName())
  305. if additional_message:
  306. result_status = "warning"
  307. success_message += additional_message
  308. return {"status": result_status, "message": success_message}
  309. # This message is throw when the profile reader doesn't find any profile in the file
  310. return {"status": "error", "message": catalog.i18nc("@info:status", "File {0} does not contain any valid profile.", file_name)}
  311. # If it hasn't returned by now, none of the plugins loaded the profile successfully.
  312. return {"status": "error", "message": catalog.i18nc("@info:status", "Profile {0} has an unknown file type or is corrupted.", file_name)}
  313. @override(ContainerRegistry)
  314. def load(self) -> None:
  315. super().load()
  316. self._registerSingleExtrusionMachinesExtruderStacks()
  317. self._connectUpgradedExtruderStacksToMachines()
  318. @override(ContainerRegistry)
  319. def loadAllMetadata(self) -> None:
  320. super().loadAllMetadata()
  321. self._cleanUpInvalidQualityChanges()
  322. def _cleanUpInvalidQualityChanges(self) -> None:
  323. # We've seen cases where it was possible for quality_changes to be incorrectly added. This is to ensure that
  324. # any such leftovers are purged from the registry.
  325. quality_changes = ContainerRegistry.getInstance().findContainersMetadata(type="quality_changes")
  326. profile_count_by_name = {} # type: Dict[str, int]
  327. for quality_change in quality_changes:
  328. name = str(quality_change.get("name", ""))
  329. if name == "empty":
  330. continue
  331. if name not in profile_count_by_name:
  332. profile_count_by_name[name] = 0
  333. profile_count_by_name[name] += 1
  334. for profile_name, profile_count in profile_count_by_name.items():
  335. if profile_count > 1:
  336. continue
  337. # Only one profile found, this should not ever be the case, so that profile needs to be removed!
  338. invalid_quality_changes = ContainerRegistry.getInstance().findContainersMetadata(name=profile_name)
  339. if invalid_quality_changes:
  340. Logger.log("d", "Found an invalid quality_changes profile with the name %s. Going to remove that now", profile_name)
  341. self.removeContainer(invalid_quality_changes[0]["id"])
  342. @override(ContainerRegistry)
  343. def _isMetadataValid(self, metadata: Optional[Dict[str, Any]]) -> bool:
  344. """Check if the metadata for a container is okay before adding it.
  345. This overrides the one from UM.Settings.ContainerRegistry because we
  346. also require that the setting_version is correct.
  347. """
  348. if metadata is None:
  349. return False
  350. if "setting_version" not in metadata:
  351. return False
  352. try:
  353. if int(metadata["setting_version"]) != cura.CuraApplication.CuraApplication.SettingVersion:
  354. return False
  355. except ValueError: # Not parsable as int.
  356. return False
  357. except TypeError: # Expecting string input here, not e.g. list or anything.
  358. return False
  359. return True
  360. def _configureProfile(self, profile: InstanceContainer, id_seed: str, new_name: str, machine_definition_id: str) -> Tuple[bool, Optional[str]]:
  361. """Update an imported profile to match the current machine configuration.
  362. :param profile: The profile to configure.
  363. :param id_seed: The base ID for the profile. May be changed so it does not conflict with existing containers.
  364. :param new_name: The new name for the profile.
  365. :returns: tuple (configuration_successful, message)
  366. WHERE
  367. bool configuration_successful: Whether the process of configuring the profile was successful
  368. optional str message: A message indicating the outcome of configuring the profile. If the configuration
  369. is successful, this message can be None or contain a warning
  370. """
  371. profile.setDirty(True) # Ensure the profiles are correctly saved
  372. new_id = self.createUniqueName("quality_changes", "", id_seed, catalog.i18nc("@label", "Custom profile"))
  373. profile.setMetaDataEntry("id", new_id)
  374. profile.setName(new_name)
  375. # Set the unique Id to the profile, so it's generating a new one even if the user imports the same profile
  376. # It also solves an issue with importing profiles from G-Codes
  377. profile.setMetaDataEntry("id", new_id)
  378. profile.setMetaDataEntry("definition", machine_definition_id)
  379. if "type" in profile.getMetaData():
  380. profile.setMetaDataEntry("type", "quality_changes")
  381. else:
  382. profile.setMetaDataEntry("type", "quality_changes")
  383. quality_type = profile.getMetaDataEntry("quality_type")
  384. if not quality_type:
  385. return False, catalog.i18nc("@info:status", "Profile is missing a quality type.")
  386. global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  387. if not global_stack:
  388. return False, catalog.i18nc("@info:status", "There is no active printer yet.")
  389. definition_id = ContainerTree.getInstance().machines[global_stack.definition.getId()].quality_definition
  390. profile.setDefinition(definition_id)
  391. if not self.addContainer(profile):
  392. return False, catalog.i18nc("@info:status", "Unable to add the profile.")
  393. # "not_supported" profiles can be imported.
  394. if quality_type == empty_quality_container.getMetaDataEntry("quality_type"):
  395. return True, None
  396. # Check to make sure the imported profile actually makes sense in context of the current configuration.
  397. # This prevents issues where importing a "draft" profile for a machine without "draft" qualities would report as
  398. # successfully imported but then fail to show up.
  399. available_quality_groups_dict = {name: quality_group for name, quality_group in ContainerTree.getInstance().getCurrentQualityGroups().items() if quality_group.is_available}
  400. all_quality_groups_dict = ContainerTree.getInstance().getCurrentQualityGroups()
  401. # If the quality type doesn't exist at all in the quality_groups of this machine, reject the profile
  402. if quality_type not in all_quality_groups_dict:
  403. return False, catalog.i18nc("@info:status", "Quality type '{0}' is not compatible with the current active machine definition '{1}'.", quality_type, definition_id)
  404. # If the quality_type exists in the quality_groups of this printer but it is not available with the current
  405. # machine configuration (e.g. not available for the selected nozzles), accept it with a warning
  406. if quality_type not in available_quality_groups_dict:
  407. return True, "\n\n" + catalog.i18nc("@info:status", "Warning: The profile is not visible because its quality type '{0}' is not available for the current configuration. "
  408. "Switch to a material/nozzle combination that can use this quality type.", quality_type)
  409. return True, None
  410. @override(ContainerRegistry)
  411. def saveDirtyContainers(self) -> None:
  412. # Lock file for "more" atomically loading and saving to/from config dir.
  413. with self.lockFile():
  414. # Save base files first
  415. for instance in self.findDirtyContainers(container_type=InstanceContainer):
  416. if instance.getMetaDataEntry("removed"):
  417. continue
  418. if instance.getId() == instance.getMetaData().get("base_file"):
  419. self.saveContainer(instance)
  420. for instance in self.findDirtyContainers(container_type=InstanceContainer):
  421. if instance.getMetaDataEntry("removed"):
  422. continue
  423. self.saveContainer(instance)
  424. for stack in self.findContainerStacks():
  425. self.saveContainer(stack)
  426. def _getIOPlugins(self, io_type):
  427. """Gets a list of profile writer plugins
  428. :return: List of tuples of (plugin_id, meta_data).
  429. """
  430. plugin_registry = PluginRegistry.getInstance()
  431. active_plugin_ids = plugin_registry.getActivePlugins()
  432. result = []
  433. for plugin_id in active_plugin_ids:
  434. meta_data = plugin_registry.getMetaData(plugin_id)
  435. if io_type in meta_data:
  436. result.append( (plugin_id, meta_data) )
  437. return result
  438. def _convertContainerStack(self, container: ContainerStack) -> Union[ExtruderStack.ExtruderStack, GlobalStack.GlobalStack]:
  439. """Convert an "old-style" pure ContainerStack to either an Extruder or Global stack."""
  440. assert type(container) == ContainerStack
  441. container_type = container.getMetaDataEntry("type")
  442. if container_type not in ("extruder_train", "machine"):
  443. # It is not an extruder or machine, so do nothing with the stack
  444. return container
  445. Logger.log("d", "Converting ContainerStack {stack} to {type}", stack = container.getId(), type = container_type)
  446. if container_type == "extruder_train":
  447. new_stack = ExtruderStack.ExtruderStack(container.getId())
  448. else:
  449. new_stack = GlobalStack.GlobalStack(container.getId())
  450. container_contents = container.serialize()
  451. new_stack.deserialize(container_contents)
  452. # Delete the old configuration file so we do not get double stacks
  453. if os.path.isfile(container.getPath()):
  454. os.remove(container.getPath())
  455. return new_stack
  456. def _registerSingleExtrusionMachinesExtruderStacks(self) -> None:
  457. machines = self.findContainerStacks(type = "machine", machine_extruder_trains = {"0": "fdmextruder"})
  458. for machine in machines:
  459. extruder_stacks = self.findContainerStacks(type = "extruder_train", machine = machine.getId())
  460. if not extruder_stacks:
  461. self.addExtruderStackForSingleExtrusionMachine(machine, "fdmextruder")
  462. def _onContainerAdded(self, container: ContainerInterface) -> None:
  463. # We don't have all the machines loaded in the beginning, so in order to add the missing extruder stack
  464. # for single extrusion machines, we subscribe to the containerAdded signal, and whenever a global stack
  465. # is added, we check to see if an extruder stack needs to be added.
  466. if not isinstance(container, ContainerStack) or container.getMetaDataEntry("type") != "machine":
  467. return
  468. machine_extruder_trains = container.getMetaDataEntry("machine_extruder_trains")
  469. if machine_extruder_trains is not None and machine_extruder_trains != {"0": "fdmextruder"}:
  470. return
  471. extruder_stacks = self.findContainerStacks(type = "extruder_train", machine = container.getId())
  472. if not extruder_stacks:
  473. self.addExtruderStackForSingleExtrusionMachine(container, "fdmextruder")
  474. #
  475. # new_global_quality_changes is optional. It is only used in project loading for a scenario like this:
  476. # - override the current machine
  477. # - create new for custom quality profile
  478. # new_global_quality_changes is the new global quality changes container in this scenario.
  479. # create_new_ids indicates if new unique ids must be created
  480. #
  481. def addExtruderStackForSingleExtrusionMachine(self, machine, extruder_id, new_global_quality_changes = None, create_new_ids = True):
  482. new_extruder_id = extruder_id
  483. application = cura.CuraApplication.CuraApplication.getInstance()
  484. extruder_definitions = self.findDefinitionContainers(id = new_extruder_id)
  485. if not extruder_definitions:
  486. Logger.log("w", "Could not find definition containers for extruder %s", new_extruder_id)
  487. return
  488. extruder_definition = extruder_definitions[0]
  489. unique_name = self.uniqueName(machine.getName() + " " + new_extruder_id) if create_new_ids else machine.getName() + " " + new_extruder_id
  490. extruder_stack = ExtruderStack.ExtruderStack(unique_name)
  491. extruder_stack.setName(extruder_definition.getName())
  492. extruder_stack.setDefinition(extruder_definition)
  493. extruder_stack.setMetaDataEntry("position", extruder_definition.getMetaDataEntry("position"))
  494. # create a new definition_changes container for the extruder stack
  495. definition_changes_id = self.uniqueName(extruder_stack.getId() + "_settings") if create_new_ids else extruder_stack.getId() + "_settings"
  496. definition_changes_name = definition_changes_id
  497. definition_changes = InstanceContainer(definition_changes_id, parent = application)
  498. definition_changes.setName(definition_changes_name)
  499. definition_changes.setMetaDataEntry("setting_version", application.SettingVersion)
  500. definition_changes.setMetaDataEntry("type", "definition_changes")
  501. definition_changes.setMetaDataEntry("definition", extruder_definition.getId())
  502. # move definition_changes settings if exist
  503. for setting_key in definition_changes.getAllKeys():
  504. if machine.definition.getProperty(setting_key, "settable_per_extruder"):
  505. setting_value = machine.definitionChanges.getProperty(setting_key, "value")
  506. if setting_value is not None:
  507. # move it to the extruder stack's definition_changes
  508. setting_definition = machine.getSettingDefinition(setting_key)
  509. new_instance = SettingInstance(setting_definition, definition_changes)
  510. new_instance.setProperty("value", setting_value)
  511. new_instance.resetState() # Ensure that the state is not seen as a user state.
  512. definition_changes.addInstance(new_instance)
  513. definition_changes.setDirty(True)
  514. machine.definitionChanges.removeInstance(setting_key, postpone_emit = True)
  515. self.addContainer(definition_changes)
  516. extruder_stack.setDefinitionChanges(definition_changes)
  517. # create empty user changes container otherwise
  518. user_container_id = self.uniqueName(extruder_stack.getId() + "_user") if create_new_ids else extruder_stack.getId() + "_user"
  519. user_container_name = user_container_id
  520. user_container = InstanceContainer(user_container_id, parent = application)
  521. user_container.setName(user_container_name)
  522. user_container.setMetaDataEntry("type", "user")
  523. user_container.setMetaDataEntry("machine", machine.getId())
  524. user_container.setMetaDataEntry("setting_version", application.SettingVersion)
  525. user_container.setDefinition(machine.definition.getId())
  526. user_container.setMetaDataEntry("position", extruder_stack.getMetaDataEntry("position"))
  527. if machine.userChanges:
  528. # For the newly created extruder stack, we need to move all "per-extruder" settings to the user changes
  529. # container to the extruder stack.
  530. for user_setting_key in machine.userChanges.getAllKeys():
  531. settable_per_extruder = machine.getProperty(user_setting_key, "settable_per_extruder")
  532. if settable_per_extruder:
  533. setting_value = machine.getProperty(user_setting_key, "value")
  534. setting_definition = machine.getSettingDefinition(user_setting_key)
  535. new_instance = SettingInstance(setting_definition, definition_changes)
  536. new_instance.setProperty("value", setting_value)
  537. new_instance.resetState() # Ensure that the state is not seen as a user state.
  538. user_container.addInstance(new_instance)
  539. user_container.setDirty(True)
  540. machine.userChanges.removeInstance(user_setting_key, postpone_emit = True)
  541. self.addContainer(user_container)
  542. extruder_stack.setUserChanges(user_container)
  543. empty_variant = application.empty_variant_container
  544. empty_material = application.empty_material_container
  545. empty_quality = application.empty_quality_container
  546. if machine.variant.getId() not in ("empty", "empty_variant"):
  547. variant = machine.variant
  548. else:
  549. variant = empty_variant
  550. extruder_stack.variant = variant
  551. if machine.material.getId() not in ("empty", "empty_material"):
  552. material = machine.material
  553. else:
  554. material = empty_material
  555. extruder_stack.material = material
  556. if machine.quality.getId() not in ("empty", "empty_quality"):
  557. quality = machine.quality
  558. else:
  559. quality = empty_quality
  560. extruder_stack.quality = quality
  561. machine_quality_changes = machine.qualityChanges
  562. if new_global_quality_changes is not None:
  563. machine_quality_changes = new_global_quality_changes
  564. if machine_quality_changes.getId() not in ("empty", "empty_quality_changes"):
  565. extruder_quality_changes_container = self.findInstanceContainers(name = machine_quality_changes.getName(), extruder = extruder_id)
  566. if extruder_quality_changes_container:
  567. extruder_quality_changes_container = extruder_quality_changes_container[0]
  568. quality_changes_id = extruder_quality_changes_container.getId()
  569. extruder_stack.qualityChanges = self.findInstanceContainers(id = quality_changes_id)[0]
  570. else:
  571. # Some extruder quality_changes containers can be created at runtime as files in the qualities
  572. # folder. Those files won't be loaded in the registry immediately. So we also need to search
  573. # the folder to see if the quality_changes exists.
  574. extruder_quality_changes_container = self._findQualityChangesContainerInCuraFolder(machine_quality_changes.getName())
  575. if extruder_quality_changes_container:
  576. quality_changes_id = extruder_quality_changes_container.getId()
  577. extruder_quality_changes_container.setMetaDataEntry("position", extruder_definition.getMetaDataEntry("position"))
  578. extruder_stack.qualityChanges = self.findInstanceContainers(id = quality_changes_id)[0]
  579. else:
  580. # If we still cannot find a quality changes container for the extruder, create a new one
  581. container_name = machine_quality_changes.getName()
  582. container_id = self.uniqueName(extruder_stack.getId() + "_qc_" + container_name)
  583. extruder_quality_changes_container = InstanceContainer(container_id, parent = application)
  584. extruder_quality_changes_container.setName(container_name)
  585. extruder_quality_changes_container.setMetaDataEntry("type", "quality_changes")
  586. extruder_quality_changes_container.setMetaDataEntry("setting_version", application.SettingVersion)
  587. extruder_quality_changes_container.setMetaDataEntry("position", extruder_definition.getMetaDataEntry("position"))
  588. extruder_quality_changes_container.setMetaDataEntry("quality_type", machine_quality_changes.getMetaDataEntry("quality_type"))
  589. extruder_quality_changes_container.setMetaDataEntry("intent_category", "default") # Intent categories weren't a thing back then.
  590. extruder_quality_changes_container.setDefinition(machine_quality_changes.getDefinition().getId())
  591. self.addContainer(extruder_quality_changes_container)
  592. extruder_stack.qualityChanges = extruder_quality_changes_container
  593. if not extruder_quality_changes_container:
  594. Logger.log("w", "Could not find quality_changes named [%s] for extruder [%s]",
  595. machine_quality_changes.getName(), extruder_stack.getId())
  596. else:
  597. # Move all per-extruder settings to the extruder's quality changes
  598. for qc_setting_key in machine_quality_changes.getAllKeys():
  599. settable_per_extruder = machine.getProperty(qc_setting_key, "settable_per_extruder")
  600. if settable_per_extruder:
  601. setting_value = machine_quality_changes.getProperty(qc_setting_key, "value")
  602. setting_definition = machine.getSettingDefinition(qc_setting_key)
  603. new_instance = SettingInstance(setting_definition, definition_changes)
  604. new_instance.setProperty("value", setting_value)
  605. new_instance.resetState() # Ensure that the state is not seen as a user state.
  606. extruder_quality_changes_container.addInstance(new_instance)
  607. extruder_quality_changes_container.setDirty(True)
  608. machine_quality_changes.removeInstance(qc_setting_key, postpone_emit=True)
  609. else:
  610. extruder_stack.qualityChanges = self.findInstanceContainers(id = "empty_quality_changes")[0]
  611. self.addContainer(extruder_stack)
  612. # Also need to fix the other qualities that are suitable for this machine. Those quality changes may still have
  613. # per-extruder settings in the container for the machine instead of the extruder.
  614. if machine_quality_changes.getId() not in ("empty", "empty_quality_changes"):
  615. quality_changes_machine_definition_id = machine_quality_changes.getDefinition().getId()
  616. else:
  617. whole_machine_definition = machine.definition
  618. machine_entry = machine.definition.getMetaDataEntry("machine")
  619. if machine_entry is not None:
  620. container_registry = ContainerRegistry.getInstance()
  621. whole_machine_definition = container_registry.findDefinitionContainers(id = machine_entry)[0]
  622. quality_changes_machine_definition_id = "fdmprinter"
  623. if whole_machine_definition.getMetaDataEntry("has_machine_quality"):
  624. quality_changes_machine_definition_id = machine.definition.getMetaDataEntry("quality_definition",
  625. whole_machine_definition.getId())
  626. qcs = self.findInstanceContainers(type = "quality_changes", definition = quality_changes_machine_definition_id)
  627. qc_groups = {} # map of qc names -> qc containers
  628. for qc in qcs:
  629. qc_name = qc.getName()
  630. if qc_name not in qc_groups:
  631. qc_groups[qc_name] = []
  632. qc_groups[qc_name].append(qc)
  633. # Try to find from the quality changes cura directory too
  634. quality_changes_container = self._findQualityChangesContainerInCuraFolder(machine_quality_changes.getName())
  635. if quality_changes_container:
  636. qc_groups[qc_name].append(quality_changes_container)
  637. for qc_name, qc_list in qc_groups.items():
  638. qc_dict = {"global": None, "extruders": []}
  639. for qc in qc_list:
  640. extruder_position = qc.getMetaDataEntry("position")
  641. if extruder_position is not None:
  642. qc_dict["extruders"].append(qc)
  643. else:
  644. qc_dict["global"] = qc
  645. if qc_dict["global"] is not None and len(qc_dict["extruders"]) == 1:
  646. # Move per-extruder settings
  647. for qc_setting_key in qc_dict["global"].getAllKeys():
  648. settable_per_extruder = machine.getProperty(qc_setting_key, "settable_per_extruder")
  649. if settable_per_extruder:
  650. setting_value = qc_dict["global"].getProperty(qc_setting_key, "value")
  651. setting_definition = machine.getSettingDefinition(qc_setting_key)
  652. new_instance = SettingInstance(setting_definition, definition_changes)
  653. new_instance.setProperty("value", setting_value)
  654. new_instance.resetState() # Ensure that the state is not seen as a user state.
  655. qc_dict["extruders"][0].addInstance(new_instance)
  656. qc_dict["extruders"][0].setDirty(True)
  657. qc_dict["global"].removeInstance(qc_setting_key, postpone_emit=True)
  658. # Set next stack at the end
  659. extruder_stack.setNextStack(machine)
  660. return extruder_stack
  661. def _findQualityChangesContainerInCuraFolder(self, name: str) -> Optional[InstanceContainer]:
  662. quality_changes_dir = Resources.getPath(cura.CuraApplication.CuraApplication.ResourceTypes.QualityChangesInstanceContainer)
  663. instance_container = None
  664. for item in os.listdir(quality_changes_dir):
  665. file_path = os.path.join(quality_changes_dir, item)
  666. if not os.path.isfile(file_path):
  667. continue
  668. parser = configparser.ConfigParser(interpolation = None)
  669. try:
  670. parser.read([file_path])
  671. except Exception:
  672. # Skip, it is not a valid stack file
  673. continue
  674. if not parser.has_option("general", "name"):
  675. continue
  676. if parser["general"]["name"] == name:
  677. # Load the container
  678. container_id = os.path.basename(file_path).replace(".inst.cfg", "")
  679. if self.findInstanceContainers(id = container_id):
  680. # This container is already in the registry, skip it
  681. continue
  682. instance_container = InstanceContainer(container_id)
  683. with open(file_path, "r", encoding = "utf-8") as f:
  684. serialized = f.read()
  685. try:
  686. instance_container.deserialize(serialized, file_path)
  687. except ContainerFormatError:
  688. Logger.logException("e", "Unable to deserialize InstanceContainer %s", file_path)
  689. continue
  690. self.addContainer(instance_container)
  691. break
  692. return instance_container
  693. # Fix the extruders that were upgraded to ExtruderStack instances during addContainer.
  694. # The stacks are now responsible for setting the next stack on deserialize. However,
  695. # due to problems with loading order, some stacks may not have the proper next stack
  696. # set after upgrading, because the proper global stack was not yet loaded. This method
  697. # makes sure those extruders also get the right stack set.
  698. def _connectUpgradedExtruderStacksToMachines(self) -> None:
  699. extruder_stacks = self.findContainers(container_type = ExtruderStack.ExtruderStack)
  700. for extruder_stack in extruder_stacks:
  701. if extruder_stack.getNextStack():
  702. # Has the right next stack, so ignore it.
  703. continue
  704. machines = ContainerRegistry.getInstance().findContainerStacks(id = extruder_stack.getMetaDataEntry("machine", ""))
  705. if machines:
  706. extruder_stack.setNextStack(machines[0])
  707. else:
  708. Logger.log("w", "Could not find machine {machine} for extruder {extruder}", machine = extruder_stack.getMetaDataEntry("machine"), extruder = extruder_stack.getId())
  709. # Override just for the type.
  710. @classmethod
  711. @override(ContainerRegistry)
  712. def getInstance(cls, *args, **kwargs) -> "CuraContainerRegistry":
  713. return cast(CuraContainerRegistry, super().getInstance(*args, **kwargs))