ExtruderManager.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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. # Update material diameter for extruders
  386. for position in extruder_positions_to_update:
  387. self.updateMaterialForDiameter(position, global_stack = global_stack)
  388. ## Get all extruder values for a certain setting.
  389. #
  390. # This is exposed to SettingFunction so it can be used in value functions.
  391. #
  392. # \param key The key of the setting to retrieve values for.
  393. #
  394. # \return A list of values for all extruders. If an extruder does not have a value, it will not be in the list.
  395. # If no extruder has the value, the list will contain the global value.
  396. @staticmethod
  397. def getExtruderValues(key):
  398. global_stack = Application.getInstance().getGlobalContainerStack()
  399. result = []
  400. for extruder in ExtruderManager.getInstance().getMachineExtruders(global_stack.getId()):
  401. if not extruder.isEnabled:
  402. continue
  403. # only include values from extruders that are "active" for the current machine instance
  404. if int(extruder.getMetaDataEntry("position")) >= global_stack.getProperty("machine_extruder_count", "value"):
  405. continue
  406. value = extruder.getRawProperty(key, "value")
  407. if value is None:
  408. continue
  409. if isinstance(value, SettingFunction):
  410. value = value(extruder)
  411. result.append(value)
  412. if not result:
  413. result.append(global_stack.getProperty(key, "value"))
  414. return result
  415. ## Get all extruder values for a certain setting. This function will skip the user settings container.
  416. #
  417. # This is exposed to SettingFunction so it can be used in value functions.
  418. #
  419. # \param key The key of the setting to retrieve values for.
  420. #
  421. # \return A list of values for all extruders. If an extruder does not have a value, it will not be in the list.
  422. # If no extruder has the value, the list will contain the global value.
  423. @staticmethod
  424. def getDefaultExtruderValues(key):
  425. global_stack = Application.getInstance().getGlobalContainerStack()
  426. context = PropertyEvaluationContext(global_stack)
  427. context.context["evaluate_from_container_index"] = 1 # skip the user settings container
  428. context.context["override_operators"] = {
  429. "extruderValue": ExtruderManager.getDefaultExtruderValue,
  430. "extruderValues": ExtruderManager.getDefaultExtruderValues,
  431. "resolveOrValue": ExtruderManager.getDefaultResolveOrValue
  432. }
  433. result = []
  434. for extruder in ExtruderManager.getInstance().getMachineExtruders(global_stack.getId()):
  435. # only include values from extruders that are "active" for the current machine instance
  436. if int(extruder.getMetaDataEntry("position")) >= global_stack.getProperty("machine_extruder_count", "value", context = context):
  437. continue
  438. value = extruder.getRawProperty(key, "value", context = context)
  439. if value is None:
  440. continue
  441. if isinstance(value, SettingFunction):
  442. value = value(extruder, context = context)
  443. result.append(value)
  444. if not result:
  445. result.append(global_stack.getProperty(key, "value", context = context))
  446. return result
  447. ## Get all extruder values for a certain setting.
  448. #
  449. # This is exposed to qml for display purposes
  450. #
  451. # \param key The key of the setting to retrieve values for.
  452. #
  453. # \return String representing the extruder values
  454. @pyqtSlot(str, result="QVariant")
  455. def getInstanceExtruderValues(self, key):
  456. return ExtruderManager.getExtruderValues(key)
  457. ## Updates the material container to a material that matches the material diameter set for the printer
  458. def updateMaterialForDiameter(self, extruder_position: int, global_stack = None):
  459. if not global_stack:
  460. global_stack = Application.getInstance().getGlobalContainerStack()
  461. if not global_stack:
  462. return
  463. if not global_stack.getMetaDataEntry("has_materials", False):
  464. return
  465. extruder_stack = global_stack.extruders[str(extruder_position)]
  466. material_diameter = extruder_stack.material.getProperty("material_diameter", "value")
  467. if not material_diameter:
  468. # in case of "empty" material
  469. material_diameter = 0
  470. material_approximate_diameter = str(round(material_diameter))
  471. material_diameter = extruder_stack.definitionChanges.getProperty("material_diameter", "value")
  472. setting_provider = extruder_stack
  473. if not material_diameter:
  474. if extruder_stack.definition.hasProperty("material_diameter", "value"):
  475. material_diameter = extruder_stack.definition.getProperty("material_diameter", "value")
  476. else:
  477. material_diameter = global_stack.definition.getProperty("material_diameter", "value")
  478. setting_provider = global_stack
  479. if isinstance(material_diameter, SettingFunction):
  480. material_diameter = material_diameter(setting_provider)
  481. machine_approximate_diameter = str(round(material_diameter))
  482. if material_approximate_diameter != machine_approximate_diameter:
  483. Logger.log("i", "The the currently active material(s) do not match the diameter set for the printer. Finding alternatives.")
  484. if global_stack.getMetaDataEntry("has_machine_materials", False):
  485. materials_definition = global_stack.definition.getId()
  486. has_material_variants = global_stack.getMetaDataEntry("has_variants", False)
  487. else:
  488. materials_definition = "fdmprinter"
  489. has_material_variants = False
  490. old_material = extruder_stack.material
  491. search_criteria = {
  492. "type": "material",
  493. "approximate_diameter": machine_approximate_diameter,
  494. "material": old_material.getMetaDataEntry("material", "value"),
  495. "brand": old_material.getMetaDataEntry("brand", "value"),
  496. "supplier": old_material.getMetaDataEntry("supplier", "value"),
  497. "color_name": old_material.getMetaDataEntry("color_name", "value"),
  498. "definition": materials_definition
  499. }
  500. if has_material_variants:
  501. search_criteria["variant"] = extruder_stack.variant.getId()
  502. container_registry = Application.getInstance().getContainerRegistry()
  503. empty_material = container_registry.findInstanceContainers(id = "empty_material")[0]
  504. if old_material == empty_material:
  505. search_criteria.pop("material", None)
  506. search_criteria.pop("supplier", None)
  507. search_criteria.pop("brand", None)
  508. search_criteria.pop("definition", None)
  509. search_criteria["id"] = extruder_stack.getMetaDataEntry("preferred_material")
  510. materials = container_registry.findInstanceContainers(**search_criteria)
  511. if not materials:
  512. # Same material with new diameter is not found, search for generic version of the same material type
  513. search_criteria.pop("supplier", None)
  514. search_criteria.pop("brand", None)
  515. search_criteria["color_name"] = "Generic"
  516. materials = container_registry.findInstanceContainers(**search_criteria)
  517. if not materials:
  518. # Generic material with new diameter is not found, search for preferred material
  519. search_criteria.pop("color_name", None)
  520. search_criteria.pop("material", None)
  521. search_criteria["id"] = extruder_stack.getMetaDataEntry("preferred_material")
  522. materials = container_registry.findInstanceContainers(**search_criteria)
  523. if not materials:
  524. # Preferred material with new diameter is not found, search for any material
  525. search_criteria.pop("id", None)
  526. materials = container_registry.findInstanceContainers(**search_criteria)
  527. if not materials:
  528. # Just use empty material as a final fallback
  529. materials = [empty_material]
  530. Logger.log("i", "Selecting new material: %s", materials[0].getId())
  531. extruder_stack.material = materials[0]
  532. ## Get the value for a setting from a specific extruder.
  533. #
  534. # This is exposed to SettingFunction to use in value functions.
  535. #
  536. # \param extruder_index The index of the extruder to get the value from.
  537. # \param key The key of the setting to get the value of.
  538. #
  539. # \return The value of the setting for the specified extruder or for the
  540. # global stack if not found.
  541. @staticmethod
  542. def getExtruderValue(extruder_index, key):
  543. if extruder_index == -1:
  544. extruder_index = int(Application.getInstance().getMachineManager().defaultExtruderPosition)
  545. extruder = ExtruderManager.getInstance().getExtruderStack(extruder_index)
  546. if extruder:
  547. value = extruder.getRawProperty(key, "value")
  548. if isinstance(value, SettingFunction):
  549. value = value(extruder)
  550. else:
  551. # Just a value from global.
  552. value = Application.getInstance().getGlobalContainerStack().getProperty(key, "value")
  553. return value
  554. ## Get the default value from the given extruder. This function will skip the user settings container.
  555. #
  556. # This is exposed to SettingFunction to use in value functions.
  557. #
  558. # \param extruder_index The index of the extruder to get the value from.
  559. # \param key The key of the setting to get the value of.
  560. #
  561. # \return The value of the setting for the specified extruder or for the
  562. # global stack if not found.
  563. @staticmethod
  564. def getDefaultExtruderValue(extruder_index, key):
  565. extruder = ExtruderManager.getInstance().getExtruderStack(extruder_index)
  566. context = PropertyEvaluationContext(extruder)
  567. context.context["evaluate_from_container_index"] = 1 # skip the user settings container
  568. context.context["override_operators"] = {
  569. "extruderValue": ExtruderManager.getDefaultExtruderValue,
  570. "extruderValues": ExtruderManager.getDefaultExtruderValues,
  571. "resolveOrValue": ExtruderManager.getDefaultResolveOrValue
  572. }
  573. if extruder:
  574. value = extruder.getRawProperty(key, "value", context = context)
  575. if isinstance(value, SettingFunction):
  576. value = value(extruder, context = context)
  577. else: # Just a value from global.
  578. value = Application.getInstance().getGlobalContainerStack().getProperty(key, "value", context = context)
  579. return value
  580. ## Get the resolve value or value for a given key
  581. #
  582. # This is the effective value for a given key, it is used for values in the global stack.
  583. # This is exposed to SettingFunction to use in value functions.
  584. # \param key The key of the setting to get the value of.
  585. #
  586. # \return The effective value
  587. @staticmethod
  588. def getResolveOrValue(key):
  589. global_stack = Application.getInstance().getGlobalContainerStack()
  590. resolved_value = global_stack.getProperty(key, "value")
  591. return resolved_value
  592. ## Get the resolve value or value for a given key without looking the first container (user container)
  593. #
  594. # This is the effective value for a given key, it is used for values in the global stack.
  595. # This is exposed to SettingFunction to use in value functions.
  596. # \param key The key of the setting to get the value of.
  597. #
  598. # \return The effective value
  599. @staticmethod
  600. def getDefaultResolveOrValue(key):
  601. global_stack = Application.getInstance().getGlobalContainerStack()
  602. context = PropertyEvaluationContext(global_stack)
  603. context.context["evaluate_from_container_index"] = 1 # skip the user settings container
  604. context.context["override_operators"] = {
  605. "extruderValue": ExtruderManager.getDefaultExtruderValue,
  606. "extruderValues": ExtruderManager.getDefaultExtruderValues,
  607. "resolveOrValue": ExtruderManager.getDefaultResolveOrValue
  608. }
  609. resolved_value = global_stack.getProperty(key, "value", context = context)
  610. return resolved_value
  611. __instance = None
  612. @classmethod
  613. def getInstance(cls, *args, **kwargs) -> "ExtruderManager":
  614. return cls.__instance