CuraContainerRegistry.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. # Copyright (c) 2017 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 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", "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", "Failed to export profile to <filename>{0}</filename>: <message>{1}</message>", file_name, str(e)), lifetime = 0)
  123. m.show()
  124. return
  125. if not success:
  126. Logger.log("w", "Failed to export profile to %s: Writer plugin reported failure.", file_name)
  127. m = Message(catalog.i18nc("@info:status", "Failed to export profile to <filename>{0}</filename>: Writer plugin reported failure.", file_name), lifetime = 0)
  128. m.show()
  129. return
  130. m = Message(catalog.i18nc("@info:status", "Exported profile to <filename>{0}</filename>", file_name))
  131. m.show()
  132. ## Gets the plugin object matching the criteria
  133. # \param extension
  134. # \param description
  135. # \return The plugin object matching the given extension and description.
  136. def _findProfileWriter(self, extension, description):
  137. plugin_registry = PluginRegistry.getInstance()
  138. for plugin_id, meta_data in self._getIOPlugins("profile_writer"):
  139. for supported_type in meta_data["profile_writer"]: # All file types this plugin can supposedly write.
  140. supported_extension = supported_type.get("extension", None)
  141. if supported_extension == extension: # This plugin supports a file type with the same extension.
  142. supported_description = supported_type.get("description", None)
  143. if supported_description == description: # The description is also identical. Assume it's the same file type.
  144. return plugin_registry.getPluginObject(plugin_id)
  145. return None
  146. ## Imports a profile from a file
  147. #
  148. # \param file_name \type{str} the full path and filename of the profile to import
  149. # \return \type{Dict} dict with a 'status' key containing the string 'ok' or 'error', and a 'message' key
  150. # containing a message for the user
  151. def importProfile(self, file_name):
  152. Logger.log("d", "Attempting to import profile %s", file_name)
  153. if not file_name:
  154. return { "status": "error", "message": catalog.i18nc("@info:status", "Failed to import profile from <filename>{0}</filename>: <message>{1}</message>", file_name, "Invalid path")}
  155. plugin_registry = PluginRegistry.getInstance()
  156. extension = file_name.split(".")[-1]
  157. global_container_stack = Application.getInstance().getGlobalContainerStack()
  158. if not global_container_stack:
  159. return
  160. machine_extruders = list(ExtruderManager.getInstance().getMachineExtruders(global_container_stack.getId()))
  161. machine_extruders.sort(key = lambda k: k.getMetaDataEntry("position"))
  162. for plugin_id, meta_data in self._getIOPlugins("profile_reader"):
  163. if meta_data["profile_reader"][0]["extension"] != extension:
  164. continue
  165. profile_reader = plugin_registry.getPluginObject(plugin_id)
  166. try:
  167. profile_or_list = profile_reader.read(file_name) # Try to open the file with the profile reader.
  168. except Exception as e:
  169. # 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.
  170. Logger.log("e", "Failed to import profile from %s: %s while using profile reader. Got exception %s", file_name,profile_reader.getPluginId(), str(e))
  171. return { "status": "error", "message": catalog.i18nc("@info:status", "Failed to import profile from <filename>{0}</filename>: <message>{1}</message>", file_name, str(e))}
  172. if profile_or_list: # Success!
  173. name_seed = os.path.splitext(os.path.basename(file_name))[0]
  174. new_name = self.uniqueName(name_seed)
  175. if type(profile_or_list) is not list:
  176. profile = profile_or_list
  177. result = self._configureProfile(profile, name_seed, new_name)
  178. if result is not None:
  179. return {"status": "error", "message": catalog.i18nc("@info:status", "Failed to import profile from <filename>{0}</filename>: <message>{1}</message>", file_name, result)}
  180. return {"status": "ok", "message": catalog.i18nc("@info:status", "Successfully imported profile {0}", profile.getName())}
  181. else:
  182. profile_index = -1
  183. global_profile = None
  184. for profile in profile_or_list:
  185. if profile_index >= 0:
  186. if len(machine_extruders) > profile_index:
  187. extruder_id = Application.getInstance().getMachineManager().getQualityDefinitionId(machine_extruders[profile_index].getBottom())
  188. # Ensure the extruder profiles get non-conflicting names
  189. # NB: these are not user-facing
  190. if "extruder" in profile.getMetaData():
  191. profile.setMetaDataEntry("extruder", extruder_id)
  192. else:
  193. profile.addMetaDataEntry("extruder", extruder_id)
  194. profile_id = (extruder_id + "_" + name_seed).lower().replace(" ", "_")
  195. elif profile_index == 0:
  196. # Importing a multiextrusion profile into a single extrusion machine; merge 1st extruder profile into global profile
  197. profile._id = self.uniqueName("temporary_profile")
  198. self.addContainer(profile)
  199. ContainerManager.getInstance().mergeContainers(global_profile.getId(), profile.getId())
  200. self.removeContainer(profile.getId())
  201. break
  202. else:
  203. # The imported composite profile has a profile for an extruder that this machine does not have. Ignore this extruder-profile
  204. break
  205. else:
  206. global_profile = profile
  207. profile_id = (global_container_stack.getBottom().getId() + "_" + name_seed).lower().replace(" ", "_")
  208. result = self._configureProfile(profile, profile_id, new_name)
  209. if result is not None:
  210. return {"status": "error", "message": catalog.i18nc("@info:status", "Failed to import profile from <filename>{0}</filename>: <message>{1}</message>", file_name, result)}
  211. profile_index += 1
  212. return {"status": "ok", "message": catalog.i18nc("@info:status", "Successfully imported profile {0}", profile_or_list[0].getName())}
  213. # If it hasn't returned by now, none of the plugins loaded the profile successfully.
  214. return {"status": "error", "message": catalog.i18nc("@info:status", "Profile {0} has an unknown file type or is corrupted.", file_name)}
  215. @override(ContainerRegistry)
  216. def load(self):
  217. super().load()
  218. self._fixupExtruders()
  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.setReadOnly(False)
  228. profile.setDirty(True) # Ensure the profiles are correctly saved
  229. new_id = self.createUniqueName("quality_changes", "", id_seed, catalog.i18nc("@label", "Custom profile"))
  230. profile._id = new_id
  231. profile.setName(new_name)
  232. if "type" in profile.getMetaData():
  233. profile.setMetaDataEntry("type", "quality_changes")
  234. else:
  235. profile.addMetaDataEntry("type", "quality_changes")
  236. quality_type = profile.getMetaDataEntry("quality_type")
  237. if not quality_type:
  238. return catalog.i18nc("@info:status", "Profile is missing a quality type.")
  239. quality_type_criteria = {"quality_type": quality_type}
  240. if self._machineHasOwnQualities():
  241. profile.setDefinition(self._activeQualityDefinition())
  242. if self._machineHasOwnMaterials():
  243. active_material_id = self._activeMaterialId()
  244. if active_material_id and active_material_id != "empty": # only update if there is an active material
  245. profile.addMetaDataEntry("material", active_material_id)
  246. quality_type_criteria["material"] = active_material_id
  247. quality_type_criteria["definition"] = profile.getDefinition().getId()
  248. else:
  249. profile.setDefinition(ContainerRegistry.getInstance().findDefinitionContainers(id="fdmprinter")[0])
  250. quality_type_criteria["definition"] = "fdmprinter"
  251. machine_definition = Application.getInstance().getGlobalContainerStack().getBottom()
  252. del quality_type_criteria["definition"]
  253. materials = None
  254. if "material" in quality_type_criteria:
  255. materials = ContainerRegistry.getInstance().findInstanceContainers(id = quality_type_criteria["material"])
  256. del quality_type_criteria["material"]
  257. # Check to make sure the imported profile actually makes sense in context of the current configuration.
  258. # This prevents issues where importing a "draft" profile for a machine without "draft" qualities would report as
  259. # successfully imported but then fail to show up.
  260. from cura.QualityManager import QualityManager
  261. qualities = QualityManager.getInstance()._getFilteredContainersForStack(machine_definition, materials, **quality_type_criteria)
  262. if not qualities:
  263. return catalog.i18nc("@info:status", "Could not find a quality type {0} for the current configuration.", quality_type)
  264. ContainerRegistry.getInstance().addContainer(profile)
  265. return None
  266. ## Gets a list of profile writer plugins
  267. # \return List of tuples of (plugin_id, meta_data).
  268. def _getIOPlugins(self, io_type):
  269. plugin_registry = PluginRegistry.getInstance()
  270. active_plugin_ids = plugin_registry.getActivePlugins()
  271. result = []
  272. for plugin_id in active_plugin_ids:
  273. meta_data = plugin_registry.getMetaData(plugin_id)
  274. if io_type in meta_data:
  275. result.append( (plugin_id, meta_data) )
  276. return result
  277. ## Get the definition to use to select quality profiles for the active machine
  278. # \return the active quality definition object or None if there is no quality definition
  279. def _activeQualityDefinition(self):
  280. global_container_stack = Application.getInstance().getGlobalContainerStack()
  281. if global_container_stack:
  282. definition_id = Application.getInstance().getMachineManager().getQualityDefinitionId(global_container_stack.getBottom())
  283. definition = self.findDefinitionContainers(id=definition_id)[0]
  284. if definition:
  285. return definition
  286. return None
  287. ## Returns true if the current machine requires its own materials
  288. # \return True if the current machine requires its own materials
  289. def _machineHasOwnMaterials(self):
  290. global_container_stack = Application.getInstance().getGlobalContainerStack()
  291. if global_container_stack:
  292. return global_container_stack.getMetaDataEntry("has_materials", False)
  293. return False
  294. ## Gets the ID of the active material
  295. # \return the ID of the active material or the empty string
  296. def _activeMaterialId(self):
  297. global_container_stack = Application.getInstance().getGlobalContainerStack()
  298. if global_container_stack and global_container_stack.material:
  299. return global_container_stack.material.getId()
  300. return ""
  301. ## Returns true if the current machien requires its own quality profiles
  302. # \return true if the current machien requires its own quality profiles
  303. def _machineHasOwnQualities(self):
  304. global_container_stack = Application.getInstance().getGlobalContainerStack()
  305. if global_container_stack:
  306. return parseBool(global_container_stack.getMetaDataEntry("has_machine_quality", False))
  307. return False
  308. ## Convert an "old-style" pure ContainerStack to either an Extruder or Global stack.
  309. def _convertContainerStack(self, container):
  310. assert type(container) == ContainerStack
  311. container_type = container.getMetaDataEntry("type")
  312. if container_type not in ("extruder_train", "machine"):
  313. # It is not an extruder or machine, so do nothing with the stack
  314. return container
  315. Logger.log("d", "Converting ContainerStack {stack} to {type}", stack = container.getId(), type = container_type)
  316. new_stack = None
  317. if container_type == "extruder_train":
  318. new_stack = ExtruderStack.ExtruderStack(container.getId())
  319. else:
  320. new_stack = GlobalStack.GlobalStack(container.getId())
  321. container_contents = container.serialize()
  322. new_stack.deserialize(container_contents)
  323. # Delete the old configuration file so we do not get double stacks
  324. if os.path.isfile(container.getPath()):
  325. os.remove(container.getPath())
  326. return new_stack
  327. # Fix the extruders that were upgraded to ExtruderStack instances during addContainer.
  328. # The stacks are now responsible for setting the next stack on deserialize. However,
  329. # due to problems with loading order, some stacks may not have the proper next stack
  330. # set after upgrading, because the proper global stack was not yet loaded. This method
  331. # makes sure those extruders also get the right stack set.
  332. def _fixupExtruders(self):
  333. extruder_stacks = self.findContainers(ExtruderStack.ExtruderStack)
  334. for extruder_stack in extruder_stacks:
  335. if extruder_stack.getNextStack():
  336. # Has the right next stack, so ignore it.
  337. continue
  338. machines = ContainerRegistry.getInstance().findContainerStacks(id=extruder_stack.getMetaDataEntry("machine", ""))
  339. if machines:
  340. extruder_stack.setNextStack(machines[0])
  341. else:
  342. Logger.log("w", "Could not find machine {machine} for extruder {extruder}", machine = extruder_stack.getMetaDataEntry("machine"), extruder = extruder_stack.getId())