CuraContainerStack.py 18 KB

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