GlobalStack.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. # Copyright (c) 2022 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, List
  6. import uuid
  7. from PyQt6.QtCore import pyqtProperty, pyqtSlot, pyqtSignal
  8. from UM.Decorators import override
  9. from UM.MimeTypeDatabase import MimeType, MimeTypeDatabase
  10. from UM.Settings.ContainerStack import ContainerStack
  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 cura.PrinterOutput.PrinterOutputDevice import ConnectionType
  19. from . import Exceptions
  20. from .CuraContainerStack import CuraContainerStack
  21. if TYPE_CHECKING:
  22. from cura.Settings.ExtruderStack import ExtruderStack
  23. class GlobalStack(CuraContainerStack):
  24. """Represents the Global or Machine stack and its related containers."""
  25. def __init__(self, container_id: str) -> None:
  26. super().__init__(container_id)
  27. self.setMetaDataEntry("type", "machine") # For backward compatibility
  28. # TL;DR: If Cura is looking for printers that belong to the same group, it should use "group_id".
  29. # Each GlobalStack by default belongs to a group which is identified via "group_id". This group_id is used to
  30. # figure out which GlobalStacks are in the printer cluster for example without knowing the implementation
  31. # details such as the um_network_key or some other identifier that's used by the underlying device plugin.
  32. self.setMetaDataEntry("group_id", str(uuid.uuid4())) # Assign a new GlobalStack to a unique group by default
  33. self._extruders = {} # type: Dict[str, "ExtruderStack"]
  34. # This property is used to track which settings we are calculating the "resolve" for
  35. # and if so, to bypass the resolve to prevent an infinite recursion that would occur
  36. # if the resolve function tried to access the same property it is a resolve for.
  37. # Per thread we have our own resolving_settings, or strange things sometimes occur.
  38. self._resolving_settings = defaultdict(set) #type: Dict[str, Set[str]] # keys are thread names
  39. # Since the metadatachanged is defined in container stack, we can't use it here as a notifier for pyqt
  40. # properties. So we need to tie them together like this.
  41. self.metaDataChanged.connect(self.configuredConnectionTypesChanged)
  42. self.setDirty(False)
  43. extrudersChanged = pyqtSignal()
  44. configuredConnectionTypesChanged = pyqtSignal()
  45. @pyqtProperty("QVariantList", notify = extrudersChanged)
  46. def extruderList(self) -> List["ExtruderStack"]:
  47. result_tuple_list = sorted(list(self._extruders.items()), key=lambda x: int(x[0]))
  48. result_list = [item[1] for item in result_tuple_list]
  49. machine_extruder_count = self.getProperty("machine_extruder_count", "value")
  50. return result_list[:machine_extruder_count]
  51. @pyqtProperty(int, constant = True)
  52. def maxExtruderCount(self):
  53. return len(self.getMetaDataEntry("machine_extruder_trains"))
  54. @pyqtProperty(bool, notify=configuredConnectionTypesChanged)
  55. def supportsNetworkConnection(self):
  56. return self.getMetaDataEntry("supports_network_connection", False)
  57. @pyqtProperty(bool, constant = True)
  58. def supportsMaterialExport(self):
  59. """
  60. Whether the printer supports Cura's export format of material profiles.
  61. :return: ``True`` if it supports it, or ``False`` if not.
  62. """
  63. return self.getMetaDataEntry("supports_material_export", False)
  64. @pyqtProperty("QVariantList", constant = True)
  65. def getOutputFileFormats(self) -> List[str]:
  66. """
  67. Which output formats the printer supports.
  68. :return: A list of strings with MIME-types.
  69. """
  70. all_formats_str = self.getMetaDataEntry("file_formats", "")
  71. return all_formats_str.split(";")
  72. @classmethod
  73. def getLoadingPriority(cls) -> int:
  74. return 2
  75. @pyqtProperty("QVariantList", notify=configuredConnectionTypesChanged)
  76. def configuredConnectionTypes(self) -> List[int]:
  77. """The configured connection types can be used to find out if the global
  78. stack is configured to be connected with a printer, without having to
  79. know all the details as to how this is exactly done (and without
  80. actually setting the stack to be active).
  81. This data can then in turn also be used when the global stack is active;
  82. If we can't get a network connection, but it is configured to have one,
  83. we can display a different icon to indicate the difference.
  84. """
  85. # Requesting it from the metadata actually gets them as strings (as that's what you get from serializing).
  86. # But we do want them returned as a list of ints (so the rest of the code can directly compare)
  87. connection_types = self.getMetaDataEntry("connection_type", "").split(",")
  88. result = []
  89. for connection_type in connection_types:
  90. if connection_type != "":
  91. try:
  92. result.append(int(connection_type))
  93. except ValueError:
  94. # We got invalid data, probably a None.
  95. pass
  96. return result
  97. # Returns a boolean indicating if this machine has a remote connection. A machine is considered as remotely
  98. # connected if its connection types contain one of the following values:
  99. # - ConnectionType.NetworkConnection
  100. # - ConnectionType.CloudConnection
  101. @pyqtProperty(bool, notify = configuredConnectionTypesChanged)
  102. def hasRemoteConnection(self) -> bool:
  103. has_remote_connection = False
  104. for connection_type in self.configuredConnectionTypes:
  105. has_remote_connection |= connection_type in [ConnectionType.NetworkConnection.value,
  106. ConnectionType.CloudConnection.value]
  107. return has_remote_connection
  108. def addConfiguredConnectionType(self, connection_type: int) -> None:
  109. """:sa configuredConnectionTypes"""
  110. configured_connection_types = self.configuredConnectionTypes
  111. if connection_type not in configured_connection_types:
  112. # Store the values as a string.
  113. configured_connection_types.append(connection_type)
  114. self.setMetaDataEntry("connection_type", ",".join([str(c_type) for c_type in configured_connection_types]))
  115. def removeConfiguredConnectionType(self, connection_type: int) -> None:
  116. """:sa configuredConnectionTypes"""
  117. configured_connection_types = self.configuredConnectionTypes
  118. if connection_type in configured_connection_types:
  119. # Store the values as a string.
  120. configured_connection_types.remove(connection_type)
  121. self.setMetaDataEntry("connection_type", ",".join([str(c_type) for c_type in configured_connection_types]))
  122. @classmethod
  123. def getConfigurationTypeFromSerialized(cls, serialized: str) -> Optional[str]:
  124. configuration_type = super().getConfigurationTypeFromSerialized(serialized)
  125. if configuration_type == "machine":
  126. return "machine_stack"
  127. return configuration_type
  128. def getIntentCategory(self) -> str:
  129. intent_category = "default"
  130. for extruder in self.extruderList:
  131. category = extruder.intent.getMetaDataEntry("intent_category", "default")
  132. if category != "default" and category != intent_category:
  133. intent_category = category
  134. return intent_category
  135. def getBuildplateName(self) -> Optional[str]:
  136. name = None
  137. if self.variant.getId() != "empty_variant":
  138. name = self.variant.getName()
  139. return name
  140. @pyqtProperty(str, constant = True)
  141. def preferred_output_file_formats(self) -> str:
  142. return self.getMetaDataEntry("file_formats")
  143. def addExtruder(self, extruder: ContainerStack) -> None:
  144. """Add an extruder to the list of extruders of this stack.
  145. :param extruder: The extruder to add.
  146. :raise Exceptions.TooManyExtrudersError: Raised when trying to add an extruder while we
  147. already have the maximum number of extruders.
  148. """
  149. position = extruder.getMetaDataEntry("position")
  150. if position is None:
  151. Logger.log("w", "No position defined for extruder {extruder}, cannot add it to stack {stack}", extruder = extruder.id, stack = self.id)
  152. return
  153. if any(item.getId() == extruder.id for item in self._extruders.values()):
  154. Logger.log("w", "Extruder [%s] has already been added to this stack [%s]", extruder.id, self.getId())
  155. return
  156. self._extruders[position] = extruder
  157. self.extrudersChanged.emit()
  158. Logger.log("i", "Extruder[%s] added to [%s] at position [%s]", extruder.id, self.id, position)
  159. @override(ContainerStack)
  160. def getProperty(self, key: str, property_name: str, context: Optional[PropertyEvaluationContext] = None) -> Any:
  161. """Overridden from ContainerStack
  162. This will return the value of the specified property for the specified setting,
  163. unless the property is "value" and that setting has a "resolve" function set.
  164. When a resolve is set, it will instead try and execute the resolve first and
  165. then fall back to the normal "value" property.
  166. :param key: The setting key to get the property of.
  167. :param property_name: The property to get the value of.
  168. :return: The value of the property for the specified setting, or None if not found.
  169. """
  170. if not self.definition.findDefinitions(key = key):
  171. return None
  172. if context:
  173. context.pushContainer(self)
  174. # Handle the "resolve" property.
  175. #TODO: Why the hell does this involve threading?
  176. # Answer: Because if multiple threads start resolving properties that have the same underlying properties that's
  177. # related, without taking a note of which thread a resolve paths belongs to, they can bump into each other and
  178. # generate unexpected behaviours.
  179. if self._shouldResolve(key, property_name, context):
  180. current_thread = threading.current_thread()
  181. self._resolving_settings[current_thread.name].add(key)
  182. resolve = super().getProperty(key, "resolve", context)
  183. self._resolving_settings[current_thread.name].remove(key)
  184. if resolve is not None:
  185. return resolve
  186. # Handle the "limit_to_extruder" property.
  187. limit_to_extruder = super().getProperty(key, "limit_to_extruder", context)
  188. if limit_to_extruder is not None:
  189. limit_to_extruder = str(limit_to_extruder)
  190. if limit_to_extruder is not None and limit_to_extruder != "-1" and limit_to_extruder in self._extruders:
  191. if super().getProperty(key, "settable_per_extruder", context):
  192. result = self._extruders[str(limit_to_extruder)].getProperty(key, property_name, context)
  193. if result is not None:
  194. if context:
  195. context.popContainer()
  196. return result
  197. else:
  198. Logger.log("e", "Setting {setting} has limit_to_extruder but is not settable per extruder!", setting = key)
  199. result = super().getProperty(key, property_name, context)
  200. if context:
  201. context.popContainer()
  202. return result
  203. @override(ContainerStack)
  204. def setNextStack(self, stack: CuraContainerStack, connect_signals: bool = True) -> None:
  205. """Overridden from ContainerStack
  206. This will simply raise an exception since the Global stack cannot have a next stack.
  207. """
  208. raise Exceptions.InvalidOperationError("Global stack cannot have a next stack!")
  209. # Determine whether or not we should try to get the "resolve" property instead of the
  210. # requested property.
  211. def _shouldResolve(self, key: str, property_name: str, context: Optional[PropertyEvaluationContext] = None) -> bool:
  212. if property_name != "value":
  213. # Do not try to resolve anything but the "value" property
  214. return False
  215. if not self.definition.getProperty(key, "resolve"):
  216. # If there isn't a resolve set for this setting, there isn't anything to do here.
  217. return False
  218. current_thread = threading.current_thread()
  219. if key in self._resolving_settings[current_thread.name]:
  220. # To prevent infinite recursion, if getProperty is called with the same key as
  221. # we are already trying to resolve, we should not try to resolve again. Since
  222. # this can happen multiple times when trying to resolve a value, we need to
  223. # track all settings that are being resolved.
  224. return False
  225. if self.hasUserValue(key):
  226. # When the user has explicitly set a value, we should ignore any resolve and just return that value.
  227. return False
  228. return True
  229. def isValid(self) -> bool:
  230. """Perform some sanity checks on the global stack
  231. Sanity check for extruders; they must have positions 0 and up to machine_extruder_count - 1
  232. """
  233. container_registry = ContainerRegistry.getInstance()
  234. extruder_trains = container_registry.findContainerStacks(type = "extruder_train", machine = self.getId())
  235. machine_extruder_count = self.getProperty("machine_extruder_count", "value")
  236. extruder_check_position = set()
  237. for extruder_train in extruder_trains:
  238. extruder_position = extruder_train.getMetaDataEntry("position")
  239. extruder_check_position.add(extruder_position)
  240. for check_position in range(machine_extruder_count):
  241. if str(check_position) not in extruder_check_position:
  242. return False
  243. return True
  244. def getHeadAndFansCoordinates(self):
  245. return self.getProperty("machine_head_with_fans_polygon", "value")
  246. @pyqtProperty(bool, constant = True)
  247. def hasMaterials(self) -> bool:
  248. return parseBool(self.getMetaDataEntry("has_materials", False))
  249. @pyqtProperty(bool, constant = True)
  250. def hasVariants(self) -> bool:
  251. return parseBool(self.getMetaDataEntry("has_variants", False))
  252. @pyqtProperty(bool, constant = True)
  253. def hasVariantBuildplates(self) -> bool:
  254. return parseBool(self.getMetaDataEntry("has_variant_buildplates", False))
  255. @pyqtSlot(result = str)
  256. def getDefaultFirmwareName(self) -> str:
  257. """Get default firmware file name if one is specified in the firmware"""
  258. machine_has_heated_bed = self.getProperty("machine_heated_bed", "value")
  259. baudrate = 250000
  260. if Platform.isLinux():
  261. # Linux prefers a baudrate of 115200 here because older versions of
  262. # pySerial did not support a baudrate of 250000
  263. baudrate = 115200
  264. # If a firmware file is available, it should be specified in the definition for the printer
  265. hex_file = self.getMetaDataEntry("firmware_file", None)
  266. if machine_has_heated_bed:
  267. hex_file = self.getMetaDataEntry("firmware_hbk_file", hex_file)
  268. if not hex_file:
  269. Logger.log("w", "There is no firmware for machine %s.", self.getBottom().id)
  270. return ""
  271. try:
  272. return Resources.getPath(cura.CuraApplication.CuraApplication.ResourceTypes.Firmware, hex_file.format(baudrate=baudrate))
  273. except FileNotFoundError:
  274. Logger.log("w", "Firmware file %s not found.", hex_file)
  275. return ""
  276. def getName(self) -> str:
  277. return self._metadata.get("group_name", self._metadata.get("name", ""))
  278. def setName(self, name: str) -> None:
  279. super().setName(name)
  280. nameChanged = pyqtSignal()
  281. name = pyqtProperty(str, fget=getName, fset=setName, notify=nameChanged)
  282. def hasNetworkedConnection(self) -> bool:
  283. has_connection = False
  284. for connection_type in [ConnectionType.NetworkConnection.value, ConnectionType.CloudConnection.value]:
  285. has_connection |= connection_type in self.configuredConnectionTypes
  286. return has_connection
  287. ## private:
  288. global_stack_mime = MimeType(
  289. name = "application/x-cura-globalstack",
  290. comment = "Cura Global Stack",
  291. suffixes = ["global.cfg"]
  292. )
  293. MimeTypeDatabase.addMimeType(global_stack_mime)
  294. ContainerRegistry.addContainerTypeByName(GlobalStack, "global_stack", global_stack_mime.name)