CuraContainerRegistry.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. from typing import Optional
  7. from PyQt5.QtWidgets import QMessageBox
  8. from UM.Decorators import override
  9. from UM.Settings.ContainerRegistry import ContainerRegistry
  10. from UM.Settings.ContainerStack import ContainerStack
  11. from UM.Settings.InstanceContainer import InstanceContainer
  12. from UM.Application import Application
  13. from UM.Logger import Logger
  14. from UM.Message import Message
  15. from UM.Platform import Platform
  16. from UM.PluginRegistry import PluginRegistry #For getting the possible profile writers to write with.
  17. from UM.Util import parseBool
  18. from . import ExtruderStack
  19. from . import GlobalStack
  20. from .ContainerManager import ContainerManager
  21. from .ExtruderManager import ExtruderManager
  22. from cura.CuraApplication import CuraApplication
  23. from UM.i18n import i18nCatalog
  24. catalog = i18nCatalog("cura")
  25. class CuraContainerRegistry(ContainerRegistry):
  26. def __init__(self, *args, **kwargs):
  27. super().__init__(*args, **kwargs)
  28. ## Overridden from ContainerRegistry
  29. #
  30. # Adds a container to the registry.
  31. #
  32. # This will also try to convert a ContainerStack to either Extruder or
  33. # Global stack based on metadata information.
  34. @override(ContainerRegistry)
  35. def addContainer(self, container):
  36. # Note: Intentional check with type() because we want to ignore subclasses
  37. if type(container) == ContainerStack:
  38. container = self._convertContainerStack(container)
  39. if isinstance(container, InstanceContainer) and type(container) != type(self.getEmptyInstanceContainer()):
  40. #Check against setting version of the definition.
  41. required_setting_version = CuraApplication.SettingVersion
  42. actual_setting_version = int(container.getMetaDataEntry("setting_version", default = 0))
  43. if required_setting_version != actual_setting_version:
  44. 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))
  45. return #Don't add.
  46. super().addContainer(container)
  47. ## Create a name that is not empty and unique
  48. # \param container_type \type{string} Type of the container (machine, quality, ...)
  49. # \param current_name \type{} Current name of the container, which may be an acceptable option
  50. # \param new_name \type{string} Base name, which may not be unique
  51. # \param fallback_name \type{string} Name to use when (stripped) new_name is empty
  52. # \return \type{string} Name that is unique for the specified type and name/id
  53. def createUniqueName(self, container_type, current_name, new_name, fallback_name):
  54. new_name = new_name.strip()
  55. num_check = re.compile("(.*?)\s*#\d+$").match(new_name)
  56. if num_check:
  57. new_name = num_check.group(1)
  58. if new_name == "":
  59. new_name = fallback_name
  60. unique_name = new_name
  61. i = 1
  62. # In case we are renaming, the current name of the container is also a valid end-result
  63. while self._containerExists(container_type, unique_name) and unique_name != current_name:
  64. i += 1
  65. unique_name = "%s #%d" % (new_name, i)
  66. return unique_name
  67. ## Check if a container with of a certain type and a certain name or id exists
  68. # Both the id and the name are checked, because they may not be the same and it is better if they are both unique
  69. # \param container_type \type{string} Type of the container (machine, quality, ...)
  70. # \param container_name \type{string} Name to check
  71. def _containerExists(self, container_type, container_name):
  72. container_class = ContainerStack if container_type == "machine" else InstanceContainer
  73. return self.findContainers(container_class, id = container_name, type = container_type, ignore_case = True) or \
  74. self.findContainers(container_class, name = container_name, type = container_type)
  75. ## Exports an profile to a file
  76. #
  77. # \param instance_ids \type{list} the IDs of the profiles to export.
  78. # \param file_name \type{str} the full path and filename to export to.
  79. # \param file_type \type{str} the file type with the format "<description> (*.<extension>)"
  80. def exportProfile(self, instance_ids, file_name, file_type):
  81. # Parse the fileType to deduce what plugin can save the file format.
  82. # fileType has the format "<description> (*.<extension>)"
  83. split = file_type.rfind(" (*.") # Find where the description ends and the extension starts.
  84. if split < 0: # Not found. Invalid format.
  85. Logger.log("e", "Invalid file format identifier %s", file_type)
  86. return
  87. description = file_type[:split]
  88. extension = file_type[split + 4:-1] # Leave out the " (*." and ")".
  89. if not file_name.endswith("." + extension): # Auto-fill the extension if the user did not provide any.
  90. file_name += "." + extension
  91. # On Windows, QML FileDialog properly asks for overwrite confirm, but not on other platforms, so handle those ourself.
  92. if not Platform.isWindows():
  93. if os.path.exists(file_name):
  94. result = QMessageBox.question(None, catalog.i18nc("@title:window", "File Already Exists"),
  95. 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))
  96. if result == QMessageBox.No:
  97. return
  98. found_containers = []
  99. extruder_positions = []
  100. for instance_id in instance_ids:
  101. containers = ContainerRegistry.getInstance().findInstanceContainers(id=instance_id)
  102. if containers:
  103. found_containers.append(containers[0])
  104. # Determine the position of the extruder of this container
  105. extruder_id = containers[0].getMetaDataEntry("extruder", "")
  106. if extruder_id == "":
  107. # Global stack
  108. extruder_positions.append(-1)
  109. else:
  110. extruder_containers = ContainerRegistry.getInstance().findDefinitionContainers(id=extruder_id)
  111. if extruder_containers:
  112. extruder_positions.append(int(extruder_containers[0].getMetaDataEntry("position", 0)))
  113. else:
  114. extruder_positions.append(0)
  115. # Ensure the profiles are always exported in order (global, extruder 0, extruder 1, ...)
  116. found_containers = [containers for (positions, containers) in sorted(zip(extruder_positions, found_containers))]
  117. profile_writer = self._findProfileWriter(extension, description)
  118. try:
  119. success = profile_writer.write(file_name, found_containers)
  120. except Exception as e:
  121. Logger.log("e", "Failed to export profile to %s: %s", file_name, str(e))
  122. 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)),
  123. lifetime = 0,
  124. title = catalog.i18nc("@info:title", "Error"))
  125. m.show()
  126. return
  127. if not success:
  128. Logger.log("w", "Failed to export profile to %s: Writer plugin reported failure.", file_name)
  129. 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),
  130. lifetime = 0,
  131. title = catalog.i18nc("@info:title", "Error"))
  132. m.show()
  133. return
  134. m = Message(catalog.i18nc("@info:status Don't translate the XML tag <filename>!", "Exported profile to <filename>{0}</filename>", file_name),
  135. title = catalog.i18nc("@info:title", "Export succeeded"))
  136. m.show()
  137. ## Gets the plugin object matching the criteria
  138. # \param extension
  139. # \param description
  140. # \return The plugin object matching the given extension and description.
  141. def _findProfileWriter(self, extension, description):
  142. plugin_registry = PluginRegistry.getInstance()
  143. for plugin_id, meta_data in self._getIOPlugins("profile_writer"):
  144. for supported_type in meta_data["profile_writer"]: # All file types this plugin can supposedly write.
  145. supported_extension = supported_type.get("extension", None)
  146. if supported_extension == extension: # This plugin supports a file type with the same extension.
  147. supported_description = supported_type.get("description", None)
  148. if supported_description == description: # The description is also identical. Assume it's the same file type.
  149. return plugin_registry.getPluginObject(plugin_id)
  150. return None
  151. ## Imports a profile from a file
  152. #
  153. # \param file_name \type{str} the full path and filename of the profile to import
  154. # \return \type{Dict} dict with a 'status' key containing the string 'ok' or 'error', and a 'message' key
  155. # containing a message for the user
  156. def importProfile(self, file_name):
  157. Logger.log("d", "Attempting to import profile %s", file_name)
  158. if not file_name:
  159. 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")}
  160. plugin_registry = PluginRegistry.getInstance()
  161. extension = file_name.split(".")[-1]
  162. global_container_stack = Application.getInstance().getGlobalContainerStack()
  163. if not global_container_stack:
  164. return
  165. machine_extruders = list(ExtruderManager.getInstance().getMachineExtruders(global_container_stack.getId()))
  166. machine_extruders.sort(key = lambda k: k.getMetaDataEntry("position"))
  167. for plugin_id, meta_data in self._getIOPlugins("profile_reader"):
  168. if meta_data["profile_reader"][0]["extension"] != extension:
  169. continue
  170. profile_reader = plugin_registry.getPluginObject(plugin_id)
  171. try:
  172. profile_or_list = profile_reader.read(file_name) # Try to open the file with the profile reader.
  173. except Exception as e:
  174. # Note that this will fail quickly. That is, if any profile reader throws an exception, it will stop reading. It will only continue reading if the reader returned None.
  175. Logger.log("e", "Failed to import profile from %s: %s while using profile reader. Got exception %s", file_name,profile_reader.getPluginId(), str(e))
  176. return { "status": "error", "message": catalog.i18nc("@info:status Don't translate the XML tags <filename> or <message>!", "Failed to import profile from <filename>{0}</filename>: <message>{1}</message>", file_name, str(e))}
  177. if profile_or_list: # Success!
  178. name_seed = os.path.splitext(os.path.basename(file_name))[0]
  179. new_name = self.uniqueName(name_seed)
  180. if type(profile_or_list) is not list:
  181. profile = profile_or_list
  182. result = self._configureProfile(profile, name_seed, new_name)
  183. if result is not None:
  184. 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, result)}
  185. return {"status": "ok", "message": catalog.i18nc("@info:status", "Successfully imported profile {0}", profile.getName())}
  186. else:
  187. profile_index = -1
  188. global_profile = None
  189. for profile in profile_or_list:
  190. if profile_index >= 0:
  191. if len(machine_extruders) > profile_index:
  192. extruder_id = Application.getInstance().getMachineManager().getQualityDefinitionId(machine_extruders[profile_index].getBottom())
  193. # Ensure the extruder profiles get non-conflicting names
  194. # NB: these are not user-facing
  195. if "extruder" in profile.getMetaData():
  196. profile.setMetaDataEntry("extruder", extruder_id)
  197. else:
  198. profile.addMetaDataEntry("extruder", extruder_id)
  199. profile_id = (extruder_id + "_" + name_seed).lower().replace(" ", "_")
  200. elif profile_index == 0:
  201. # Importing a multiextrusion profile into a single extrusion machine; merge 1st extruder profile into global profile
  202. profile._id = self.uniqueName("temporary_profile")
  203. self.addContainer(profile)
  204. ContainerManager.getInstance().mergeContainers(global_profile.getId(), profile.getId())
  205. self.removeContainer(profile.getId())
  206. break
  207. else:
  208. # The imported composite profile has a profile for an extruder that this machine does not have. Ignore this extruder-profile
  209. break
  210. else:
  211. global_profile = profile
  212. profile_id = (global_container_stack.getBottom().getId() + "_" + name_seed).lower().replace(" ", "_")
  213. result = self._configureProfile(profile, profile_id, new_name)
  214. if result is not None:
  215. 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, result)}
  216. profile_index += 1
  217. return {"status": "ok", "message": catalog.i18nc("@info:status", "Successfully imported profile {0}", profile_or_list[0].getName())}
  218. # If it hasn't returned by now, none of the plugins loaded the profile successfully.
  219. return {"status": "error", "message": catalog.i18nc("@info:status", "Profile {0} has an unknown file type or is corrupted.", file_name)}
  220. @override(ContainerRegistry)
  221. def load(self):
  222. super().load()
  223. self._fixupExtruders()
  224. ## Update an imported profile to match the current machine configuration.
  225. #
  226. # \param profile The profile to configure.
  227. # \param id_seed The base ID for the profile. May be changed so it does not conflict with existing containers.
  228. # \param new_name The new name for the profile.
  229. #
  230. # \return None if configuring was successful or an error message if an error occurred.
  231. def _configureProfile(self, profile: InstanceContainer, id_seed: str, new_name: str) -> Optional[str]:
  232. profile.setReadOnly(False)
  233. profile.setDirty(True) # Ensure the profiles are correctly saved
  234. new_id = self.createUniqueName("quality_changes", "", id_seed, catalog.i18nc("@label", "Custom profile"))
  235. profile._id = new_id
  236. profile.setName(new_name)
  237. if "type" in profile.getMetaData():
  238. profile.setMetaDataEntry("type", "quality_changes")
  239. else:
  240. profile.addMetaDataEntry("type", "quality_changes")
  241. quality_type = profile.getMetaDataEntry("quality_type")
  242. if not quality_type:
  243. return catalog.i18nc("@info:status", "Profile is missing a quality type.")
  244. quality_type_criteria = {"quality_type": quality_type}
  245. if self._machineHasOwnQualities():
  246. profile.setDefinition(self._activeQualityDefinition())
  247. if self._machineHasOwnMaterials():
  248. active_material_id = self._activeMaterialId()
  249. if active_material_id and active_material_id != "empty": # only update if there is an active material
  250. profile.addMetaDataEntry("material", active_material_id)
  251. quality_type_criteria["material"] = active_material_id
  252. quality_type_criteria["definition"] = profile.getDefinition().getId()
  253. else:
  254. profile.setDefinition(ContainerRegistry.getInstance().findDefinitionContainers(id="fdmprinter")[0])
  255. quality_type_criteria["definition"] = "fdmprinter"
  256. machine_definition = Application.getInstance().getGlobalContainerStack().getBottom()
  257. del quality_type_criteria["definition"]
  258. materials = None
  259. if "material" in quality_type_criteria:
  260. materials = ContainerRegistry.getInstance().findInstanceContainers(id = quality_type_criteria["material"])
  261. del quality_type_criteria["material"]
  262. # Check to make sure the imported profile actually makes sense in context of the current configuration.
  263. # This prevents issues where importing a "draft" profile for a machine without "draft" qualities would report as
  264. # successfully imported but then fail to show up.
  265. from cura.QualityManager import QualityManager
  266. qualities = QualityManager.getInstance()._getFilteredContainersForStack(machine_definition, materials, **quality_type_criteria)
  267. if not qualities:
  268. return catalog.i18nc("@info:status", "Could not find a quality type {0} for the current configuration.", quality_type)
  269. ContainerRegistry.getInstance().addContainer(profile)
  270. return None
  271. ## Gets a list of profile writer plugins
  272. # \return List of tuples of (plugin_id, meta_data).
  273. def _getIOPlugins(self, io_type):
  274. plugin_registry = PluginRegistry.getInstance()
  275. active_plugin_ids = plugin_registry.getActivePlugins()
  276. result = []
  277. for plugin_id in active_plugin_ids:
  278. meta_data = plugin_registry.getMetaData(plugin_id)
  279. if io_type in meta_data:
  280. result.append( (plugin_id, meta_data) )
  281. return result
  282. ## Get the definition to use to select quality profiles for the active machine
  283. # \return the active quality definition object or None if there is no quality definition
  284. def _activeQualityDefinition(self):
  285. global_container_stack = Application.getInstance().getGlobalContainerStack()
  286. if global_container_stack:
  287. definition_id = Application.getInstance().getMachineManager().getQualityDefinitionId(global_container_stack.getBottom())
  288. definition = self.findDefinitionContainers(id=definition_id)[0]
  289. if definition:
  290. return definition
  291. return None
  292. ## Returns true if the current machine requires its own materials
  293. # \return True if the current machine requires its own materials
  294. def _machineHasOwnMaterials(self):
  295. global_container_stack = Application.getInstance().getGlobalContainerStack()
  296. if global_container_stack:
  297. return global_container_stack.getMetaDataEntry("has_materials", False)
  298. return False
  299. ## Gets the ID of the active material
  300. # \return the ID of the active material or the empty string
  301. def _activeMaterialId(self):
  302. global_container_stack = Application.getInstance().getGlobalContainerStack()
  303. if global_container_stack and global_container_stack.material:
  304. return global_container_stack.material.getId()
  305. return ""
  306. ## Returns true if the current machien requires its own quality profiles
  307. # \return true if the current machien requires its own quality profiles
  308. def _machineHasOwnQualities(self):
  309. global_container_stack = Application.getInstance().getGlobalContainerStack()
  310. if global_container_stack:
  311. return parseBool(global_container_stack.getMetaDataEntry("has_machine_quality", False))
  312. return False
  313. ## Convert an "old-style" pure ContainerStack to either an Extruder or Global stack.
  314. def _convertContainerStack(self, container):
  315. assert type(container) == ContainerStack
  316. container_type = container.getMetaDataEntry("type")
  317. if container_type not in ("extruder_train", "machine"):
  318. # It is not an extruder or machine, so do nothing with the stack
  319. return container
  320. Logger.log("d", "Converting ContainerStack {stack} to {type}", stack = container.getId(), type = container_type)
  321. new_stack = None
  322. if container_type == "extruder_train":
  323. new_stack = ExtruderStack.ExtruderStack(container.getId())
  324. else:
  325. new_stack = GlobalStack.GlobalStack(container.getId())
  326. container_contents = container.serialize()
  327. new_stack.deserialize(container_contents)
  328. # Delete the old configuration file so we do not get double stacks
  329. if os.path.isfile(container.getPath()):
  330. os.remove(container.getPath())
  331. return new_stack
  332. # Fix the extruders that were upgraded to ExtruderStack instances during addContainer.
  333. # The stacks are now responsible for setting the next stack on deserialize. However,
  334. # due to problems with loading order, some stacks may not have the proper next stack
  335. # set after upgrading, because the proper global stack was not yet loaded. This method
  336. # makes sure those extruders also get the right stack set.
  337. def _fixupExtruders(self):
  338. extruder_stacks = self.findContainers(ExtruderStack.ExtruderStack)
  339. for extruder_stack in extruder_stacks:
  340. if extruder_stack.getNextStack():
  341. # Has the right next stack, so ignore it.
  342. continue
  343. machines = ContainerRegistry.getInstance().findContainerStacks(id=extruder_stack.getMetaDataEntry("machine", ""))
  344. if machines:
  345. extruder_stack.setNextStack(machines[0])
  346. else:
  347. Logger.log("w", "Could not find machine {machine} for extruder {extruder}", machine = extruder_stack.getMetaDataEntry("machine"), extruder = extruder_stack.getId())