CuraContainerRegistry.py 43 KB

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