CuraContainerRegistry.py 43 KB

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