ExtruderManager.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  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 None
  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. self._extruder_trains[global_stack_id][extruder_train.getMetaDataEntry("position")] = extruder_train
  335. # regardless of what the next stack is, we have to set it again, because of signal routing. ???
  336. extruder_train.setParent(global_stack)
  337. extruder_train.setNextStack(global_stack)
  338. extruders_changed = True
  339. self._fixMaterialDiameterAndNozzleSize(global_stack, extruder_trains)
  340. if extruders_changed:
  341. self.extrudersChanged.emit(global_stack_id)
  342. self.setActiveExtruderIndex(0)
  343. #
  344. # This function tries to fix the problem with per-extruder-settable nozzle size and material diameter problems
  345. # in early versions (3.0 - 3.2.1).
  346. #
  347. # In earlier versions, "nozzle size" and "material diameter" are only applicable to the complete machine, so all
  348. # extruders share the same values. In this case, "nozzle size" and "material diameter" are saved in the
  349. # GlobalStack's DefinitionChanges container.
  350. #
  351. # Later, we could have different "nozzle size" for each extruder, but "material diameter" could only be set for
  352. # the entire machine. In this case, "nozzle size" should be saved in each ExtruderStack's DefinitionChanges, but
  353. # "material diameter" still remains in the GlobalStack's DefinitionChanges.
  354. #
  355. # Lateer, both "nozzle size" and "material diameter" are settable per-extruder, and both settings should be saved
  356. # in the ExtruderStack's DefinitionChanges.
  357. #
  358. # There were some bugs in upgrade so the data weren't saved correct as described above. This function tries fix
  359. # this.
  360. #
  361. # One more thing is about material diameter and single-extrusion machines. Most single-extrusion machines don't
  362. # specifically define their extruder definition, so they reuse "fdmextruder", but for those machines, they may
  363. # define "material diameter = 1.75" in their machine definition, but in "fdmextruder", it's still "2.85". This
  364. # causes a problem with incorrect default values.
  365. #
  366. # This is also fixed here in this way: If no "material diameter" is specified, it will look for the default value
  367. # in both the Extruder's definition and the Global's definition. If 2 values don't match, we will use the value
  368. # from the Global definition by setting it in the Extruder's DefinitionChanges container.
  369. #
  370. def _fixMaterialDiameterAndNozzleSize(self, global_stack, extruder_stack_list):
  371. keys_to_copy = ["material_diameter", "machine_nozzle_size"] # these will be copied over to all extruders
  372. extruder_positions_to_update = set()
  373. for extruder_stack in extruder_stack_list:
  374. for key in keys_to_copy:
  375. # Only copy the value when this extruder doesn't have the value.
  376. if extruder_stack.definitionChanges.hasProperty(key, "value"):
  377. continue
  378. setting_value_in_global_def_changes = global_stack.definitionChanges.getProperty(key, "value")
  379. setting_value_in_global_def = global_stack.definition.getProperty(key, "value")
  380. setting_value = setting_value_in_global_def
  381. if setting_value_in_global_def_changes is not None:
  382. setting_value = setting_value_in_global_def_changes
  383. if setting_value == extruder_stack.definition.getProperty(key, "value"):
  384. continue
  385. setting_definition = global_stack.getSettingDefinition(key)
  386. new_instance = SettingInstance(setting_definition, extruder_stack.definitionChanges)
  387. new_instance.setProperty("value", setting_value)
  388. new_instance.resetState() # Ensure that the state is not seen as a user state.
  389. extruder_stack.definitionChanges.addInstance(new_instance)
  390. extruder_stack.definitionChanges.setDirty(True)
  391. # Make sure the material diameter is up to date for the extruder stack.
  392. if key == "material_diameter":
  393. position = int(extruder_stack.getMetaDataEntry("position"))
  394. extruder_positions_to_update.add(position)
  395. # We have to remove those settings here because we know that those values have been copied to all
  396. # the extruders at this point.
  397. for key in keys_to_copy:
  398. if global_stack.definitionChanges.hasProperty(key, "value"):
  399. global_stack.definitionChanges.removeInstance(key, postpone_emit = True)
  400. # Update material diameter for extruders
  401. for position in extruder_positions_to_update:
  402. self.updateMaterialForDiameter(position, global_stack = global_stack)
  403. ## Get all extruder values for a certain setting.
  404. #
  405. # This is exposed to SettingFunction so it can be used in value functions.
  406. #
  407. # \param key The key of the setting to retrieve values for.
  408. #
  409. # \return A list of values for all extruders. If an extruder does not have a value, it will not be in the list.
  410. # If no extruder has the value, the list will contain the global value.
  411. @staticmethod
  412. def getExtruderValues(key):
  413. global_stack = Application.getInstance().getGlobalContainerStack()
  414. result = []
  415. for extruder in ExtruderManager.getInstance().getMachineExtruders(global_stack.getId()):
  416. if not extruder.isEnabled:
  417. continue
  418. # only include values from extruders that are "active" for the current machine instance
  419. if int(extruder.getMetaDataEntry("position")) >= global_stack.getProperty("machine_extruder_count", "value"):
  420. continue
  421. value = extruder.getRawProperty(key, "value")
  422. if value is None:
  423. continue
  424. if isinstance(value, SettingFunction):
  425. value = value(extruder)
  426. result.append(value)
  427. if not result:
  428. result.append(global_stack.getProperty(key, "value"))
  429. return result
  430. ## Get all extruder values for a certain setting. This function will skip the user settings container.
  431. #
  432. # This is exposed to SettingFunction so it can be used in value functions.
  433. #
  434. # \param key The key of the setting to retrieve values for.
  435. #
  436. # \return A list of values for all extruders. If an extruder does not have a value, it will not be in the list.
  437. # If no extruder has the value, the list will contain the global value.
  438. @staticmethod
  439. def getDefaultExtruderValues(key):
  440. global_stack = Application.getInstance().getGlobalContainerStack()
  441. context = PropertyEvaluationContext(global_stack)
  442. context.context["evaluate_from_container_index"] = 1 # skip the user settings container
  443. context.context["override_operators"] = {
  444. "extruderValue": ExtruderManager.getDefaultExtruderValue,
  445. "extruderValues": ExtruderManager.getDefaultExtruderValues,
  446. "resolveOrValue": ExtruderManager.getDefaultResolveOrValue
  447. }
  448. result = []
  449. for extruder in ExtruderManager.getInstance().getMachineExtruders(global_stack.getId()):
  450. # only include values from extruders that are "active" for the current machine instance
  451. if int(extruder.getMetaDataEntry("position")) >= global_stack.getProperty("machine_extruder_count", "value", context = context):
  452. continue
  453. value = extruder.getRawProperty(key, "value", context = context)
  454. if value is None:
  455. continue
  456. if isinstance(value, SettingFunction):
  457. value = value(extruder, context = context)
  458. result.append(value)
  459. if not result:
  460. result.append(global_stack.getProperty(key, "value", context = context))
  461. return result
  462. ## Get all extruder values for a certain setting.
  463. #
  464. # This is exposed to qml for display purposes
  465. #
  466. # \param key The key of the setting to retrieve values for.
  467. #
  468. # \return String representing the extruder values
  469. @pyqtSlot(str, result="QVariant")
  470. def getInstanceExtruderValues(self, key):
  471. return ExtruderManager.getExtruderValues(key)
  472. ## Updates the material container to a material that matches the material diameter set for the printer
  473. def updateMaterialForDiameter(self, extruder_position: int, global_stack = None):
  474. if not global_stack:
  475. global_stack = Application.getInstance().getGlobalContainerStack()
  476. if not global_stack:
  477. return
  478. if not global_stack.getMetaDataEntry("has_materials", False):
  479. return
  480. extruder_stack = global_stack.extruders[str(extruder_position)]
  481. material_diameter = extruder_stack.material.getProperty("material_diameter", "value")
  482. if not material_diameter:
  483. # in case of "empty" material
  484. material_diameter = 0
  485. material_approximate_diameter = str(round(material_diameter))
  486. material_diameter = extruder_stack.definitionChanges.getProperty("material_diameter", "value")
  487. setting_provider = extruder_stack
  488. if not material_diameter:
  489. if extruder_stack.definition.hasProperty("material_diameter", "value"):
  490. material_diameter = extruder_stack.definition.getProperty("material_diameter", "value")
  491. else:
  492. material_diameter = global_stack.definition.getProperty("material_diameter", "value")
  493. setting_provider = global_stack
  494. if isinstance(material_diameter, SettingFunction):
  495. material_diameter = material_diameter(setting_provider)
  496. machine_approximate_diameter = str(round(material_diameter))
  497. if material_approximate_diameter != machine_approximate_diameter:
  498. Logger.log("i", "The the currently active material(s) do not match the diameter set for the printer. Finding alternatives.")
  499. if global_stack.getMetaDataEntry("has_machine_materials", False):
  500. materials_definition = global_stack.definition.getId()
  501. has_material_variants = global_stack.getMetaDataEntry("has_variants", False)
  502. else:
  503. materials_definition = "fdmprinter"
  504. has_material_variants = False
  505. old_material = extruder_stack.material
  506. search_criteria = {
  507. "type": "material",
  508. "approximate_diameter": machine_approximate_diameter,
  509. "material": old_material.getMetaDataEntry("material", "value"),
  510. "brand": old_material.getMetaDataEntry("brand", "value"),
  511. "supplier": old_material.getMetaDataEntry("supplier", "value"),
  512. "color_name": old_material.getMetaDataEntry("color_name", "value"),
  513. "definition": materials_definition
  514. }
  515. if has_material_variants:
  516. search_criteria["variant"] = extruder_stack.variant.getId()
  517. container_registry = Application.getInstance().getContainerRegistry()
  518. empty_material = container_registry.findInstanceContainers(id = "empty_material")[0]
  519. if old_material == empty_material:
  520. search_criteria.pop("material", None)
  521. search_criteria.pop("supplier", None)
  522. search_criteria.pop("brand", None)
  523. search_criteria.pop("definition", None)
  524. search_criteria["id"] = extruder_stack.getMetaDataEntry("preferred_material")
  525. materials = container_registry.findInstanceContainers(**search_criteria)
  526. if not materials:
  527. # Same material with new diameter is not found, search for generic version of the same material type
  528. search_criteria.pop("supplier", None)
  529. search_criteria.pop("brand", None)
  530. search_criteria["color_name"] = "Generic"
  531. materials = container_registry.findInstanceContainers(**search_criteria)
  532. if not materials:
  533. # Generic material with new diameter is not found, search for preferred material
  534. search_criteria.pop("color_name", None)
  535. search_criteria.pop("material", None)
  536. search_criteria["id"] = extruder_stack.getMetaDataEntry("preferred_material")
  537. materials = container_registry.findInstanceContainers(**search_criteria)
  538. if not materials:
  539. # Preferred material with new diameter is not found, search for any material
  540. search_criteria.pop("id", None)
  541. materials = container_registry.findInstanceContainers(**search_criteria)
  542. if not materials:
  543. # Just use empty material as a final fallback
  544. materials = [empty_material]
  545. Logger.log("i", "Selecting new material: %s", materials[0].getId())
  546. extruder_stack.material = materials[0]
  547. ## Get the value for a setting from a specific extruder.
  548. #
  549. # This is exposed to SettingFunction to use in value functions.
  550. #
  551. # \param extruder_index The index of the extruder to get the value from.
  552. # \param key The key of the setting to get the value of.
  553. #
  554. # \return The value of the setting for the specified extruder or for the
  555. # global stack if not found.
  556. @staticmethod
  557. def getExtruderValue(extruder_index, key):
  558. if extruder_index == -1:
  559. extruder_index = int(Application.getInstance().getMachineManager().defaultExtruderPosition)
  560. extruder = ExtruderManager.getInstance().getExtruderStack(extruder_index)
  561. if extruder:
  562. value = extruder.getRawProperty(key, "value")
  563. if isinstance(value, SettingFunction):
  564. value = value(extruder)
  565. else:
  566. # Just a value from global.
  567. value = Application.getInstance().getGlobalContainerStack().getProperty(key, "value")
  568. return value
  569. ## Get the default value from the given extruder. This function will skip the user settings container.
  570. #
  571. # This is exposed to SettingFunction to use in value functions.
  572. #
  573. # \param extruder_index The index of the extruder to get the value from.
  574. # \param key The key of the setting to get the value of.
  575. #
  576. # \return The value of the setting for the specified extruder or for the
  577. # global stack if not found.
  578. @staticmethod
  579. def getDefaultExtruderValue(extruder_index, key):
  580. extruder = ExtruderManager.getInstance().getExtruderStack(extruder_index)
  581. context = PropertyEvaluationContext(extruder)
  582. context.context["evaluate_from_container_index"] = 1 # skip the user settings container
  583. context.context["override_operators"] = {
  584. "extruderValue": ExtruderManager.getDefaultExtruderValue,
  585. "extruderValues": ExtruderManager.getDefaultExtruderValues,
  586. "resolveOrValue": ExtruderManager.getDefaultResolveOrValue
  587. }
  588. if extruder:
  589. value = extruder.getRawProperty(key, "value", context = context)
  590. if isinstance(value, SettingFunction):
  591. value = value(extruder, context = context)
  592. else: # Just a value from global.
  593. value = Application.getInstance().getGlobalContainerStack().getProperty(key, "value", context = context)
  594. return value
  595. ## Get the resolve value or value for a given key
  596. #
  597. # This is the effective value for a given key, it is used for values in the global stack.
  598. # This is exposed to SettingFunction to use in value functions.
  599. # \param key The key of the setting to get the value of.
  600. #
  601. # \return The effective value
  602. @staticmethod
  603. def getResolveOrValue(key):
  604. global_stack = Application.getInstance().getGlobalContainerStack()
  605. resolved_value = global_stack.getProperty(key, "value")
  606. return resolved_value
  607. ## Get the resolve value or value for a given key without looking the first container (user container)
  608. #
  609. # This is the effective value for a given key, it is used for values in the global stack.
  610. # This is exposed to SettingFunction to use in value functions.
  611. # \param key The key of the setting to get the value of.
  612. #
  613. # \return The effective value
  614. @staticmethod
  615. def getDefaultResolveOrValue(key):
  616. global_stack = Application.getInstance().getGlobalContainerStack()
  617. context = PropertyEvaluationContext(global_stack)
  618. context.context["evaluate_from_container_index"] = 1 # skip the user settings container
  619. context.context["override_operators"] = {
  620. "extruderValue": ExtruderManager.getDefaultExtruderValue,
  621. "extruderValues": ExtruderManager.getDefaultExtruderValues,
  622. "resolveOrValue": ExtruderManager.getDefaultResolveOrValue
  623. }
  624. resolved_value = global_stack.getProperty(key, "value", context = context)
  625. return resolved_value