CuraContainerRegistry.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. # Copyright (c) 2016 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 PyQt5.QtWidgets import QMessageBox
  7. from UM.Decorators import override
  8. from UM.Settings.ContainerRegistry import ContainerRegistry
  9. from UM.Settings.ContainerStack import ContainerStack
  10. from UM.Settings.InstanceContainer import InstanceContainer
  11. from UM.Application import Application
  12. from UM.Logger import Logger
  13. from UM.Message import Message
  14. from UM.Platform import Platform
  15. from UM.PluginRegistry import PluginRegistry #For getting the possible profile writers to write with.
  16. from UM.Util import parseBool
  17. from . import ExtruderStack
  18. from . import GlobalStack
  19. from UM.i18n import i18nCatalog
  20. catalog = i18nCatalog("cura")
  21. class CuraContainerRegistry(ContainerRegistry):
  22. def __init__(self, *args, **kwargs):
  23. super().__init__(*args, **kwargs)
  24. ## Overridden from ContainerRegistry
  25. @override(ContainerRegistry)
  26. def addContainer(self, container):
  27. # Note: Intentional check with type() because we want to ignore subclasses
  28. if type(container) == ContainerStack:
  29. container = self._convertContainerStack(container)
  30. super().addContainer(container)
  31. ## Create a name that is not empty and unique
  32. # \param container_type \type{string} Type of the container (machine, quality, ...)
  33. # \param current_name \type{} Current name of the container, which may be an acceptable option
  34. # \param new_name \type{string} Base name, which may not be unique
  35. # \param fallback_name \type{string} Name to use when (stripped) new_name is empty
  36. # \return \type{string} Name that is unique for the specified type and name/id
  37. def createUniqueName(self, container_type, current_name, new_name, fallback_name):
  38. new_name = new_name.strip()
  39. num_check = re.compile("(.*?)\s*#\d+$").match(new_name)
  40. if num_check:
  41. new_name = num_check.group(1)
  42. if new_name == "":
  43. new_name = fallback_name
  44. unique_name = new_name
  45. i = 1
  46. # In case we are renaming, the current name of the container is also a valid end-result
  47. while self._containerExists(container_type, unique_name) and unique_name != current_name:
  48. i += 1
  49. unique_name = "%s #%d" % (new_name, i)
  50. return unique_name
  51. ## Check if a container with of a certain type and a certain name or id exists
  52. # Both the id and the name are checked, because they may not be the same and it is better if they are both unique
  53. # \param container_type \type{string} Type of the container (machine, quality, ...)
  54. # \param container_name \type{string} Name to check
  55. def _containerExists(self, container_type, container_name):
  56. container_class = ContainerStack if container_type == "machine" else InstanceContainer
  57. return self.findContainers(container_class, id = container_name, type = container_type, ignore_case = True) or \
  58. self.findContainers(container_class, name = container_name, type = container_type)
  59. ## Exports an profile to a file
  60. #
  61. # \param instance_ids \type{list} the IDs of the profiles to export.
  62. # \param file_name \type{str} the full path and filename to export to.
  63. # \param file_type \type{str} the file type with the format "<description> (*.<extension>)"
  64. def exportProfile(self, instance_ids, file_name, file_type):
  65. # Parse the fileType to deduce what plugin can save the file format.
  66. # fileType has the format "<description> (*.<extension>)"
  67. split = file_type.rfind(" (*.") # Find where the description ends and the extension starts.
  68. if split < 0: # Not found. Invalid format.
  69. Logger.log("e", "Invalid file format identifier %s", file_type)
  70. return
  71. description = file_type[:split]
  72. extension = file_type[split + 4:-1] # Leave out the " (*." and ")".
  73. if not file_name.endswith("." + extension): # Auto-fill the extension if the user did not provide any.
  74. file_name += "." + extension
  75. # On Windows, QML FileDialog properly asks for overwrite confirm, but not on other platforms, so handle those ourself.
  76. if not Platform.isWindows():
  77. if os.path.exists(file_name):
  78. result = QMessageBox.question(None, catalog.i18nc("@title:window", "File Already Exists"),
  79. catalog.i18nc("@label", "The file <filename>{0}</filename> already exists. Are you sure you want to overwrite it?").format(file_name))
  80. if result == QMessageBox.No:
  81. return
  82. found_containers = []
  83. extruder_positions = []
  84. for instance_id in instance_ids:
  85. containers = ContainerRegistry.getInstance().findInstanceContainers(id=instance_id)
  86. if containers:
  87. found_containers.append(containers[0])
  88. # Determine the position of the extruder of this container
  89. extruder_id = containers[0].getMetaDataEntry("extruder", "")
  90. if extruder_id == "":
  91. # Global stack
  92. extruder_positions.append(-1)
  93. else:
  94. extruder_containers = ContainerRegistry.getInstance().findDefinitionContainers(id=extruder_id)
  95. if extruder_containers:
  96. extruder_positions.append(int(extruder_containers[0].getMetaDataEntry("position", 0)))
  97. else:
  98. extruder_positions.append(0)
  99. # Ensure the profiles are always exported in order (global, extruder 0, extruder 1, ...)
  100. found_containers = [containers for (positions, containers) in sorted(zip(extruder_positions, found_containers))]
  101. profile_writer = self._findProfileWriter(extension, description)
  102. try:
  103. success = profile_writer.write(file_name, found_containers)
  104. except Exception as e:
  105. Logger.log("e", "Failed to export profile to %s: %s", file_name, str(e))
  106. m = Message(catalog.i18nc("@info:status", "Failed to export profile to <filename>{0}</filename>: <message>{1}</message>", file_name, str(e)), lifetime = 0)
  107. m.show()
  108. return
  109. if not success:
  110. Logger.log("w", "Failed to export profile to %s: Writer plugin reported failure.", file_name)
  111. m = Message(catalog.i18nc("@info:status", "Failed to export profile to <filename>{0}</filename>: Writer plugin reported failure.", file_name), lifetime = 0)
  112. m.show()
  113. return
  114. m = Message(catalog.i18nc("@info:status", "Exported profile to <filename>{0}</filename>", file_name))
  115. m.show()
  116. ## Gets the plugin object matching the criteria
  117. # \param extension
  118. # \param description
  119. # \return The plugin object matching the given extension and description.
  120. def _findProfileWriter(self, extension, description):
  121. plugin_registry = PluginRegistry.getInstance()
  122. for plugin_id, meta_data in self._getIOPlugins("profile_writer"):
  123. for supported_type in meta_data["profile_writer"]: # All file types this plugin can supposedly write.
  124. supported_extension = supported_type.get("extension", None)
  125. if supported_extension == extension: # This plugin supports a file type with the same extension.
  126. supported_description = supported_type.get("description", None)
  127. if supported_description == description: # The description is also identical. Assume it's the same file type.
  128. return plugin_registry.getPluginObject(plugin_id)
  129. return None
  130. ## Imports a profile from a file
  131. #
  132. # \param file_name \type{str} the full path and filename of the profile to import
  133. # \return \type{Dict} dict with a 'status' key containing the string 'ok' or 'error', and a 'message' key
  134. # containing a message for the user
  135. def importProfile(self, file_name):
  136. Logger.log("d", "Attempting to import profile %s", file_name)
  137. if not file_name:
  138. return { "status": "error", "message": catalog.i18nc("@info:status", "Failed to import profile from <filename>{0}</filename>: <message>{1}</message>", file_name, "Invalid path")}
  139. plugin_registry = PluginRegistry.getInstance()
  140. extension = file_name.split(".")[-1]
  141. global_container_stack = Application.getInstance().getGlobalContainerStack()
  142. if not global_container_stack:
  143. return
  144. machine_extruders = list(ExtruderManager.getInstance().getMachineExtruders(global_container_stack.getId()))
  145. machine_extruders.sort(key = lambda k: k.getMetaDataEntry("position"))
  146. for plugin_id, meta_data in self._getIOPlugins("profile_reader"):
  147. if meta_data["profile_reader"][0]["extension"] != extension:
  148. continue
  149. profile_reader = plugin_registry.getPluginObject(plugin_id)
  150. try:
  151. profile_or_list = profile_reader.read(file_name) # Try to open the file with the profile reader.
  152. except Exception as e:
  153. # 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.
  154. Logger.log("e", "Failed to import profile from %s: %s while using profile reader. Got exception %s", file_name,profile_reader.getPluginId(), str(e))
  155. return { "status": "error", "message": catalog.i18nc("@info:status", "Failed to import profile from <filename>{0}</filename>: <message>{1}</message>", file_name, str(e))}
  156. if profile_or_list: # Success!
  157. name_seed = os.path.splitext(os.path.basename(file_name))[0]
  158. new_name = self.uniqueName(name_seed)
  159. if type(profile_or_list) is not list:
  160. profile = profile_or_list
  161. self._configureProfile(profile, name_seed, new_name)
  162. return { "status": "ok", "message": catalog.i18nc("@info:status", "Successfully imported profile {0}", profile.getName()) }
  163. else:
  164. profile_index = -1
  165. global_profile = None
  166. for profile in profile_or_list:
  167. if profile_index >= 0:
  168. if len(machine_extruders) > profile_index:
  169. extruder_id = Application.getInstance().getMachineManager().getQualityDefinitionId(machine_extruders[profile_index].getBottom())
  170. # Ensure the extruder profiles get non-conflicting names
  171. # NB: these are not user-facing
  172. if "extruder" in profile.getMetaData():
  173. profile.setMetaDataEntry("extruder", extruder_id)
  174. else:
  175. profile.addMetaDataEntry("extruder", extruder_id)
  176. profile_id = (extruder_id + "_" + name_seed).lower().replace(" ", "_")
  177. elif profile_index == 0:
  178. # Importing a multiextrusion profile into a single extrusion machine; merge 1st extruder profile into global profile
  179. profile._id = self.uniqueName("temporary_profile")
  180. self.addContainer(profile)
  181. ContainerManager.getInstance().mergeContainers(global_profile.getId(), profile.getId())
  182. self.removeContainer(profile.getId())
  183. break
  184. else:
  185. # The imported composite profile has a profile for an extruder that this machine does not have. Ignore this extruder-profile
  186. break
  187. else:
  188. global_profile = profile
  189. profile_id = (global_container_stack.getBottom().getId() + "_" + name_seed).lower().replace(" ", "_")
  190. self._configureProfile(profile, profile_id, new_name)
  191. profile_index += 1
  192. return {"status": "ok", "message": catalog.i18nc("@info:status", "Successfully imported profile {0}", profile_or_list[0].getName())}
  193. # If it hasn't returned by now, none of the plugins loaded the profile successfully.
  194. return {"status": "error", "message": catalog.i18nc("@info:status", "Profile {0} has an unknown file type or is corrupted.", file_name)}
  195. def _configureProfile(self, profile, id_seed, new_name):
  196. profile.setReadOnly(False)
  197. profile.setDirty(True) # Ensure the profiles are correctly saved
  198. new_id = self.createUniqueName("quality_changes", "", id_seed, catalog.i18nc("@label", "Custom profile"))
  199. profile._id = new_id
  200. profile.setName(new_name)
  201. if "type" in profile.getMetaData():
  202. profile.setMetaDataEntry("type", "quality_changes")
  203. else:
  204. profile.addMetaDataEntry("type", "quality_changes")
  205. if self._machineHasOwnQualities():
  206. profile.setDefinition(self._activeQualityDefinition())
  207. if self._machineHasOwnMaterials():
  208. profile.addMetaDataEntry("material", self._activeMaterialId())
  209. else:
  210. profile.setDefinition(ContainerRegistry.getInstance().findDefinitionContainers(id="fdmprinter")[0])
  211. ContainerRegistry.getInstance().addContainer(profile)
  212. ## Gets a list of profile writer plugins
  213. # \return List of tuples of (plugin_id, meta_data).
  214. def _getIOPlugins(self, io_type):
  215. plugin_registry = PluginRegistry.getInstance()
  216. active_plugin_ids = plugin_registry.getActivePlugins()
  217. result = []
  218. for plugin_id in active_plugin_ids:
  219. meta_data = plugin_registry.getMetaData(plugin_id)
  220. if io_type in meta_data:
  221. result.append( (plugin_id, meta_data) )
  222. return result
  223. ## Get the definition to use to select quality profiles for the active machine
  224. # \return the active quality definition object or None if there is no quality definition
  225. def _activeQualityDefinition(self):
  226. global_container_stack = Application.getInstance().getGlobalContainerStack()
  227. if global_container_stack:
  228. definition_id = Application.getInstance().getMachineManager().getQualityDefinitionId(global_container_stack.getBottom())
  229. definition = self.findDefinitionContainers(id=definition_id)[0]
  230. if definition:
  231. return definition
  232. return None
  233. ## Returns true if the current machine requires its own materials
  234. # \return True if the current machine requires its own materials
  235. def _machineHasOwnMaterials(self):
  236. global_container_stack = Application.getInstance().getGlobalContainerStack()
  237. if global_container_stack:
  238. return global_container_stack.getMetaDataEntry("has_materials", False)
  239. return False
  240. ## Gets the ID of the active material
  241. # \return the ID of the active material or the empty string
  242. def _activeMaterialId(self):
  243. global_container_stack = Application.getInstance().getGlobalContainerStack()
  244. if global_container_stack:
  245. material = global_container_stack.findContainer({"type": "material"})
  246. if material:
  247. return material.getId()
  248. return ""
  249. ## Returns true if the current machien requires its own quality profiles
  250. # \return true if the current machien requires its own quality profiles
  251. def _machineHasOwnQualities(self):
  252. global_container_stack = Application.getInstance().getGlobalContainerStack()
  253. if global_container_stack:
  254. return parseBool(global_container_stack.getMetaDataEntry("has_machine_quality", False))
  255. return False
  256. def _convertContainerStack(self, container):
  257. assert type(container) == ContainerStack
  258. container_type = container.getMetaDataEntry("type")
  259. if container_type not in ("extruder_train", "machine"):
  260. # It is not an extruder or machine, so do nothing with the stack
  261. return container
  262. new_stack = None
  263. if container_type == "extruder_train":
  264. new_stack = ExtruderStack.ExtruderStack(container.getId())
  265. else:
  266. new_stack = GlobalStack.GlobalStack(container.getId())
  267. container_contents = container.serialize()
  268. new_stack.deserialize(container_contents)
  269. # Delete the old configuration file so we do not get double stacks
  270. if os.path.isfile(container.getPath()):
  271. os.remove(container.getPath())
  272. return new_stack