SettingInheritanceManager.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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, TYPE_CHECKING
  4. from PyQt5.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 _settingIsOverwritingInheritance(self, key: str, stack: ContainerStack = None) -> bool:
  137. """Check if a setting has an inheritance function that is overwritten"""
  138. has_setting_function = False
  139. if not stack:
  140. stack = self._active_container_stack
  141. if not stack: # No active container stack yet!
  142. return False
  143. if self._active_container_stack is None:
  144. return False
  145. all_keys = self._active_container_stack.getAllKeys()
  146. containers = [] # type: List[ContainerInterface]
  147. has_user_state = stack.getProperty(key, "state") == InstanceState.User
  148. """Check if the setting has a user state. If not, it is never overwritten."""
  149. if not has_user_state:
  150. return False
  151. # If a setting is not enabled, don't label it as overwritten (It's never visible anyway).
  152. if not stack.getProperty(key, "enabled"):
  153. return False
  154. user_container = stack.getTop()
  155. """Also check if the top container is not a setting function (this happens if the inheritance is restored)."""
  156. if user_container and isinstance(user_container.getProperty(key, "value"), SettingFunction):
  157. return False
  158. ## Mash all containers for all the stacks together.
  159. while stack:
  160. containers.extend(stack.getContainers())
  161. stack = stack.getNextStack()
  162. has_non_function_value = False
  163. for container in containers:
  164. try:
  165. value = container.getProperty(key, "value")
  166. except AttributeError:
  167. continue
  168. if value is not None:
  169. # 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
  170. has_setting_function = isinstance(value, SettingFunction)
  171. if has_setting_function:
  172. for setting_key in value.getUsedSettingKeys():
  173. if setting_key in all_keys:
  174. break # We found an actual setting. So has_setting_function can remain true
  175. else:
  176. # All of the setting_keys turned out to not be setting keys at all!
  177. # This can happen due enum keys also being marked as settings.
  178. has_setting_function = False
  179. if has_setting_function is False:
  180. has_non_function_value = True
  181. continue
  182. if has_setting_function:
  183. break # There is a setting function somewhere, stop looking deeper.
  184. return has_setting_function and has_non_function_value
  185. def _update(self) -> None:
  186. self._settings_with_inheritance_warning = [] # Reset previous data.
  187. # Make sure that the GlobalStack is not None. sometimes the globalContainerChanged signal gets here late.
  188. if self._global_container_stack is None:
  189. return
  190. # Check all setting keys that we know of and see if they are overridden.
  191. for setting_key in self._global_container_stack.getAllKeys():
  192. override = self._settingIsOverwritingInheritance(setting_key)
  193. if override:
  194. self._settings_with_inheritance_warning.append(setting_key)
  195. # Check all the categories if any of their children have their inheritance overwritten.
  196. for category in self._global_container_stack.definition.findDefinitions(type = "category"):
  197. if self._recursiveCheck(category):
  198. self._settings_with_inheritance_warning.append(category.key)
  199. # Notify others that things have changed.
  200. self.settingsWithIntheritanceChanged.emit()
  201. def _onGlobalContainerChanged(self) -> None:
  202. if self._global_container_stack:
  203. self._global_container_stack.propertyChanged.disconnect(self._onPropertyChanged)
  204. self._global_container_stack.containersChanged.disconnect(self._onContainersChanged)
  205. self._global_container_stack = Application.getInstance().getGlobalContainerStack()
  206. if self._global_container_stack:
  207. self._global_container_stack.containersChanged.connect(self._onContainersChanged)
  208. self._global_container_stack.propertyChanged.connect(self._onPropertyChanged)
  209. self._onActiveExtruderChanged()
  210. def _onContainersChanged(self, container):
  211. self._update_timer.start()
  212. @staticmethod
  213. def createSettingInheritanceManager(engine=None, script_engine=None):
  214. return SettingInheritanceManager()