ExtruderManager.py 31 KB

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