GlobalStack.py 9.3 KB

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