CuraContainerRegistry.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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(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, str(e))}
  184. if profile_or_list:
  185. name_seed = os.path.splitext(os.path.basename(file_name))[0]
  186. new_name = self.uniqueName(name_seed)
  187. # Ensure it is always a list of profiles
  188. if type(profile_or_list) is not list:
  189. profile_or_list = [profile_or_list]
  190. # Import all profiles
  191. for profile_index, profile in enumerate(profile_or_list):
  192. if profile_index == 0:
  193. # This is assumed to be the global profile
  194. profile_id = (global_container_stack.getBottom().getId() + "_" + name_seed).lower().replace(" ", "_")
  195. elif profile_index < len(machine_extruders) + 1:
  196. # This is assumed to be an extruder profile
  197. extruder_id = Application.getInstance().getMachineManager().getQualityDefinitionId(machine_extruders[profile_index - 1].getBottom())
  198. if not profile.getMetaDataEntry("extruder"):
  199. profile.addMetaDataEntry("extruder", extruder_id)
  200. else:
  201. profile.setMetaDataEntry("extruder", extruder_id)
  202. profile_id = (extruder_id + "_" + name_seed).lower().replace(" ", "_")
  203. else: #More extruders in the imported file than in the machine.
  204. continue #Delete the additional profiles.
  205. result = self._configureProfile(profile, profile_id, new_name)
  206. if result is not None:
  207. return {"status": "error", "message": catalog.i18nc(
  208. "@info:status Don't translate the XML tags <filename> or <message>!",
  209. "Failed to import profile from <filename>{0}</filename>: <message>{1}</message>",
  210. file_name, result)}
  211. return {"status": "ok", "message": catalog.i18nc("@info:status", "Successfully imported profile {0}", profile_or_list[0].getName())}
  212. # If it hasn't returned by now, none of the plugins loaded the profile successfully.
  213. return {"status": "error", "message": catalog.i18nc("@info:status", "Profile {0} has an unknown file type or is corrupted.", file_name)}
  214. @override(ContainerRegistry)
  215. def load(self):
  216. super().load()
  217. self._registerSingleExtrusionMachinesExtruderStacks()
  218. self._connectUpgradedExtruderStacksToMachines()
  219. ## Update an imported profile to match the current machine configuration.
  220. #
  221. # \param profile The profile to configure.
  222. # \param id_seed The base ID for the profile. May be changed so it does not conflict with existing containers.
  223. # \param new_name The new name for the profile.
  224. #
  225. # \return None if configuring was successful or an error message if an error occurred.
  226. def _configureProfile(self, profile: InstanceContainer, id_seed: str, new_name: str) -> Optional[str]:
  227. profile.setDirty(True) # Ensure the profiles are correctly saved
  228. new_id = self.createUniqueName("quality_changes", "", id_seed, catalog.i18nc("@label", "Custom profile"))
  229. profile._id = new_id
  230. profile.setName(new_name)
  231. if "type" in profile.getMetaData():
  232. profile.setMetaDataEntry("type", "quality_changes")
  233. else:
  234. profile.addMetaDataEntry("type", "quality_changes")
  235. quality_type = profile.getMetaDataEntry("quality_type")
  236. if not quality_type:
  237. return catalog.i18nc("@info:status", "Profile is missing a quality type.")
  238. quality_type_criteria = {"quality_type": quality_type}
  239. if self._machineHasOwnQualities():
  240. profile.setDefinition(self._activeQualityDefinition().getId())
  241. if self._machineHasOwnMaterials():
  242. active_material_id = self._activeMaterialId()
  243. if active_material_id and active_material_id != "empty": # only update if there is an active material
  244. profile.addMetaDataEntry("material", active_material_id)
  245. quality_type_criteria["material"] = active_material_id
  246. quality_type_criteria["definition"] = profile.getDefinition().getId()
  247. else:
  248. profile.setDefinition("fdmprinter")
  249. quality_type_criteria["definition"] = "fdmprinter"
  250. machine_definition = Application.getInstance().getGlobalContainerStack().getBottom()
  251. del quality_type_criteria["definition"]
  252. # materials = None
  253. if "material" in quality_type_criteria:
  254. # materials = ContainerRegistry.getInstance().findInstanceContainers(id = quality_type_criteria["material"])
  255. del quality_type_criteria["material"]
  256. # Do not filter quality containers here with materials because we are trying to import a profile, so it should
  257. # NOT be restricted by the active materials on the current machine.
  258. materials = None
  259. # Check to make sure the imported profile actually makes sense in context of the current configuration.
  260. # This prevents issues where importing a "draft" profile for a machine without "draft" qualities would report as
  261. # successfully imported but then fail to show up.
  262. from cura.QualityManager import QualityManager
  263. qualities = QualityManager.getInstance()._getFilteredContainersForStack(machine_definition, materials, **quality_type_criteria)
  264. if not qualities:
  265. return catalog.i18nc("@info:status", "Could not find a quality type {0} for the current configuration.", quality_type)
  266. ContainerRegistry.getInstance().addContainer(profile)
  267. return None
  268. ## Gets a list of profile writer plugins
  269. # \return List of tuples of (plugin_id, meta_data).
  270. def _getIOPlugins(self, io_type):
  271. plugin_registry = PluginRegistry.getInstance()
  272. active_plugin_ids = plugin_registry.getActivePlugins()
  273. result = []
  274. for plugin_id in active_plugin_ids:
  275. meta_data = plugin_registry.getMetaData(plugin_id)
  276. if io_type in meta_data:
  277. result.append( (plugin_id, meta_data) )
  278. return result
  279. ## Get the definition to use to select quality profiles for the active machine
  280. # \return the active quality definition object or None if there is no quality definition
  281. def _activeQualityDefinition(self):
  282. global_container_stack = Application.getInstance().getGlobalContainerStack()
  283. if global_container_stack:
  284. definition_id = Application.getInstance().getMachineManager().getQualityDefinitionId(global_container_stack.getBottom())
  285. definition = self.findDefinitionContainers(id = definition_id)[0]
  286. if definition:
  287. return definition
  288. return None
  289. ## Returns true if the current machine requires its own materials
  290. # \return True if the current machine requires its own materials
  291. def _machineHasOwnMaterials(self):
  292. global_container_stack = Application.getInstance().getGlobalContainerStack()
  293. if global_container_stack:
  294. return global_container_stack.getMetaDataEntry("has_materials", False)
  295. return False
  296. ## Gets the ID of the active material
  297. # \return the ID of the active material or the empty string
  298. def _activeMaterialId(self):
  299. global_container_stack = Application.getInstance().getGlobalContainerStack()
  300. if global_container_stack and global_container_stack.material:
  301. return global_container_stack.material.getId()
  302. return ""
  303. ## Returns true if the current machine requires its own quality profiles
  304. # \return true if the current machine requires its own quality profiles
  305. def _machineHasOwnQualities(self):
  306. global_container_stack = Application.getInstance().getGlobalContainerStack()
  307. if global_container_stack:
  308. return parseBool(global_container_stack.getMetaDataEntry("has_machine_quality", False))
  309. return False
  310. ## Convert an "old-style" pure ContainerStack to either an Extruder or Global stack.
  311. def _convertContainerStack(self, container):
  312. assert type(container) == ContainerStack
  313. container_type = container.getMetaDataEntry("type")
  314. if container_type not in ("extruder_train", "machine"):
  315. # It is not an extruder or machine, so do nothing with the stack
  316. return container
  317. Logger.log("d", "Converting ContainerStack {stack} to {type}", stack = container.getId(), type = container_type)
  318. new_stack = None
  319. if container_type == "extruder_train":
  320. new_stack = ExtruderStack.ExtruderStack(container.getId())
  321. else:
  322. new_stack = GlobalStack.GlobalStack(container.getId())
  323. container_contents = container.serialize()
  324. new_stack.deserialize(container_contents)
  325. # Delete the old configuration file so we do not get double stacks
  326. if os.path.isfile(container.getPath()):
  327. os.remove(container.getPath())
  328. return new_stack
  329. def _registerSingleExtrusionMachinesExtruderStacks(self):
  330. machines = self.findContainerStacks(type = "machine", machine_extruder_trains = {"0": "fdmextruder"})
  331. for machine in machines:
  332. extruder_stacks = self.findContainerStacks(type = "extruder_train", machine = machine.getId())
  333. if not extruder_stacks:
  334. self.addExtruderStackForSingleExtrusionMachine(machine, "fdmextruder")
  335. def _onContainerAdded(self, container):
  336. # We don't have all the machines loaded in the beginning, so in order to add the missing extruder stack
  337. # for single extrusion machines, we subscribe to the containerAdded signal, and whenever a global stack
  338. # is added, we check to see if an extruder stack needs to be added.
  339. if not isinstance(container, ContainerStack) or container.getMetaDataEntry("type") != "machine":
  340. return
  341. machine_extruder_trains = container.getMetaDataEntry("machine_extruder_trains")
  342. if machine_extruder_trains is not None and machine_extruder_trains != {"0": "fdmextruder"}:
  343. return
  344. extruder_stacks = self.findContainerStacks(type = "extruder_train", machine = container.getId())
  345. if not extruder_stacks:
  346. self.addExtruderStackForSingleExtrusionMachine(container, "fdmextruder")
  347. def addExtruderStackForSingleExtrusionMachine(self, machine, extruder_id):
  348. new_extruder_id = extruder_id
  349. extruder_definitions = self.findDefinitionContainers(id = new_extruder_id)
  350. if not extruder_definitions:
  351. Logger.log("w", "Could not find definition containers for extruder %s", new_extruder_id)
  352. return
  353. extruder_definition = extruder_definitions[0]
  354. unique_name = self.uniqueName(machine.getName() + " " + new_extruder_id)
  355. extruder_stack = ExtruderStack.ExtruderStack(unique_name)
  356. extruder_stack.setName(extruder_definition.getName())
  357. extruder_stack.setDefinition(extruder_definition)
  358. extruder_stack.addMetaDataEntry("position", extruder_definition.getMetaDataEntry("position"))
  359. from cura.CuraApplication import CuraApplication
  360. # create a new definition_changes container for the extruder stack
  361. definition_changes_id = self.uniqueName(extruder_stack.getId() + "_settings")
  362. definition_changes_name = definition_changes_id
  363. definition_changes = InstanceContainer(definition_changes_id)
  364. definition_changes.setName(definition_changes_name)
  365. definition_changes.addMetaDataEntry("setting_version", CuraApplication.SettingVersion)
  366. definition_changes.addMetaDataEntry("type", "definition_changes")
  367. definition_changes.addMetaDataEntry("definition", extruder_definition.getId())
  368. # move definition_changes settings if exist
  369. for setting_key in definition_changes.getAllKeys():
  370. if machine.definition.getProperty(setting_key, "settable_per_extruder"):
  371. setting_value = machine.definitionChanges.getProperty(setting_key, "value")
  372. if setting_value is not None:
  373. # move it to the extruder stack's definition_changes
  374. setting_definition = machine.getSettingDefinition(setting_key)
  375. new_instance = SettingInstance(setting_definition, definition_changes)
  376. new_instance.setProperty("value", setting_value)
  377. new_instance.resetState() # Ensure that the state is not seen as a user state.
  378. definition_changes.addInstance(new_instance)
  379. definition_changes.setDirty(True)
  380. machine.definitionChanges.removeInstance(setting_key, postpone_emit = True)
  381. self.addContainer(definition_changes)
  382. extruder_stack.setDefinitionChanges(definition_changes)
  383. # create empty user changes container otherwise
  384. user_container_id = self.uniqueName(extruder_stack.getId() + "_user")
  385. user_container_name = user_container_id
  386. user_container = InstanceContainer(user_container_id)
  387. user_container.setName(user_container_name)
  388. user_container.addMetaDataEntry("type", "user")
  389. user_container.addMetaDataEntry("machine", extruder_stack.getId())
  390. user_container.addMetaDataEntry("setting_version", CuraApplication.SettingVersion)
  391. user_container.setDefinition(machine.definition.getId())
  392. if machine.userChanges:
  393. # for the newly created extruder stack, we need to move all "per-extruder" settings to the user changes
  394. # container to the extruder stack.
  395. for user_setting_key in machine.userChanges.getAllKeys():
  396. settable_per_extruder = machine.getProperty(user_setting_key, "settable_per_extruder")
  397. if settable_per_extruder:
  398. setting_value = machine.getProperty(user_setting_key, "value")
  399. setting_definition = machine.getSettingDefinition(user_setting_key)
  400. new_instance = SettingInstance(setting_definition, definition_changes)
  401. new_instance.setProperty("value", setting_value)
  402. new_instance.resetState() # Ensure that the state is not seen as a user state.
  403. user_container.addInstance(new_instance)
  404. user_container.setDirty(True)
  405. machine.userChanges.removeInstance(user_setting_key, postpone_emit = True)
  406. self.addContainer(user_container)
  407. extruder_stack.setUserChanges(user_container)
  408. variant_id = "default"
  409. if machine.variant.getId() not in ("empty", "empty_variant"):
  410. variant_id = machine.variant.getId()
  411. else:
  412. variant_id = "empty_variant"
  413. extruder_stack.setVariantById(variant_id)
  414. material_id = "default"
  415. if machine.material.getId() not in ("empty", "empty_material"):
  416. material_id = machine.material.getId()
  417. else:
  418. material_id = "empty_material"
  419. extruder_stack.setMaterialById(material_id)
  420. quality_id = "default"
  421. if machine.quality.getId() not in ("empty", "empty_quality"):
  422. quality_id = machine.quality.getId()
  423. else:
  424. quality_id = "empty_quality"
  425. extruder_stack.setQualityById(quality_id)
  426. if machine.qualityChanges.getId() not in ("empty", "empty_quality_changes"):
  427. extruder_quality_changes_container = self.findInstanceContainers(name = machine.qualityChanges.getName(), extruder = extruder_id)
  428. if extruder_quality_changes_container:
  429. extruder_quality_changes_container = extruder_quality_changes_container[0]
  430. quality_changes_id = extruder_quality_changes_container.getId()
  431. extruder_stack.setQualityChangesById(quality_changes_id)
  432. else:
  433. # Some extruder quality_changes containers can be created at runtime as files in the qualities
  434. # folder. Those files won't be loaded in the registry immediately. So we also need to search
  435. # the folder to see if the quality_changes exists.
  436. extruder_quality_changes_container = self._findQualityChangesContainerInCuraFolder(machine.qualityChanges.getName())
  437. if extruder_quality_changes_container:
  438. quality_changes_id = extruder_quality_changes_container.getId()
  439. extruder_stack.setQualityChangesById(quality_changes_id)
  440. if not extruder_quality_changes_container:
  441. Logger.log("w", "Could not find quality_changes named [%s] for extruder [%s]",
  442. machine.qualityChanges.getName(), extruder_stack.getId())
  443. else:
  444. extruder_stack.setQualityChangesById("empty_quality_changes")
  445. self.addContainer(extruder_stack)
  446. # Set next stack at the end
  447. extruder_stack.setNextStack(machine)
  448. return extruder_stack
  449. def _findQualityChangesContainerInCuraFolder(self, name):
  450. quality_changes_dir = Resources.getPath(CuraApplication.ResourceTypes.QualityInstanceContainer)
  451. instance_container = None
  452. for item in os.listdir(quality_changes_dir):
  453. file_path = os.path.join(quality_changes_dir, item)
  454. if not os.path.isfile(file_path):
  455. continue
  456. parser = configparser.ConfigParser()
  457. try:
  458. parser.read([file_path])
  459. except:
  460. # skip, it is not a valid stack file
  461. continue
  462. if not parser.has_option("general", "name"):
  463. continue
  464. if parser["general"]["name"] == name:
  465. # load the container
  466. container_id = os.path.basename(file_path).replace(".inst.cfg", "")
  467. instance_container = InstanceContainer(container_id)
  468. with open(file_path, "r") as f:
  469. serialized = f.read()
  470. instance_container.deserialize(serialized, file_path)
  471. self.addContainer(instance_container)
  472. break
  473. return instance_container
  474. # Fix the extruders that were upgraded to ExtruderStack instances during addContainer.
  475. # The stacks are now responsible for setting the next stack on deserialize. However,
  476. # due to problems with loading order, some stacks may not have the proper next stack
  477. # set after upgrading, because the proper global stack was not yet loaded. This method
  478. # makes sure those extruders also get the right stack set.
  479. def _connectUpgradedExtruderStacksToMachines(self):
  480. extruder_stacks = self.findContainers(container_type = ExtruderStack.ExtruderStack)
  481. for extruder_stack in extruder_stacks:
  482. if extruder_stack.getNextStack():
  483. # Has the right next stack, so ignore it.
  484. continue
  485. machines = ContainerRegistry.getInstance().findContainerStacks(id = extruder_stack.getMetaDataEntry("machine", ""))
  486. if machines:
  487. extruder_stack.setNextStack(machines[0])
  488. else:
  489. Logger.log("w", "Could not find machine {machine} for extruder {extruder}", machine = extruder_stack.getMetaDataEntry("machine"), extruder = extruder_stack.getId())