GlobalStack.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from collections import defaultdict
  4. import threading
  5. from typing import Any, Dict, Optional, Set, TYPE_CHECKING
  6. from PyQt5.QtCore import pyqtProperty
  7. from UM.Decorators import override
  8. from UM.MimeTypeDatabase import MimeType, MimeTypeDatabase
  9. from UM.Settings.ContainerStack import ContainerStack
  10. from UM.Settings.SettingInstance import InstanceState
  11. from UM.Settings.ContainerRegistry import ContainerRegistry
  12. from UM.Settings.Interfaces import PropertyEvaluationContext
  13. from UM.Logger import Logger
  14. import cura.CuraApplication
  15. from . import Exceptions
  16. from .CuraContainerStack import CuraContainerStack
  17. if TYPE_CHECKING:
  18. from cura.Settings.ExtruderStack import ExtruderStack
  19. ## Represents the Global or Machine stack and its related containers.
  20. #
  21. class GlobalStack(CuraContainerStack):
  22. def __init__(self, container_id: str) -> None:
  23. super().__init__(container_id)
  24. self.setMetaDataEntry("type", "machine") # For backward compatibility
  25. self._extruders = {} # type: Dict[str, "ExtruderStack"]
  26. # This property is used to track which settings we are calculating the "resolve" for
  27. # and if so, to bypass the resolve to prevent an infinite recursion that would occur
  28. # if the resolve function tried to access the same property it is a resolve for.
  29. # Per thread we have our own resolving_settings, or strange things sometimes occur.
  30. self._resolving_settings = defaultdict(set) #type: Dict[str, Set[str]] # keys are thread names
  31. ## Get the list of extruders of this stack.
  32. #
  33. # \return The extruders registered with this stack.
  34. @pyqtProperty("QVariantMap")
  35. def extruders(self) -> Dict[str, "ExtruderStack"]:
  36. return self._extruders
  37. @classmethod
  38. def getLoadingPriority(cls) -> int:
  39. return 2
  40. @classmethod
  41. def getConfigurationTypeFromSerialized(cls, serialized: str) -> Optional[str]:
  42. configuration_type = super().getConfigurationTypeFromSerialized(serialized)
  43. if configuration_type == "machine":
  44. return "machine_stack"
  45. return configuration_type
  46. ## Add an extruder to the list of extruders of this stack.
  47. #
  48. # \param extruder The extruder to add.
  49. #
  50. # \throws Exceptions.TooManyExtrudersError Raised when trying to add an extruder while we
  51. # already have the maximum number of extruders.
  52. def addExtruder(self, extruder: ContainerStack) -> None:
  53. position = extruder.getMetaDataEntry("position")
  54. if position is None:
  55. Logger.log("w", "No position defined for extruder {extruder}, cannot add it to stack {stack}", extruder = extruder.id, stack = self.id)
  56. return
  57. if any(item.getId() == extruder.id for item in self._extruders.values()):
  58. Logger.log("w", "Extruder [%s] has already been added to this stack [%s]", extruder.id, self.getId())
  59. return
  60. self._extruders[position] = extruder
  61. Logger.log("i", "Extruder[%s] added to [%s] at position [%s]", extruder.id, self.id, position)
  62. ## Overridden from ContainerStack
  63. #
  64. # This will return the value of the specified property for the specified setting,
  65. # unless the property is "value" and that setting has a "resolve" function set.
  66. # When a resolve is set, it will instead try and execute the resolve first and
  67. # then fall back to the normal "value" property.
  68. #
  69. # \param key The setting key to get the property of.
  70. # \param property_name The property to get the value of.
  71. #
  72. # \return The value of the property for the specified setting, or None if not found.
  73. @override(ContainerStack)
  74. def getProperty(self, key: str, property_name: str, context: Optional[PropertyEvaluationContext] = None) -> Any:
  75. if not self.definition.findDefinitions(key = key):
  76. return None
  77. if context is None:
  78. context = PropertyEvaluationContext()
  79. context.pushContainer(self)
  80. # Handle the "resolve" property.
  81. #TODO: Why the hell does this involve threading?
  82. if self._shouldResolve(key, property_name, context):
  83. current_thread = threading.current_thread()
  84. self._resolving_settings[current_thread.name].add(key)
  85. resolve = super().getProperty(key, "resolve", context)
  86. self._resolving_settings[current_thread.name].remove(key)
  87. if resolve is not None:
  88. return resolve
  89. # Handle the "limit_to_extruder" property.
  90. limit_to_extruder = super().getProperty(key, "limit_to_extruder", context)
  91. if limit_to_extruder is not None:
  92. if limit_to_extruder == -1:
  93. limit_to_extruder = int(cura.CuraApplication.CuraApplication.getInstance().getMachineManager().defaultExtruderPosition)
  94. limit_to_extruder = str(limit_to_extruder)
  95. if limit_to_extruder is not None and limit_to_extruder != "-1" and limit_to_extruder in self._extruders:
  96. if super().getProperty(key, "settable_per_extruder", context):
  97. result = self._extruders[str(limit_to_extruder)].getProperty(key, property_name, context)
  98. if result is not None:
  99. context.popContainer()
  100. return result
  101. else:
  102. Logger.log("e", "Setting {setting} has limit_to_extruder but is not settable per extruder!", setting = key)
  103. result = super().getProperty(key, property_name, context)
  104. context.popContainer()
  105. return result
  106. ## Overridden from ContainerStack
  107. #
  108. # This will simply raise an exception since the Global stack cannot have a next stack.
  109. @override(ContainerStack)
  110. def setNextStack(self, stack: CuraContainerStack, connect_signals: bool = True) -> None:
  111. raise Exceptions.InvalidOperationError("Global stack cannot have a next stack!")
  112. # protected:
  113. # Determine whether or not we should try to get the "resolve" property instead of the
  114. # requested property.
  115. def _shouldResolve(self, key: str, property_name: str, context: Optional[PropertyEvaluationContext] = None) -> bool:
  116. if property_name is not "value":
  117. # Do not try to resolve anything but the "value" property
  118. return False
  119. current_thread = threading.current_thread()
  120. if key in self._resolving_settings[current_thread.name]:
  121. # To prevent infinite recursion, if getProperty is called with the same key as
  122. # we are already trying to resolve, we should not try to resolve again. Since
  123. # this can happen multiple times when trying to resolve a value, we need to
  124. # track all settings that are being resolved.
  125. return False
  126. setting_state = super().getProperty(key, "state", context = context)
  127. if setting_state is not None and setting_state != InstanceState.Default:
  128. # When the user has explicitly set a value, we should ignore any resolve and
  129. # just return that value.
  130. return False
  131. return True
  132. ## Perform some sanity checks on the global stack
  133. # Sanity check for extruders; they must have positions 0 and up to machine_extruder_count - 1
  134. def isValid(self) -> bool:
  135. container_registry = ContainerRegistry.getInstance()
  136. extruder_trains = container_registry.findContainerStacks(type = "extruder_train", machine = self.getId())
  137. machine_extruder_count = self.getProperty("machine_extruder_count", "value")
  138. extruder_check_position = set()
  139. for extruder_train in extruder_trains:
  140. extruder_position = extruder_train.getMetaDataEntry("position")
  141. extruder_check_position.add(extruder_position)
  142. for check_position in range(machine_extruder_count):
  143. if str(check_position) not in extruder_check_position:
  144. return False
  145. return True
  146. ## private:
  147. global_stack_mime = MimeType(
  148. name = "application/x-cura-globalstack",
  149. comment = "Cura Global Stack",
  150. suffixes = ["global.cfg"]
  151. )
  152. MimeTypeDatabase.addMimeType(global_stack_mime)
  153. ContainerRegistry.addContainerTypeByName(GlobalStack, "global_stack", global_stack_mime.name)