ExtruderManager.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from PyQt5.QtCore import pyqtSignal, pyqtProperty, QObject, QVariant # For communicating data and events to Qt.
  4. from UM.FlameProfiler import pyqtSlot
  5. import cura.CuraApplication # To get the global container stack to find the current machine.
  6. from cura.Settings.GlobalStack import GlobalStack
  7. from UM.Logger import Logger
  8. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  9. from UM.Scene.SceneNode import SceneNode
  10. from UM.Scene.Selection import Selection
  11. from UM.Scene.Iterator.BreadthFirstIterator import BreadthFirstIterator
  12. from UM.Settings.ContainerRegistry import ContainerRegistry # Finding containers by ID.
  13. from UM.Settings.SettingFunction import SettingFunction
  14. from UM.Settings.ContainerStack import ContainerStack
  15. from UM.Settings.PropertyEvaluationContext import PropertyEvaluationContext
  16. from typing import Any, cast, Dict, List, Optional, TYPE_CHECKING
  17. if TYPE_CHECKING:
  18. from cura.Settings.ExtruderStack import ExtruderStack
  19. ## Manages all existing extruder stacks.
  20. #
  21. # This keeps a list of extruder stacks for each machine.
  22. class ExtruderManager(QObject):
  23. ## Registers listeners and such to listen to changes to the extruders.
  24. def __init__(self, parent = None):
  25. if ExtruderManager.__instance is not None:
  26. raise RuntimeError("Try to create singleton '%s' more than once" % self.__class__.__name__)
  27. ExtruderManager.__instance = self
  28. super().__init__(parent)
  29. self._application = cura.CuraApplication.CuraApplication.getInstance()
  30. # Per machine, a dictionary of extruder container stack IDs. Only for separately defined extruders.
  31. self._extruder_trains = {} # type: Dict[str, Dict[str, ExtruderStack]]
  32. self._active_extruder_index = -1 # Indicates the index of the active extruder stack. -1 means no active extruder stack
  33. self._selected_object_extruders = [] # type: List[str]
  34. self._addCurrentMachineExtruders()
  35. Selection.selectionChanged.connect(self.resetSelectedObjectExtruders)
  36. ## Signal to notify other components when the list of extruders for a machine definition changes.
  37. extrudersChanged = pyqtSignal(QVariant)
  38. ## Notify when the user switches the currently active extruder.
  39. activeExtruderChanged = pyqtSignal()
  40. ## Gets the unique identifier of the currently active extruder stack.
  41. #
  42. # The currently active extruder stack is the stack that is currently being
  43. # edited.
  44. #
  45. # \return The unique ID of the currently active extruder stack.
  46. @pyqtProperty(str, notify = activeExtruderChanged)
  47. def activeExtruderStackId(self) -> Optional[str]:
  48. if not self._application.getGlobalContainerStack():
  49. return None # No active machine, so no active extruder.
  50. try:
  51. return self._extruder_trains[self._application.getGlobalContainerStack().getId()][str(self._active_extruder_index)].getId()
  52. except KeyError: # Extruder index could be -1 if the global tab is selected, or the entry doesn't exist if the machine definition is wrong.
  53. return None
  54. ## Return extruder count according to extruder trains.
  55. @pyqtProperty(int, notify = extrudersChanged)
  56. def extruderCount(self) -> int:
  57. if not self._application.getGlobalContainerStack():
  58. return 0 # No active machine, so no extruders.
  59. try:
  60. return len(self._extruder_trains[self._application.getGlobalContainerStack().getId()])
  61. except KeyError:
  62. return 0
  63. ## Gets a dict with the extruder stack ids with the extruder number as the key.
  64. @pyqtProperty("QVariantMap", notify = extrudersChanged)
  65. def extruderIds(self) -> Dict[str, str]:
  66. extruder_stack_ids = {} # type: Dict[str, str]
  67. global_container_stack = self._application.getGlobalContainerStack()
  68. if global_container_stack:
  69. extruder_stack_ids = {position: extruder.id for position, extruder in global_container_stack.extruders.items()}
  70. return extruder_stack_ids
  71. ## Changes the active extruder by index.
  72. #
  73. # \param index The index of the new active extruder.
  74. @pyqtSlot(int)
  75. def setActiveExtruderIndex(self, index: int) -> None:
  76. self._active_extruder_index = index
  77. self.activeExtruderChanged.emit()
  78. @pyqtProperty(int, notify = activeExtruderChanged)
  79. def activeExtruderIndex(self) -> int:
  80. return self._active_extruder_index
  81. ## Gets the extruder name of an extruder of the currently active machine.
  82. #
  83. # \param index The index of the extruder whose name to get.
  84. @pyqtSlot(int, result = str)
  85. def getExtruderName(self, index: int) -> str:
  86. try:
  87. return self.getActiveExtruderStacks()[index].getName()
  88. except IndexError:
  89. return ""
  90. ## Emitted whenever the selectedObjectExtruders property changes.
  91. selectedObjectExtrudersChanged = pyqtSignal()
  92. ## Provides a list of extruder IDs used by the current selected objects.
  93. @pyqtProperty("QVariantList", notify = selectedObjectExtrudersChanged)
  94. def selectedObjectExtruders(self) -> List[str]:
  95. if not self._selected_object_extruders:
  96. object_extruders = set()
  97. # First, build a list of the actual selected objects (including children of groups, excluding group nodes)
  98. selected_nodes = [] # type: List["SceneNode"]
  99. for node in Selection.getAllSelectedObjects():
  100. if node.callDecoration("isGroup"):
  101. for grouped_node in BreadthFirstIterator(node): #type: ignore #Ignore type error because iter() should get called automatically by Python syntax.
  102. if grouped_node.callDecoration("isGroup"):
  103. continue
  104. selected_nodes.append(grouped_node)
  105. else:
  106. selected_nodes.append(node)
  107. # Then, figure out which nodes are used by those selected nodes.
  108. current_extruder_trains = self.getActiveExtruderStacks()
  109. for node in selected_nodes:
  110. extruder = node.callDecoration("getActiveExtruder")
  111. if extruder:
  112. object_extruders.add(extruder)
  113. elif current_extruder_trains:
  114. object_extruders.add(current_extruder_trains[0].getId())
  115. self._selected_object_extruders = list(object_extruders)
  116. return self._selected_object_extruders
  117. ## Reset the internal list used for the selectedObjectExtruders property
  118. #
  119. # This will trigger a recalculation of the extruders used for the
  120. # selection.
  121. def resetSelectedObjectExtruders(self) -> None:
  122. self._selected_object_extruders = []
  123. self.selectedObjectExtrudersChanged.emit()
  124. @pyqtSlot(result = QObject)
  125. def getActiveExtruderStack(self) -> Optional["ExtruderStack"]:
  126. return self.getExtruderStack(self._active_extruder_index)
  127. ## Get an extruder stack by index
  128. def getExtruderStack(self, index) -> Optional["ExtruderStack"]:
  129. global_container_stack = self._application.getGlobalContainerStack()
  130. if global_container_stack:
  131. if global_container_stack.getId() in self._extruder_trains:
  132. if str(index) in self._extruder_trains[global_container_stack.getId()]:
  133. return self._extruder_trains[global_container_stack.getId()][str(index)]
  134. return None
  135. def registerExtruder(self, extruder_train: "ExtruderStack", machine_id: str) -> None:
  136. changed = False
  137. if machine_id not in self._extruder_trains:
  138. self._extruder_trains[machine_id] = {}
  139. changed = True
  140. # do not register if an extruder has already been registered at the position on this machine
  141. if any(item.getId() == extruder_train.getId() for item in self._extruder_trains[machine_id].values()):
  142. Logger.log("w", "Extruder [%s] has already been registered on machine [%s], not doing anything",
  143. extruder_train.getId(), machine_id)
  144. return
  145. if extruder_train:
  146. self._extruder_trains[machine_id][extruder_train.getMetaDataEntry("position")] = extruder_train
  147. changed = True
  148. if changed:
  149. self.extrudersChanged.emit(machine_id)
  150. ## Gets a property of a setting for all extruders.
  151. #
  152. # \param setting_key \type{str} The setting to get the property of.
  153. # \param property \type{str} The property to get.
  154. # \return \type{List} the list of results
  155. def getAllExtruderSettings(self, setting_key: str, prop: str) -> List:
  156. result = []
  157. for extruder_stack in self.getActiveExtruderStacks():
  158. result.append(extruder_stack.getProperty(setting_key, prop))
  159. return result
  160. def extruderValueWithDefault(self, value: str) -> str:
  161. machine_manager = self._application.getMachineManager()
  162. if value == "-1":
  163. return machine_manager.defaultExtruderPosition
  164. else:
  165. return value
  166. ## Gets the extruder stacks that are actually being used at the moment.
  167. #
  168. # An extruder stack is being used if it is the extruder to print any mesh
  169. # with, or if it is the support infill extruder, the support interface
  170. # extruder, or the bed adhesion extruder.
  171. #
  172. # If there are no extruders, this returns the global stack as a singleton
  173. # list.
  174. #
  175. # \return A list of extruder stacks.
  176. def getUsedExtruderStacks(self) -> List["ContainerStack"]:
  177. global_stack = self._application.getGlobalContainerStack()
  178. container_registry = ContainerRegistry.getInstance()
  179. used_extruder_stack_ids = set()
  180. # Get the extruders of all meshes in the scene
  181. support_enabled = False
  182. support_bottom_enabled = False
  183. support_roof_enabled = False
  184. scene_root = self._application.getController().getScene().getRoot()
  185. # If no extruders are registered in the extruder manager yet, return an empty array
  186. if len(self.extruderIds) == 0:
  187. return []
  188. # Get the extruders of all printable meshes in the scene
  189. meshes = [node for node in DepthFirstIterator(scene_root) if isinstance(node, SceneNode) and node.isSelectable()] #type: ignore #Ignore type error because iter() should get called automatically by Python syntax.
  190. for mesh in meshes:
  191. extruder_stack_id = mesh.callDecoration("getActiveExtruder")
  192. if not extruder_stack_id:
  193. # No per-object settings for this node
  194. extruder_stack_id = self.extruderIds["0"]
  195. used_extruder_stack_ids.add(extruder_stack_id)
  196. # Get whether any of them use support.
  197. stack_to_use = mesh.callDecoration("getStack") # if there is a per-mesh stack, we use it
  198. if not stack_to_use:
  199. # if there is no per-mesh stack, we use the build extruder for this mesh
  200. stack_to_use = container_registry.findContainerStacks(id = extruder_stack_id)[0]
  201. support_enabled |= stack_to_use.getProperty("support_enable", "value")
  202. support_bottom_enabled |= stack_to_use.getProperty("support_bottom_enable", "value")
  203. support_roof_enabled |= stack_to_use.getProperty("support_roof_enable", "value")
  204. # Check limit to extruders
  205. limit_to_extruder_feature_list = ["wall_0_extruder_nr",
  206. "wall_x_extruder_nr",
  207. "roofing_extruder_nr",
  208. "top_bottom_extruder_nr",
  209. "infill_extruder_nr",
  210. ]
  211. for extruder_nr_feature_name in limit_to_extruder_feature_list:
  212. extruder_nr = int(global_stack.getProperty(extruder_nr_feature_name, "value"))
  213. if extruder_nr == -1:
  214. continue
  215. used_extruder_stack_ids.add(self.extruderIds[str(extruder_nr)])
  216. # Check support extruders
  217. if support_enabled:
  218. used_extruder_stack_ids.add(self.extruderIds[self.extruderValueWithDefault(str(global_stack.getProperty("support_infill_extruder_nr", "value")))])
  219. used_extruder_stack_ids.add(self.extruderIds[self.extruderValueWithDefault(str(global_stack.getProperty("support_extruder_nr_layer_0", "value")))])
  220. if support_bottom_enabled:
  221. used_extruder_stack_ids.add(self.extruderIds[self.extruderValueWithDefault(str(global_stack.getProperty("support_bottom_extruder_nr", "value")))])
  222. if support_roof_enabled:
  223. used_extruder_stack_ids.add(self.extruderIds[self.extruderValueWithDefault(str(global_stack.getProperty("support_roof_extruder_nr", "value")))])
  224. # The platform adhesion extruder. Not used if using none.
  225. if global_stack.getProperty("adhesion_type", "value") != "none":
  226. extruder_str_nr = str(global_stack.getProperty("adhesion_extruder_nr", "value"))
  227. if extruder_str_nr == "-1":
  228. extruder_str_nr = self._application.getMachineManager().defaultExtruderPosition
  229. used_extruder_stack_ids.add(self.extruderIds[extruder_str_nr])
  230. try:
  231. return [container_registry.findContainerStacks(id = stack_id)[0] for stack_id in used_extruder_stack_ids]
  232. except IndexError: # One or more of the extruders was not found.
  233. Logger.log("e", "Unable to find one or more of the extruders in %s", used_extruder_stack_ids)
  234. return []
  235. ## Removes the container stack and user profile for the extruders for a specific machine.
  236. #
  237. # \param machine_id The machine to remove the extruders for.
  238. def removeMachineExtruders(self, machine_id: str) -> None:
  239. for extruder in self.getMachineExtruders(machine_id):
  240. ContainerRegistry.getInstance().removeContainer(extruder.userChanges.getId())
  241. ContainerRegistry.getInstance().removeContainer(extruder.getId())
  242. if machine_id in self._extruder_trains:
  243. del self._extruder_trains[machine_id]
  244. ## Returns extruders for a specific machine.
  245. #
  246. # \param machine_id The machine to get the extruders of.
  247. def getMachineExtruders(self, machine_id: str) -> List["ExtruderStack"]:
  248. if machine_id not in self._extruder_trains:
  249. return []
  250. return [self._extruder_trains[machine_id][name] for name in self._extruder_trains[machine_id]]
  251. ## Returns the list of active extruder stacks, taking into account the machine extruder count.
  252. #
  253. # \return \type{List[ContainerStack]} a list of
  254. def getActiveExtruderStacks(self) -> List["ExtruderStack"]:
  255. global_stack = self._application.getGlobalContainerStack()
  256. if not global_stack:
  257. return []
  258. result_tuple_list = sorted(list(global_stack.extruders.items()), key = lambda x: int(x[0]))
  259. result_list = [item[1] for item in result_tuple_list]
  260. machine_extruder_count = global_stack.getProperty("machine_extruder_count", "value")
  261. return result_list[:machine_extruder_count]
  262. def _globalContainerStackChanged(self) -> None:
  263. # If the global container changed, the machine changed and might have extruders that were not registered yet
  264. self._addCurrentMachineExtruders()
  265. self.resetSelectedObjectExtruders()
  266. ## Adds the extruders of the currently active machine.
  267. def _addCurrentMachineExtruders(self) -> None:
  268. global_stack = self._application.getGlobalContainerStack()
  269. extruders_changed = False
  270. if global_stack:
  271. container_registry = ContainerRegistry.getInstance()
  272. global_stack_id = global_stack.getId()
  273. # Gets the extruder trains that we just created as well as any that still existed.
  274. extruder_trains = container_registry.findContainerStacks(type = "extruder_train", machine = global_stack_id)
  275. # Make sure the extruder trains for the new machine can be placed in the set of sets
  276. if global_stack_id not in self._extruder_trains:
  277. self._extruder_trains[global_stack_id] = {}
  278. extruders_changed = True
  279. # Register the extruder trains by position
  280. for extruder_train in extruder_trains:
  281. extruder_position = extruder_train.getMetaDataEntry("position")
  282. self._extruder_trains[global_stack_id][extruder_position] = extruder_train
  283. # regardless of what the next stack is, we have to set it again, because of signal routing. ???
  284. extruder_train.setParent(global_stack)
  285. extruder_train.setNextStack(global_stack)
  286. extruders_changed = True
  287. self._fixSingleExtrusionMachineExtruderDefinition(global_stack)
  288. if extruders_changed:
  289. self.extrudersChanged.emit(global_stack_id)
  290. self.setActiveExtruderIndex(0)
  291. # After 3.4, all single-extrusion machines have their own extruder definition files instead of reusing
  292. # "fdmextruder". We need to check a machine here so its extruder definition is correct according to this.
  293. def _fixSingleExtrusionMachineExtruderDefinition(self, global_stack: "GlobalStack") -> None:
  294. container_registry = ContainerRegistry.getInstance()
  295. expected_extruder_definition_0_id = global_stack.getMetaDataEntry("machine_extruder_trains")["0"]
  296. extruder_stack_0 = global_stack.extruders.get("0")
  297. # At this point, extruder stacks for this machine may not have been loaded yet. In this case, need to look in
  298. # the container registry as well.
  299. if not global_stack.extruders:
  300. extruder_trains = container_registry.findContainerStacks(type = "extruder_train",
  301. machine = global_stack.getId())
  302. if extruder_trains:
  303. for extruder in extruder_trains:
  304. if extruder.getMetaDataEntry("position") == "0":
  305. extruder_stack_0 = extruder
  306. break
  307. if extruder_stack_0 is None:
  308. Logger.log("i", "No extruder stack for global stack [%s], create one", global_stack.getId())
  309. # Single extrusion machine without an ExtruderStack, create it
  310. from cura.Settings.CuraStackBuilder import CuraStackBuilder
  311. CuraStackBuilder.createExtruderStackWithDefaultSetup(global_stack, 0)
  312. elif extruder_stack_0.definition.getId() != expected_extruder_definition_0_id:
  313. Logger.log("e", "Single extruder printer [{printer}] expected extruder [{expected}], but got [{got}]. I'm making it [{expected}].".format(
  314. printer = global_stack.getId(), expected = expected_extruder_definition_0_id, got = extruder_stack_0.definition.getId()))
  315. extruder_definition = container_registry.findDefinitionContainers(id = expected_extruder_definition_0_id)[0]
  316. extruder_stack_0.definition = extruder_definition
  317. ## Get all extruder values for a certain setting.
  318. #
  319. # This is exposed to SettingFunction so it can be used in value functions.
  320. #
  321. # \param key The key of the setting to retrieve values for.
  322. #
  323. # \return A list of values for all extruders. If an extruder does not have a value, it will not be in the list.
  324. # If no extruder has the value, the list will contain the global value.
  325. @staticmethod
  326. def getExtruderValues(key: str) -> List[Any]:
  327. global_stack = cast(GlobalStack, cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()) #We know that there must be a global stack by the time you're requesting setting values.
  328. result = []
  329. for extruder in ExtruderManager.getInstance().getActiveExtruderStacks():
  330. if not extruder.isEnabled:
  331. continue
  332. # only include values from extruders that are "active" for the current machine instance
  333. if int(extruder.getMetaDataEntry("position")) >= global_stack.getProperty("machine_extruder_count", "value"):
  334. continue
  335. value = extruder.getRawProperty(key, "value")
  336. if value is None:
  337. continue
  338. if isinstance(value, SettingFunction):
  339. value = value(extruder)
  340. result.append(value)
  341. if not result:
  342. result.append(global_stack.getProperty(key, "value"))
  343. return result
  344. ## Get all extruder values for a certain setting. This function will skip the user settings container.
  345. #
  346. # This is exposed to SettingFunction so it can be used in value functions.
  347. #
  348. # \param key The key of the setting to retrieve values for.
  349. #
  350. # \return A list of values for all extruders. If an extruder does not have a value, it will not be in the list.
  351. # If no extruder has the value, the list will contain the global value.
  352. @staticmethod
  353. def getDefaultExtruderValues(key: str) -> List[Any]:
  354. global_stack = cast(GlobalStack, cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()) #We know that there must be a global stack by the time you're requesting setting values.
  355. context = PropertyEvaluationContext(global_stack)
  356. context.context["evaluate_from_container_index"] = 1 # skip the user settings container
  357. context.context["override_operators"] = {
  358. "extruderValue": ExtruderManager.getDefaultExtruderValue,
  359. "extruderValues": ExtruderManager.getDefaultExtruderValues,
  360. "resolveOrValue": ExtruderManager.getDefaultResolveOrValue
  361. }
  362. result = []
  363. for extruder in ExtruderManager.getInstance().getActiveExtruderStacks():
  364. # only include values from extruders that are "active" for the current machine instance
  365. if int(extruder.getMetaDataEntry("position")) >= global_stack.getProperty("machine_extruder_count", "value", context = context):
  366. continue
  367. value = extruder.getRawProperty(key, "value", context = context)
  368. if value is None:
  369. continue
  370. if isinstance(value, SettingFunction):
  371. value = value(extruder, context = context)
  372. result.append(value)
  373. if not result:
  374. result.append(global_stack.getProperty(key, "value", context = context))
  375. return result
  376. ## Return the default extruder position from the machine manager
  377. @staticmethod
  378. def getDefaultExtruderPosition() -> str:
  379. return cura.CuraApplication.CuraApplication.getInstance().getMachineManager().defaultExtruderPosition
  380. ## Get all extruder values for a certain setting.
  381. #
  382. # This is exposed to qml for display purposes
  383. #
  384. # \param key The key of the setting to retrieve values for.
  385. #
  386. # \return String representing the extruder values
  387. @pyqtSlot(str, result="QVariant")
  388. def getInstanceExtruderValues(self, key) -> List:
  389. return ExtruderManager.getExtruderValues(key)
  390. ## Get the value for a setting from a specific extruder.
  391. #
  392. # This is exposed to SettingFunction to use in value functions.
  393. #
  394. # \param extruder_index The index of the extruder to get the value from.
  395. # \param key The key of the setting to get the value of.
  396. #
  397. # \return The value of the setting for the specified extruder or for the
  398. # global stack if not found.
  399. @staticmethod
  400. def getExtruderValue(extruder_index: int, key: str) -> Any:
  401. if extruder_index == -1:
  402. extruder_index = int(cura.CuraApplication.CuraApplication.getInstance().getMachineManager().defaultExtruderPosition)
  403. extruder = ExtruderManager.getInstance().getExtruderStack(extruder_index)
  404. if extruder:
  405. value = extruder.getRawProperty(key, "value")
  406. if isinstance(value, SettingFunction):
  407. value = value(extruder)
  408. else:
  409. # Just a value from global.
  410. value = cast(GlobalStack, cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()).getProperty(key, "value")
  411. return value
  412. ## Get the default value from the given extruder. This function will skip the user settings container.
  413. #
  414. # This is exposed to SettingFunction to use in value functions.
  415. #
  416. # \param extruder_index The index of the extruder to get the value from.
  417. # \param key The key of the setting to get the value of.
  418. #
  419. # \return The value of the setting for the specified extruder or for the
  420. # global stack if not found.
  421. @staticmethod
  422. def getDefaultExtruderValue(extruder_index: int, key: str) -> Any:
  423. extruder = ExtruderManager.getInstance().getExtruderStack(extruder_index)
  424. context = PropertyEvaluationContext(extruder)
  425. context.context["evaluate_from_container_index"] = 1 # skip the user settings container
  426. context.context["override_operators"] = {
  427. "extruderValue": ExtruderManager.getDefaultExtruderValue,
  428. "extruderValues": ExtruderManager.getDefaultExtruderValues,
  429. "resolveOrValue": ExtruderManager.getDefaultResolveOrValue
  430. }
  431. if extruder:
  432. value = extruder.getRawProperty(key, "value", context = context)
  433. if isinstance(value, SettingFunction):
  434. value = value(extruder, context = context)
  435. else: # Just a value from global.
  436. value = cast(GlobalStack, cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()).getProperty(key, "value", context = context)
  437. return value
  438. ## Get the resolve value or value for a given key
  439. #
  440. # This is the effective value for a given key, it is used for values in the global stack.
  441. # This is exposed to SettingFunction to use in value functions.
  442. # \param key The key of the setting to get the value of.
  443. #
  444. # \return The effective value
  445. @staticmethod
  446. def getResolveOrValue(key: str) -> Any:
  447. global_stack = cast(GlobalStack, cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack())
  448. resolved_value = global_stack.getProperty(key, "value")
  449. return resolved_value
  450. ## Get the resolve value or value for a given key without looking the first container (user container)
  451. #
  452. # This is the effective value for a given key, it is used for values in the global stack.
  453. # This is exposed to SettingFunction to use in value functions.
  454. # \param key The key of the setting to get the value of.
  455. #
  456. # \return The effective value
  457. @staticmethod
  458. def getDefaultResolveOrValue(key: str) -> Any:
  459. global_stack = cast(GlobalStack, cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack())
  460. context = PropertyEvaluationContext(global_stack)
  461. context.context["evaluate_from_container_index"] = 1 # skip the user settings container
  462. context.context["override_operators"] = {
  463. "extruderValue": ExtruderManager.getDefaultExtruderValue,
  464. "extruderValues": ExtruderManager.getDefaultExtruderValues,
  465. "resolveOrValue": ExtruderManager.getDefaultResolveOrValue
  466. }
  467. resolved_value = global_stack.getProperty(key, "value", context = context)
  468. return resolved_value
  469. __instance = None # type: ExtruderManager
  470. @classmethod
  471. def getInstance(cls, *args, **kwargs) -> "ExtruderManager":
  472. return cls.__instance