ExtruderManager.py 35 KB

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