QualityManagementModel.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from typing import Any, cast, Dict, Optional, TYPE_CHECKING
  4. from PyQt5.QtCore import pyqtSlot, QObject, Qt
  5. from UM.Logger import Logger
  6. from UM.Qt.ListModel import ListModel
  7. from UM.Settings.InstanceContainer import InstanceContainer # To create new profiles.
  8. import cura.CuraApplication # Imported this way to prevent circular imports.
  9. from cura.Settings.ContainerManager import ContainerManager
  10. from cura.Machines.ContainerTree import ContainerTree
  11. from cura.Settings.cura_empty_instance_containers import empty_quality_changes_container
  12. if TYPE_CHECKING:
  13. from UM.Settings.Interfaces import ContainerInterface
  14. from cura.Machines.QualityChangesGroup import QualityChangesGroup
  15. from cura.Settings.ExtruderStack import ExtruderStack
  16. from cura.Settings.GlobalStack import GlobalStack
  17. #
  18. # This the QML model for the quality management page.
  19. #
  20. class QualityManagementModel(ListModel):
  21. NameRole = Qt.UserRole + 1
  22. IsReadOnlyRole = Qt.UserRole + 2
  23. QualityGroupRole = Qt.UserRole + 3
  24. QualityChangesGroupRole = Qt.UserRole + 4
  25. def __init__(self, parent = None):
  26. super().__init__(parent)
  27. self.addRoleName(self.NameRole, "name")
  28. self.addRoleName(self.IsReadOnlyRole, "is_read_only")
  29. self.addRoleName(self.QualityGroupRole, "quality_group")
  30. self.addRoleName(self.QualityChangesGroupRole, "quality_changes_group")
  31. application = cura.CuraApplication.CuraApplication.getInstance()
  32. container_registry = application.getContainerRegistry()
  33. self._machine_manager = application.getMachineManager()
  34. self._extruder_manager = application.getExtruderManager()
  35. self._machine_manager.globalContainerChanged.connect(self._update)
  36. container_registry.containerAdded.connect(self._qualityChangesListChanged)
  37. container_registry.containerRemoved.connect(self._qualityChangesListChanged)
  38. container_registry.containerMetaDataChanged.connect(self._qualityChangesListChanged)
  39. self._update()
  40. ## Deletes a custom profile. It will be gone forever.
  41. # \param quality_changes_group The quality changes group representing the
  42. # profile to delete.
  43. @pyqtSlot(QObject)
  44. def removeQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup") -> None:
  45. Logger.log("i", "Removing quality changes group {group_name}".format(group_name = quality_changes_group.name))
  46. removed_quality_changes_ids = set()
  47. container_registry = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry()
  48. for metadata in [quality_changes_group.metadata_for_global] + list(quality_changes_group.metadata_per_extruder.values()):
  49. container_id = metadata["id"]
  50. container_registry.removeContainer(container_id)
  51. removed_quality_changes_ids.add(container_id)
  52. # Reset all machines that have activated this custom profile.
  53. for global_stack in container_registry.findContainerStacks(type = "machine"):
  54. if global_stack.qualityChanges.getId() in removed_quality_changes_ids:
  55. global_stack.qualityChanges = empty_quality_changes_container
  56. for extruder_stack in container_registry.findContainerStacks(type = "extruder_train"):
  57. if extruder_stack.qualityChanges.getId() in removed_quality_changes_ids:
  58. extruder_stack.qualityChanges = empty_quality_changes_container
  59. ## Rename a custom profile.
  60. #
  61. # Because the names must be unique, the new name may not actually become
  62. # the name that was given. The actual name is returned by this function.
  63. # \param quality_changes_group The custom profile that must be renamed.
  64. # \param new_name The desired name for the profile.
  65. # \return The actual new name of the profile, after making the name
  66. # unique.
  67. @pyqtSlot(QObject, str, result = str)
  68. def renameQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup", new_name: str) -> str:
  69. Logger.log("i", "Renaming QualityChangesGroup {old_name} to {new_name}.".format(old_name = quality_changes_group.name, new_name = new_name))
  70. if new_name == quality_changes_group.name:
  71. Logger.log("i", "QualityChangesGroup name {name} unchanged.".format(name = quality_changes_group.name))
  72. return new_name
  73. application = cura.CuraApplication.CuraApplication.getInstance()
  74. container_registry = application.getContainerRegistry()
  75. new_name = container_registry.uniqueName(new_name)
  76. global_container = cast(InstanceContainer, container_registry.findContainers(id = quality_changes_group.metadata_for_global["id"])[0])
  77. global_container.setName(new_name)
  78. for metadata in quality_changes_group.metadata_per_extruder.values():
  79. extruder_container = cast(InstanceContainer, container_registry.findContainers(id = metadata["id"])[0])
  80. extruder_container.setName(new_name)
  81. quality_changes_group.name = new_name
  82. application.getMachineManager().activeQualityChanged.emit()
  83. application.getMachineManager().activeQualityGroupChanged.emit()
  84. return new_name
  85. ## Duplicates a given quality profile OR quality changes profile.
  86. # \param new_name The desired name of the new profile. This will be made
  87. # unique, so it might end up with a different name.
  88. # \param quality_model_item The item of this model to duplicate, as
  89. # dictionary. See the descriptions of the roles of this list model.
  90. @pyqtSlot(str, "QVariantMap")
  91. def duplicateQualityChanges(self, new_name: str, quality_model_item: Dict[str, Any]) -> None:
  92. global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  93. if not global_stack:
  94. Logger.log("i", "No active global stack, cannot duplicate quality (changes) profile.")
  95. return
  96. container_registry = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry()
  97. new_name = container_registry.uniqueName(new_name)
  98. quality_group = quality_model_item["quality_group"]
  99. quality_changes_group = quality_model_item["quality_changes_group"]
  100. if quality_changes_group is None:
  101. # Create global quality changes only.
  102. new_quality_changes = self._createQualityChanges(quality_group.quality_type, None, new_name, global_stack, extruder_stack = None)
  103. container_registry.addContainer(new_quality_changes)
  104. else:
  105. for metadata in [quality_changes_group.metadata_for_global] + list(quality_changes_group.metadata_per_extruder.values()):
  106. containers = container_registry.findContainers(id = metadata["id"])
  107. if not containers:
  108. continue
  109. container = containers[0]
  110. new_id = container_registry.uniqueName(container.getId())
  111. container_registry.addContainer(container.duplicate(new_id, new_name))
  112. ## Create quality changes containers from the user containers in the active
  113. # stacks.
  114. #
  115. # This will go through the global and extruder stacks and create
  116. # quality_changes containers from the user containers in each stack. These
  117. # then replace the quality_changes containers in the stack and clear the
  118. # user settings.
  119. # \param base_name The new name for the quality changes profile. The final
  120. # name of the profile might be different from this, because it needs to be
  121. # made unique.
  122. @pyqtSlot(str)
  123. def createQualityChanges(self, base_name: str) -> None:
  124. machine_manager = cura.CuraApplication.CuraApplication.getInstance().getMachineManager()
  125. global_stack = machine_manager.activeMachine
  126. if not global_stack:
  127. return
  128. active_quality_name = machine_manager.activeQualityOrQualityChangesName
  129. if active_quality_name == "":
  130. Logger.log("w", "No quality container found in stack %s, cannot create profile", global_stack.getId())
  131. return
  132. machine_manager.blurSettings.emit()
  133. if base_name is None or base_name == "":
  134. base_name = active_quality_name
  135. container_registry = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry()
  136. unique_name = container_registry.uniqueName(base_name)
  137. # Go through the active stacks and create quality_changes containers from the user containers.
  138. container_manager = ContainerManager.getInstance()
  139. stack_list = [global_stack] + list(global_stack.extruders.values())
  140. for stack in stack_list:
  141. quality_container = stack.quality
  142. quality_changes_container = stack.qualityChanges
  143. if not quality_container or not quality_changes_container:
  144. Logger.log("w", "No quality or quality changes container found in stack %s, ignoring it", stack.getId())
  145. continue
  146. extruder_stack = None
  147. intent_category = None
  148. if stack.getMetaDataEntry("position") is not None:
  149. extruder_stack = stack
  150. intent_category = stack.intent.getMetaDataEntry("intent_category")
  151. new_changes = self._createQualityChanges(quality_container.getMetaDataEntry("quality_type"), intent_category, unique_name, global_stack, extruder_stack)
  152. container_manager._performMerge(new_changes, quality_changes_container, clear_settings = False)
  153. container_manager._performMerge(new_changes, stack.userChanges)
  154. container_registry.addContainer(new_changes)
  155. ## Create a quality changes container with the given set-up.
  156. # \param quality_type The quality type of the new container.
  157. # \param intent_category The intent category of the new container.
  158. # \param new_name The name of the container. This name must be unique.
  159. # \param machine The global stack to create the profile for.
  160. # \param extruder_stack The extruder stack to create the profile for. If
  161. # not provided, only a global container will be created.
  162. def _createQualityChanges(self, quality_type: str, intent_category: Optional[str], new_name: str, machine: "GlobalStack", extruder_stack: Optional["ExtruderStack"]) -> "InstanceContainer":
  163. container_registry = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry()
  164. base_id = machine.definition.getId() if extruder_stack is None else extruder_stack.getId()
  165. new_id = base_id + "_" + new_name
  166. new_id = new_id.lower().replace(" ", "_")
  167. new_id = container_registry.uniqueName(new_id)
  168. # Create a new quality_changes container for the quality.
  169. quality_changes = InstanceContainer(new_id)
  170. quality_changes.setName(new_name)
  171. quality_changes.setMetaDataEntry("type", "quality_changes")
  172. quality_changes.setMetaDataEntry("quality_type", quality_type)
  173. if intent_category is not None:
  174. quality_changes.setMetaDataEntry("intent_category", intent_category)
  175. # If we are creating a container for an extruder, ensure we add that to the container.
  176. if extruder_stack is not None:
  177. quality_changes.setMetaDataEntry("position", extruder_stack.getMetaDataEntry("position"))
  178. # If the machine specifies qualities should be filtered, ensure we match the current criteria.
  179. machine_definition_id = ContainerTree.getInstance().machines[machine.definition.getId()].quality_definition
  180. quality_changes.setDefinition(machine_definition_id)
  181. quality_changes.setMetaDataEntry("setting_version", cura.CuraApplication.CuraApplication.getInstance().SettingVersion)
  182. return quality_changes
  183. ## Triggered when any container changed.
  184. #
  185. # This filters the updates to the container manager: When it applies to
  186. # the list of quality changes, we need to update our list.
  187. def _qualityChangesListChanged(self, container: "ContainerInterface") -> None:
  188. if container.getMetaDataEntry("type") == "quality_changes":
  189. self._update()
  190. def _update(self):
  191. Logger.log("d", "Updating {model_class_name}.".format(model_class_name = self.__class__.__name__))
  192. global_stack = self._machine_manager.activeMachine
  193. if not global_stack:
  194. self.setItems([])
  195. return
  196. container_tree = ContainerTree.getInstance()
  197. quality_group_dict = container_tree.getCurrentQualityGroups()
  198. quality_changes_group_list = container_tree.getCurrentQualityChangesGroups()
  199. available_quality_types = set(quality_type for quality_type, quality_group in quality_group_dict.items()
  200. if quality_group.is_available)
  201. if not available_quality_types and not quality_changes_group_list:
  202. # Nothing to show
  203. self.setItems([])
  204. return
  205. item_list = []
  206. # Create quality group items
  207. for quality_group in quality_group_dict.values():
  208. if not quality_group.is_available:
  209. continue
  210. item = {"name": quality_group.name,
  211. "is_read_only": True,
  212. "quality_group": quality_group,
  213. "quality_changes_group": None}
  214. item_list.append(item)
  215. # Sort by quality names
  216. item_list = sorted(item_list, key = lambda x: x["name"].upper())
  217. # Create quality_changes group items
  218. quality_changes_item_list = []
  219. for quality_changes_group in quality_changes_group_list:
  220. quality_group = quality_group_dict.get(quality_changes_group.quality_type)
  221. item = {"name": quality_changes_group.name,
  222. "is_read_only": False,
  223. "quality_group": quality_group,
  224. "quality_changes_group": quality_changes_group}
  225. quality_changes_item_list.append(item)
  226. # Sort quality_changes items by names and append to the item list
  227. quality_changes_item_list = sorted(quality_changes_item_list, key = lambda x: x["name"].upper())
  228. item_list += quality_changes_item_list
  229. self.setItems(item_list)
  230. # TODO: Duplicated code here from InstanceContainersModel. Refactor and remove this later.
  231. #
  232. ## Gets a list of the possible file filters that the plugins have
  233. # registered they can read or write. The convenience meta-filters
  234. # "All Supported Types" and "All Files" are added when listing
  235. # readers, but not when listing writers.
  236. #
  237. # \param io_type \type{str} name of the needed IO type
  238. # \return A list of strings indicating file name filters for a file
  239. # dialog.
  240. @pyqtSlot(str, result = "QVariantList")
  241. def getFileNameFilters(self, io_type):
  242. from UM.i18n import i18nCatalog
  243. catalog = i18nCatalog("uranium")
  244. #TODO: This function should be in UM.Resources!
  245. filters = []
  246. all_types = []
  247. for plugin_id, meta_data in self._getIOPlugins(io_type):
  248. for io_plugin in meta_data[io_type]:
  249. filters.append(io_plugin["description"] + " (*." + io_plugin["extension"] + ")")
  250. all_types.append("*.{0}".format(io_plugin["extension"]))
  251. if "_reader" in io_type:
  252. # if we're listing readers, add the option to show all supported files as the default option
  253. filters.insert(0, catalog.i18nc("@item:inlistbox", "All Supported Types ({0})", " ".join(all_types)))
  254. filters.append(catalog.i18nc("@item:inlistbox", "All Files (*)")) # Also allow arbitrary files, if the user so prefers.
  255. return filters
  256. ## Gets a list of profile reader or writer plugins
  257. # \return List of tuples of (plugin_id, meta_data).
  258. def _getIOPlugins(self, io_type):
  259. from UM.PluginRegistry import PluginRegistry
  260. pr = PluginRegistry.getInstance()
  261. active_plugin_ids = pr.getActivePlugins()
  262. result = []
  263. for plugin_id in active_plugin_ids:
  264. meta_data = pr.getMetaData(plugin_id)
  265. if io_type in meta_data:
  266. result.append( (plugin_id, meta_data) )
  267. return result