ExtruderManager.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. # Copyright (c) 2017 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 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. from UM.Application import Application #To get the global container stack to find the current machine.
  6. from UM.Logger import Logger
  7. from UM.Decorators import deprecated
  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.InstanceContainer import InstanceContainer
  14. from UM.Settings.SettingFunction import SettingFunction
  15. from UM.Settings.ContainerStack import ContainerStack
  16. from UM.Settings.DefinitionContainer import DefinitionContainer
  17. from typing import Optional, List, TYPE_CHECKING, Union
  18. if TYPE_CHECKING:
  19. from cura.Settings.ExtruderStack import ExtruderStack
  20. from cura.Settings.GlobalStack import GlobalStack
  21. ## Manages all existing extruder stacks.
  22. #
  23. # This keeps a list of extruder stacks for each machine.
  24. class ExtruderManager(QObject):
  25. ## Signal to notify other components when the list of extruders for a machine definition changes.
  26. extrudersChanged = pyqtSignal(QVariant)
  27. ## Signal to notify other components when the global container stack is switched to a definition
  28. # that has different extruders than the previous global container stack
  29. globalContainerStackDefinitionChanged = pyqtSignal()
  30. ## Notify when the user switches the currently active extruder.
  31. activeExtruderChanged = pyqtSignal()
  32. ## Registers listeners and such to listen to changes to the extruders.
  33. def __init__(self, parent = None):
  34. super().__init__(parent)
  35. self._extruder_trains = { } #Per machine, a dictionary of extruder container stack IDs. Only for separately defined extruders.
  36. self._active_extruder_index = 0
  37. self._selected_object_extruders = []
  38. Application.getInstance().globalContainerStackChanged.connect(self.__globalContainerStackChanged)
  39. self._global_container_stack_definition_id = None
  40. self._addCurrentMachineExtruders()
  41. Selection.selectionChanged.connect(self.resetSelectedObjectExtruders)
  42. ## Gets the unique identifier of the currently active extruder stack.
  43. #
  44. # The currently active extruder stack is the stack that is currently being
  45. # edited.
  46. #
  47. # \return The unique ID of the currently active extruder stack.
  48. @pyqtProperty(str, notify = activeExtruderChanged)
  49. def activeExtruderStackId(self) -> Optional[str]:
  50. if not Application.getInstance().getGlobalContainerStack():
  51. return None # No active machine, so no active extruder.
  52. try:
  53. return self._extruder_trains[Application.getInstance().getGlobalContainerStack().getId()][str(self._active_extruder_index)].getId()
  54. 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.
  55. return None
  56. ## Return extruder count according to extruder trains.
  57. @pyqtProperty(int, notify = extrudersChanged)
  58. def extruderCount(self):
  59. if not Application.getInstance().getGlobalContainerStack():
  60. return 0 # No active machine, so no extruders.
  61. try:
  62. return len(self._extruder_trains[Application.getInstance().getGlobalContainerStack().getId()])
  63. except KeyError:
  64. return 0
  65. @pyqtProperty("QVariantMap", notify=extrudersChanged)
  66. def extruderIds(self):
  67. map = {}
  68. for position in self._extruder_trains[Application.getInstance().getGlobalContainerStack().getId()]:
  69. map[position] = self._extruder_trains[Application.getInstance().getGlobalContainerStack().getId()][position].getId()
  70. return map
  71. @pyqtSlot(str, result = str)
  72. def getQualityChangesIdByExtruderStackId(self, id: str) -> str:
  73. for position in self._extruder_trains[Application.getInstance().getGlobalContainerStack().getId()]:
  74. extruder = self._extruder_trains[Application.getInstance().getGlobalContainerStack().getId()][position]
  75. if extruder.getId() == id:
  76. return extruder.qualityChanges.getId()
  77. ## The instance of the singleton pattern.
  78. #
  79. # It's None if the extruder manager hasn't been created yet.
  80. __instance = None
  81. ## Gets an instance of the extruder manager, or creates one if no instance
  82. # exists yet.
  83. #
  84. # This is an implementation of singleton. If an extruder manager already
  85. # exists, it is re-used.
  86. #
  87. # \return The extruder manager.
  88. @classmethod
  89. def getInstance(cls) -> "ExtruderManager":
  90. if not cls.__instance:
  91. cls.__instance = ExtruderManager()
  92. return cls.__instance
  93. ## Changes the active extruder by index.
  94. #
  95. # \param index The index of the new active extruder.
  96. @pyqtSlot(int)
  97. def setActiveExtruderIndex(self, index: int) -> None:
  98. self._active_extruder_index = index
  99. self.activeExtruderChanged.emit()
  100. @pyqtProperty(int, notify = activeExtruderChanged)
  101. def activeExtruderIndex(self) -> int:
  102. return self._active_extruder_index
  103. ## Gets the extruder name of an extruder of the currently active machine.
  104. #
  105. # \param index The index of the extruder whose name to get.
  106. @pyqtSlot(int, result = str)
  107. def getExtruderName(self, index):
  108. try:
  109. return list(self.getActiveExtruderStacks())[index].getName()
  110. except IndexError:
  111. return ""
  112. ## Emitted whenever the selectedObjectExtruders property changes.
  113. selectedObjectExtrudersChanged = pyqtSignal()
  114. ## Provides a list of extruder IDs used by the current selected objects.
  115. @pyqtProperty("QVariantList", notify = selectedObjectExtrudersChanged)
  116. def selectedObjectExtruders(self) -> List[str]:
  117. if not self._selected_object_extruders:
  118. object_extruders = set()
  119. # First, build a list of the actual selected objects (including children of groups, excluding group nodes)
  120. selected_nodes = []
  121. for node in Selection.getAllSelectedObjects():
  122. if node.callDecoration("isGroup"):
  123. for grouped_node in BreadthFirstIterator(node):
  124. if grouped_node.callDecoration("isGroup"):
  125. continue
  126. selected_nodes.append(grouped_node)
  127. else:
  128. selected_nodes.append(node)
  129. # Then, figure out which nodes are used by those selected nodes.
  130. for node in selected_nodes:
  131. extruder = node.callDecoration("getActiveExtruder")
  132. if extruder:
  133. object_extruders.add(extruder)
  134. else:
  135. global_stack = Application.getInstance().getGlobalContainerStack()
  136. if global_stack.getId() in self._extruder_trains:
  137. object_extruders.add(self._extruder_trains[global_stack.getId()]["0"].getId())
  138. self._selected_object_extruders = list(object_extruders)
  139. return self._selected_object_extruders
  140. ## Reset the internal list used for the selectedObjectExtruders property
  141. #
  142. # This will trigger a recalculation of the extruders used for the
  143. # selection.
  144. def resetSelectedObjectExtruders(self) -> None:
  145. self._selected_object_extruders = []
  146. self.selectedObjectExtrudersChanged.emit()
  147. def getActiveExtruderStack(self) -> Optional["ExtruderStack"]:
  148. global_container_stack = Application.getInstance().getGlobalContainerStack()
  149. if global_container_stack:
  150. if global_container_stack.getId() in self._extruder_trains:
  151. if str(self._active_extruder_index) in self._extruder_trains[global_container_stack.getId()]:
  152. return self._extruder_trains[global_container_stack.getId()][str(self._active_extruder_index)]
  153. return None
  154. ## Get an extruder stack by index
  155. def getExtruderStack(self, index) -> Optional["ExtruderStack"]:
  156. global_container_stack = Application.getInstance().getGlobalContainerStack()
  157. if global_container_stack:
  158. if global_container_stack.getId() in self._extruder_trains:
  159. if str(index) in self._extruder_trains[global_container_stack.getId()]:
  160. return self._extruder_trains[global_container_stack.getId()][str(index)]
  161. return None
  162. ## Get all extruder stacks
  163. def getExtruderStacks(self) -> List["ExtruderStack"]:
  164. result = []
  165. for i in range(self.extruderCount):
  166. result.append(self.getExtruderStack(i))
  167. return result
  168. ## Adds all extruders of a specific machine definition to the extruder
  169. # manager.
  170. #
  171. # \param machine_definition The machine definition to add the extruders for.
  172. # \param machine_id The machine_id to add the extruders for.
  173. @deprecated("Use CuraStackBuilder", "2.6")
  174. def addMachineExtruders(self, machine_definition: DefinitionContainer, machine_id: str) -> None:
  175. changed = False
  176. machine_definition_id = machine_definition.getId()
  177. if machine_id not in self._extruder_trains:
  178. self._extruder_trains[machine_id] = { }
  179. changed = True
  180. container_registry = ContainerRegistry.getInstance()
  181. if container_registry:
  182. # Add the extruder trains that don't exist yet.
  183. for extruder_definition in container_registry.findDefinitionContainers(machine = machine_definition_id):
  184. position = extruder_definition.getMetaDataEntry("position", None)
  185. if not position:
  186. Logger.log("w", "Extruder definition %s specifies no position metadata entry.", extruder_definition.getId())
  187. if not container_registry.findContainerStacks(machine = machine_id, position = position): # Doesn't exist yet.
  188. self.createExtruderTrain(extruder_definition, machine_definition, position, machine_id)
  189. changed = True
  190. # Gets the extruder trains that we just created as well as any that still existed.
  191. extruder_trains = container_registry.findContainerStacks(type = "extruder_train", machine = machine_id)
  192. for extruder_train in extruder_trains:
  193. self._extruder_trains[machine_id][extruder_train.getMetaDataEntry("position")] = extruder_train
  194. # regardless of what the next stack is, we have to set it again, because of signal routing.
  195. extruder_train.setNextStack(Application.getInstance().getGlobalContainerStack())
  196. changed = True
  197. if changed:
  198. self.extrudersChanged.emit(machine_id)
  199. def registerExtruder(self, extruder_train, machine_id):
  200. changed = False
  201. if machine_id not in self._extruder_trains:
  202. self._extruder_trains[machine_id] = {}
  203. changed = True
  204. if extruder_train:
  205. self._extruder_trains[machine_id][extruder_train.getMetaDataEntry("position")] = extruder_train
  206. changed = True
  207. if changed:
  208. self.extrudersChanged.emit(machine_id)
  209. ## Creates a container stack for an extruder train.
  210. #
  211. # The container stack has an extruder definition at the bottom, which is
  212. # linked to a machine definition. Then it has a variant profile, a material
  213. # profile, a quality profile and a user profile, in that order.
  214. #
  215. # The resulting container stack is added to the registry.
  216. #
  217. # \param extruder_definition The extruder to create the extruder train for.
  218. # \param machine_definition The machine that the extruder train belongs to.
  219. # \param position The position of this extruder train in the extruder slots of the machine.
  220. # \param machine_id The id of the "global" stack this extruder is linked to.
  221. @deprecated("Use CuraStackBuilder::createExtruderStack", "2.6")
  222. def createExtruderTrain(self, extruder_definition: DefinitionContainer, machine_definition: DefinitionContainer,
  223. position, machine_id: str) -> None:
  224. # Cache some things.
  225. container_registry = ContainerRegistry.getInstance()
  226. machine_definition_id = Application.getInstance().getMachineManager().getQualityDefinitionId(machine_definition)
  227. # Create a container stack for this extruder.
  228. extruder_stack_id = container_registry.uniqueName(extruder_definition.getId())
  229. container_stack = ContainerStack(extruder_stack_id)
  230. container_stack.setName(extruder_definition.getName()) # Take over the display name to display the stack with.
  231. container_stack.addMetaDataEntry("type", "extruder_train")
  232. container_stack.addMetaDataEntry("machine", machine_id)
  233. container_stack.addMetaDataEntry("position", position)
  234. container_stack.addContainer(extruder_definition)
  235. # Find the variant to use for this extruder.
  236. variant = container_registry.findInstanceContainers(id = "empty_variant")[0]
  237. if machine_definition.getMetaDataEntry("has_variants"):
  238. # First add any variant. Later, overwrite with preference if the preference is valid.
  239. variants = container_registry.findInstanceContainers(definition = machine_definition_id, type = "variant")
  240. if len(variants) >= 1:
  241. variant = variants[0]
  242. preferred_variant_id = machine_definition.getMetaDataEntry("preferred_variant")
  243. if preferred_variant_id:
  244. preferred_variants = container_registry.findInstanceContainers(id = preferred_variant_id, definition = machine_definition_id, type = "variant")
  245. if len(preferred_variants) >= 1:
  246. variant = preferred_variants[0]
  247. else:
  248. Logger.log("w", "The preferred variant \"%s\" of machine %s doesn't exist or is not a variant profile.", preferred_variant_id, machine_id)
  249. # And leave it at the default variant.
  250. container_stack.addContainer(variant)
  251. # Find a material to use for this variant.
  252. material = container_registry.findInstanceContainers(id = "empty_material")[0]
  253. if machine_definition.getMetaDataEntry("has_materials"):
  254. # First add any material. Later, overwrite with preference if the preference is valid.
  255. machine_has_variant_materials = machine_definition.getMetaDataEntry("has_variant_materials", default = False)
  256. if machine_has_variant_materials or machine_has_variant_materials == "True":
  257. materials = container_registry.findInstanceContainers(type = "material", definition = machine_definition_id, variant = variant.getId())
  258. else:
  259. materials = container_registry.findInstanceContainers(type = "material", definition = machine_definition_id)
  260. if len(materials) >= 1:
  261. material = materials[0]
  262. preferred_material_id = machine_definition.getMetaDataEntry("preferred_material")
  263. if preferred_material_id:
  264. global_stack = ContainerRegistry.getInstance().findContainerStacks(id = machine_id)
  265. if global_stack:
  266. approximate_material_diameter = round(global_stack[0].getProperty("material_diameter", "value"))
  267. else:
  268. approximate_material_diameter = round(machine_definition.getProperty("material_diameter", "value"))
  269. search_criteria = { "type": "material", "id": preferred_material_id, "approximate_diameter": approximate_material_diameter}
  270. if machine_definition.getMetaDataEntry("has_machine_materials"):
  271. search_criteria["definition"] = machine_definition_id
  272. if machine_definition.getMetaDataEntry("has_variants") and variant:
  273. search_criteria["variant"] = variant.id
  274. else:
  275. search_criteria["definition"] = "fdmprinter"
  276. preferred_materials = container_registry.findInstanceContainers(**search_criteria)
  277. if len(preferred_materials) >= 1:
  278. # In some cases we get multiple materials. In that case, prefer materials that are marked as read only.
  279. read_only_preferred_materials = [preferred_material for preferred_material in preferred_materials if preferred_material.isReadOnly()]
  280. if len(read_only_preferred_materials) >= 1:
  281. material = read_only_preferred_materials[0]
  282. else:
  283. material = preferred_materials[0]
  284. else:
  285. Logger.log("w", "The preferred material \"%s\" of machine %s doesn't exist or is not a material profile.", preferred_material_id, machine_id)
  286. # And leave it at the default material.
  287. container_stack.addContainer(material)
  288. # Find a quality to use for this extruder.
  289. quality = container_registry.getEmptyInstanceContainer()
  290. search_criteria = { "type": "quality" }
  291. if machine_definition.getMetaDataEntry("has_machine_quality"):
  292. search_criteria["definition"] = machine_definition_id
  293. if machine_definition.getMetaDataEntry("has_materials") and material:
  294. search_criteria["material"] = material.id
  295. else:
  296. search_criteria["definition"] = "fdmprinter"
  297. preferred_quality = machine_definition.getMetaDataEntry("preferred_quality")
  298. if preferred_quality:
  299. search_criteria["id"] = preferred_quality
  300. containers = ContainerRegistry.getInstance().findInstanceContainers(**search_criteria)
  301. if not containers and preferred_quality:
  302. Logger.log("w", "The preferred quality \"%s\" of machine %s doesn't exist or is not a quality profile.", preferred_quality, machine_id)
  303. search_criteria.pop("id", None)
  304. containers = ContainerRegistry.getInstance().findInstanceContainers(**search_criteria)
  305. if containers:
  306. quality = containers[0]
  307. container_stack.addContainer(quality)
  308. empty_quality_changes = container_registry.findInstanceContainers(id = "empty_quality_changes")[0]
  309. container_stack.addContainer(empty_quality_changes)
  310. user_profile = container_registry.findInstanceContainers(type = "user", extruder = extruder_stack_id)
  311. if user_profile: # There was already a user profile, loaded from settings.
  312. user_profile = user_profile[0]
  313. else:
  314. user_profile = InstanceContainer(extruder_stack_id + "_current_settings") # Add an empty user profile.
  315. user_profile.addMetaDataEntry("type", "user")
  316. user_profile.addMetaDataEntry("extruder", extruder_stack_id)
  317. from cura.CuraApplication import CuraApplication
  318. user_profile.addMetaDataEntry("setting_version", CuraApplication.SettingVersion)
  319. user_profile.setDefinition(machine_definition)
  320. container_registry.addContainer(user_profile)
  321. container_stack.addContainer(user_profile)
  322. # regardless of what the next stack is, we have to set it again, because of signal routing.
  323. container_stack.setNextStack(Application.getInstance().getGlobalContainerStack())
  324. container_registry.addContainer(container_stack)
  325. def getAllExtruderValues(self, setting_key):
  326. return self.getAllExtruderSettings(setting_key, "value")
  327. ## Gets a property of a setting for all extruders.
  328. #
  329. # \param setting_key \type{str} The setting to get the property of.
  330. # \param property \type{str} The property to get.
  331. # \return \type{List} the list of results
  332. def getAllExtruderSettings(self, setting_key, property):
  333. global_container_stack = Application.getInstance().getGlobalContainerStack()
  334. if global_container_stack.getProperty("machine_extruder_count", "value") <= 1:
  335. return [global_container_stack.getProperty(setting_key, property)]
  336. result = []
  337. for index in self.extruderIds:
  338. extruder_stack_id = self.extruderIds[str(index)]
  339. stack = ContainerRegistry.getInstance().findContainerStacks(id = extruder_stack_id)[0]
  340. result.append(stack.getProperty(setting_key, property))
  341. return result
  342. ## Gets the extruder stacks that are actually being used at the moment.
  343. #
  344. # An extruder stack is being used if it is the extruder to print any mesh
  345. # with, or if it is the support infill extruder, the support interface
  346. # extruder, or the bed adhesion extruder.
  347. #
  348. # If there are no extruders, this returns the global stack as a singleton
  349. # list.
  350. #
  351. # \return A list of extruder stacks.
  352. def getUsedExtruderStacks(self) -> List["ContainerStack"]:
  353. global_stack = Application.getInstance().getGlobalContainerStack()
  354. container_registry = ContainerRegistry.getInstance()
  355. if global_stack.getProperty("machine_extruder_count", "value") <= 1: #For single extrusion.
  356. return [global_stack]
  357. used_extruder_stack_ids = set()
  358. #Get the extruders of all meshes in the scene.
  359. support_enabled = False
  360. support_bottom_enabled = False
  361. support_roof_enabled = False
  362. scene_root = Application.getInstance().getController().getScene().getRoot()
  363. meshes = [node for node in DepthFirstIterator(scene_root) if type(node) is SceneNode and node.isSelectable()] #Only use the nodes that will be printed.
  364. for mesh in meshes:
  365. extruder_stack_id = mesh.callDecoration("getActiveExtruder")
  366. if not extruder_stack_id: #No per-object settings for this node.
  367. extruder_stack_id = self.extruderIds["0"]
  368. used_extruder_stack_ids.add(extruder_stack_id)
  369. #Get whether any of them use support.
  370. per_mesh_stack = mesh.callDecoration("getStack")
  371. if per_mesh_stack:
  372. support_enabled |= per_mesh_stack.getProperty("support_enable", "value")
  373. support_bottom_enabled |= per_mesh_stack.getProperty("support_bottom_enable", "value")
  374. support_roof_enabled |= per_mesh_stack.getProperty("support_roof_enable", "value")
  375. else: #Take the setting from the build extruder stack.
  376. extruder_stack = container_registry.findContainerStacks(id = extruder_stack_id)[0]
  377. support_enabled |= extruder_stack.getProperty("support_enable", "value")
  378. support_bottom_enabled |= extruder_stack.getProperty("support_bottom_enable", "value")
  379. support_roof_enabled |= extruder_stack.getProperty("support_roof_enable", "value")
  380. #The support extruders.
  381. if support_enabled:
  382. used_extruder_stack_ids.add(self.extruderIds[str(global_stack.getProperty("support_infill_extruder_nr", "value"))])
  383. used_extruder_stack_ids.add(self.extruderIds[str(global_stack.getProperty("support_extruder_nr_layer_0", "value"))])
  384. if support_bottom_enabled:
  385. used_extruder_stack_ids.add(self.extruderIds[str(global_stack.getProperty("support_bottom_extruder_nr", "value"))])
  386. if support_roof_enabled:
  387. used_extruder_stack_ids.add(self.extruderIds[str(global_stack.getProperty("support_roof_extruder_nr", "value"))])
  388. #The platform adhesion extruder. Not used if using none.
  389. if global_stack.getProperty("adhesion_type", "value") != "none":
  390. used_extruder_stack_ids.add(self.extruderIds[str(global_stack.getProperty("adhesion_extruder_nr", "value"))])
  391. try:
  392. return [container_registry.findContainerStacks(id = stack_id)[0] for stack_id in used_extruder_stack_ids]
  393. except IndexError: # One or more of the extruders was not found.
  394. Logger.log("e", "Unable to find one or more of the extruders in %s", used_extruder_stack_ids)
  395. return []
  396. ## Removes the container stack and user profile for the extruders for a specific machine.
  397. #
  398. # \param machine_id The machine to remove the extruders for.
  399. def removeMachineExtruders(self, machine_id: str):
  400. for extruder in self.getMachineExtruders(machine_id):
  401. ContainerRegistry.getInstance().removeContainer(extruder.userChanges.getId())
  402. ContainerRegistry.getInstance().removeContainer(extruder.getId())
  403. ## Returns extruders for a specific machine.
  404. #
  405. # \param machine_id The machine to get the extruders of.
  406. def getMachineExtruders(self, machine_id: str):
  407. if machine_id not in self._extruder_trains:
  408. return []
  409. return [self._extruder_trains[machine_id][name] for name in self._extruder_trains[machine_id]]
  410. ## Returns a list containing the global stack and active extruder stacks.
  411. #
  412. # The first element is the global container stack, followed by any extruder stacks.
  413. # \return \type{List[ContainerStack]}
  414. def getActiveGlobalAndExtruderStacks(self) -> Optional[List[Union["ExtruderStack", "GlobalStack"]]]:
  415. global_stack = Application.getInstance().getGlobalContainerStack()
  416. if not global_stack:
  417. return None
  418. result = [global_stack]
  419. result.extend(self.getActiveExtruderStacks())
  420. return result
  421. ## Returns the list of active extruder stacks.
  422. #
  423. # \return \type{List[ContainerStack]} a list of
  424. def getActiveExtruderStacks(self) -> List["ExtruderStack"]:
  425. global_stack = Application.getInstance().getGlobalContainerStack()
  426. result = []
  427. if global_stack and global_stack.getId() in self._extruder_trains:
  428. for extruder in sorted(self._extruder_trains[global_stack.getId()]):
  429. result.append(self._extruder_trains[global_stack.getId()][extruder])
  430. return result
  431. def __globalContainerStackChanged(self) -> None:
  432. global_container_stack = Application.getInstance().getGlobalContainerStack()
  433. if global_container_stack and global_container_stack.getBottom() and global_container_stack.getBottom().getId() != self._global_container_stack_definition_id:
  434. self._global_container_stack_definition_id = global_container_stack.getBottom().getId()
  435. self.globalContainerStackDefinitionChanged.emit()
  436. self.activeExtruderChanged.emit()
  437. self.resetSelectedObjectExtruders()
  438. ## Adds the extruders of the currently active machine.
  439. def _addCurrentMachineExtruders(self) -> None:
  440. global_stack = Application.getInstance().getGlobalContainerStack()
  441. if global_stack and global_stack.getBottom():
  442. self.addMachineExtruders(global_stack.getBottom(), global_stack.getId())
  443. ## Get all extruder values for a certain setting.
  444. #
  445. # This is exposed to SettingFunction so it can be used in value functions.
  446. #
  447. # \param key The key of the setting to retieve values for.
  448. #
  449. # \return A list of values for all extruders. If an extruder does not have a value, it will not be in the list.
  450. # If no extruder has the value, the list will contain the global value.
  451. @staticmethod
  452. def getExtruderValues(key):
  453. global_stack = Application.getInstance().getGlobalContainerStack()
  454. result = []
  455. for extruder in ExtruderManager.getInstance().getMachineExtruders(global_stack.getId()):
  456. # only include values from extruders that are "active" for the current machine instance
  457. if int(extruder.getMetaDataEntry("position")) >= global_stack.getProperty("machine_extruder_count", "value"):
  458. continue
  459. value = extruder.getRawProperty(key, "value")
  460. if value is None:
  461. continue
  462. if isinstance(value, SettingFunction):
  463. value = value(extruder)
  464. result.append(value)
  465. if not result:
  466. result.append(global_stack.getProperty(key, "value"))
  467. return result
  468. ## Get all extruder values for a certain setting.
  469. #
  470. # This is exposed to qml for display purposes
  471. #
  472. # \param key The key of the setting to retieve values for.
  473. #
  474. # \return String representing the extruder values
  475. @pyqtSlot(str, result="QVariant")
  476. def getInstanceExtruderValues(self, key):
  477. return ExtruderManager.getExtruderValues(key)
  478. ## Get the value for a setting from a specific extruder.
  479. #
  480. # This is exposed to SettingFunction to use in value functions.
  481. #
  482. # \param extruder_index The index of the extruder to get the value from.
  483. # \param key The key of the setting to get the value of.
  484. #
  485. # \return The value of the setting for the specified extruder or for the
  486. # global stack if not found.
  487. @staticmethod
  488. def getExtruderValue(extruder_index, key):
  489. extruder = ExtruderManager.getInstance().getExtruderStack(extruder_index)
  490. if extruder:
  491. value = extruder.getRawProperty(key, "value")
  492. if isinstance(value, SettingFunction):
  493. value = value(extruder)
  494. else: #Just a value from global.
  495. value = Application.getInstance().getGlobalContainerStack().getProperty(key, "value")
  496. return value
  497. ## Get the resolve value or value for a given key
  498. #
  499. # This is the effective value for a given key, it is used for values in the global stack.
  500. # This is exposed to SettingFunction to use in value functions.
  501. # \param key The key of the setting to get the value of.
  502. #
  503. # \return The effective value
  504. @staticmethod
  505. def getResolveOrValue(key):
  506. global_stack = Application.getInstance().getGlobalContainerStack()
  507. resolved_value = global_stack.getProperty(key, "value")
  508. return resolved_value