ExtruderManager.py 36 KB

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