ExtruderManager.py 32 KB

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