ExtruderManager.py 31 KB

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