SettingInheritanceManager.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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. ## Get the keys of all children settings with an override.
  37. @pyqtSlot(str, result = "QStringList")
  38. def getChildrenKeysWithOverride(self, key: str) -> List[str]:
  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 = "QStringList")
  51. def getOverridesForExtruder(self, key: str, extruder_index: str) -> List[str]:
  52. if self._global_container_stack is None:
  53. return []
  54. result = [] # type: List[str]
  55. extruder_stack = ExtruderManager.getInstance().getExtruderStack(extruder_index)
  56. if not extruder_stack:
  57. Logger.log("w", "Unable to find extruder for current machine with index %s", extruder_index)
  58. return result
  59. definitions = self._global_container_stack.definition.findDefinitions(key = key)
  60. if not definitions:
  61. Logger.log("w", "Could not find definition for key [%s] (2)", key)
  62. return result
  63. for key in definitions[0].getAllKeys():
  64. if self._settingIsOverwritingInheritance(key, extruder_stack):
  65. result.append(key)
  66. return result
  67. @pyqtSlot(str)
  68. def manualRemoveOverride(self, key: str) -> None:
  69. if key in self._settings_with_inheritance_warning:
  70. self._settings_with_inheritance_warning.remove(key)
  71. self.settingsWithIntheritanceChanged.emit()
  72. @pyqtSlot()
  73. def scheduleUpdate(self) -> None:
  74. self._update_timer.start()
  75. def _onActiveExtruderChanged(self) -> None:
  76. new_active_stack = ExtruderManager.getInstance().getActiveExtruderStack()
  77. if not new_active_stack:
  78. self._active_container_stack = None
  79. return
  80. if new_active_stack != self._active_container_stack: # Check if changed
  81. if self._active_container_stack: # Disconnect signal from old container (if any)
  82. self._active_container_stack.propertyChanged.disconnect(self._onPropertyChanged)
  83. self._active_container_stack.containersChanged.disconnect(self._onContainersChanged)
  84. self._active_container_stack = new_active_stack
  85. if self._active_container_stack is not None:
  86. self._active_container_stack.propertyChanged.connect(self._onPropertyChanged)
  87. self._active_container_stack.containersChanged.connect(self._onContainersChanged)
  88. self._update_timer.start() # Ensure that the settings_with_inheritance_warning list is populated.
  89. def _onPropertyChanged(self, key: str, property_name: str) -> None:
  90. if (property_name == "value" or property_name == "enabled") and self._global_container_stack:
  91. definitions = self._global_container_stack.definition.findDefinitions(key = key) # type: List["SettingDefinition"]
  92. if not definitions:
  93. return
  94. has_overwritten_inheritance = self._settingIsOverwritingInheritance(key)
  95. settings_with_inheritance_warning_changed = False
  96. # Check if the setting needs to be in the list.
  97. if key not in self._settings_with_inheritance_warning and has_overwritten_inheritance:
  98. self._settings_with_inheritance_warning.append(key)
  99. settings_with_inheritance_warning_changed = True
  100. elif key in self._settings_with_inheritance_warning and not has_overwritten_inheritance:
  101. self._settings_with_inheritance_warning.remove(key)
  102. settings_with_inheritance_warning_changed = True
  103. parent = definitions[0].parent
  104. # Find the topmost parent (Assumed to be a category)
  105. if parent is not None:
  106. while parent.parent is not None:
  107. parent = parent.parent
  108. else:
  109. parent = definitions[0] # Already at a category
  110. if parent.key not in self._settings_with_inheritance_warning and has_overwritten_inheritance:
  111. # Category was not in the list yet, so needs to be added now.
  112. self._settings_with_inheritance_warning.append(parent.key)
  113. settings_with_inheritance_warning_changed = True
  114. elif parent.key in self._settings_with_inheritance_warning and not has_overwritten_inheritance:
  115. # Category was in the list and one of it's settings is not overwritten.
  116. if not self._recursiveCheck(parent): # Check if any of it's children have overwritten inheritance.
  117. self._settings_with_inheritance_warning.remove(parent.key)
  118. settings_with_inheritance_warning_changed = True
  119. # Emit the signal if there was any change to the list.
  120. if settings_with_inheritance_warning_changed:
  121. self.settingsWithIntheritanceChanged.emit()
  122. def _recursiveCheck(self, definition: "SettingDefinition") -> bool:
  123. for child in definition.children:
  124. if child.key in self._settings_with_inheritance_warning:
  125. return True
  126. if child.children:
  127. if self._recursiveCheck(child):
  128. return True
  129. return False
  130. @pyqtProperty("QVariantList", notify = settingsWithIntheritanceChanged)
  131. def settingsWithInheritanceWarning(self) -> List[str]:
  132. return self._settings_with_inheritance_warning
  133. ## Check if a setting has an inheritance function that is overwritten
  134. def _settingIsOverwritingInheritance(self, key: str, stack: ContainerStack = None) -> bool:
  135. has_setting_function = False
  136. if not stack:
  137. stack = self._active_container_stack
  138. if not stack: # No active container stack yet!
  139. return False
  140. if self._active_container_stack is None:
  141. return False
  142. all_keys = self._active_container_stack.getAllKeys()
  143. containers = [] # type: List[ContainerInterface]
  144. ## Check if the setting has a user state. If not, it is never overwritten.
  145. has_user_state = stack.getProperty(key, "state") == InstanceState.User
  146. if not has_user_state:
  147. return False
  148. ## If a setting is not enabled, don't label it as overwritten (It's never visible anyway).
  149. if not stack.getProperty(key, "enabled"):
  150. return False
  151. ## Also check if the top container is not a setting function (this happens if the inheritance is restored).
  152. user_container = stack.getTop()
  153. if user_container and isinstance(user_container.getProperty(key, "value"), SettingFunction):
  154. return False
  155. ## Mash all containers for all the stacks together.
  156. while stack:
  157. containers.extend(stack.getContainers())
  158. stack = stack.getNextStack()
  159. has_non_function_value = False
  160. for container in containers:
  161. try:
  162. value = container.getProperty(key, "value")
  163. except AttributeError:
  164. continue
  165. if value is not None:
  166. # 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
  167. has_setting_function = isinstance(value, SettingFunction)
  168. if has_setting_function:
  169. for setting_key in value.getUsedSettingKeys():
  170. if setting_key in all_keys:
  171. break # We found an actual setting. So has_setting_function can remain true
  172. else:
  173. # All of the setting_keys turned out to not be setting keys at all!
  174. # This can happen due enum keys also being marked as settings.
  175. has_setting_function = False
  176. if has_setting_function is False:
  177. has_non_function_value = True
  178. continue
  179. if has_setting_function:
  180. break # There is a setting function somewhere, stop looking deeper.
  181. return has_setting_function and has_non_function_value
  182. def _update(self) -> None:
  183. self._settings_with_inheritance_warning = [] # Reset previous data.
  184. # Make sure that the GlobalStack is not None. sometimes the globalContainerChanged signal gets here late.
  185. if self._global_container_stack is None:
  186. return
  187. # Check all setting keys that we know of and see if they are overridden.
  188. for setting_key in self._global_container_stack.getAllKeys():
  189. override = self._settingIsOverwritingInheritance(setting_key)
  190. if override:
  191. self._settings_with_inheritance_warning.append(setting_key)
  192. # Check all the categories if any of their children have their inheritance overwritten.
  193. for category in self._global_container_stack.definition.findDefinitions(type = "category"):
  194. if self._recursiveCheck(category):
  195. self._settings_with_inheritance_warning.append(category.key)
  196. # Notify others that things have changed.
  197. self.settingsWithIntheritanceChanged.emit()
  198. def _onGlobalContainerChanged(self) -> None:
  199. if self._global_container_stack:
  200. self._global_container_stack.propertyChanged.disconnect(self._onPropertyChanged)
  201. self._global_container_stack.containersChanged.disconnect(self._onContainersChanged)
  202. self._global_container_stack = Application.getInstance().getGlobalContainerStack()
  203. if self._global_container_stack:
  204. self._global_container_stack.containersChanged.connect(self._onContainersChanged)
  205. self._global_container_stack.propertyChanged.connect(self._onPropertyChanged)
  206. self._onActiveExtruderChanged()
  207. def _onContainersChanged(self, container):
  208. self._update_timer.start()
  209. @staticmethod
  210. def createSettingInheritanceManager(engine=None, script_engine=None):
  211. return SettingInheritanceManager()