CuraContainerRegistry.py 44 KB

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