ExtruderManager.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  8. from UM.Scene.SceneNode import SceneNode
  9. from UM.Scene.Selection import Selection
  10. from UM.Scene.Iterator.BreadthFirstIterator import BreadthFirstIterator
  11. from UM.Settings.ContainerRegistry import ContainerRegistry # Finding containers by ID.
  12. from UM.Settings.SettingFunction import SettingFunction
  13. from UM.Settings.SettingInstance import SettingInstance
  14. from UM.Settings.ContainerStack import ContainerStack
  15. from UM.Settings.PropertyEvaluationContext import PropertyEvaluationContext
  16. from typing import Optional, List, TYPE_CHECKING, Union
  17. if TYPE_CHECKING:
  18. from cura.Settings.ExtruderStack import ExtruderStack
  19. from cura.Settings.GlobalStack import GlobalStack
  20. ## Manages all existing extruder stacks.
  21. #
  22. # This keeps a list of extruder stacks for each machine.
  23. class ExtruderManager(QObject):
  24. ## Registers listeners and such to listen to changes to the extruders.
  25. def __init__(self, parent = None):
  26. if ExtruderManager.__instance is not None:
  27. raise RuntimeError("Try to create singleton '%s' more than once" % self.__class__.__name__)
  28. ExtruderManager.__instance = self
  29. super().__init__(parent)
  30. self._application = Application.getInstance()
  31. self._extruder_trains = {} # Per machine, a dictionary of extruder container stack IDs. Only for separately defined extruders.
  32. self._active_extruder_index = -1 # Indicates the index of the active extruder stack. -1 means no active extruder stack
  33. self._selected_object_extruders = []
  34. self._addCurrentMachineExtruders()
  35. #Application.getInstance().globalContainerStackChanged.connect(self._globalContainerStackChanged)
  36. Selection.selectionChanged.connect(self.resetSelectedObjectExtruders)
  37. ## Signal to notify other components when the list of extruders for a machine definition changes.
  38. extrudersChanged = pyqtSignal(QVariant)
  39. ## Notify when the user switches the currently active extruder.
  40. activeExtruderChanged = pyqtSignal()
  41. ## Gets the unique identifier of the currently active extruder stack.
  42. #
  43. # The currently active extruder stack is the stack that is currently being
  44. # edited.
  45. #
  46. # \return The unique ID of the currently active extruder stack.
  47. @pyqtProperty(str, notify = activeExtruderChanged)
  48. def activeExtruderStackId(self) -> Optional[str]:
  49. if not Application.getInstance().getGlobalContainerStack():
  50. return None # No active machine, so no active extruder.
  51. try:
  52. return self._extruder_trains[Application.getInstance().getGlobalContainerStack().getId()][str(self._active_extruder_index)].getId()
  53. 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.
  54. return None
  55. ## Return extruder count according to extruder trains.
  56. @pyqtProperty(int, notify = extrudersChanged)
  57. def extruderCount(self):
  58. if not Application.getInstance().getGlobalContainerStack():
  59. return 0 # No active machine, so no extruders.
  60. try:
  61. return len(self._extruder_trains[Application.getInstance().getGlobalContainerStack().getId()])
  62. except KeyError:
  63. return 0
  64. ## Gets a dict with the extruder stack ids with the extruder number as the key.
  65. @pyqtProperty("QVariantMap", notify = extrudersChanged)
  66. def extruderIds(self):
  67. extruder_stack_ids = {}
  68. global_stack_id = Application.getInstance().getGlobalContainerStack().getId()
  69. if global_stack_id in self._extruder_trains:
  70. for position in self._extruder_trains[global_stack_id]:
  71. extruder_stack_ids[position] = self._extruder_trains[global_stack_id][position].getId()
  72. return extruder_stack_ids
  73. @pyqtSlot(str, result = str)
  74. def getQualityChangesIdByExtruderStackId(self, extruder_stack_id: str) -> str:
  75. for position in self._extruder_trains[Application.getInstance().getGlobalContainerStack().getId()]:
  76. extruder = self._extruder_trains[Application.getInstance().getGlobalContainerStack().getId()][position]
  77. if extruder.getId() == extruder_stack_id:
  78. return extruder.qualityChanges.getId()
  79. ## Changes the active extruder by index.
  80. #
  81. # \param index The index of the new active extruder.
  82. @pyqtSlot(int)
  83. def setActiveExtruderIndex(self, index: int) -> None:
  84. self._active_extruder_index = index
  85. self.activeExtruderChanged.emit()
  86. @pyqtProperty(int, notify = activeExtruderChanged)
  87. def activeExtruderIndex(self) -> int:
  88. return self._active_extruder_index
  89. ## Gets the extruder name of an extruder of the currently active machine.
  90. #
  91. # \param index The index of the extruder whose name to get.
  92. @pyqtSlot(int, result = str)
  93. def getExtruderName(self, index):
  94. try:
  95. return list(self.getActiveExtruderStacks())[index].getName()
  96. except IndexError:
  97. return ""
  98. ## Emitted whenever the selectedObjectExtruders property changes.
  99. selectedObjectExtrudersChanged = pyqtSignal()
  100. ## Provides a list of extruder IDs used by the current selected objects.
  101. @pyqtProperty("QVariantList", notify = selectedObjectExtrudersChanged)
  102. def selectedObjectExtruders(self) -> List[str]:
  103. if not self._selected_object_extruders:
  104. object_extruders = set()
  105. # First, build a list of the actual selected objects (including children of groups, excluding group nodes)
  106. selected_nodes = []
  107. for node in Selection.getAllSelectedObjects():
  108. if node.callDecoration("isGroup"):
  109. for grouped_node in BreadthFirstIterator(node):
  110. if grouped_node.callDecoration("isGroup"):
  111. continue
  112. selected_nodes.append(grouped_node)
  113. else:
  114. selected_nodes.append(node)
  115. # Then, figure out which nodes are used by those selected nodes.
  116. global_stack = Application.getInstance().getGlobalContainerStack()
  117. current_extruder_trains = self._extruder_trains.get(global_stack.getId())
  118. for node in selected_nodes:
  119. extruder = node.callDecoration("getActiveExtruder")
  120. if extruder:
  121. object_extruders.add(extruder)
  122. elif current_extruder_trains:
  123. object_extruders.add(current_extruder_trains["0"].getId())
  124. self._selected_object_extruders = list(object_extruders)
  125. return self._selected_object_extruders
  126. ## Reset the internal list used for the selectedObjectExtruders property
  127. #
  128. # This will trigger a recalculation of the extruders used for the
  129. # selection.
  130. def resetSelectedObjectExtruders(self) -> None:
  131. self._selected_object_extruders = []
  132. self.selectedObjectExtrudersChanged.emit()
  133. @pyqtSlot(result = QObject)
  134. def getActiveExtruderStack(self) -> Optional["ExtruderStack"]:
  135. global_container_stack = Application.getInstance().getGlobalContainerStack()
  136. if global_container_stack:
  137. if global_container_stack.getId() in self._extruder_trains:
  138. if str(self._active_extruder_index) in self._extruder_trains[global_container_stack.getId()]:
  139. return self._extruder_trains[global_container_stack.getId()][str(self._active_extruder_index)]
  140. return None
  141. ## Get an extruder stack by index
  142. def getExtruderStack(self, index) -> Optional["ExtruderStack"]:
  143. global_container_stack = Application.getInstance().getGlobalContainerStack()
  144. if global_container_stack:
  145. if global_container_stack.getId() in self._extruder_trains:
  146. if str(index) in self._extruder_trains[global_container_stack.getId()]:
  147. return self._extruder_trains[global_container_stack.getId()][str(index)]
  148. return None
  149. ## Get all extruder stacks
  150. def getExtruderStacks(self) -> List["ExtruderStack"]:
  151. result = []
  152. for i in range(self.extruderCount):
  153. result.append(self.getExtruderStack(i))
  154. return result
  155. def registerExtruder(self, extruder_train, machine_id):
  156. changed = False
  157. if machine_id not in self._extruder_trains:
  158. self._extruder_trains[machine_id] = {}
  159. changed = True
  160. # do not register if an extruder has already been registered at the position on this machine
  161. if any(item.getId() == extruder_train.getId() for item in self._extruder_trains[machine_id].values()):
  162. Logger.log("w", "Extruder [%s] has already been registered on machine [%s], not doing anything",
  163. extruder_train.getId(), machine_id)
  164. return
  165. if extruder_train:
  166. self._extruder_trains[machine_id][extruder_train.getMetaDataEntry("position")] = extruder_train
  167. changed = True
  168. if changed:
  169. self.extrudersChanged.emit(machine_id)
  170. def getAllExtruderValues(self, setting_key):
  171. return self.getAllExtruderSettings(setting_key, "value")
  172. ## Gets a property of a setting for all extruders.
  173. #
  174. # \param setting_key \type{str} The setting to get the property of.
  175. # \param property \type{str} The property to get.
  176. # \return \type{List} the list of results
  177. def getAllExtruderSettings(self, setting_key: str, prop: str):
  178. result = []
  179. for index in self.extruderIds:
  180. extruder_stack_id = self.extruderIds[str(index)]
  181. extruder_stack = ContainerRegistry.getInstance().findContainerStacks(id = extruder_stack_id)[0]
  182. result.append(extruder_stack.getProperty(setting_key, prop))
  183. return result
  184. def extruderValueWithDefault(self, value):
  185. machine_manager = self._application.getMachineManager()
  186. if value == "-1":
  187. return machine_manager.defaultExtruderPosition
  188. else:
  189. return value
  190. ## Gets the extruder stacks that are actually being used at the moment.
  191. #
  192. # An extruder stack is being used if it is the extruder to print any mesh
  193. # with, or if it is the support infill extruder, the support interface
  194. # extruder, or the bed adhesion extruder.
  195. #
  196. # If there are no extruders, this returns the global stack as a singleton
  197. # list.
  198. #
  199. # \return A list of extruder stacks.
  200. def getUsedExtruderStacks(self) -> List["ContainerStack"]:
  201. global_stack = self._application.getGlobalContainerStack()
  202. container_registry = ContainerRegistry.getInstance()
  203. used_extruder_stack_ids = set()
  204. # Get the extruders of all meshes in the scene
  205. support_enabled = False
  206. support_bottom_enabled = False
  207. support_roof_enabled = False
  208. scene_root = Application.getInstance().getController().getScene().getRoot()
  209. # If no extruders are registered in the extruder manager yet, return an empty array
  210. if len(self.extruderIds) == 0:
  211. return []
  212. # Get the extruders of all printable meshes in the scene
  213. meshes = [node for node in DepthFirstIterator(scene_root) if isinstance(node, SceneNode) and node.isSelectable()]
  214. for mesh in meshes:
  215. extruder_stack_id = mesh.callDecoration("getActiveExtruder")
  216. if not extruder_stack_id:
  217. # No per-object settings for this node
  218. extruder_stack_id = self.extruderIds["0"]
  219. used_extruder_stack_ids.add(extruder_stack_id)
  220. # Get whether any of them use support.
  221. stack_to_use = mesh.callDecoration("getStack") # if there is a per-mesh stack, we use it
  222. if not stack_to_use:
  223. # if there is no per-mesh stack, we use the build extruder for this mesh
  224. stack_to_use = container_registry.findContainerStacks(id = extruder_stack_id)[0]
  225. support_enabled |= stack_to_use.getProperty("support_enable", "value")
  226. support_bottom_enabled |= stack_to_use.getProperty("support_bottom_enable", "value")
  227. support_roof_enabled |= stack_to_use.getProperty("support_roof_enable", "value")
  228. # Check limit to extruders
  229. limit_to_extruder_feature_list = ["wall_0_extruder_nr",
  230. "wall_x_extruder_nr",
  231. "roofing_extruder_nr",
  232. "top_bottom_extruder_nr",
  233. "infill_extruder_nr",
  234. ]
  235. for extruder_nr_feature_name in limit_to_extruder_feature_list:
  236. extruder_nr = int(global_stack.getProperty(extruder_nr_feature_name, "value"))
  237. if extruder_nr == -1:
  238. continue
  239. used_extruder_stack_ids.add(self.extruderIds[str(extruder_nr)])
  240. # Check support extruders
  241. if support_enabled:
  242. used_extruder_stack_ids.add(self.extruderIds[self.extruderValueWithDefault(str(global_stack.getProperty("support_infill_extruder_nr", "value")))])
  243. used_extruder_stack_ids.add(self.extruderIds[self.extruderValueWithDefault(str(global_stack.getProperty("support_extruder_nr_layer_0", "value")))])
  244. if support_bottom_enabled:
  245. used_extruder_stack_ids.add(self.extruderIds[self.extruderValueWithDefault(str(global_stack.getProperty("support_bottom_extruder_nr", "value")))])
  246. if support_roof_enabled:
  247. used_extruder_stack_ids.add(self.extruderIds[self.extruderValueWithDefault(str(global_stack.getProperty("support_roof_extruder_nr", "value")))])
  248. # The platform adhesion extruder. Not used if using none.
  249. if global_stack.getProperty("adhesion_type", "value") != "none":
  250. extruder_nr = str(global_stack.getProperty("adhesion_extruder_nr", "value"))
  251. if extruder_nr == "-1":
  252. extruder_nr = Application.getInstance().getMachineManager().defaultExtruderPosition
  253. used_extruder_stack_ids.add(self.extruderIds[extruder_nr])
  254. try:
  255. return [container_registry.findContainerStacks(id = stack_id)[0] for stack_id in used_extruder_stack_ids]
  256. except IndexError: # One or more of the extruders was not found.
  257. Logger.log("e", "Unable to find one or more of the extruders in %s", used_extruder_stack_ids)
  258. return []
  259. ## Removes the container stack and user profile for the extruders for a specific machine.
  260. #
  261. # \param machine_id The machine to remove the extruders for.
  262. def removeMachineExtruders(self, machine_id: str):
  263. for extruder in self.getMachineExtruders(machine_id):
  264. ContainerRegistry.getInstance().removeContainer(extruder.userChanges.getId())
  265. ContainerRegistry.getInstance().removeContainer(extruder.getId())
  266. if machine_id in self._extruder_trains:
  267. del self._extruder_trains[machine_id]
  268. ## Returns extruders for a specific machine.
  269. #
  270. # \param machine_id The machine to get the extruders of.
  271. def getMachineExtruders(self, machine_id: str):
  272. if machine_id not in self._extruder_trains:
  273. return []
  274. return [self._extruder_trains[machine_id][name] for name in self._extruder_trains[machine_id]]
  275. ## Returns a list containing the global stack and active extruder stacks.
  276. #
  277. # The first element is the global container stack, followed by any extruder stacks.
  278. # \return \type{List[ContainerStack]}
  279. def getActiveGlobalAndExtruderStacks(self) -> Optional[List[Union["ExtruderStack", "GlobalStack"]]]:
  280. global_stack = Application.getInstance().getGlobalContainerStack()
  281. if not global_stack:
  282. return None
  283. result = [global_stack]
  284. result.extend(self.getActiveExtruderStacks())
  285. return result
  286. ## Returns the list of active extruder stacks, taking into account the machine extruder count.
  287. #
  288. # \return \type{List[ContainerStack]} a list of
  289. def getActiveExtruderStacks(self) -> List["ExtruderStack"]:
  290. global_stack = Application.getInstance().getGlobalContainerStack()
  291. if not global_stack:
  292. return []
  293. result = []
  294. if global_stack.getId() in self._extruder_trains:
  295. for extruder in sorted(self._extruder_trains[global_stack.getId()]):
  296. result.append(self._extruder_trains[global_stack.getId()][extruder])
  297. machine_extruder_count = global_stack.getProperty("machine_extruder_count", "value")
  298. return result[:machine_extruder_count]
  299. def _globalContainerStackChanged(self) -> None:
  300. # If the global container changed, the machine changed and might have extruders that were not registered yet
  301. self._addCurrentMachineExtruders()
  302. self.resetSelectedObjectExtruders()
  303. ## Adds the extruders of the currently active machine.
  304. def _addCurrentMachineExtruders(self) -> None:
  305. global_stack = self._application.getGlobalContainerStack()
  306. extruders_changed = False
  307. if global_stack:
  308. container_registry = ContainerRegistry.getInstance()
  309. global_stack_id = global_stack.getId()
  310. # Gets the extruder trains that we just created as well as any that still existed.
  311. extruder_trains = container_registry.findContainerStacks(type = "extruder_train", machine = global_stack_id)
  312. # Make sure the extruder trains for the new machine can be placed in the set of sets
  313. if global_stack_id not in self._extruder_trains:
  314. self._extruder_trains[global_stack_id] = {}
  315. extruders_changed = True
  316. # Register the extruder trains by position
  317. for extruder_train in extruder_trains:
  318. extruder_position = extruder_train.getMetaDataEntry("position")
  319. self._extruder_trains[global_stack_id][extruder_position] = extruder_train
  320. # regardless of what the next stack is, we have to set it again, because of signal routing. ???
  321. extruder_train.setParent(global_stack)
  322. extruder_train.setNextStack(global_stack)
  323. extruders_changed = True
  324. self._fixMaterialDiameterAndNozzleSize(global_stack, extruder_trains)
  325. if extruders_changed:
  326. self.extrudersChanged.emit(global_stack_id)
  327. self.setActiveExtruderIndex(0)
  328. #
  329. # This function tries to fix the problem with per-extruder-settable nozzle size and material diameter problems
  330. # in early versions (3.0 - 3.2.1).
  331. #
  332. # In earlier versions, "nozzle size" and "material diameter" are only applicable to the complete machine, so all
  333. # extruders share the same values. In this case, "nozzle size" and "material diameter" are saved in the
  334. # GlobalStack's DefinitionChanges container.
  335. #
  336. # Later, we could have different "nozzle size" for each extruder, but "material diameter" could only be set for
  337. # the entire machine. In this case, "nozzle size" should be saved in each ExtruderStack's DefinitionChanges, but
  338. # "material diameter" still remains in the GlobalStack's DefinitionChanges.
  339. #
  340. # Lateer, both "nozzle size" and "material diameter" are settable per-extruder, and both settings should be saved
  341. # in the ExtruderStack's DefinitionChanges.
  342. #
  343. # There were some bugs in upgrade so the data weren't saved correct as described above. This function tries fix
  344. # this.
  345. #
  346. # One more thing is about material diameter and single-extrusion machines. Most single-extrusion machines don't
  347. # specifically define their extruder definition, so they reuse "fdmextruder", but for those machines, they may
  348. # define "material diameter = 1.75" in their machine definition, but in "fdmextruder", it's still "2.85". This
  349. # causes a problem with incorrect default values.
  350. #
  351. # This is also fixed here in this way: If no "material diameter" is specified, it will look for the default value
  352. # in both the Extruder's definition and the Global's definition. If 2 values don't match, we will use the value
  353. # from the Global definition by setting it in the Extruder's DefinitionChanges container.
  354. #
  355. def _fixMaterialDiameterAndNozzleSize(self, global_stack, extruder_stack_list):
  356. keys_to_copy = ["material_diameter", "machine_nozzle_size"] # these will be copied over to all extruders
  357. extruder_positions_to_update = set()
  358. for extruder_stack in extruder_stack_list:
  359. for key in keys_to_copy:
  360. # Only copy the value when this extruder doesn't have the value.
  361. if extruder_stack.definitionChanges.hasProperty(key, "value"):
  362. continue
  363. setting_value_in_global_def_changes = global_stack.definitionChanges.getProperty(key, "value")
  364. setting_value_in_global_def = global_stack.definition.getProperty(key, "value")
  365. setting_value = setting_value_in_global_def
  366. if setting_value_in_global_def_changes is not None:
  367. setting_value = setting_value_in_global_def_changes
  368. if setting_value == extruder_stack.definition.getProperty(key, "value"):
  369. continue
  370. setting_definition = global_stack.getSettingDefinition(key)
  371. new_instance = SettingInstance(setting_definition, extruder_stack.definitionChanges)
  372. new_instance.setProperty("value", setting_value)
  373. new_instance.resetState() # Ensure that the state is not seen as a user state.
  374. extruder_stack.definitionChanges.addInstance(new_instance)
  375. extruder_stack.definitionChanges.setDirty(True)
  376. # Make sure the material diameter is up to date for the extruder stack.
  377. if key == "material_diameter":
  378. position = int(extruder_stack.getMetaDataEntry("position"))
  379. extruder_positions_to_update.add(position)
  380. # We have to remove those settings here because we know that those values have been copied to all
  381. # the extruders at this point.
  382. for key in keys_to_copy:
  383. if global_stack.definitionChanges.hasProperty(key, "value"):
  384. global_stack.definitionChanges.removeInstance(key, postpone_emit = True)
  385. ## Get all extruder values for a certain setting.
  386. #
  387. # This is exposed to SettingFunction so it can be used in value functions.
  388. #
  389. # \param key The key of the setting to retrieve values for.
  390. #
  391. # \return A list of values for all extruders. If an extruder does not have a value, it will not be in the list.
  392. # If no extruder has the value, the list will contain the global value.
  393. @staticmethod
  394. def getExtruderValues(key):
  395. global_stack = Application.getInstance().getGlobalContainerStack()
  396. result = []
  397. for extruder in ExtruderManager.getInstance().getMachineExtruders(global_stack.getId()):
  398. if not extruder.isEnabled:
  399. continue
  400. # only include values from extruders that are "active" for the current machine instance
  401. if int(extruder.getMetaDataEntry("position")) >= global_stack.getProperty("machine_extruder_count", "value"):
  402. continue
  403. value = extruder.getRawProperty(key, "value")
  404. if value is None:
  405. continue
  406. if isinstance(value, SettingFunction):
  407. value = value(extruder)
  408. result.append(value)
  409. if not result:
  410. result.append(global_stack.getProperty(key, "value"))
  411. return result
  412. ## Get all extruder values for a certain setting. This function will skip the user settings container.
  413. #
  414. # This is exposed to SettingFunction so it can be used in value functions.
  415. #
  416. # \param key The key of the setting to retrieve values for.
  417. #
  418. # \return A list of values for all extruders. If an extruder does not have a value, it will not be in the list.
  419. # If no extruder has the value, the list will contain the global value.
  420. @staticmethod
  421. def getDefaultExtruderValues(key):
  422. global_stack = Application.getInstance().getGlobalContainerStack()
  423. context = PropertyEvaluationContext(global_stack)
  424. context.context["evaluate_from_container_index"] = 1 # skip the user settings container
  425. context.context["override_operators"] = {
  426. "extruderValue": ExtruderManager.getDefaultExtruderValue,
  427. "extruderValues": ExtruderManager.getDefaultExtruderValues,
  428. "resolveOrValue": ExtruderManager.getDefaultResolveOrValue
  429. }
  430. result = []
  431. for extruder in ExtruderManager.getInstance().getMachineExtruders(global_stack.getId()):
  432. # only include values from extruders that are "active" for the current machine instance
  433. if int(extruder.getMetaDataEntry("position")) >= global_stack.getProperty("machine_extruder_count", "value", context = context):
  434. continue
  435. value = extruder.getRawProperty(key, "value", context = context)
  436. if value is None:
  437. continue
  438. if isinstance(value, SettingFunction):
  439. value = value(extruder, context = context)
  440. result.append(value)
  441. if not result:
  442. result.append(global_stack.getProperty(key, "value", context = context))
  443. return result
  444. ## Return the default extruder position from the machine manager
  445. @staticmethod
  446. def getDefaultExtruderPosition() -> str:
  447. return Application.getInstance().getMachineManager().defaultExtruderPosition
  448. ## Get all extruder values for a certain setting.
  449. #
  450. # This is exposed to qml for display purposes
  451. #
  452. # \param key The key of the setting to retrieve values for.
  453. #
  454. # \return String representing the extruder values
  455. @pyqtSlot(str, result="QVariant")
  456. def getInstanceExtruderValues(self, key):
  457. return ExtruderManager.getExtruderValues(key)
  458. ## Get the value for a setting from a specific extruder.
  459. #
  460. # This is exposed to SettingFunction to use in value functions.
  461. #
  462. # \param extruder_index The index of the extruder to get the value from.
  463. # \param key The key of the setting to get the value of.
  464. #
  465. # \return The value of the setting for the specified extruder or for the
  466. # global stack if not found.
  467. @staticmethod
  468. def getExtruderValue(extruder_index, key):
  469. if extruder_index == -1:
  470. extruder_index = int(Application.getInstance().getMachineManager().defaultExtruderPosition)
  471. extruder = ExtruderManager.getInstance().getExtruderStack(extruder_index)
  472. if extruder:
  473. value = extruder.getRawProperty(key, "value")
  474. if isinstance(value, SettingFunction):
  475. value = value(extruder)
  476. else:
  477. # Just a value from global.
  478. value = Application.getInstance().getGlobalContainerStack().getProperty(key, "value")
  479. return value
  480. ## Get the default value from the given extruder. This function will skip the user settings container.
  481. #
  482. # This is exposed to SettingFunction to use in value functions.
  483. #
  484. # \param extruder_index The index of the extruder to get the value from.
  485. # \param key The key of the setting to get the value of.
  486. #
  487. # \return The value of the setting for the specified extruder or for the
  488. # global stack if not found.
  489. @staticmethod
  490. def getDefaultExtruderValue(extruder_index, key):
  491. extruder = ExtruderManager.getInstance().getExtruderStack(extruder_index)
  492. context = PropertyEvaluationContext(extruder)
  493. context.context["evaluate_from_container_index"] = 1 # skip the user settings container
  494. context.context["override_operators"] = {
  495. "extruderValue": ExtruderManager.getDefaultExtruderValue,
  496. "extruderValues": ExtruderManager.getDefaultExtruderValues,
  497. "resolveOrValue": ExtruderManager.getDefaultResolveOrValue
  498. }
  499. if extruder:
  500. value = extruder.getRawProperty(key, "value", context = context)
  501. if isinstance(value, SettingFunction):
  502. value = value(extruder, context = context)
  503. else: # Just a value from global.
  504. value = Application.getInstance().getGlobalContainerStack().getProperty(key, "value", context = context)
  505. return value
  506. ## Get the resolve value or value for a given key
  507. #
  508. # This is the effective value for a given key, it is used for values in the global stack.
  509. # This is exposed to SettingFunction to use in value functions.
  510. # \param key The key of the setting to get the value of.
  511. #
  512. # \return The effective value
  513. @staticmethod
  514. def getResolveOrValue(key):
  515. global_stack = Application.getInstance().getGlobalContainerStack()
  516. resolved_value = global_stack.getProperty(key, "value")
  517. return resolved_value
  518. ## Get the resolve value or value for a given key without looking the first container (user container)
  519. #
  520. # This is the effective value for a given key, it is used for values in the global stack.
  521. # This is exposed to SettingFunction to use in value functions.
  522. # \param key The key of the setting to get the value of.
  523. #
  524. # \return The effective value
  525. @staticmethod
  526. def getDefaultResolveOrValue(key):
  527. global_stack = Application.getInstance().getGlobalContainerStack()
  528. context = PropertyEvaluationContext(global_stack)
  529. context.context["evaluate_from_container_index"] = 1 # skip the user settings container
  530. context.context["override_operators"] = {
  531. "extruderValue": ExtruderManager.getDefaultExtruderValue,
  532. "extruderValues": ExtruderManager.getDefaultExtruderValues,
  533. "resolveOrValue": ExtruderManager.getDefaultResolveOrValue
  534. }
  535. resolved_value = global_stack.getProperty(key, "value", context = context)
  536. return resolved_value
  537. __instance = None
  538. @classmethod
  539. def getInstance(cls, *args, **kwargs) -> "ExtruderManager":
  540. return cls.__instance