ExtruderManager.py 31 KB

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