CuraContainerRegistry.py 45 KB

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