ExtruderManager.py 36 KB

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