SettingInheritanceManager.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. # Copyright (c) 2017 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from typing import List, Optional, Set, TYPE_CHECKING
  4. from PyQt6.QtCore import QObject, QTimer, pyqtProperty, pyqtSignal
  5. from UM.FlameProfiler import pyqtSlot
  6. from UM.Application import Application
  7. from UM.Logger import Logger
  8. ## The settingInheritance manager is responsible for checking each setting in order to see if one of the "deeper"
  9. # containers has a setting function and the topmost one with a value has a value. We need to have this check
  10. # because some profiles tend to have 'hardcoded' values that break our inheritance. A good example of that are the
  11. # speed settings. If all the children of print_speed have a single value override, changing the speed won't
  12. # actually do anything, as only the 'leaf' settings are used by the engine.
  13. from UM.Settings.ContainerStack import ContainerStack
  14. from UM.Settings.Interfaces import ContainerInterface
  15. from UM.Settings.SettingFunction import SettingFunction
  16. from UM.Settings.SettingInstance import InstanceState
  17. from cura.Settings.ExtruderManager import ExtruderManager
  18. if TYPE_CHECKING:
  19. from cura.Settings.ExtruderStack import ExtruderStack
  20. from UM.Settings.SettingDefinition import SettingDefinition
  21. class SettingInheritanceManager(QObject):
  22. def __init__(self, parent = None) -> None:
  23. super().__init__(parent)
  24. self._global_container_stack = None # type: Optional[ContainerStack]
  25. self._settings_with_inheritance_warning = [] # type: List[str]
  26. self._active_container_stack = None # type: Optional[ExtruderStack]
  27. self._update_timer = QTimer()
  28. self._update_timer.setInterval(500)
  29. self._update_timer.setSingleShot(True)
  30. self._update_timer.timeout.connect(self._update)
  31. Application.getInstance().globalContainerStackChanged.connect(self._onGlobalContainerChanged)
  32. ExtruderManager.getInstance().activeExtruderChanged.connect(self._onActiveExtruderChanged)
  33. self._onGlobalContainerChanged()
  34. self._onActiveExtruderChanged()
  35. settingsWithIntheritanceChanged = pyqtSignal()
  36. @pyqtSlot(str, result = "QStringList")
  37. def getChildrenKeysWithOverride(self, key: str) -> List[str]:
  38. """Get the keys of all children settings with an override."""
  39. if self._global_container_stack is None:
  40. return []
  41. definitions = self._global_container_stack.definition.findDefinitions(key=key)
  42. if not definitions:
  43. Logger.log("w", "Could not find definition for key [%s]", key)
  44. return []
  45. result = []
  46. for key in definitions[0].getAllKeys():
  47. if key in self._settings_with_inheritance_warning:
  48. result.append(key)
  49. return result
  50. @pyqtSlot(str, str, result = bool)
  51. def hasOverrides(self, key: str, extruder_index: str):
  52. return key in self.getOverridesForExtruder(key, extruder_index)
  53. @pyqtSlot(str, str, result = "QStringList")
  54. def getOverridesForExtruder(self, key: str, extruder_index: str) -> List[str]:
  55. if self._global_container_stack is None:
  56. return []
  57. result = [] # type: List[str]
  58. extruder_stack = ExtruderManager.getInstance().getExtruderStack(extruder_index)
  59. if not extruder_stack:
  60. Logger.log("w", "Unable to find extruder for current machine with index %s", extruder_index)
  61. return result
  62. definitions = self._global_container_stack.definition.findDefinitions(key = key)
  63. if not definitions:
  64. Logger.log("w", "Could not find definition for key [%s] (2)", key)
  65. return result
  66. for key in definitions[0].getAllKeys():
  67. if self._settingIsOverwritingInheritance(key, extruder_stack):
  68. result.append(key)
  69. return result
  70. @pyqtSlot(str)
  71. def manualRemoveOverride(self, key: str) -> None:
  72. if key in self._settings_with_inheritance_warning:
  73. self._settings_with_inheritance_warning.remove(key)
  74. self.settingsWithIntheritanceChanged.emit()
  75. @pyqtSlot()
  76. def scheduleUpdate(self) -> None:
  77. self._update_timer.start()
  78. def _onActiveExtruderChanged(self) -> None:
  79. new_active_stack = ExtruderManager.getInstance().getActiveExtruderStack()
  80. if not new_active_stack:
  81. self._active_container_stack = None
  82. return
  83. if new_active_stack != self._active_container_stack: # Check if changed
  84. if self._active_container_stack: # Disconnect signal from old container (if any)
  85. self._active_container_stack.propertyChanged.disconnect(self._onPropertyChanged)
  86. self._active_container_stack.containersChanged.disconnect(self._onContainersChanged)
  87. self._active_container_stack = new_active_stack
  88. if self._active_container_stack is not None:
  89. self._active_container_stack.propertyChanged.connect(self._onPropertyChanged)
  90. self._active_container_stack.containersChanged.connect(self._onContainersChanged)
  91. self._update_timer.start() # Ensure that the settings_with_inheritance_warning list is populated.
  92. def _onPropertyChanged(self, key: str, property_name: str) -> None:
  93. if (property_name == "value" or property_name == "enabled") and self._global_container_stack:
  94. definitions = self._global_container_stack.definition.findDefinitions(key = key) # type: List["SettingDefinition"]
  95. if not definitions:
  96. return
  97. has_overwritten_inheritance = self._settingIsOverwritingInheritance(key)
  98. settings_with_inheritance_warning_changed = False
  99. # Check if the setting needs to be in the list.
  100. if key not in self._settings_with_inheritance_warning and has_overwritten_inheritance:
  101. self._settings_with_inheritance_warning.append(key)
  102. settings_with_inheritance_warning_changed = True
  103. elif key in self._settings_with_inheritance_warning and not has_overwritten_inheritance:
  104. self._settings_with_inheritance_warning.remove(key)
  105. settings_with_inheritance_warning_changed = True
  106. parent = definitions[0].parent
  107. # Find the topmost parent (Assumed to be a category)
  108. if parent is not None:
  109. while parent.parent is not None:
  110. parent = parent.parent
  111. else:
  112. parent = definitions[0] # Already at a category
  113. if parent.key not in self._settings_with_inheritance_warning and has_overwritten_inheritance:
  114. # Category was not in the list yet, so needs to be added now.
  115. self._settings_with_inheritance_warning.append(parent.key)
  116. settings_with_inheritance_warning_changed = True
  117. elif parent.key in self._settings_with_inheritance_warning and not has_overwritten_inheritance:
  118. # Category was in the list and one of it's settings is not overwritten.
  119. if not self._recursiveCheck(parent): # Check if any of it's children have overwritten inheritance.
  120. self._settings_with_inheritance_warning.remove(parent.key)
  121. settings_with_inheritance_warning_changed = True
  122. # Emit the signal if there was any change to the list.
  123. if settings_with_inheritance_warning_changed:
  124. self.settingsWithIntheritanceChanged.emit()
  125. def _recursiveCheck(self, definition: "SettingDefinition") -> bool:
  126. for child in definition.children:
  127. if child.key in self._settings_with_inheritance_warning:
  128. return True
  129. if child.children:
  130. if self._recursiveCheck(child):
  131. return True
  132. return False
  133. @pyqtProperty("QVariantList", notify = settingsWithIntheritanceChanged)
  134. def settingsWithInheritanceWarning(self) -> List[str]:
  135. return self._settings_with_inheritance_warning
  136. def _userSettingIsOverwritingInheritance(self, key: str, stack: ContainerStack, all_keys: Set[str] = set()) -> bool:
  137. """Check if a setting known as having a User state has an inheritance function that is overwritten"""
  138. has_setting_function = False
  139. containers = [] # type: List[ContainerInterface]
  140. # If a setting is not enabled, don't label it as overwritten (It's never visible anyway).
  141. if not stack.getProperty(key, "enabled"):
  142. return False
  143. user_container = stack.getTop()
  144. # Also check if the top container is not a setting function (this happens if the inheritance is restored).
  145. if user_container and isinstance(user_container.getProperty(key, "value"), SettingFunction):
  146. return False
  147. if not all_keys:
  148. all_keys = self._active_container_stack.getAllKeys()
  149. ## Mash all containers for all the stacks together.
  150. while stack:
  151. containers.extend(stack.getContainers())
  152. stack = stack.getNextStack()
  153. has_non_function_value = False
  154. for container in containers:
  155. try:
  156. value = container.getProperty(key, "value")
  157. except AttributeError:
  158. continue
  159. if value is not None:
  160. # If a setting doesn't use any keys, it won't change it's value, so treat it as if it's a fixed value
  161. has_setting_function = isinstance(value, SettingFunction)
  162. if has_setting_function:
  163. for setting_key in value.getUsedSettingKeys():
  164. if setting_key in all_keys:
  165. break # We found an actual setting. So has_setting_function can remain true
  166. else:
  167. # All of the setting_keys turned out to not be setting keys at all!
  168. # This can happen due enum keys also being marked as settings.
  169. has_setting_function = False
  170. if has_setting_function is False:
  171. has_non_function_value = True
  172. continue
  173. if has_setting_function:
  174. break # There is a setting function somewhere, stop looking deeper.
  175. return has_setting_function and has_non_function_value
  176. def _settingIsOverwritingInheritance(self, key: str, stack: ContainerStack = None) -> bool:
  177. """Check if a setting has an inheritance function that is overwritten"""
  178. if not stack:
  179. stack = self._active_container_stack
  180. if not stack: # No active container stack yet!
  181. return False
  182. if self._active_container_stack is None:
  183. return False
  184. has_user_state = stack.getProperty(key, "state") == InstanceState.User
  185. if not has_user_state:
  186. return False
  187. return self._userSettingIsOverwritingInheritance(key, stack)
  188. def _update(self) -> None:
  189. self._settings_with_inheritance_warning = [] # Reset previous data.
  190. # Make sure that the GlobalStack is not None. sometimes the globalContainerChanged signal gets here late.
  191. if self._global_container_stack is None or self._active_container_stack is None:
  192. return
  193. # Check all user setting keys that we know of and see if they are overridden.
  194. all_keys = self._active_container_stack.getAllKeys()
  195. for setting_key in self._active_container_stack.getAllKeysWithUserState():
  196. if self._userSettingIsOverwritingInheritance(setting_key, self._active_container_stack, all_keys):
  197. self._settings_with_inheritance_warning.append(setting_key)
  198. # Check all the categories if any of their children have their inheritance overwritten.
  199. for category in self._global_container_stack.definition.findDefinitions(type = "category"):
  200. if self._recursiveCheck(category):
  201. self._settings_with_inheritance_warning.append(category.key)
  202. # Notify others that things have changed.
  203. self.settingsWithIntheritanceChanged.emit()
  204. def _onGlobalContainerChanged(self) -> None:
  205. if self._global_container_stack:
  206. self._global_container_stack.propertyChanged.disconnect(self._onPropertyChanged)
  207. self._global_container_stack.containersChanged.disconnect(self._onContainersChanged)
  208. self._global_container_stack = Application.getInstance().getGlobalContainerStack()
  209. if self._global_container_stack:
  210. self._global_container_stack.containersChanged.connect(self._onContainersChanged)
  211. self._global_container_stack.propertyChanged.connect(self._onPropertyChanged)
  212. self._onActiveExtruderChanged()
  213. def _onContainersChanged(self, container):
  214. self._update_timer.start()
  215. @staticmethod
  216. def createSettingInheritanceManager(engine=None, script_engine=None):
  217. return SettingInheritanceManager()