GlobalStack.py 10 KB

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