QualityManagementModel.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. from cura.Settings.IntentManager import IntentManager
  13. from cura.Machines.Models.MachineModelUtils import fetchLayerHeight
  14. from UM.i18n import i18nCatalog
  15. catalog = i18nCatalog("cura")
  16. if TYPE_CHECKING:
  17. from UM.Settings.Interfaces import ContainerInterface
  18. from cura.Machines.QualityChangesGroup import QualityChangesGroup
  19. from cura.Settings.ExtruderStack import ExtruderStack
  20. from cura.Settings.GlobalStack import GlobalStack
  21. #
  22. # This the QML model for the quality management page.
  23. #
  24. class QualityManagementModel(ListModel):
  25. NameRole = Qt.UserRole + 1
  26. IsReadOnlyRole = Qt.UserRole + 2
  27. QualityGroupRole = Qt.UserRole + 3
  28. QualityTypeRole = Qt.UserRole + 4
  29. QualityChangesGroupRole = Qt.UserRole + 5
  30. IntentCategoryRole = Qt.UserRole + 6
  31. SectionNameRole = Qt.UserRole + 7
  32. def __init__(self, parent: Optional["QObject"] = None) -> None:
  33. super().__init__(parent)
  34. self.addRoleName(self.NameRole, "name")
  35. self.addRoleName(self.IsReadOnlyRole, "is_read_only")
  36. self.addRoleName(self.QualityGroupRole, "quality_group")
  37. self.addRoleName(self.QualityTypeRole, "quality_type")
  38. self.addRoleName(self.QualityChangesGroupRole, "quality_changes_group")
  39. self.addRoleName(self.IntentCategoryRole, "intent_category")
  40. self.addRoleName(self.SectionNameRole, "section_name")
  41. application = cura.CuraApplication.CuraApplication.getInstance()
  42. container_registry = application.getContainerRegistry()
  43. self._machine_manager = application.getMachineManager()
  44. self._extruder_manager = application.getExtruderManager()
  45. self._machine_manager.globalContainerChanged.connect(self._update)
  46. container_registry.containerAdded.connect(self._qualityChangesListChanged)
  47. container_registry.containerRemoved.connect(self._qualityChangesListChanged)
  48. container_registry.containerMetaDataChanged.connect(self._qualityChangesListChanged)
  49. self._update()
  50. ## Deletes a custom profile. It will be gone forever.
  51. # \param quality_changes_group The quality changes group representing the
  52. # profile to delete.
  53. @pyqtSlot(QObject)
  54. def removeQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup") -> None:
  55. Logger.log("i", "Removing quality changes group {group_name}".format(group_name = quality_changes_group.name))
  56. removed_quality_changes_ids = set()
  57. container_registry = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry()
  58. for metadata in [quality_changes_group.metadata_for_global] + list(quality_changes_group.metadata_per_extruder.values()):
  59. container_id = metadata["id"]
  60. container_registry.removeContainer(container_id)
  61. removed_quality_changes_ids.add(container_id)
  62. # Reset all machines that have activated this custom profile.
  63. for global_stack in container_registry.findContainerStacks(type = "machine"):
  64. if global_stack.qualityChanges.getId() in removed_quality_changes_ids:
  65. global_stack.qualityChanges = empty_quality_changes_container
  66. for extruder_stack in container_registry.findContainerStacks(type = "extruder_train"):
  67. if extruder_stack.qualityChanges.getId() in removed_quality_changes_ids:
  68. extruder_stack.qualityChanges = empty_quality_changes_container
  69. ## Rename a custom profile.
  70. #
  71. # Because the names must be unique, the new name may not actually become
  72. # the name that was given. The actual name is returned by this function.
  73. # \param quality_changes_group The custom profile that must be renamed.
  74. # \param new_name The desired name for the profile.
  75. # \return The actual new name of the profile, after making the name
  76. # unique.
  77. @pyqtSlot(QObject, str, result = str)
  78. def renameQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup", new_name: str) -> str:
  79. Logger.log("i", "Renaming QualityChangesGroup {old_name} to {new_name}.".format(old_name = quality_changes_group.name, new_name = new_name))
  80. if new_name == quality_changes_group.name:
  81. Logger.log("i", "QualityChangesGroup name {name} unchanged.".format(name = quality_changes_group.name))
  82. return new_name
  83. application = cura.CuraApplication.CuraApplication.getInstance()
  84. container_registry = application.getContainerRegistry()
  85. new_name = container_registry.uniqueName(new_name)
  86. # CURA-6842
  87. # FIXME: setName() will trigger metaDataChanged signal that are connected with type Qt.AutoConnection. In this
  88. # case, setName() will trigger direct connections which in turn causes the quality changes group and the models
  89. # to update. Because multiple containers need to be renamed, and every time a container gets renamed, updates
  90. # gets triggered and this results in partial updates. For example, if we rename the global quality changes
  91. # container first, the rest of the system still thinks that I have selected "my_profile" instead of
  92. # "my_new_profile", but an update already gets triggered, and the quality changes group that's selected will
  93. # have no container for the global stack, because "my_profile" just got renamed to "my_new_profile". This results
  94. # in crashes because the rest of the system assumes that all data in a QualityChangesGroup will be correct.
  95. #
  96. # Renaming the container for the global stack in the end seems to be ok, because the assumption is mostly based
  97. # on the quality changes container for the global stack.
  98. for metadata in quality_changes_group.metadata_per_extruder.values():
  99. extruder_container = cast(InstanceContainer, container_registry.findContainers(id = metadata["id"])[0])
  100. extruder_container.setName(new_name)
  101. global_container = cast(InstanceContainer, container_registry.findContainers(id=quality_changes_group.metadata_for_global["id"])[0])
  102. global_container.setName(new_name)
  103. quality_changes_group.name = new_name
  104. application.getMachineManager().activeQualityChanged.emit()
  105. application.getMachineManager().activeQualityGroupChanged.emit()
  106. return new_name
  107. ## Duplicates a given quality profile OR quality changes profile.
  108. # \param new_name The desired name of the new profile. This will be made
  109. # unique, so it might end up with a different name.
  110. # \param quality_model_item The item of this model to duplicate, as
  111. # dictionary. See the descriptions of the roles of this list model.
  112. @pyqtSlot(str, "QVariantMap")
  113. def duplicateQualityChanges(self, new_name: str, quality_model_item: Dict[str, Any]) -> None:
  114. global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  115. if not global_stack:
  116. Logger.log("i", "No active global stack, cannot duplicate quality (changes) profile.")
  117. return
  118. container_registry = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry()
  119. new_name = container_registry.uniqueName(new_name)
  120. intent_category = quality_model_item["intent_category"]
  121. quality_group = quality_model_item["quality_group"]
  122. quality_changes_group = quality_model_item["quality_changes_group"]
  123. if quality_changes_group is None:
  124. # Create global quality changes only.
  125. new_quality_changes = self._createQualityChanges(quality_group.quality_type, intent_category, new_name,
  126. global_stack, extruder_stack = None)
  127. container_registry.addContainer(new_quality_changes)
  128. else:
  129. for metadata in [quality_changes_group.metadata_for_global] + list(quality_changes_group.metadata_per_extruder.values()):
  130. containers = container_registry.findContainers(id = metadata["id"])
  131. if not containers:
  132. continue
  133. container = containers[0]
  134. new_id = container_registry.uniqueName(container.getId())
  135. container_registry.addContainer(container.duplicate(new_id, new_name))
  136. ## Create quality changes containers from the user containers in the active
  137. # stacks.
  138. #
  139. # This will go through the global and extruder stacks and create
  140. # quality_changes containers from the user containers in each stack. These
  141. # then replace the quality_changes containers in the stack and clear the
  142. # user settings.
  143. # \param base_name The new name for the quality changes profile. The final
  144. # name of the profile might be different from this, because it needs to be
  145. # made unique.
  146. @pyqtSlot(str)
  147. def createQualityChanges(self, base_name: str) -> None:
  148. machine_manager = cura.CuraApplication.CuraApplication.getInstance().getMachineManager()
  149. global_stack = machine_manager.activeMachine
  150. if not global_stack:
  151. return
  152. active_quality_name = machine_manager.activeQualityOrQualityChangesName
  153. if active_quality_name == "":
  154. Logger.log("w", "No quality container found in stack %s, cannot create profile", global_stack.getId())
  155. return
  156. machine_manager.blurSettings.emit()
  157. if base_name is None or base_name == "":
  158. base_name = active_quality_name
  159. container_registry = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry()
  160. unique_name = container_registry.uniqueName(base_name)
  161. # Go through the active stacks and create quality_changes containers from the user containers.
  162. container_manager = ContainerManager.getInstance()
  163. stack_list = [global_stack] + list(global_stack.extruders.values())
  164. for stack in stack_list:
  165. quality_container = stack.quality
  166. quality_changes_container = stack.qualityChanges
  167. if not quality_container or not quality_changes_container:
  168. Logger.log("w", "No quality or quality changes container found in stack %s, ignoring it", stack.getId())
  169. continue
  170. extruder_stack = None
  171. intent_category = None
  172. if stack.getMetaDataEntry("position") is not None:
  173. extruder_stack = stack
  174. intent_category = stack.intent.getMetaDataEntry("intent_category")
  175. new_changes = self._createQualityChanges(quality_container.getMetaDataEntry("quality_type"), intent_category, unique_name, global_stack, extruder_stack)
  176. container_manager._performMerge(new_changes, quality_changes_container, clear_settings = False)
  177. container_manager._performMerge(new_changes, stack.userChanges)
  178. container_registry.addContainer(new_changes)
  179. ## Create a quality changes container with the given set-up.
  180. # \param quality_type The quality type of the new container.
  181. # \param intent_category The intent category of the new container.
  182. # \param new_name The name of the container. This name must be unique.
  183. # \param machine The global stack to create the profile for.
  184. # \param extruder_stack The extruder stack to create the profile for. If
  185. # not provided, only a global container will be created.
  186. def _createQualityChanges(self, quality_type: str, intent_category: Optional[str], new_name: str, machine: "GlobalStack", extruder_stack: Optional["ExtruderStack"]) -> "InstanceContainer":
  187. container_registry = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry()
  188. base_id = machine.definition.getId() if extruder_stack is None else extruder_stack.getId()
  189. new_id = base_id + "_" + new_name
  190. new_id = new_id.lower().replace(" ", "_")
  191. new_id = container_registry.uniqueName(new_id)
  192. # Create a new quality_changes container for the quality.
  193. quality_changes = InstanceContainer(new_id)
  194. quality_changes.setName(new_name)
  195. quality_changes.setMetaDataEntry("type", "quality_changes")
  196. quality_changes.setMetaDataEntry("quality_type", quality_type)
  197. if intent_category is not None:
  198. quality_changes.setMetaDataEntry("intent_category", intent_category)
  199. # If we are creating a container for an extruder, ensure we add that to the container.
  200. if extruder_stack is not None:
  201. quality_changes.setMetaDataEntry("position", extruder_stack.getMetaDataEntry("position"))
  202. # If the machine specifies qualities should be filtered, ensure we match the current criteria.
  203. machine_definition_id = ContainerTree.getInstance().machines[machine.definition.getId()].quality_definition
  204. quality_changes.setDefinition(machine_definition_id)
  205. quality_changes.setMetaDataEntry("setting_version", cura.CuraApplication.CuraApplication.getInstance().SettingVersion)
  206. return quality_changes
  207. ## Triggered when any container changed.
  208. #
  209. # This filters the updates to the container manager: When it applies to
  210. # the list of quality changes, we need to update our list.
  211. def _qualityChangesListChanged(self, container: "ContainerInterface") -> None:
  212. if container.getMetaDataEntry("type") == "quality_changes":
  213. self._update()
  214. @pyqtSlot("QVariantMap", result = str)
  215. def getQualityItemDisplayName(self, quality_model_item: Dict[str, Any]) -> str:
  216. quality_group = quality_model_item["quality_group"]
  217. is_read_only = quality_model_item["is_read_only"]
  218. intent_category = quality_model_item["intent_category"]
  219. quality_level_name = "Not Supported"
  220. if quality_group is not None:
  221. quality_level_name = quality_group.name
  222. display_name = quality_level_name
  223. if intent_category != "default":
  224. intent_display_name = catalog.i18nc("@label", intent_category.capitalize())
  225. display_name = "{intent_name} - {the_rest}".format(intent_name = intent_display_name,
  226. the_rest = display_name)
  227. # A custom quality
  228. if not is_read_only:
  229. display_name = "{custom_profile_name} - {the_rest}".format(custom_profile_name = quality_model_item["name"],
  230. the_rest = display_name)
  231. return display_name
  232. def _update(self):
  233. Logger.log("d", "Updating {model_class_name}.".format(model_class_name = self.__class__.__name__))
  234. global_stack = self._machine_manager.activeMachine
  235. if not global_stack:
  236. self.setItems([])
  237. return
  238. container_tree = ContainerTree.getInstance()
  239. quality_group_dict = container_tree.getCurrentQualityGroups()
  240. quality_changes_group_list = container_tree.getCurrentQualityChangesGroups()
  241. available_quality_types = set(quality_type for quality_type, quality_group in quality_group_dict.items()
  242. if quality_group.is_available)
  243. if not available_quality_types and not quality_changes_group_list:
  244. # Nothing to show
  245. self.setItems([])
  246. return
  247. item_list = []
  248. # Create quality group items (intent category = "default")
  249. for quality_group in quality_group_dict.values():
  250. if not quality_group.is_available:
  251. continue
  252. layer_height = fetchLayerHeight(quality_group)
  253. item = {"name": quality_group.name,
  254. "is_read_only": True,
  255. "quality_group": quality_group,
  256. "quality_type": quality_group.quality_type,
  257. "quality_changes_group": None,
  258. "intent_category": "default",
  259. "section_name": catalog.i18nc("@label", "Default"),
  260. "layer_height": layer_height, # layer_height is only used for sorting
  261. }
  262. item_list.append(item)
  263. # Sort by layer_height for built-in qualities
  264. item_list = sorted(item_list, key = lambda x: x["layer_height"])
  265. # Create intent items (non-default)
  266. available_intent_list = IntentManager.getInstance().getCurrentAvailableIntents()
  267. available_intent_list = [i for i in available_intent_list if i[0] != "default"]
  268. result = []
  269. for intent_category, quality_type in available_intent_list:
  270. result.append({
  271. "name": quality_group_dict[quality_type].name, # Use the quality name as the display name
  272. "is_read_only": True,
  273. "quality_group": quality_group_dict[quality_type],
  274. "quality_type": quality_type,
  275. "quality_changes_group": None,
  276. "intent_category": intent_category,
  277. "section_name": catalog.i18nc("@label", intent_category.capitalize()),
  278. })
  279. # Sort by quality_type for each intent category
  280. result = sorted(result, key = lambda x: (x["intent_category"], x["quality_type"]))
  281. item_list += result
  282. # Create quality_changes group items
  283. quality_changes_item_list = []
  284. for quality_changes_group in quality_changes_group_list:
  285. quality_group = quality_group_dict.get(quality_changes_group.quality_type)
  286. item = {"name": quality_changes_group.name,
  287. "is_read_only": False,
  288. "quality_group": quality_group,
  289. "quality_type": quality_group.quality_type,
  290. "quality_changes_group": quality_changes_group,
  291. "intent_category": quality_changes_group.intent_category,
  292. "section_name": catalog.i18nc("@label", "Custom profiles"),
  293. }
  294. quality_changes_item_list.append(item)
  295. # Sort quality_changes items by names and append to the item list
  296. quality_changes_item_list = sorted(quality_changes_item_list, key = lambda x: x["name"].upper())
  297. item_list += quality_changes_item_list
  298. self.setItems(item_list)
  299. # TODO: Duplicated code here from InstanceContainersModel. Refactor and remove this later.
  300. #
  301. ## Gets a list of the possible file filters that the plugins have
  302. # registered they can read or write. The convenience meta-filters
  303. # "All Supported Types" and "All Files" are added when listing
  304. # readers, but not when listing writers.
  305. #
  306. # \param io_type \type{str} name of the needed IO type
  307. # \return A list of strings indicating file name filters for a file
  308. # dialog.
  309. @pyqtSlot(str, result = "QVariantList")
  310. def getFileNameFilters(self, io_type):
  311. from UM.i18n import i18nCatalog
  312. catalog = i18nCatalog("uranium")
  313. #TODO: This function should be in UM.Resources!
  314. filters = []
  315. all_types = []
  316. for plugin_id, meta_data in self._getIOPlugins(io_type):
  317. for io_plugin in meta_data[io_type]:
  318. filters.append(io_plugin["description"] + " (*." + io_plugin["extension"] + ")")
  319. all_types.append("*.{0}".format(io_plugin["extension"]))
  320. if "_reader" in io_type:
  321. # if we're listing readers, add the option to show all supported files as the default option
  322. filters.insert(0, catalog.i18nc("@item:inlistbox", "All Supported Types ({0})", " ".join(all_types)))
  323. filters.append(catalog.i18nc("@item:inlistbox", "All Files (*)")) # Also allow arbitrary files, if the user so prefers.
  324. return filters
  325. ## Gets a list of profile reader or writer plugins
  326. # \return List of tuples of (plugin_id, meta_data).
  327. def _getIOPlugins(self, io_type):
  328. from UM.PluginRegistry import PluginRegistry
  329. pr = PluginRegistry.getInstance()
  330. active_plugin_ids = pr.getActivePlugins()
  331. result = []
  332. for plugin_id in active_plugin_ids:
  333. meta_data = pr.getMetaData(plugin_id)
  334. if io_type in meta_data:
  335. result.append( (plugin_id, meta_data) )
  336. return result