CuraContainerStack.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from typing import Any, cast, List, Optional, Dict
  4. from PyQt6.QtCore import pyqtProperty, pyqtSignal, QObject
  5. from UM.Application import Application
  6. from UM.Decorators import CachedMemberFunctions, override
  7. from UM.FlameProfiler import pyqtSlot
  8. from UM.Logger import Logger
  9. from UM.Settings.ContainerStack import ContainerStack, InvalidContainerStackError
  10. from UM.Settings.InstanceContainer import InstanceContainer
  11. from UM.Settings.DefinitionContainer import DefinitionContainer
  12. from UM.Settings.ContainerRegistry import ContainerRegistry
  13. from UM.Settings.Interfaces import ContainerInterface, DefinitionContainerInterface
  14. from cura.Settings import cura_empty_instance_containers
  15. from . import Exceptions
  16. class CuraContainerStack(ContainerStack):
  17. """Base class for Cura related stacks that want to enforce certain containers are available.
  18. This class makes sure that the stack has the following containers set: user changes, quality
  19. changes, quality, material, variant, definition changes and finally definition. Initially,
  20. these will be equal to the empty instance container.
  21. The container types are determined based on the following criteria:
  22. - user: An InstanceContainer with the metadata entry "type" set to "user".
  23. - quality changes: An InstanceContainer with the metadata entry "type" set to "quality_changes".
  24. - quality: An InstanceContainer with the metadata entry "type" set to "quality".
  25. - material: An InstanceContainer with the metadata entry "type" set to "material".
  26. - variant: An InstanceContainer with the metadata entry "type" set to "variant".
  27. - definition changes: An InstanceContainer with the metadata entry "type" set to "definition_changes".
  28. - definition: A DefinitionContainer.
  29. Internally, this class ensures the mentioned containers are always there and kept in a specific order.
  30. This also means that operations on the stack that modifies the container ordering is prohibited and
  31. will raise an exception.
  32. """
  33. def __init__(self, container_id: str) -> None:
  34. super().__init__(container_id)
  35. self._empty_instance_container = cura_empty_instance_containers.empty_container #type: InstanceContainer
  36. self._empty_quality_changes = cura_empty_instance_containers.empty_quality_changes_container #type: InstanceContainer
  37. self._empty_quality = cura_empty_instance_containers.empty_quality_container #type: InstanceContainer
  38. self._empty_material = cura_empty_instance_containers.empty_material_container #type: InstanceContainer
  39. self._empty_variant = cura_empty_instance_containers.empty_variant_container #type: InstanceContainer
  40. self._containers: List[ContainerInterface] = [self._empty_instance_container for i in _ContainerIndexes.IndexTypeMap]
  41. self._containers[_ContainerIndexes.QualityChanges] = self._empty_quality_changes
  42. self._containers[_ContainerIndexes.Quality] = self._empty_quality
  43. self._containers[_ContainerIndexes.Material] = self._empty_material
  44. self._containers[_ContainerIndexes.Variant] = self._empty_variant
  45. self.containersChanged.connect(self._onContainersChanged)
  46. import cura.CuraApplication #Here to prevent circular imports.
  47. self.setMetaDataEntry("setting_version", cura.CuraApplication.CuraApplication.SettingVersion)
  48. self._settable_per_extruder_cache = {} # type: Dict[str, Any]
  49. self.setDirty(False)
  50. # This is emitted whenever the containersChanged signal from the ContainerStack base class is emitted.
  51. pyqtContainersChanged = pyqtSignal()
  52. def setUserChanges(self, new_user_changes: InstanceContainer) -> None:
  53. """Set the user changes container.
  54. :param new_user_changes: The new user changes container. It is expected to have a "type" metadata entry with the value "user".
  55. """
  56. self.replaceContainer(_ContainerIndexes.UserChanges, new_user_changes)
  57. @pyqtProperty(QObject, fset = setUserChanges, notify = pyqtContainersChanged)
  58. def userChanges(self) -> InstanceContainer:
  59. """Get the user changes container.
  60. :return: The user changes container. Should always be a valid container, but can be equal to the empty InstanceContainer.
  61. """
  62. return cast(InstanceContainer, self._containers[_ContainerIndexes.UserChanges])
  63. def setQualityChanges(self, new_quality_changes: InstanceContainer, postpone_emit = False) -> None:
  64. """Set the quality changes container.
  65. :param new_quality_changes: The new quality changes container. It is expected to have a "type" metadata entry with the value "quality_changes".
  66. """
  67. self.replaceContainer(_ContainerIndexes.QualityChanges, new_quality_changes, postpone_emit = postpone_emit)
  68. @pyqtProperty(QObject, fset = setQualityChanges, notify = pyqtContainersChanged)
  69. def qualityChanges(self) -> InstanceContainer:
  70. """Get the quality changes container.
  71. :return: The quality changes container. Should always be a valid container, but can be equal to the empty InstanceContainer.
  72. """
  73. return cast(InstanceContainer, self._containers[_ContainerIndexes.QualityChanges])
  74. def setIntent(self, new_intent: InstanceContainer, postpone_emit: bool = False) -> None:
  75. """Set the intent container.
  76. :param new_intent: The new intent container. It is expected to have a "type" metadata entry with the value "intent".
  77. """
  78. self.replaceContainer(_ContainerIndexes.Intent, new_intent, postpone_emit = postpone_emit)
  79. @pyqtProperty(QObject, fset = setIntent, notify = pyqtContainersChanged)
  80. def intent(self) -> InstanceContainer:
  81. """Get the quality container.
  82. :return: The intent container. Should always be a valid container, but can be equal to the empty InstanceContainer.
  83. """
  84. return cast(InstanceContainer, self._containers[_ContainerIndexes.Intent])
  85. def setQuality(self, new_quality: InstanceContainer, postpone_emit: bool = False) -> None:
  86. """Set the quality container.
  87. :param new_quality: The new quality container. It is expected to have a "type" metadata entry with the value "quality".
  88. """
  89. self.replaceContainer(_ContainerIndexes.Quality, new_quality, postpone_emit = postpone_emit)
  90. @pyqtProperty(QObject, fset = setQuality, notify = pyqtContainersChanged)
  91. def quality(self) -> InstanceContainer:
  92. """Get the quality container.
  93. :return: The quality container. Should always be a valid container, but can be equal to the empty InstanceContainer.
  94. """
  95. return cast(InstanceContainer, self._containers[_ContainerIndexes.Quality])
  96. def setMaterial(self, new_material: InstanceContainer, postpone_emit: bool = False) -> None:
  97. """Set the material container.
  98. :param new_material: The new material container. It is expected to have a "type" metadata entry with the value "material".
  99. """
  100. self.replaceContainer(_ContainerIndexes.Material, new_material, postpone_emit = postpone_emit)
  101. @pyqtProperty(QObject, fset = setMaterial, notify = pyqtContainersChanged)
  102. def material(self) -> InstanceContainer:
  103. """Get the material container.
  104. :return: The material container. Should always be a valid container, but can be equal to the empty InstanceContainer.
  105. """
  106. return cast(InstanceContainer, self._containers[_ContainerIndexes.Material])
  107. def setVariant(self, new_variant: InstanceContainer) -> None:
  108. """Set the variant container.
  109. :param new_variant: The new variant container. It is expected to have a "type" metadata entry with the value "variant".
  110. """
  111. self.replaceContainer(_ContainerIndexes.Variant, new_variant)
  112. @pyqtProperty(QObject, fset = setVariant, notify = pyqtContainersChanged)
  113. def variant(self) -> InstanceContainer:
  114. """Get the variant container.
  115. :return: The variant container. Should always be a valid container, but can be equal to the empty InstanceContainer.
  116. """
  117. return cast(InstanceContainer, self._containers[_ContainerIndexes.Variant])
  118. def setDefinitionChanges(self, new_definition_changes: InstanceContainer) -> None:
  119. """Set the definition changes container.
  120. :param new_definition_changes: The new definition changes container. It is expected to have a "type" metadata entry with the value "definition_changes".
  121. """
  122. self.replaceContainer(_ContainerIndexes.DefinitionChanges, new_definition_changes)
  123. @pyqtProperty(QObject, fset = setDefinitionChanges, notify = pyqtContainersChanged)
  124. def definitionChanges(self) -> InstanceContainer:
  125. """Get the definition changes container.
  126. :return: The definition changes container. Should always be a valid container, but can be equal to the empty InstanceContainer.
  127. """
  128. return cast(InstanceContainer, self._containers[_ContainerIndexes.DefinitionChanges])
  129. def setDefinition(self, new_definition: DefinitionContainerInterface) -> None:
  130. """Set the definition container.
  131. :param new_definition: The new definition container. It is expected to have a "type" metadata entry with the value "definition".
  132. """
  133. self.replaceContainer(_ContainerIndexes.Definition, new_definition)
  134. def getDefinition(self) -> "DefinitionContainer":
  135. return cast(DefinitionContainer, self._containers[_ContainerIndexes.Definition])
  136. definition = pyqtProperty(QObject, fget = getDefinition, fset = setDefinition, notify = pyqtContainersChanged)
  137. @override(ContainerStack)
  138. def getBottom(self) -> "DefinitionContainer":
  139. return self.definition
  140. @override(ContainerStack)
  141. def getTop(self) -> "InstanceContainer":
  142. return self.userChanges
  143. @pyqtSlot(str, result = bool)
  144. def hasUserValue(self, key: str) -> bool:
  145. """Check whether the specified setting has a 'user' value.
  146. A user value here is defined as the setting having a value in either
  147. the UserChanges or QualityChanges container.
  148. :return: True if the setting has a user value, False if not.
  149. """
  150. if self._containers[_ContainerIndexes.UserChanges].hasProperty(key, "value"):
  151. return True
  152. if self._containers[_ContainerIndexes.QualityChanges].hasProperty(key, "value"):
  153. return True
  154. return False
  155. def setProperty(self, key: str, property_name: str, property_value: Any, container: "ContainerInterface" = None, set_from_cache: bool = False) -> None:
  156. """Set a property of a setting.
  157. This will set a property of a specified setting. Since the container stack does not contain
  158. any settings itself, it is required to specify a container to set the property on. The target
  159. container is matched by container type.
  160. :param key: The key of the setting to set.
  161. :param property_name: The name of the property to set.
  162. :param new_value: The new value to set the property to.
  163. """
  164. CachedMemberFunctions.clearInstanceCache(self)
  165. container_index = _ContainerIndexes.UserChanges
  166. self._containers[container_index].setProperty(key, property_name, property_value, container, set_from_cache)
  167. @override(ContainerStack)
  168. def addContainer(self, container: ContainerInterface) -> None:
  169. """Overridden from ContainerStack
  170. Since we have a fixed order of containers in the stack and this method would modify the container
  171. ordering, we disallow this operation.
  172. """
  173. raise Exceptions.InvalidOperationError("Cannot add a container to Global stack")
  174. @override(ContainerStack)
  175. def insertContainer(self, index: int, container: ContainerInterface) -> None:
  176. """Overridden from ContainerStack
  177. Since we have a fixed order of containers in the stack and this method would modify the container
  178. ordering, we disallow this operation.
  179. """
  180. raise Exceptions.InvalidOperationError("Cannot insert a container into Global stack")
  181. @override(ContainerStack)
  182. def removeContainer(self, index: int = 0) -> None:
  183. """Overridden from ContainerStack
  184. Since we have a fixed order of containers in the stack and this method would modify the container
  185. ordering, we disallow this operation.
  186. """
  187. raise Exceptions.InvalidOperationError("Cannot remove a container from Global stack")
  188. @override(ContainerStack)
  189. def replaceContainer(self, index: int, container: ContainerInterface, postpone_emit: bool = False) -> None:
  190. """Overridden from ContainerStack
  191. Replaces the container at the specified index with another container.
  192. This version performs checks to make sure the new container has the expected metadata and type.
  193. :throws Exception.InvalidContainerError Raised when trying to replace a container with a container that has an incorrect type.
  194. """
  195. expected_type = _ContainerIndexes.IndexTypeMap[index]
  196. if expected_type == "definition":
  197. if not isinstance(container, DefinitionContainer):
  198. raise Exceptions.InvalidContainerError("Cannot replace container at index {index} with a container that is not a DefinitionContainer".format(index = index))
  199. elif container != self._empty_instance_container and container.getMetaDataEntry("type") != expected_type:
  200. raise Exceptions.InvalidContainerError("Cannot replace container at index {index} with a container that is not of {type} type, but {actual_type} type.".format(index = index, type = expected_type, actual_type = container.getMetaDataEntry("type")))
  201. current_container = self._containers[index]
  202. if current_container.getId() == container.getId():
  203. return
  204. super().replaceContainer(index, container, postpone_emit)
  205. @override(ContainerStack)
  206. def deserialize(self, serialized: str, file_name: Optional[str] = None) -> str:
  207. """Overridden from ContainerStack
  208. This deserialize will make sure the internal list of containers matches with what we expect.
  209. It will first check to see if the container at a certain index already matches with what we
  210. expect. If it does not, it will search for a matching container with the correct type. Should
  211. no container with the correct type be found, it will use the empty container.
  212. :raise InvalidContainerStackError: Raised when no definition can be found for the stack.
  213. """
  214. # update the serialized data first
  215. serialized = super().deserialize(serialized, file_name)
  216. new_containers = self._containers.copy()
  217. while len(new_containers) < len(_ContainerIndexes.IndexTypeMap):
  218. new_containers.append(self._empty_instance_container)
  219. # Validate and ensure the list of containers matches with what we expect
  220. for index, type_name in _ContainerIndexes.IndexTypeMap.items():
  221. container = None
  222. try:
  223. container = new_containers[index]
  224. except IndexError:
  225. pass
  226. if type_name == "definition":
  227. if not container or not isinstance(container, DefinitionContainer):
  228. definition = self.findContainer(container_type = DefinitionContainer)
  229. if not definition:
  230. raise InvalidContainerStackError("Stack {id} does not have a definition!".format(id = self.getId()))
  231. new_containers[index] = definition
  232. continue
  233. if not container or container.getMetaDataEntry("type") != type_name:
  234. actual_container = self.findContainer(type = type_name)
  235. if actual_container:
  236. new_containers[index] = actual_container
  237. else:
  238. new_containers[index] = self._empty_instance_container
  239. self._containers = new_containers
  240. # CURA-5281
  241. # Some stacks can have empty definition_changes containers which will cause problems.
  242. # Make sure that all stacks here have non-empty definition_changes containers.
  243. if isinstance(new_containers[_ContainerIndexes.DefinitionChanges], type(self._empty_instance_container)):
  244. from cura.Settings.CuraStackBuilder import CuraStackBuilder
  245. CuraStackBuilder.createDefinitionChangesContainer(self, self.getId() + "_settings")
  246. ## TODO; Deserialize the containers.
  247. return serialized
  248. def _onContainersChanged(self, container: Any) -> None:
  249. """Helper to make sure we emit a PyQt signal on container changes."""
  250. Application.getInstance().callLater(self.pyqtContainersChanged.emit)
  251. # Helper that can be overridden to get the "machine" definition, that is, the definition that defines the machine
  252. # and its properties rather than, for example, the extruder. Defaults to simply returning the definition property.
  253. def _getMachineDefinition(self) -> DefinitionContainer:
  254. return self.definition
  255. @classmethod
  256. def findInstanceContainerDefinitionId(cls, machine_definition: DefinitionContainerInterface) -> str:
  257. """Find the ID that should be used when searching for instance containers for a specified definition.
  258. This handles the situation where the definition specifies we should use a different definition when
  259. searching for instance containers.
  260. :param machine_definition: The definition to find the "quality definition" for.
  261. :return: The ID of the definition container to use when searching for instance containers.
  262. """
  263. quality_definition = machine_definition.getMetaDataEntry("quality_definition")
  264. if not quality_definition:
  265. return machine_definition.id #type: ignore
  266. definitions = ContainerRegistry.getInstance().findDefinitionContainers(id = quality_definition)
  267. if not definitions:
  268. Logger.log("w", "Unable to find parent definition {parent} for machine {machine}", parent = quality_definition, machine = machine_definition.id) #type: ignore
  269. return machine_definition.id #type: ignore
  270. return cls.findInstanceContainerDefinitionId(definitions[0])
  271. def getExtruderPositionValueWithDefault(self, key):
  272. """getProperty for extruder positions, with translation from -1 to default extruder number"""
  273. value = self.getProperty(key, "value")
  274. if value == -1:
  275. value = int(Application.getInstance().getMachineManager().defaultExtruderPosition)
  276. return value
  277. def getProperty(self, key: str, property_name: str, context = None) -> Any:
  278. if property_name == "settable_per_extruder":
  279. # Setable per extruder isn't a value that can ever change. So once we requested it once, we can just keep
  280. # that in memory.
  281. try:
  282. return self._settable_per_extruder_cache[key]
  283. except KeyError:
  284. self._settable_per_extruder_cache[key] = super().getProperty(key, property_name, context)
  285. return self._settable_per_extruder_cache[key]
  286. return super().getProperty(key, property_name, context)
  287. class _ContainerIndexes:
  288. """Private helper class to keep track of container positions and their types."""
  289. UserChanges = 0
  290. QualityChanges = 1
  291. Intent = 2
  292. Quality = 3
  293. Material = 4
  294. Variant = 5
  295. DefinitionChanges = 6
  296. Definition = 7
  297. # Simple hash map to map from index to "type" metadata entry
  298. IndexTypeMap = {
  299. UserChanges: "user",
  300. QualityChanges: "quality_changes",
  301. Intent: "intent",
  302. Quality: "quality",
  303. Material: "material",
  304. Variant: "variant",
  305. DefinitionChanges: "definition_changes",
  306. Definition: "definition",
  307. }
  308. # Reverse lookup: type -> index
  309. TypeIndexMap = {v: k for k, v in IndexTypeMap.items()}