CuraContainerRegistry.py 16 KB

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