QualityManager.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from typing import TYPE_CHECKING, Optional
  4. from PyQt5.QtCore import QObject, QTimer, pyqtSignal, pyqtSlot
  5. from UM.Application import Application
  6. from UM.ConfigurationErrorMessage import ConfigurationErrorMessage
  7. from UM.Logger import Logger
  8. from UM.Util import parseBool
  9. from UM.Settings.InstanceContainer import InstanceContainer
  10. from cura.Settings.ExtruderStack import ExtruderStack
  11. from .QualityGroup import QualityGroup
  12. from .QualityNode import QualityNode
  13. if TYPE_CHECKING:
  14. from UM.Settings.DefinitionContainer import DefinitionContainer
  15. from cura.Settings.GlobalStack import GlobalStack
  16. from .QualityChangesGroup import QualityChangesGroup
  17. #
  18. # Similar to MaterialManager, QualityManager maintains a number of maps and trees for quality profile lookup.
  19. # The models GUI and QML use are now only dependent on the QualityManager. That means as long as the data in
  20. # QualityManager gets updated correctly, the GUI models should be updated correctly too, and the same goes for GUI.
  21. #
  22. # For now, updating the lookup maps and trees here is very simple: we discard the old data completely and recreate them
  23. # again. This means the update is exactly the same as initialization. There are performance concerns about this approach
  24. # but so far the creation of the tables and maps is very fast and there is no noticeable slowness, we keep it like this
  25. # because it's simple.
  26. #
  27. class QualityManager(QObject):
  28. qualitiesUpdated = pyqtSignal()
  29. def __init__(self, container_registry, parent = None):
  30. super().__init__(parent)
  31. self._application = Application.getInstance()
  32. self._material_manager = self._application.getMaterialManager()
  33. self._container_registry = container_registry
  34. self._empty_quality_container = self._application.empty_quality_container
  35. self._empty_quality_changes_container = self._application.empty_quality_changes_container
  36. self._machine_variant_material_quality_type_to_quality_dict = {} # for quality lookup
  37. self._machine_quality_type_to_quality_changes_dict = {} # for quality_changes lookup
  38. self._default_machine_definition_id = "fdmprinter"
  39. self._container_registry.containerMetaDataChanged.connect(self._onContainerMetadataChanged)
  40. self._container_registry.containerAdded.connect(self._onContainerMetadataChanged)
  41. self._container_registry.containerRemoved.connect(self._onContainerMetadataChanged)
  42. # When a custom quality gets added/imported, there can be more than one InstanceContainers. In those cases,
  43. # we don't want to react on every container/metadata changed signal. The timer here is to buffer it a bit so
  44. # we don't react too many time.
  45. self._update_timer = QTimer(self)
  46. self._update_timer.setInterval(300)
  47. self._update_timer.setSingleShot(True)
  48. self._update_timer.timeout.connect(self._updateMaps)
  49. def initialize(self):
  50. # Initialize the lookup tree for quality profiles with following structure:
  51. # <machine> -> <variant> -> <material>
  52. # -> <material>
  53. self._machine_variant_material_quality_type_to_quality_dict = {} # for quality lookup
  54. self._machine_quality_type_to_quality_changes_dict = {} # for quality_changes lookup
  55. quality_metadata_list = self._container_registry.findContainersMetadata(type = "quality")
  56. for metadata in quality_metadata_list:
  57. if metadata["id"] == "empty_quality":
  58. continue
  59. definition_id = metadata["definition"]
  60. quality_type = metadata["quality_type"]
  61. root_material_id = metadata.get("material")
  62. variant_name = metadata.get("variant")
  63. is_global_quality = metadata.get("global_quality", False)
  64. is_global_quality = is_global_quality or (root_material_id is None and variant_name is None)
  65. # Sanity check: material+variant and is_global_quality cannot be present at the same time
  66. if is_global_quality and (root_material_id or variant_name):
  67. ConfigurationErrorMessage.getInstance().addFaultyContainers(metadata["id"])
  68. continue
  69. if definition_id not in self._machine_variant_material_quality_type_to_quality_dict:
  70. self._machine_variant_material_quality_type_to_quality_dict[definition_id] = QualityNode()
  71. machine_node = self._machine_variant_material_quality_type_to_quality_dict[definition_id]
  72. if is_global_quality:
  73. # For global qualities, save data in the machine node
  74. machine_node.addQualityMetadata(quality_type, metadata)
  75. continue
  76. if variant_name is not None:
  77. # If variant_name is specified in the quality/quality_changes profile, check if material is specified,
  78. # too.
  79. if variant_name not in machine_node.children_map:
  80. machine_node.children_map[variant_name] = QualityNode()
  81. variant_node = machine_node.children_map[variant_name]
  82. if root_material_id is None:
  83. # If only variant_name is specified but material is not, add the quality/quality_changes metadata
  84. # into the current variant node.
  85. variant_node.addQualityMetadata(quality_type, metadata)
  86. else:
  87. # If only variant_name and material are both specified, go one level deeper: create a material node
  88. # under the current variant node, and then add the quality/quality_changes metadata into the
  89. # material node.
  90. if root_material_id not in variant_node.children_map:
  91. variant_node.children_map[root_material_id] = QualityNode()
  92. material_node = variant_node.children_map[root_material_id]
  93. material_node.addQualityMetadata(quality_type, metadata)
  94. else:
  95. # If variant_name is not specified, check if material is specified.
  96. if root_material_id is not None:
  97. if root_material_id not in machine_node.children_map:
  98. machine_node.children_map[root_material_id] = QualityNode()
  99. material_node = machine_node.children_map[root_material_id]
  100. material_node.addQualityMetadata(quality_type, metadata)
  101. # Initialize the lookup tree for quality_changes profiles with following structure:
  102. # <machine> -> <quality_type> -> <name>
  103. quality_changes_metadata_list = self._container_registry.findContainersMetadata(type = "quality_changes")
  104. for metadata in quality_changes_metadata_list:
  105. if metadata["id"] == "empty_quality_changes":
  106. continue
  107. machine_definition_id = metadata["definition"]
  108. quality_type = metadata["quality_type"]
  109. if machine_definition_id not in self._machine_quality_type_to_quality_changes_dict:
  110. self._machine_quality_type_to_quality_changes_dict[machine_definition_id] = QualityNode()
  111. machine_node = self._machine_quality_type_to_quality_changes_dict[machine_definition_id]
  112. machine_node.addQualityChangesMetadata(quality_type, metadata)
  113. Logger.log("d", "Lookup tables updated.")
  114. self.qualitiesUpdated.emit()
  115. def _updateMaps(self):
  116. self.initialize()
  117. def _onContainerMetadataChanged(self, container):
  118. self._onContainerChanged(container)
  119. def _onContainerChanged(self, container):
  120. container_type = container.getMetaDataEntry("type")
  121. if container_type not in ("quality", "quality_changes"):
  122. return
  123. # update the cache table
  124. self._update_timer.start()
  125. # Updates the given quality groups' availabilities according to which extruders are being used/ enabled.
  126. def _updateQualityGroupsAvailability(self, machine: "GlobalStack", quality_group_list):
  127. used_extruders = set()
  128. for i in range(machine.getProperty("machine_extruder_count", "value")):
  129. if str(i) in machine.extruders and machine.extruders[str(i)].isEnabled:
  130. used_extruders.add(str(i))
  131. # Update the "is_available" flag for each quality group.
  132. for quality_group in quality_group_list:
  133. is_available = True
  134. if quality_group.node_for_global is None:
  135. is_available = False
  136. if is_available:
  137. for position in used_extruders:
  138. if position not in quality_group.nodes_for_extruders:
  139. is_available = False
  140. break
  141. quality_group.is_available = is_available
  142. # Returns a dict of "custom profile name" -> QualityChangesGroup
  143. def getQualityChangesGroups(self, machine: "GlobalStack") -> dict:
  144. machine_definition_id = getMachineDefinitionIDForQualitySearch(machine.definition)
  145. machine_node = self._machine_quality_type_to_quality_changes_dict.get(machine_definition_id)
  146. if not machine_node:
  147. Logger.log("i", "Cannot find node for machine def [%s] in QualityChanges lookup table", machine_definition_id)
  148. return dict()
  149. # Update availability for each QualityChangesGroup:
  150. # A custom profile is always available as long as the quality_type it's based on is available
  151. quality_group_dict = self.getQualityGroups(machine)
  152. available_quality_type_list = [qt for qt, qg in quality_group_dict.items() if qg.is_available]
  153. # Iterate over all quality_types in the machine node
  154. quality_changes_group_dict = dict()
  155. for quality_type, quality_changes_node in machine_node.quality_type_map.items():
  156. for quality_changes_name, quality_changes_group in quality_changes_node.children_map.items():
  157. quality_changes_group_dict[quality_changes_name] = quality_changes_group
  158. quality_changes_group.is_available = quality_type in available_quality_type_list
  159. return quality_changes_group_dict
  160. #
  161. # Gets all quality groups for the given machine. Both available and none available ones will be included.
  162. # It returns a dictionary with "quality_type"s as keys and "QualityGroup"s as values.
  163. # Whether a QualityGroup is available can be unknown via the field QualityGroup.is_available.
  164. # For more details, see QualityGroup.
  165. #
  166. def getQualityGroups(self, machine: "GlobalStack") -> dict:
  167. machine_definition_id = getMachineDefinitionIDForQualitySearch(machine.definition)
  168. # This determines if we should only get the global qualities for the global stack and skip the global qualities for the extruder stacks
  169. has_variant_materials = parseBool(machine.getMetaDataEntry("has_variant_materials", False))
  170. # To find the quality container for the GlobalStack, check in the following fall-back manner:
  171. # (1) the machine-specific node
  172. # (2) the generic node
  173. machine_node = self._machine_variant_material_quality_type_to_quality_dict.get(machine_definition_id)
  174. default_machine_node = self._machine_variant_material_quality_type_to_quality_dict.get(self._default_machine_definition_id)
  175. nodes_to_check = [machine_node, default_machine_node]
  176. # Iterate over all quality_types in the machine node
  177. quality_group_dict = {}
  178. for node in nodes_to_check:
  179. if node and node.quality_type_map:
  180. # Only include global qualities
  181. if has_variant_materials:
  182. quality_node = list(node.quality_type_map.values())[0]
  183. is_global_quality = parseBool(quality_node.metadata.get("global_quality", False))
  184. if not is_global_quality:
  185. continue
  186. for quality_type, quality_node in node.quality_type_map.items():
  187. quality_group = QualityGroup(quality_node.metadata["name"], quality_type)
  188. quality_group.node_for_global = quality_node
  189. quality_group_dict[quality_type] = quality_group
  190. break
  191. # Iterate over all extruders to find quality containers for each extruder
  192. for position, extruder in machine.extruders.items():
  193. variant_name = None
  194. if extruder.variant.getId() != "empty_variant":
  195. variant_name = extruder.variant.getName()
  196. # This is a list of root material IDs to use for searching for suitable quality profiles.
  197. # The root material IDs in this list are in prioritized order.
  198. root_material_id_list = []
  199. has_material = False # flag indicating whether this extruder has a material assigned
  200. if extruder.material.getId() != "empty_material":
  201. has_material = True
  202. root_material_id = extruder.material.getMetaDataEntry("base_file")
  203. # Convert possible generic_pla_175 -> generic_pla
  204. root_material_id = self._material_manager.getRootMaterialIDWithoutDiameter(root_material_id)
  205. root_material_id_list.append(root_material_id)
  206. # Also try to get the fallback material
  207. material_type = extruder.material.getMetaDataEntry("material")
  208. fallback_root_material_id = self._material_manager.getFallbackMaterialIdByMaterialType(material_type)
  209. if fallback_root_material_id:
  210. root_material_id_list.append(fallback_root_material_id)
  211. # Here we construct a list of nodes we want to look for qualities with the highest priority first.
  212. # The use case is that, when we look for qualities for a machine, we first want to search in the following
  213. # order:
  214. # 1. machine-variant-and-material-specific qualities if exist
  215. # 2. machine-variant-specific qualities if exist
  216. # 3. machine-material-specific qualities if exist
  217. # 4. machine-specific qualities if exist
  218. # 5. generic qualities if exist
  219. # Each points above can be represented as a node in the lookup tree, so here we simply put those nodes into
  220. # the list with priorities as the order. Later, we just need to loop over each node in this list and fetch
  221. # qualities from there.
  222. nodes_to_check = []
  223. if variant_name:
  224. # In this case, we have both a specific variant and a specific material
  225. variant_node = machine_node.getChildNode(variant_name)
  226. if variant_node and has_material:
  227. for root_material_id in root_material_id_list:
  228. material_node = variant_node.getChildNode(root_material_id)
  229. if material_node:
  230. nodes_to_check.append(material_node)
  231. break
  232. nodes_to_check.append(variant_node)
  233. # In this case, we only have a specific material but NOT a variant
  234. if has_material:
  235. for root_material_id in root_material_id_list:
  236. material_node = machine_node.getChildNode(root_material_id)
  237. if material_node:
  238. nodes_to_check.append(material_node)
  239. break
  240. nodes_to_check += [machine_node, default_machine_node]
  241. for node in nodes_to_check:
  242. if node and node.quality_type_map:
  243. if has_variant_materials:
  244. # Only include variant qualities; skip non global qualities
  245. quality_node = list(node.quality_type_map.values())[0]
  246. is_global_quality = parseBool(quality_node.metadata.get("global_quality", False))
  247. if is_global_quality:
  248. continue
  249. for quality_type, quality_node in node.quality_type_map.items():
  250. if quality_type not in quality_group_dict:
  251. quality_group = QualityGroup(quality_node.metadata["name"], quality_type)
  252. quality_group_dict[quality_type] = quality_group
  253. quality_group = quality_group_dict[quality_type]
  254. quality_group.nodes_for_extruders[position] = quality_node
  255. break
  256. # Update availabilities for each quality group
  257. self._updateQualityGroupsAvailability(machine, quality_group_dict.values())
  258. return quality_group_dict
  259. def getQualityGroupsForMachineDefinition(self, machine: "GlobalStack") -> dict:
  260. machine_definition_id = getMachineDefinitionIDForQualitySearch(machine.definition)
  261. # To find the quality container for the GlobalStack, check in the following fall-back manner:
  262. # (1) the machine-specific node
  263. # (2) the generic node
  264. machine_node = self._machine_variant_material_quality_type_to_quality_dict.get(machine_definition_id)
  265. default_machine_node = self._machine_variant_material_quality_type_to_quality_dict.get(
  266. self._default_machine_definition_id)
  267. nodes_to_check = [machine_node, default_machine_node]
  268. # Iterate over all quality_types in the machine node
  269. quality_group_dict = dict()
  270. for node in nodes_to_check:
  271. if node and node.quality_type_map:
  272. for quality_type, quality_node in node.quality_type_map.items():
  273. quality_group = QualityGroup(quality_node.metadata["name"], quality_type)
  274. quality_group.node_for_global = quality_node
  275. quality_group_dict[quality_type] = quality_group
  276. break
  277. return quality_group_dict
  278. #
  279. # Methods for GUI
  280. #
  281. #
  282. # Remove the given quality changes group.
  283. #
  284. @pyqtSlot(QObject)
  285. def removeQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup"):
  286. Logger.log("i", "Removing quality changes group [%s]", quality_changes_group.name)
  287. for node in quality_changes_group.getAllNodes():
  288. self._container_registry.removeContainer(node.metadata["id"])
  289. #
  290. # Rename a set of quality changes containers. Returns the new name.
  291. #
  292. @pyqtSlot(QObject, str, result = str)
  293. def renameQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup", new_name: str) -> str:
  294. Logger.log("i", "Renaming QualityChangesGroup[%s] to [%s]", quality_changes_group.name, new_name)
  295. if new_name == quality_changes_group.name:
  296. Logger.log("i", "QualityChangesGroup name [%s] unchanged.", quality_changes_group.name)
  297. return new_name
  298. new_name = self._container_registry.uniqueName(new_name)
  299. for node in quality_changes_group.getAllNodes():
  300. node.getContainer().setName(new_name)
  301. quality_changes_group.name = new_name
  302. self._application.getMachineManager().activeQualityChanged.emit()
  303. self._application.getMachineManager().activeQualityGroupChanged.emit()
  304. return new_name
  305. #
  306. # Duplicates the given quality.
  307. #
  308. @pyqtSlot(str, "QVariantMap")
  309. def duplicateQualityChanges(self, quality_changes_name, quality_model_item):
  310. global_stack = self._application.getGlobalContainerStack()
  311. if not global_stack:
  312. Logger.log("i", "No active global stack, cannot duplicate quality changes.")
  313. return
  314. quality_group = quality_model_item["quality_group"]
  315. quality_changes_group = quality_model_item["quality_changes_group"]
  316. if quality_changes_group is None:
  317. # create global quality changes only
  318. new_quality_changes = self._createQualityChanges(quality_group.quality_type, quality_changes_name,
  319. global_stack, None)
  320. self._container_registry.addContainer(new_quality_changes)
  321. else:
  322. new_name = self._container_registry.uniqueName(quality_changes_name)
  323. for node in quality_changes_group.getAllNodes():
  324. container = node.getContainer()
  325. if not container:
  326. continue
  327. new_id = self._container_registry.uniqueName(container.getId())
  328. self._container_registry.addContainer(container.duplicate(new_id, new_name))
  329. ## Create quality changes containers from the user containers in the active stacks.
  330. #
  331. # This will go through the global and extruder stacks and create quality_changes containers from
  332. # the user containers in each stack. These then replace the quality_changes containers in the
  333. # stack and clear the user settings.
  334. @pyqtSlot(str)
  335. def createQualityChanges(self, base_name):
  336. machine_manager = Application.getInstance().getMachineManager()
  337. global_stack = machine_manager.activeMachine
  338. if not global_stack:
  339. return
  340. active_quality_name = machine_manager.activeQualityOrQualityChangesName
  341. if active_quality_name == "":
  342. Logger.log("w", "No quality container found in stack %s, cannot create profile", global_stack.getId())
  343. return
  344. machine_manager.blurSettings.emit()
  345. if base_name is None or base_name == "":
  346. base_name = active_quality_name
  347. unique_name = self._container_registry.uniqueName(base_name)
  348. # Go through the active stacks and create quality_changes containers from the user containers.
  349. stack_list = [global_stack] + list(global_stack.extruders.values())
  350. for stack in stack_list:
  351. user_container = stack.userChanges
  352. quality_container = stack.quality
  353. quality_changes_container = stack.qualityChanges
  354. if not quality_container or not quality_changes_container:
  355. Logger.log("w", "No quality or quality changes container found in stack %s, ignoring it", stack.getId())
  356. continue
  357. quality_type = quality_container.getMetaDataEntry("quality_type")
  358. extruder_stack = None
  359. if isinstance(stack, ExtruderStack):
  360. extruder_stack = stack
  361. new_changes = self._createQualityChanges(quality_type, unique_name, global_stack, extruder_stack)
  362. from cura.Settings.ContainerManager import ContainerManager
  363. ContainerManager.getInstance()._performMerge(new_changes, quality_changes_container, clear_settings = False)
  364. ContainerManager.getInstance()._performMerge(new_changes, user_container)
  365. self._container_registry.addContainer(new_changes)
  366. #
  367. # Create a quality changes container with the given setup.
  368. #
  369. def _createQualityChanges(self, quality_type: str, new_name: str, machine: "GlobalStack",
  370. extruder_stack: Optional["ExtruderStack"]) -> "InstanceContainer":
  371. base_id = machine.definition.getId() if extruder_stack is None else extruder_stack.getId()
  372. new_id = base_id + "_" + new_name
  373. new_id = new_id.lower().replace(" ", "_")
  374. new_id = self._container_registry.uniqueName(new_id)
  375. # Create a new quality_changes container for the quality.
  376. quality_changes = InstanceContainer(new_id)
  377. quality_changes.setName(new_name)
  378. quality_changes.addMetaDataEntry("type", "quality_changes")
  379. quality_changes.addMetaDataEntry("quality_type", quality_type)
  380. # If we are creating a container for an extruder, ensure we add that to the container
  381. if extruder_stack is not None:
  382. quality_changes.addMetaDataEntry("position", extruder_stack.getMetaDataEntry("position"))
  383. # If the machine specifies qualities should be filtered, ensure we match the current criteria.
  384. machine_definition_id = getMachineDefinitionIDForQualitySearch(machine.definition)
  385. quality_changes.setDefinition(machine_definition_id)
  386. quality_changes.addMetaDataEntry("setting_version", self._application.SettingVersion)
  387. return quality_changes
  388. #
  389. # Gets the machine definition ID that can be used to search for Quality containers that are suitable for the given
  390. # machine. The rule is as follows:
  391. # 1. By default, the machine definition ID for quality container search will be "fdmprinter", which is the generic
  392. # machine.
  393. # 2. If a machine has its own machine quality (with "has_machine_quality = True"), we should use the given machine's
  394. # own machine definition ID for quality search.
  395. # Example: for an Ultimaker 3, the definition ID should be "ultimaker3".
  396. # 3. When condition (2) is met, AND the machine has "quality_definition" defined in its definition file, then the
  397. # definition ID specified in "quality_definition" should be used.
  398. # Example: for an Ultimaker 3 Extended, it has "quality_definition = ultimaker3". This means Ultimaker 3 Extended
  399. # shares the same set of qualities profiles as Ultimaker 3.
  400. #
  401. def getMachineDefinitionIDForQualitySearch(machine_definition: "DefinitionContainer",
  402. default_definition_id: str = "fdmprinter") -> str:
  403. machine_definition_id = default_definition_id
  404. if parseBool(machine_definition.getMetaDataEntry("has_machine_quality", False)):
  405. # Only use the machine's own quality definition ID if this machine has machine quality.
  406. machine_definition_id = machine_definition.getMetaDataEntry("quality_definition")
  407. if machine_definition_id is None:
  408. machine_definition_id = machine_definition.getId()
  409. return machine_definition_id