CuraContainerRegistry.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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.Application import Application
  14. from UM.Logger import Logger
  15. from UM.Message import Message
  16. from UM.Platform import Platform
  17. from UM.PluginRegistry import PluginRegistry # For getting the possible profile writers to write with.
  18. from UM.Util import parseBool
  19. from UM.Resources import Resources
  20. from . import ExtruderStack
  21. from . import GlobalStack
  22. from .ContainerManager import ContainerManager
  23. from .ExtruderManager import ExtruderManager
  24. from cura.CuraApplication import CuraApplication
  25. from UM.i18n import i18nCatalog
  26. catalog = i18nCatalog("cura")
  27. class CuraContainerRegistry(ContainerRegistry):
  28. def __init__(self, *args, **kwargs):
  29. super().__init__(*args, **kwargs)
  30. ## Overridden from ContainerRegistry
  31. #
  32. # Adds a container to the registry.
  33. #
  34. # This will also try to convert a ContainerStack to either Extruder or
  35. # Global stack based on metadata information.
  36. @override(ContainerRegistry)
  37. def addContainer(self, container):
  38. # Note: Intentional check with type() because we want to ignore subclasses
  39. if type(container) == ContainerStack:
  40. container = self._convertContainerStack(container)
  41. if isinstance(container, InstanceContainer) and type(container) != type(self.getEmptyInstanceContainer()):
  42. # Check against setting version of the definition.
  43. required_setting_version = CuraApplication.SettingVersion
  44. actual_setting_version = int(container.getMetaDataEntry("setting_version", default = 0))
  45. if required_setting_version != actual_setting_version:
  46. 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))
  47. return #Don't add.
  48. super().addContainer(container)
  49. ## Create a name that is not empty and unique
  50. # \param container_type \type{string} Type of the container (machine, quality, ...)
  51. # \param current_name \type{} Current name of the container, which may be an acceptable option
  52. # \param new_name \type{string} Base name, which may not be unique
  53. # \param fallback_name \type{string} Name to use when (stripped) new_name is empty
  54. # \return \type{string} Name that is unique for the specified type and name/id
  55. def createUniqueName(self, container_type, current_name, new_name, fallback_name):
  56. new_name = new_name.strip()
  57. num_check = re.compile("(.*?)\s*#\d+$").match(new_name)
  58. if num_check:
  59. new_name = num_check.group(1)
  60. if new_name == "":
  61. new_name = fallback_name
  62. unique_name = new_name
  63. i = 1
  64. # In case we are renaming, the current name of the container is also a valid end-result
  65. while self._containerExists(container_type, unique_name) and unique_name != current_name:
  66. i += 1
  67. unique_name = "%s #%d" % (new_name, i)
  68. return unique_name
  69. ## Check if a container with of a certain type and a certain name or id exists
  70. # Both the id and the name are checked, because they may not be the same and it is better if they are both unique
  71. # \param container_type \type{string} Type of the container (machine, quality, ...)
  72. # \param container_name \type{string} Name to check
  73. def _containerExists(self, container_type, container_name):
  74. container_class = ContainerStack if container_type == "machine" else InstanceContainer
  75. return self.findContainers(container_class, id = container_name, type = container_type, ignore_case = True) or \
  76. self.findContainers(container_class, name = container_name, type = container_type)
  77. ## Exports an profile to a file
  78. #
  79. # \param instance_ids \type{list} the IDs of the profiles to export.
  80. # \param file_name \type{str} the full path and filename to export to.
  81. # \param file_type \type{str} the file type with the format "<description> (*.<extension>)"
  82. def exportProfile(self, instance_ids, file_name, file_type):
  83. # Parse the fileType to deduce what plugin can save the file format.
  84. # fileType has the format "<description> (*.<extension>)"
  85. split = file_type.rfind(" (*.") # Find where the description ends and the extension starts.
  86. if split < 0: # Not found. Invalid format.
  87. Logger.log("e", "Invalid file format identifier %s", file_type)
  88. return
  89. description = file_type[:split]
  90. extension = file_type[split + 4:-1] # Leave out the " (*." and ")".
  91. if not file_name.endswith("." + extension): # Auto-fill the extension if the user did not provide any.
  92. file_name += "." + extension
  93. # On Windows, QML FileDialog properly asks for overwrite confirm, but not on other platforms, so handle those ourself.
  94. if not Platform.isWindows():
  95. if os.path.exists(file_name):
  96. result = QMessageBox.question(None, catalog.i18nc("@title:window", "File Already Exists"),
  97. 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))
  98. if result == QMessageBox.No:
  99. return
  100. found_containers = []
  101. extruder_positions = []
  102. for instance_id in instance_ids:
  103. containers = ContainerRegistry.getInstance().findInstanceContainers(id=instance_id)
  104. if containers:
  105. found_containers.append(containers[0])
  106. # Determine the position of the extruder of this container
  107. extruder_id = containers[0].getMetaDataEntry("extruder", "")
  108. if extruder_id == "":
  109. # Global stack
  110. extruder_positions.append(-1)
  111. else:
  112. extruder_containers = ContainerRegistry.getInstance().findDefinitionContainers(id=extruder_id)
  113. if extruder_containers:
  114. extruder_positions.append(int(extruder_containers[0].getMetaDataEntry("position", 0)))
  115. else:
  116. extruder_positions.append(0)
  117. # Ensure the profiles are always exported in order (global, extruder 0, extruder 1, ...)
  118. found_containers = [containers for (positions, containers) in sorted(zip(extruder_positions, found_containers))]
  119. profile_writer = self._findProfileWriter(extension, description)
  120. try:
  121. success = profile_writer.write(file_name, found_containers)
  122. except Exception as e:
  123. Logger.log("e", "Failed to export profile to %s: %s", file_name, str(e))
  124. 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)),
  125. lifetime = 0,
  126. title = catalog.i18nc("@info:title", "Error"))
  127. m.show()
  128. return
  129. if not success:
  130. Logger.log("w", "Failed to export profile to %s: Writer plugin reported failure.", file_name)
  131. 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),
  132. lifetime = 0,
  133. title = catalog.i18nc("@info:title", "Error"))
  134. m.show()
  135. return
  136. m = Message(catalog.i18nc("@info:status Don't translate the XML tag <filename>!", "Exported profile to <filename>{0}</filename>", file_name),
  137. title = catalog.i18nc("@info:title", "Export succeeded"))
  138. m.show()
  139. ## Gets the plugin object matching the criteria
  140. # \param extension
  141. # \param description
  142. # \return The plugin object matching the given extension and description.
  143. def _findProfileWriter(self, extension, description):
  144. plugin_registry = PluginRegistry.getInstance()
  145. for plugin_id, meta_data in self._getIOPlugins("profile_writer"):
  146. for supported_type in meta_data["profile_writer"]: # All file types this plugin can supposedly write.
  147. supported_extension = supported_type.get("extension", None)
  148. if supported_extension == extension: # This plugin supports a file type with the same extension.
  149. supported_description = supported_type.get("description", None)
  150. if supported_description == description: # The description is also identical. Assume it's the same file type.
  151. return plugin_registry.getPluginObject(plugin_id)
  152. return None
  153. ## Imports a profile from a file
  154. #
  155. # \param file_name \type{str} the full path and filename of the profile to import
  156. # \return \type{Dict} dict with a 'status' key containing the string 'ok' or 'error', and a 'message' key
  157. # containing a message for the user
  158. def importProfile(self, file_name):
  159. Logger.log("d", "Attempting to import profile %s", file_name)
  160. if not file_name:
  161. 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")}
  162. plugin_registry = PluginRegistry.getInstance()
  163. extension = file_name.split(".")[-1]
  164. global_container_stack = Application.getInstance().getGlobalContainerStack()
  165. if not global_container_stack:
  166. return
  167. machine_extruders = list(ExtruderManager.getInstance().getMachineExtruders(global_container_stack.getId()))
  168. machine_extruders.sort(key = lambda k: k.getMetaDataEntry("position"))
  169. for plugin_id, meta_data in self._getIOPlugins("profile_reader"):
  170. if meta_data["profile_reader"][0]["extension"] != extension:
  171. continue
  172. profile_reader = plugin_registry.getPluginObject(plugin_id)
  173. try:
  174. profile_or_list = profile_reader.read(file_name) # Try to open the file with the profile reader.
  175. except Exception as e:
  176. # 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.
  177. Logger.log("e", "Failed to import profile from %s: %s while using profile reader. Got exception %s", file_name,profile_reader.getPluginId(), str(e))
  178. 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))}
  179. if profile_or_list:
  180. name_seed = os.path.splitext(os.path.basename(file_name))[0]
  181. new_name = self.uniqueName(name_seed)
  182. # Ensure it is always a list of profiles
  183. if type(profile_or_list) is not list:
  184. profile_or_list = [profile_or_list]
  185. if len(profile_or_list) == 1:
  186. # If there is only 1 stack file it means we're loading a legacy (pre-3.1) .curaprofile.
  187. # In that case we find the per-extruder settings and put those in a new quality_changes container
  188. # so that it is compatible with the new stack setup.
  189. profile = profile_or_list[0]
  190. extruder_stack_quality_changes_container = ContainerManager.getInstance().duplicateContainerInstance(profile)
  191. extruder_stack_quality_changes_container.addMetaDataEntry("extruder", "fdmextruder")
  192. for quality_changes_setting_key in extruder_stack_quality_changes_container.getAllKeys():
  193. settable_per_extruder = extruder_stack_quality_changes_container.getProperty(quality_changes_setting_key, "settable_per_extruder")
  194. if settable_per_extruder:
  195. profile.removeInstance(quality_changes_setting_key, postpone_emit = True)
  196. else:
  197. extruder_stack_quality_changes_container.removeInstance(quality_changes_setting_key, postpone_emit = True)
  198. # We add the new container to the profile list so things like extruder positions are taken care of
  199. # in the next code segment.
  200. profile_or_list.append(extruder_stack_quality_changes_container)
  201. # Import all profiles
  202. for profile_index, profile in enumerate(profile_or_list):
  203. if profile_index == 0:
  204. # This is assumed to be the global profile
  205. profile_id = (global_container_stack.getBottom().getId() + "_" + name_seed).lower().replace(" ", "_")
  206. result = self._configureProfile(profile, profile_id, new_name)
  207. if result is not None:
  208. return {"status": "error", "message": catalog.i18nc(
  209. "@info:status Don't translate the XML tags <filename> or <message>!",
  210. "Failed to import profile from <filename>{0}</filename>: <message>{1}</message>",
  211. file_name, result)}
  212. elif len(machine_extruders) > profile_index:
  213. # This is assumed to be an extruder profile
  214. extruder_id = Application.getInstance().getMachineManager().getQualityDefinitionId(machine_extruders[profile_index - 1].getBottom())
  215. if not profile.getMetaDataEntry("extruder"):
  216. profile.addMetaDataEntry("extruder", extruder_id)
  217. else:
  218. profile.setMetaDataEntry("extruder", extruder_id)
  219. return {"status": "ok", "message": catalog.i18nc("@info:status", "Successfully imported profile {0}", profile_or_list[0].getName())}
  220. # If it hasn't returned by now, none of the plugins loaded the profile successfully.
  221. return {"status": "error", "message": catalog.i18nc("@info:status", "Profile {0} has an unknown file type or is corrupted.", file_name)}
  222. @override(ContainerRegistry)
  223. def load(self):
  224. super().load()
  225. self._registerSingleExtrusionMachinesExtruderStacks()
  226. self._connectUpgradedExtruderStacksToMachines()
  227. ## Update an imported profile to match the current machine configuration.
  228. #
  229. # \param profile The profile to configure.
  230. # \param id_seed The base ID for the profile. May be changed so it does not conflict with existing containers.
  231. # \param new_name The new name for the profile.
  232. #
  233. # \return None if configuring was successful or an error message if an error occurred.
  234. def _configureProfile(self, profile: InstanceContainer, id_seed: str, new_name: str) -> Optional[str]:
  235. profile.setReadOnly(False)
  236. profile.setDirty(True) # Ensure the profiles are correctly saved
  237. new_id = self.createUniqueName("quality_changes", "", id_seed, catalog.i18nc("@label", "Custom profile"))
  238. profile._id = new_id
  239. profile.setName(new_name)
  240. if "type" in profile.getMetaData():
  241. profile.setMetaDataEntry("type", "quality_changes")
  242. else:
  243. profile.addMetaDataEntry("type", "quality_changes")
  244. quality_type = profile.getMetaDataEntry("quality_type")
  245. if not quality_type:
  246. return catalog.i18nc("@info:status", "Profile is missing a quality type.")
  247. quality_type_criteria = {"quality_type": quality_type}
  248. if self._machineHasOwnQualities():
  249. profile.setDefinition(self._activeQualityDefinition())
  250. if self._machineHasOwnMaterials():
  251. active_material_id = self._activeMaterialId()
  252. if active_material_id and active_material_id != "empty": # only update if there is an active material
  253. profile.addMetaDataEntry("material", active_material_id)
  254. quality_type_criteria["material"] = active_material_id
  255. quality_type_criteria["definition"] = profile.getDefinition().getId()
  256. else:
  257. profile.setDefinition(ContainerRegistry.getInstance().findDefinitionContainers(id="fdmprinter")[0])
  258. quality_type_criteria["definition"] = "fdmprinter"
  259. machine_definition = Application.getInstance().getGlobalContainerStack().getBottom()
  260. del quality_type_criteria["definition"]
  261. # materials = None
  262. if "material" in quality_type_criteria:
  263. # materials = ContainerRegistry.getInstance().findInstanceContainers(id = quality_type_criteria["material"])
  264. del quality_type_criteria["material"]
  265. # Do not filter quality containers here with materials because we are trying to import a profile, so it should
  266. # NOT be restricted by the active materials on the current machine.
  267. materials = None
  268. # Check to make sure the imported profile actually makes sense in context of the current configuration.
  269. # This prevents issues where importing a "draft" profile for a machine without "draft" qualities would report as
  270. # successfully imported but then fail to show up.
  271. from cura.QualityManager import QualityManager
  272. qualities = QualityManager.getInstance()._getFilteredContainersForStack(machine_definition, materials, **quality_type_criteria)
  273. if not qualities:
  274. return catalog.i18nc("@info:status", "Could not find a quality type {0} for the current configuration.", quality_type)
  275. ContainerRegistry.getInstance().addContainer(profile)
  276. return None
  277. ## Gets a list of profile writer plugins
  278. # \return List of tuples of (plugin_id, meta_data).
  279. def _getIOPlugins(self, io_type):
  280. plugin_registry = PluginRegistry.getInstance()
  281. active_plugin_ids = plugin_registry.getActivePlugins()
  282. result = []
  283. for plugin_id in active_plugin_ids:
  284. meta_data = plugin_registry.getMetaData(plugin_id)
  285. if io_type in meta_data:
  286. result.append( (plugin_id, meta_data) )
  287. return result
  288. ## Get the definition to use to select quality profiles for the active machine
  289. # \return the active quality definition object or None if there is no quality definition
  290. def _activeQualityDefinition(self):
  291. global_container_stack = Application.getInstance().getGlobalContainerStack()
  292. if global_container_stack:
  293. definition_id = Application.getInstance().getMachineManager().getQualityDefinitionId(global_container_stack.getBottom())
  294. definition = self.findDefinitionContainers(id=definition_id)[0]
  295. if definition:
  296. return definition
  297. return None
  298. ## Returns true if the current machine requires its own materials
  299. # \return True if the current machine requires its own materials
  300. def _machineHasOwnMaterials(self):
  301. global_container_stack = Application.getInstance().getGlobalContainerStack()
  302. if global_container_stack:
  303. return global_container_stack.getMetaDataEntry("has_materials", False)
  304. return False
  305. ## Gets the ID of the active material
  306. # \return the ID of the active material or the empty string
  307. def _activeMaterialId(self):
  308. global_container_stack = Application.getInstance().getGlobalContainerStack()
  309. if global_container_stack and global_container_stack.material:
  310. return global_container_stack.material.getId()
  311. return ""
  312. ## Returns true if the current machine requires its own quality profiles
  313. # \return true if the current machine requires its own quality profiles
  314. def _machineHasOwnQualities(self):
  315. global_container_stack = Application.getInstance().getGlobalContainerStack()
  316. if global_container_stack:
  317. return parseBool(global_container_stack.getMetaDataEntry("has_machine_quality", False))
  318. return False
  319. ## Convert an "old-style" pure ContainerStack to either an Extruder or Global stack.
  320. def _convertContainerStack(self, container):
  321. assert type(container) == ContainerStack
  322. container_type = container.getMetaDataEntry("type")
  323. if container_type not in ("extruder_train", "machine"):
  324. # It is not an extruder or machine, so do nothing with the stack
  325. return container
  326. Logger.log("d", "Converting ContainerStack {stack} to {type}", stack = container.getId(), type = container_type)
  327. new_stack = None
  328. if container_type == "extruder_train":
  329. new_stack = ExtruderStack.ExtruderStack(container.getId())
  330. else:
  331. new_stack = GlobalStack.GlobalStack(container.getId())
  332. container_contents = container.serialize()
  333. new_stack.deserialize(container_contents)
  334. # Delete the old configuration file so we do not get double stacks
  335. if os.path.isfile(container.getPath()):
  336. os.remove(container.getPath())
  337. return new_stack
  338. def _registerSingleExtrusionMachinesExtruderStacks(self):
  339. machines = self.findContainerStacks(type = "machine", machine_extruder_trains = {"0": "fdmextruder"})
  340. for machine in machines:
  341. extruder_stacks = self.findContainerStacks(type = "extruder_train", machine = machine.getId())
  342. if not extruder_stacks:
  343. self.addExtruderStackForSingleExtrusionMachine(machine, "fdmextruder")
  344. def addExtruderStackForSingleExtrusionMachine(self, machine, extruder_id):
  345. new_extruder_id = extruder_id
  346. extruder_definitions = self.findDefinitionContainers(id = new_extruder_id)
  347. if not extruder_definitions:
  348. Logger.log("w", "Could not find definition containers for extruder %s", new_extruder_id)
  349. return
  350. extruder_definition = extruder_definitions[0]
  351. unique_name = self.uniqueName(machine.getName() + " " + new_extruder_id)
  352. extruder_stack = ExtruderStack.ExtruderStack(unique_name)
  353. extruder_stack.setName(extruder_definition.getName())
  354. extruder_stack.setDefinition(extruder_definition)
  355. extruder_stack.addMetaDataEntry("position", extruder_definition.getMetaDataEntry("position"))
  356. extruder_stack.setNextStack(machine)
  357. # create empty user changes container otherwise
  358. user_container = InstanceContainer(extruder_stack.id + "_user")
  359. user_container.addMetaDataEntry("type", "user")
  360. user_container.addMetaDataEntry("machine", extruder_stack.getId())
  361. from cura.CuraApplication import CuraApplication
  362. user_container.addMetaDataEntry("setting_version", CuraApplication.SettingVersion)
  363. user_container.setDefinition(machine.definition)
  364. if machine.userChanges:
  365. # for the newly created extruder stack, we need to move all "per-extruder" settings to the user changes
  366. # container to the extruder stack.
  367. for user_setting_key in machine.userChanges.getAllKeys():
  368. settable_per_extruder = machine.getProperty(user_setting_key, "settable_per_extruder")
  369. if settable_per_extruder:
  370. user_container.addInstance(machine.userChanges.getInstance(user_setting_key))
  371. machine.userChanges.removeInstance(user_setting_key, postpone_emit = True)
  372. extruder_stack.setUserChanges(user_container)
  373. self.addContainer(user_container)
  374. variant_id = "default"
  375. if machine.variant.getId() not in ("empty", "empty_variant"):
  376. variant_id = machine.variant.getId()
  377. else:
  378. variant_id = "empty_variant"
  379. extruder_stack.setVariantById(variant_id)
  380. material_id = "default"
  381. if machine.material.getId() not in ("empty", "empty_material"):
  382. material_id = machine.material.getId()
  383. else:
  384. material_id = "empty_material"
  385. extruder_stack.setMaterialById(material_id)
  386. quality_id = "default"
  387. if machine.quality.getId() not in ("empty", "empty_quality"):
  388. quality_id = machine.quality.getId()
  389. else:
  390. quality_id = "empty_quality"
  391. extruder_stack.setQualityById(quality_id)
  392. if machine.qualityChanges.getId() not in ("empty", "empty_quality_changes"):
  393. extruder_quality_changes_container = self.findInstanceContainers(name = machine.qualityChanges.getName(), extruder = extruder_id)
  394. if extruder_quality_changes_container:
  395. extruder_quality_changes_container = extruder_quality_changes_container[0]
  396. quality_changes_id = extruder_quality_changes_container.getId()
  397. extruder_stack.setQualityChangesById(quality_changes_id)
  398. else:
  399. # Some extruder quality_changes containers can be created at runtime as files in the qualities
  400. # folder. Those files won't be loaded in the registry immediately. So we also need to search
  401. # the folder to see if the quality_changes exists.
  402. extruder_quality_changes_container = self._findQualityChangesContainerInCuraFolder(machine.qualityChanges.getName())
  403. if extruder_quality_changes_container:
  404. quality_changes_id = extruder_quality_changes_container.getId()
  405. extruder_stack.setQualityChangesById(quality_changes_id)
  406. if not extruder_quality_changes_container:
  407. Logger.log("w", "Could not find quality_changes named [%s] for extruder [%s]",
  408. machine.qualityChanges.getName(), extruder_stack.getId())
  409. else:
  410. extruder_stack.setQualityChangesById("empty_quality_changes")
  411. self.addContainer(extruder_stack)
  412. return extruder_stack
  413. def _findQualityChangesContainerInCuraFolder(self, name):
  414. quality_changes_dir = Resources.getPath(CuraApplication.ResourceTypes.QualityInstanceContainer)
  415. instance_container = None
  416. for item in os.listdir(quality_changes_dir):
  417. file_path = os.path.join(quality_changes_dir, item)
  418. if not os.path.isfile(file_path):
  419. continue
  420. parser = configparser.ConfigParser()
  421. try:
  422. parser.read([file_path])
  423. except:
  424. # skip, it is not a valid stack file
  425. continue
  426. if not parser.has_option("general", "name"):
  427. continue
  428. if parser["general"]["name"] == name:
  429. # load the container
  430. container_id = os.path.basename(file_path).replace(".inst.cfg", "")
  431. instance_container = InstanceContainer(container_id)
  432. with open(file_path, "r") as f:
  433. serialized = f.read()
  434. instance_container.deserialize(serialized, file_path)
  435. self.addContainer(instance_container)
  436. break
  437. return instance_container
  438. # Fix the extruders that were upgraded to ExtruderStack instances during addContainer.
  439. # The stacks are now responsible for setting the next stack on deserialize. However,
  440. # due to problems with loading order, some stacks may not have the proper next stack
  441. # set after upgrading, because the proper global stack was not yet loaded. This method
  442. # makes sure those extruders also get the right stack set.
  443. def _connectUpgradedExtruderStacksToMachines(self):
  444. extruder_stacks = self.findContainers(ExtruderStack.ExtruderStack)
  445. for extruder_stack in extruder_stacks:
  446. if extruder_stack.getNextStack():
  447. # Has the right next stack, so ignore it.
  448. continue
  449. machines = ContainerRegistry.getInstance().findContainerStacks(id=extruder_stack.getMetaDataEntry("machine", ""))
  450. if machines:
  451. extruder_stack.setNextStack(machines[0])
  452. else:
  453. Logger.log("w", "Could not find machine {machine} for extruder {extruder}", machine = extruder_stack.getMetaDataEntry("machine"), extruder = extruder_stack.getId())