MachineManager.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  1. # Copyright (c) 2017 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import collections
  4. import time
  5. #Type hinting.
  6. from typing import Union, List, Dict, TYPE_CHECKING, Optional
  7. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  8. from UM.Signal import Signal
  9. from PyQt5.QtCore import QObject, pyqtProperty, pyqtSignal, QTimer
  10. import UM.FlameProfiler
  11. from UM.FlameProfiler import pyqtSlot
  12. from UM import Util
  13. from UM.Application import Application
  14. from UM.Preferences import Preferences
  15. from UM.Logger import Logger
  16. from UM.Message import Message
  17. from UM.Settings.ContainerRegistry import ContainerRegistry
  18. from UM.Settings.InstanceContainer import InstanceContainer
  19. from UM.Settings.SettingFunction import SettingFunction
  20. from UM.Signal import postponeSignals, CompressTechnique
  21. from cura.Machines.QualityManager import getMachineDefinitionIDForQualitySearch
  22. from cura.PrinterOutputDevice import PrinterOutputDevice
  23. from cura.Settings.ExtruderManager import ExtruderManager
  24. from .CuraStackBuilder import CuraStackBuilder
  25. from UM.i18n import i18nCatalog
  26. catalog = i18nCatalog("cura")
  27. if TYPE_CHECKING:
  28. from cura.Settings.CuraContainerStack import CuraContainerStack
  29. from cura.Settings.GlobalStack import GlobalStack
  30. class MachineManager(QObject):
  31. def __init__(self, parent = None):
  32. super().__init__(parent)
  33. self._active_container_stack = None # type: CuraContainerStack
  34. self._global_container_stack = None # type: GlobalStack
  35. self._current_root_material_id = {}
  36. self._current_root_material_name = {}
  37. self._current_quality_group = None
  38. self._current_quality_changes_group = None
  39. self._default_extruder_position = "0" # to be updated when extruders are switched on and off
  40. self.machine_extruder_material_update_dict = collections.defaultdict(list)
  41. self._error_check_timer = QTimer()
  42. self._error_check_timer.setInterval(250)
  43. self._error_check_timer.setSingleShot(True)
  44. self._error_check_timer.timeout.connect(self._updateStacksHaveErrors)
  45. self._instance_container_timer = QTimer()
  46. self._instance_container_timer.setInterval(250)
  47. self._instance_container_timer.setSingleShot(True)
  48. self._instance_container_timer.timeout.connect(self.__emitChangedSignals)
  49. self._application = Application.getInstance()
  50. self._application.globalContainerStackChanged.connect(self._onGlobalContainerChanged)
  51. self._application.getContainerRegistry().containerLoadComplete.connect(self._onInstanceContainersChanged)
  52. ## When the global container is changed, active material probably needs to be updated.
  53. self.globalContainerChanged.connect(self.activeMaterialChanged)
  54. self.globalContainerChanged.connect(self.activeVariantChanged)
  55. self.globalContainerChanged.connect(self.activeQualityChanged)
  56. self.globalContainerChanged.connect(self.activeQualityChangesGroupChanged)
  57. self.globalContainerChanged.connect(self.activeQualityGroupChanged)
  58. self._stacks_have_errors = None # type:Optional[bool]
  59. self._empty_definition_changes_container = ContainerRegistry.getInstance().findContainers(id = "empty_definition_changes")[0]
  60. self._empty_variant_container = ContainerRegistry.getInstance().findContainers(id = "empty_variant")[0]
  61. self._empty_material_container = ContainerRegistry.getInstance().findContainers(id = "empty_material")[0]
  62. self._empty_quality_container = ContainerRegistry.getInstance().findContainers(id = "empty_quality")[0]
  63. self._empty_quality_changes_container = ContainerRegistry.getInstance().findContainers(id = "empty_quality_changes")[0]
  64. self._onGlobalContainerChanged()
  65. ExtruderManager.getInstance().activeExtruderChanged.connect(self._onActiveExtruderStackChanged)
  66. self._onActiveExtruderStackChanged()
  67. ExtruderManager.getInstance().activeExtruderChanged.connect(self.activeMaterialChanged)
  68. ExtruderManager.getInstance().activeExtruderChanged.connect(self.activeVariantChanged)
  69. ExtruderManager.getInstance().activeExtruderChanged.connect(self.activeQualityChanged)
  70. self.globalContainerChanged.connect(self.activeStackChanged)
  71. self.globalValueChanged.connect(self.activeStackValueChanged)
  72. ExtruderManager.getInstance().activeExtruderChanged.connect(self.activeStackChanged)
  73. self.activeStackChanged.connect(self.activeStackValueChanged)
  74. Preferences.getInstance().addPreference("cura/active_machine", "")
  75. self._global_event_keys = set()
  76. self._printer_output_devices = []
  77. Application.getInstance().getOutputDeviceManager().outputDevicesChanged.connect(self._onOutputDevicesChanged)
  78. # There might already be some output devices by the time the signal is connected
  79. self._onOutputDevicesChanged()
  80. self._application.callLater(self.setInitialActiveMachine)
  81. self._material_incompatible_message = Message(catalog.i18nc("@info:status",
  82. "The selected material is incompatible with the selected machine or configuration."),
  83. title = catalog.i18nc("@info:title", "Incompatible Material"))
  84. containers = ContainerRegistry.getInstance().findInstanceContainers(id = self.activeMaterialId)
  85. if containers:
  86. containers[0].nameChanged.connect(self._onMaterialNameChanged)
  87. self._material_manager = self._application._material_manager
  88. self._quality_manager = self._application.getQualityManager()
  89. # When the materials lookup table gets updated, it can mean that a material has its name changed, which should
  90. # be reflected on the GUI. This signal emission makes sure that it happens.
  91. self._material_manager.materialsUpdated.connect(self.rootMaterialChanged)
  92. activeQualityGroupChanged = pyqtSignal()
  93. activeQualityChangesGroupChanged = pyqtSignal()
  94. globalContainerChanged = pyqtSignal() # Emitted whenever the global stack is changed (ie: when changing between printers, changing a global profile, but not when changing a value)
  95. activeMaterialChanged = pyqtSignal()
  96. activeVariantChanged = pyqtSignal()
  97. activeQualityChanged = pyqtSignal()
  98. activeStackChanged = pyqtSignal() # Emitted whenever the active stack is changed (ie: when changing between extruders, changing a profile, but not when changing a value)
  99. extruderChanged = pyqtSignal()
  100. globalValueChanged = pyqtSignal() # Emitted whenever a value inside global container is changed.
  101. activeStackValueChanged = pyqtSignal() # Emitted whenever a value inside the active stack is changed.
  102. activeStackValidationChanged = pyqtSignal() # Emitted whenever a validation inside active container is changed
  103. stacksValidationChanged = pyqtSignal() # Emitted whenever a validation is changed
  104. blurSettings = pyqtSignal() # Emitted to force fields in the advanced sidebar to un-focus, so they update properly
  105. outputDevicesChanged = pyqtSignal()
  106. rootMaterialChanged = pyqtSignal()
  107. def setInitialActiveMachine(self):
  108. active_machine_id = Preferences.getInstance().getValue("cura/active_machine")
  109. if active_machine_id != "" and ContainerRegistry.getInstance().findContainerStacksMetadata(id = active_machine_id):
  110. # An active machine was saved, so restore it.
  111. self.setActiveMachine(active_machine_id)
  112. # Make sure _active_container_stack is properly initiated
  113. ExtruderManager.getInstance().setActiveExtruderIndex(0)
  114. def _onOutputDevicesChanged(self) -> None:
  115. self._printer_output_devices = []
  116. for printer_output_device in Application.getInstance().getOutputDeviceManager().getOutputDevices():
  117. if isinstance(printer_output_device, PrinterOutputDevice):
  118. self._printer_output_devices.append(printer_output_device)
  119. self.outputDevicesChanged.emit()
  120. @pyqtProperty("QVariantList", notify = outputDevicesChanged)
  121. def printerOutputDevices(self):
  122. return self._printer_output_devices
  123. @pyqtProperty(int, constant=True)
  124. def totalNumberOfSettings(self) -> int:
  125. return len(ContainerRegistry.getInstance().findDefinitionContainers(id = "fdmprinter")[0].getAllKeys())
  126. def _onGlobalContainerChanged(self) -> None:
  127. if self._global_container_stack:
  128. try:
  129. self._global_container_stack.nameChanged.disconnect(self._onMachineNameChanged)
  130. except TypeError: # pyQtSignal gives a TypeError when disconnecting from something that was already disconnected.
  131. pass
  132. try:
  133. self._global_container_stack.containersChanged.disconnect(self._onInstanceContainersChanged)
  134. except TypeError:
  135. pass
  136. try:
  137. self._global_container_stack.propertyChanged.disconnect(self._onPropertyChanged)
  138. except TypeError:
  139. pass
  140. for extruder_stack in ExtruderManager.getInstance().getActiveExtruderStacks():
  141. extruder_stack.propertyChanged.disconnect(self._onPropertyChanged)
  142. extruder_stack.containersChanged.disconnect(self._onInstanceContainersChanged)
  143. # Update the local global container stack reference
  144. self._global_container_stack = Application.getInstance().getGlobalContainerStack()
  145. if self._global_container_stack:
  146. self.updateDefaultExtruder()
  147. self.updateNumberExtrudersEnabled()
  148. self.globalContainerChanged.emit()
  149. # after switching the global stack we reconnect all the signals and set the variant and material references
  150. if self._global_container_stack:
  151. Preferences.getInstance().setValue("cura/active_machine", self._global_container_stack.getId())
  152. self._global_container_stack.nameChanged.connect(self._onMachineNameChanged)
  153. self._global_container_stack.containersChanged.connect(self._onInstanceContainersChanged)
  154. self._global_container_stack.propertyChanged.connect(self._onPropertyChanged)
  155. # Global stack can have only a variant if it is a buildplate
  156. global_variant = self._global_container_stack.variant
  157. if global_variant != self._empty_variant_container:
  158. if global_variant.getMetaDataEntry("hardware_type") != "buildplate":
  159. self._global_container_stack.setVariant(self._empty_variant_container)
  160. # set the global material to empty as we now use the extruder stack at all times - CURA-4482
  161. global_material = self._global_container_stack.material
  162. if global_material != self._empty_material_container:
  163. self._global_container_stack.setMaterial(self._empty_material_container)
  164. # Listen for changes on all extruder stacks
  165. for extruder_stack in ExtruderManager.getInstance().getActiveExtruderStacks():
  166. extruder_stack.propertyChanged.connect(self._onPropertyChanged)
  167. extruder_stack.containersChanged.connect(self._onInstanceContainersChanged)
  168. if self._global_container_stack.getId() in self.machine_extruder_material_update_dict:
  169. for func in self.machine_extruder_material_update_dict[self._global_container_stack.getId()]:
  170. Application.getInstance().callLater(func)
  171. del self.machine_extruder_material_update_dict[self._global_container_stack.getId()]
  172. self.activeQualityGroupChanged.emit()
  173. self._error_check_timer.start()
  174. ## Update self._stacks_valid according to _checkStacksForErrors and emit if change.
  175. def _updateStacksHaveErrors(self) -> None:
  176. old_stacks_have_errors = self._stacks_have_errors
  177. self._stacks_have_errors = self._checkStacksHaveErrors()
  178. if old_stacks_have_errors != self._stacks_have_errors:
  179. self.stacksValidationChanged.emit()
  180. Application.getInstance().stacksValidationFinished.emit()
  181. def _onActiveExtruderStackChanged(self) -> None:
  182. self.blurSettings.emit() # Ensure no-one has focus.
  183. old_active_container_stack = self._active_container_stack
  184. self._active_container_stack = ExtruderManager.getInstance().getActiveExtruderStack()
  185. if old_active_container_stack != self._active_container_stack:
  186. # Many methods and properties related to the active quality actually depend
  187. # on _active_container_stack. If it changes, then the properties change.
  188. self.activeQualityChanged.emit()
  189. def __emitChangedSignals(self) -> None:
  190. self.activeQualityChanged.emit()
  191. self.activeVariantChanged.emit()
  192. self.activeMaterialChanged.emit()
  193. self.rootMaterialChanged.emit()
  194. self._error_check_timer.start()
  195. def _onInstanceContainersChanged(self, container) -> None:
  196. self._instance_container_timer.start()
  197. def _onPropertyChanged(self, key: str, property_name: str) -> None:
  198. if property_name == "value":
  199. # Notify UI items, such as the "changed" star in profile pull down menu.
  200. self.activeStackValueChanged.emit()
  201. elif property_name == "validationState":
  202. self._error_check_timer.start()
  203. ## Given a global_stack, make sure that it's all valid by searching for this quality group and applying it again
  204. def _initMachineState(self, global_stack):
  205. material_dict = {}
  206. for position, extruder in global_stack.extruders.items():
  207. material_dict[position] = extruder.material.getMetaDataEntry("base_file")
  208. self._current_root_material_id = material_dict
  209. global_quality = global_stack.quality
  210. quality_type = global_quality.getMetaDataEntry("quality_type")
  211. global_quality_changes = global_stack.qualityChanges
  212. global_quality_changes_name = global_quality_changes.getName()
  213. if global_quality_changes.getId() != "empty_quality_changes":
  214. quality_changes_groups = self._application._quality_manager.getQualityChangesGroups(global_stack)
  215. if global_quality_changes_name in quality_changes_groups:
  216. new_quality_changes_group = quality_changes_groups[global_quality_changes_name]
  217. self._setQualityChangesGroup(new_quality_changes_group)
  218. else:
  219. quality_groups = self._application._quality_manager.getQualityGroups(global_stack)
  220. if quality_type not in quality_groups:
  221. Logger.log("w", "Quality type [%s] not found in available qualities [%s]", quality_type, str(quality_groups.values()))
  222. self._setEmptyQuality()
  223. return
  224. new_quality_group = quality_groups[quality_type]
  225. self._setQualityGroup(new_quality_group, empty_quality_changes = True)
  226. @pyqtSlot(str)
  227. def setActiveMachine(self, stack_id: str) -> None:
  228. self.blurSettings.emit() # Ensure no-one has focus.
  229. container_registry = ContainerRegistry.getInstance()
  230. containers = container_registry.findContainerStacks(id = stack_id)
  231. if containers:
  232. global_stack = containers[0]
  233. ExtruderManager.getInstance().setActiveExtruderIndex(0) # Switch to first extruder
  234. self._global_container_stack = global_stack
  235. Application.getInstance().setGlobalContainerStack(global_stack)
  236. ExtruderManager.getInstance()._globalContainerStackChanged()
  237. self._initMachineState(containers[0])
  238. self._onGlobalContainerChanged()
  239. self.__emitChangedSignals()
  240. @staticmethod
  241. def getMachine(definition_id: str) -> Optional["GlobalStack"]:
  242. machines = ContainerRegistry.getInstance().findContainerStacks(type = "machine")
  243. for machine in machines:
  244. if machine.definition.getId() == definition_id:
  245. return machine
  246. return None
  247. @pyqtSlot(str, str)
  248. def addMachine(self, name: str, definition_id: str) -> None:
  249. new_stack = CuraStackBuilder.createMachine(name, definition_id)
  250. if new_stack:
  251. # Instead of setting the global container stack here, we set the active machine and so the signals are emitted
  252. self.setActiveMachine(new_stack.getId())
  253. else:
  254. Logger.log("w", "Failed creating a new machine!")
  255. def _checkStacksHaveErrors(self) -> bool:
  256. time_start = time.time()
  257. if self._global_container_stack is None: #No active machine.
  258. return False
  259. if self._global_container_stack.hasErrors():
  260. Logger.log("d", "Checking global stack for errors took %0.2f s and we found and error" % (time.time() - time_start))
  261. return True
  262. # Not a very pretty solution, but the extruder manager doesn't really know how many extruders there are
  263. machine_extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  264. extruder_stacks = ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId())
  265. count = 1 # we start with the global stack
  266. for stack in extruder_stacks:
  267. md = stack.getMetaData()
  268. if "position" in md and int(md["position"]) >= machine_extruder_count:
  269. continue
  270. count += 1
  271. if stack.hasErrors():
  272. Logger.log("d", "Checking %s stacks for errors took %.2f s and we found an error in stack [%s]" % (count, time.time() - time_start, str(stack)))
  273. return True
  274. Logger.log("d", "Checking %s stacks for errors took %.2f s" % (count, time.time() - time_start))
  275. return False
  276. ## Check if the global_container has instances in the user container
  277. @pyqtProperty(bool, notify = activeStackValueChanged)
  278. def hasUserSettings(self) -> bool:
  279. if not self._global_container_stack:
  280. return False
  281. if self._global_container_stack.getTop().findInstances():
  282. return True
  283. stacks = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
  284. for stack in stacks:
  285. if stack.getTop().findInstances():
  286. return True
  287. return False
  288. @pyqtProperty(int, notify = activeStackValueChanged)
  289. def numUserSettings(self) -> int:
  290. if not self._global_container_stack:
  291. return 0
  292. num_user_settings = 0
  293. num_user_settings += len(self._global_container_stack.getTop().findInstances())
  294. stacks = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
  295. for stack in stacks:
  296. num_user_settings += len(stack.getTop().findInstances())
  297. return num_user_settings
  298. ## Delete a user setting from the global stack and all extruder stacks.
  299. # \param key \type{str} the name of the key to delete
  300. @pyqtSlot(str)
  301. def clearUserSettingAllCurrentStacks(self, key: str) -> None:
  302. if not self._global_container_stack:
  303. return
  304. send_emits_containers = []
  305. top_container = self._global_container_stack.getTop()
  306. top_container.removeInstance(key, postpone_emit=True)
  307. send_emits_containers.append(top_container)
  308. linked = not self._global_container_stack.getProperty(key, "settable_per_extruder") or \
  309. self._global_container_stack.getProperty(key, "limit_to_extruder") != "-1"
  310. if not linked:
  311. stack = ExtruderManager.getInstance().getActiveExtruderStack()
  312. stacks = [stack]
  313. else:
  314. stacks = ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId())
  315. for stack in stacks:
  316. if stack is not None:
  317. container = stack.getTop()
  318. container.removeInstance(key, postpone_emit=True)
  319. send_emits_containers.append(container)
  320. for container in send_emits_containers:
  321. container.sendPostponedEmits()
  322. ## Check if none of the stacks contain error states
  323. # Note that the _stacks_have_errors is cached due to performance issues
  324. # Calling _checkStack(s)ForErrors on every change is simply too expensive
  325. @pyqtProperty(bool, notify = stacksValidationChanged)
  326. def stacksHaveErrors(self) -> bool:
  327. return bool(self._stacks_have_errors)
  328. @pyqtProperty(str, notify = globalContainerChanged)
  329. def activeMachineName(self) -> str:
  330. if self._global_container_stack:
  331. return self._global_container_stack.getName()
  332. return ""
  333. @pyqtProperty(str, notify = globalContainerChanged)
  334. def activeMachineId(self) -> str:
  335. if self._global_container_stack:
  336. return self._global_container_stack.getId()
  337. return ""
  338. @pyqtProperty(QObject, notify = globalContainerChanged)
  339. def activeMachine(self) -> Optional["GlobalStack"]:
  340. return self._global_container_stack
  341. @pyqtProperty(str, notify = activeStackChanged)
  342. def activeStackId(self) -> str:
  343. if self._active_container_stack:
  344. return self._active_container_stack.getId()
  345. return ""
  346. @pyqtProperty(QObject, notify = activeStackChanged)
  347. def activeStack(self) -> Optional["ExtruderStack"]:
  348. return self._active_container_stack
  349. @pyqtProperty(str, notify=activeMaterialChanged)
  350. def activeMaterialId(self) -> str:
  351. if self._active_container_stack:
  352. material = self._active_container_stack.material
  353. if material:
  354. return material.getId()
  355. return ""
  356. ## Gets a dict with the active materials ids set in all extruder stacks and the global stack
  357. # (when there is one extruder, the material is set in the global stack)
  358. #
  359. # \return The material ids in all stacks
  360. @pyqtProperty("QVariantMap", notify = activeMaterialChanged)
  361. def allActiveMaterialIds(self) -> Dict[str, str]:
  362. result = {}
  363. active_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  364. if active_stacks is not None: # If we have extruder stacks
  365. for stack in active_stacks:
  366. material_container = stack.material
  367. if not material_container:
  368. continue
  369. result[stack.getId()] = material_container.getId()
  370. return result
  371. ## Gets the layer height of the currently active quality profile.
  372. #
  373. # This is indicated together with the name of the active quality profile.
  374. #
  375. # \return The layer height of the currently active quality profile. If
  376. # there is no quality profile, this returns 0.
  377. @pyqtProperty(float, notify = activeQualityGroupChanged)
  378. def activeQualityLayerHeight(self) -> float:
  379. if not self._global_container_stack:
  380. return 0
  381. if self._current_quality_changes_group:
  382. value = self._global_container_stack.getRawProperty("layer_height", "value", skip_until_container = self._global_container_stack.qualityChanges.getId())
  383. if isinstance(value, SettingFunction):
  384. value = value(self._global_container_stack)
  385. return value
  386. elif self._current_quality_group:
  387. value = self._global_container_stack.getRawProperty("layer_height", "value", skip_until_container = self._global_container_stack.quality.getId())
  388. if isinstance(value, SettingFunction):
  389. value = value(self._global_container_stack)
  390. return value
  391. return 0
  392. @pyqtProperty(str, notify = activeVariantChanged)
  393. def globalVariantName(self) -> str:
  394. if self._global_container_stack:
  395. variant = self._global_container_stack.variant
  396. if variant and not isinstance(variant, type(self._empty_variant_container)):
  397. return variant.getName()
  398. return ""
  399. @pyqtProperty(str, notify = activeQualityGroupChanged)
  400. def activeQualityType(self) -> str:
  401. quality_type = ""
  402. if self._active_container_stack:
  403. if self._current_quality_group:
  404. quality_type = self._current_quality_group.quality_type
  405. return quality_type
  406. @pyqtProperty(bool, notify = activeQualityGroupChanged)
  407. def isActiveQualitySupported(self) -> bool:
  408. is_supported = False
  409. if self._global_container_stack:
  410. if self._current_quality_group:
  411. is_supported = self._current_quality_group.is_available
  412. return is_supported
  413. ## Returns whether there is anything unsupported in the current set-up.
  414. #
  415. # The current set-up signifies the global stack and all extruder stacks,
  416. # so this indicates whether there is any container in any of the container
  417. # stacks that is not marked as supported.
  418. @pyqtProperty(bool, notify = activeQualityChanged)
  419. def isCurrentSetupSupported(self) -> bool:
  420. if not self._global_container_stack:
  421. return False
  422. for stack in [self._global_container_stack] + list(self._global_container_stack.extruders.values()):
  423. for container in stack.getContainers():
  424. if not container:
  425. return False
  426. if not Util.parseBool(container.getMetaDataEntry("supported", True)):
  427. return False
  428. return True
  429. ## Check if a container is read_only
  430. @pyqtSlot(str, result = bool)
  431. def isReadOnly(self, container_id: str) -> bool:
  432. return ContainerRegistry.getInstance().isReadOnly(container_id)
  433. ## Copy the value of the setting of the current extruder to all other extruders as well as the global container.
  434. @pyqtSlot(str)
  435. def copyValueToExtruders(self, key: str):
  436. new_value = self._active_container_stack.getProperty(key, "value")
  437. extruder_stacks = [stack for stack in ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId())]
  438. # check in which stack the value has to be replaced
  439. for extruder_stack in extruder_stacks:
  440. if extruder_stack != self._active_container_stack and extruder_stack.getProperty(key, "value") != new_value:
  441. extruder_stack.userChanges.setProperty(key, "value", new_value) # TODO: nested property access, should be improved
  442. @pyqtProperty(str, notify = activeVariantChanged)
  443. def activeVariantName(self) -> str:
  444. if self._active_container_stack:
  445. variant = self._active_container_stack.variant
  446. if variant:
  447. return variant.getName()
  448. return ""
  449. @pyqtProperty(str, notify = activeVariantChanged)
  450. def activeVariantBuildplateName(self) -> str:
  451. if self._global_container_stack:
  452. variant = self._global_container_stack.variant
  453. if variant:
  454. return variant.getName()
  455. return ""
  456. @pyqtProperty(str, notify = globalContainerChanged)
  457. def activeDefinitionId(self) -> str:
  458. if self._global_container_stack:
  459. return self._global_container_stack.definition.id
  460. return ""
  461. ## Get the Definition ID to use to select quality profiles for the currently active machine
  462. # \returns DefinitionID (string) if found, empty string otherwise
  463. @pyqtProperty(str, notify = globalContainerChanged)
  464. def activeQualityDefinitionId(self) -> str:
  465. if self._global_container_stack:
  466. return getMachineDefinitionIDForQualitySearch(self._global_container_stack)
  467. return ""
  468. ## Gets how the active definition calls variants
  469. # Caveat: per-definition-variant-title is currently not translated (though the fallback is)
  470. @pyqtProperty(str, notify = globalContainerChanged)
  471. def activeDefinitionVariantsName(self) -> str:
  472. fallback_title = catalog.i18nc("@label", "Nozzle")
  473. if self._global_container_stack:
  474. return self._global_container_stack.definition.getMetaDataEntry("variants_name", fallback_title)
  475. return fallback_title
  476. @pyqtSlot(str, str)
  477. def renameMachine(self, machine_id: str, new_name: str):
  478. container_registry = ContainerRegistry.getInstance()
  479. machine_stack = container_registry.findContainerStacks(id = machine_id)
  480. if machine_stack:
  481. new_name = container_registry.createUniqueName("machine", machine_stack[0].getName(), new_name, machine_stack[0].definition.getName())
  482. machine_stack[0].setName(new_name)
  483. self.globalContainerChanged.emit()
  484. @pyqtSlot(str)
  485. def removeMachine(self, machine_id: str):
  486. # If the machine that is being removed is the currently active machine, set another machine as the active machine.
  487. activate_new_machine = (self._global_container_stack and self._global_container_stack.getId() == machine_id)
  488. # activate a new machine before removing a machine because this is safer
  489. if activate_new_machine:
  490. machine_stacks = ContainerRegistry.getInstance().findContainerStacksMetadata(type = "machine")
  491. other_machine_stacks = [s for s in machine_stacks if s["id"] != machine_id]
  492. if other_machine_stacks:
  493. self.setActiveMachine(other_machine_stacks[0]["id"])
  494. ExtruderManager.getInstance().removeMachineExtruders(machine_id)
  495. containers = ContainerRegistry.getInstance().findInstanceContainersMetadata(type = "user", machine = machine_id)
  496. for container in containers:
  497. ContainerRegistry.getInstance().removeContainer(container["id"])
  498. ContainerRegistry.getInstance().removeContainer(machine_id)
  499. @pyqtProperty(bool, notify = globalContainerChanged)
  500. def hasMaterials(self) -> bool:
  501. if self._global_container_stack:
  502. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_materials", False))
  503. return False
  504. @pyqtProperty(bool, notify = globalContainerChanged)
  505. def hasVariants(self) -> bool:
  506. if self._global_container_stack:
  507. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_variants", False))
  508. return False
  509. @pyqtProperty(bool, notify = globalContainerChanged)
  510. def hasVariantBuildplates(self) -> bool:
  511. if self._global_container_stack:
  512. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_variant_buildplates", False))
  513. return False
  514. ## The selected buildplate is compatible if it is compatible with all the materials in all the extruders
  515. @pyqtProperty(bool, notify = activeMaterialChanged)
  516. def variantBuildplateCompatible(self) -> bool:
  517. if not self._global_container_stack:
  518. return True
  519. buildplate_compatible = True # It is compatible by default
  520. extruder_stacks = self._global_container_stack.extruders.values()
  521. for stack in extruder_stacks:
  522. if not stack.isEnabled:
  523. continue
  524. material_container = stack.material
  525. if material_container == self._empty_material_container:
  526. continue
  527. if material_container.getMetaDataEntry("buildplate_compatible"):
  528. buildplate_compatible = buildplate_compatible and material_container.getMetaDataEntry("buildplate_compatible")[self.activeVariantBuildplateName]
  529. return buildplate_compatible
  530. ## The selected buildplate is usable if it is usable for all materials OR it is compatible for one but not compatible
  531. # for the other material but the buildplate is still usable
  532. @pyqtProperty(bool, notify = activeMaterialChanged)
  533. def variantBuildplateUsable(self) -> bool:
  534. if not self._global_container_stack:
  535. return True
  536. # Here the next formula is being calculated:
  537. # result = (not (material_left_compatible and material_right_compatible)) and
  538. # (material_left_compatible or material_left_usable) and
  539. # (material_right_compatible or material_right_usable)
  540. result = not self.variantBuildplateCompatible
  541. extruder_stacks = self._global_container_stack.extruders.values()
  542. for stack in extruder_stacks:
  543. material_container = stack.material
  544. if material_container == self._empty_material_container:
  545. continue
  546. buildplate_compatible = material_container.getMetaDataEntry("buildplate_compatible")[self.activeVariantBuildplateName] if material_container.getMetaDataEntry("buildplate_compatible") else True
  547. buildplate_usable = material_container.getMetaDataEntry("buildplate_recommended")[self.activeVariantBuildplateName] if material_container.getMetaDataEntry("buildplate_recommended") else True
  548. result = result and (buildplate_compatible or buildplate_usable)
  549. return result
  550. ## Property to indicate if a machine has "specialized" material profiles.
  551. # Some machines have their own material profiles that "override" the default catch all profiles.
  552. @pyqtProperty(bool, notify = globalContainerChanged)
  553. def filterMaterialsByMachine(self) -> bool:
  554. if self._global_container_stack:
  555. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_machine_materials", False))
  556. return False
  557. ## Property to indicate if a machine has "specialized" quality profiles.
  558. # Some machines have their own quality profiles that "override" the default catch all profiles.
  559. @pyqtProperty(bool, notify = globalContainerChanged)
  560. def filterQualityByMachine(self) -> bool:
  561. if self._global_container_stack:
  562. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_machine_quality", False))
  563. return False
  564. ## Get the Definition ID of a machine (specified by ID)
  565. # \param machine_id string machine id to get the definition ID of
  566. # \returns DefinitionID (string) if found, None otherwise
  567. @pyqtSlot(str, result = str)
  568. def getDefinitionByMachineId(self, machine_id: str) -> str:
  569. containers = ContainerRegistry.getInstance().findContainerStacks(id = machine_id)
  570. if containers:
  571. return containers[0].definition.getId()
  572. def getIncompatibleSettingsOnEnabledExtruders(self, container):
  573. extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  574. result = []
  575. for setting_instance in container.findInstances():
  576. setting_key = setting_instance.definition.key
  577. setting_enabled = self._global_container_stack.getProperty(setting_key, "enabled")
  578. if not setting_enabled:
  579. # A setting is not visible anymore
  580. result.append(setting_key)
  581. Logger.log("d", "Reset setting [%s] from [%s] because the setting is no longer enabled", setting_key, container)
  582. continue
  583. if not self._global_container_stack.getProperty(setting_key, "type") in ("extruder", "optional_extruder"):
  584. continue
  585. old_value = container.getProperty(setting_key, "value")
  586. if int(old_value) >= extruder_count or not self._global_container_stack.extruders[str(old_value)].isEnabled:
  587. result.append(setting_key)
  588. Logger.log("d", "Reset setting [%s] in [%s] because its old value [%s] is no longer valid", setting_key, container, old_value)
  589. return result
  590. ## Update extruder number to a valid value when the number of extruders are changed, or when an extruder is changed
  591. def correctExtruderSettings(self):
  592. for setting_key in self.getIncompatibleSettingsOnEnabledExtruders(self._global_container_stack.userChanges):
  593. self._global_container_stack.userChanges.removeInstance(setting_key)
  594. add_user_changes = self.getIncompatibleSettingsOnEnabledExtruders(self._global_container_stack.qualityChanges)
  595. for setting_key in add_user_changes:
  596. # Apply quality changes that are incompatible to user changes, so we do not change the quality changes itself.
  597. self._global_container_stack.userChanges.setProperty(setting_key, "value", self._default_extruder_position)
  598. if add_user_changes:
  599. caution_message = Message(catalog.i18nc(
  600. "@info:generic",
  601. "Settings have been changed to match the current availability of extruders: [%s]" % ", ".join(add_user_changes)),
  602. lifetime=0,
  603. title = catalog.i18nc("@info:title", "Settings updated"))
  604. caution_message.show()
  605. ## Set the amount of extruders on the active machine (global stack)
  606. # \param extruder_count int the number of extruders to set
  607. def setActiveMachineExtruderCount(self, extruder_count):
  608. extruder_manager = Application.getInstance().getExtruderManager()
  609. definition_changes_container = self._global_container_stack.definitionChanges
  610. if not self._global_container_stack or definition_changes_container == self._empty_definition_changes_container:
  611. return
  612. previous_extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  613. if extruder_count == previous_extruder_count:
  614. return
  615. definition_changes_container.setProperty("machine_extruder_count", "value", extruder_count)
  616. self.updateDefaultExtruder()
  617. self.updateNumberExtrudersEnabled()
  618. self.correctExtruderSettings()
  619. # Check to see if any objects are set to print with an extruder that will no longer exist
  620. root_node = Application.getInstance().getController().getScene().getRoot()
  621. for node in DepthFirstIterator(root_node):
  622. if node.getMeshData():
  623. extruder_nr = node.callDecoration("getActiveExtruderPosition")
  624. if extruder_nr is not None and int(extruder_nr) > extruder_count - 1:
  625. node.callDecoration("setActiveExtruder", extruder_manager.getExtruderStack(extruder_count - 1).getId())
  626. # Make sure one of the extruder stacks is active
  627. extruder_manager.setActiveExtruderIndex(0)
  628. # Move settable_per_extruder values out of the global container
  629. # After CURA-4482 this should not be the case anymore, but we still want to support older project files.
  630. global_user_container = self._global_container_stack.userChanges
  631. # Make sure extruder_stacks exists
  632. extruder_stacks = []
  633. if previous_extruder_count == 1:
  634. extruder_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  635. global_user_container = self._global_container_stack.userChanges
  636. for setting_instance in global_user_container.findInstances():
  637. setting_key = setting_instance.definition.key
  638. settable_per_extruder = self._global_container_stack.getProperty(setting_key, "settable_per_extruder")
  639. if settable_per_extruder:
  640. limit_to_extruder = int(self._global_container_stack.getProperty(setting_key, "limit_to_extruder"))
  641. extruder_stack = extruder_stacks[max(0, limit_to_extruder)]
  642. extruder_stack.userChanges.setProperty(setting_key, "value", global_user_container.getProperty(setting_key, "value"))
  643. global_user_container.removeInstance(setting_key)
  644. # Signal that the global stack has changed
  645. Application.getInstance().globalContainerStackChanged.emit()
  646. self.forceUpdateAllSettings()
  647. @pyqtSlot(int, result = QObject)
  648. def getExtruder(self, position: int):
  649. extruder = None
  650. if self._global_container_stack:
  651. extruder = self._global_container_stack.extruders.get(str(position))
  652. return extruder
  653. def updateDefaultExtruder(self):
  654. extruder_items = sorted(self._global_container_stack.extruders.items())
  655. old_position = self._default_extruder_position
  656. new_default_position = "0"
  657. for position, extruder in extruder_items:
  658. if extruder.isEnabled:
  659. new_default_position = position
  660. break
  661. if new_default_position != old_position:
  662. self._default_extruder_position = new_default_position
  663. self.extruderChanged.emit()
  664. def updateNumberExtrudersEnabled(self):
  665. definition_changes_container = self._global_container_stack.definitionChanges
  666. extruder_count = 0
  667. for position, extruder in self._global_container_stack.extruders.items():
  668. if extruder.isEnabled:
  669. extruder_count += 1
  670. definition_changes_container.setProperty("extruders_enabled_count", "value", extruder_count)
  671. @pyqtProperty(str, notify = extruderChanged)
  672. def defaultExtruderPosition(self):
  673. return self._default_extruder_position
  674. ## This will fire the propertiesChanged for all settings so they will be updated in the front-end
  675. def forceUpdateAllSettings(self):
  676. property_names = ["value", "resolve"]
  677. for setting_key in self._global_container_stack.getAllKeys():
  678. self._global_container_stack.propertiesChanged.emit(setting_key, property_names)
  679. @pyqtSlot(int, bool)
  680. def setExtruderEnabled(self, position: int, enabled) -> None:
  681. extruder = self.getExtruder(position)
  682. extruder.setEnabled(enabled)
  683. self.updateDefaultExtruder()
  684. self.updateNumberExtrudersEnabled()
  685. self.correctExtruderSettings()
  686. # ensure that the quality profile is compatible with current combination, or choose a compatible one if available
  687. self._updateQualityWithMaterial()
  688. self.extruderChanged.emit()
  689. # update material compatibility color
  690. self.activeQualityGroupChanged.emit()
  691. # update items in SettingExtruder
  692. ExtruderManager.getInstance().extrudersChanged.emit(self._global_container_stack.getId())
  693. # Make sure the front end reflects changes
  694. self.forceUpdateAllSettings()
  695. def _onMachineNameChanged(self):
  696. self.globalContainerChanged.emit()
  697. def _onMaterialNameChanged(self):
  698. self.activeMaterialChanged.emit()
  699. def _onQualityNameChanged(self):
  700. self.activeQualityChanged.emit()
  701. def _getContainerChangedSignals(self) -> List[Signal]:
  702. stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  703. stacks.append(self._global_container_stack)
  704. return [ s.containersChanged for s in stacks ]
  705. @pyqtSlot(str, str, str)
  706. def setSettingForAllExtruders(self, setting_name: str, property_name: str, property_value: str):
  707. for key, extruder in self._global_container_stack.extruders.items():
  708. container = extruder.userChanges
  709. container.setProperty(setting_name, property_name, property_value)
  710. @pyqtProperty("QVariantList", notify = rootMaterialChanged)
  711. def currentExtruderPositions(self):
  712. return sorted(list(self._current_root_material_id.keys()))
  713. @pyqtProperty("QVariant", notify = rootMaterialChanged)
  714. def currentRootMaterialId(self):
  715. # initial filling the current_root_material_id
  716. self._current_root_material_id = {}
  717. for position in self._global_container_stack.extruders:
  718. self._current_root_material_id[position] = self._global_container_stack.extruders[position].material.getMetaDataEntry("base_file")
  719. return self._current_root_material_id
  720. @pyqtProperty("QVariant", notify = rootMaterialChanged)
  721. def currentRootMaterialName(self):
  722. # initial filling the current_root_material_name
  723. if self._global_container_stack:
  724. self._current_root_material_name = {}
  725. for position in self._global_container_stack.extruders:
  726. if position not in self._current_root_material_name:
  727. material = self._global_container_stack.extruders[position].material
  728. self._current_root_material_name[position] = material.getName()
  729. return self._current_root_material_name
  730. ## Return the variant names in the extruder stack(s).
  731. ## For the variant in the global stack, use activeVariantBuildplateName
  732. @pyqtProperty("QVariant", notify = activeVariantChanged)
  733. def activeVariantNames(self):
  734. result = {}
  735. active_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  736. if active_stacks is not None:
  737. for stack in active_stacks:
  738. variant_container = stack.variant
  739. position = stack.getMetaDataEntry("position")
  740. if variant_container and variant_container != self._empty_variant_container:
  741. result[position] = variant_container.getName()
  742. return result
  743. #
  744. # Sets all quality and quality_changes containers to empty_quality and empty_quality_changes containers
  745. # for all stacks in the currently active machine.
  746. #
  747. def _setEmptyQuality(self):
  748. self._current_quality_group = None
  749. self._current_quality_changes_group = None
  750. self._global_container_stack.quality = self._empty_quality_container
  751. self._global_container_stack.qualityChanges = self._empty_quality_changes_container
  752. for extruder in self._global_container_stack.extruders.values():
  753. extruder.quality = self._empty_quality_container
  754. extruder.qualityChanges = self._empty_quality_changes_container
  755. self.activeQualityGroupChanged.emit()
  756. self.activeQualityChangesGroupChanged.emit()
  757. def _setQualityGroup(self, quality_group, empty_quality_changes = True):
  758. self._current_quality_group = quality_group
  759. if empty_quality_changes:
  760. self._current_quality_changes_group = None
  761. # Set quality and quality_changes for the GlobalStack
  762. self._global_container_stack.quality = quality_group.node_for_global.getContainer()
  763. if empty_quality_changes:
  764. self._global_container_stack.qualityChanges = self._empty_quality_changes_container
  765. # Set quality and quality_changes for each ExtruderStack
  766. for position, node in quality_group.nodes_for_extruders.items():
  767. self._global_container_stack.extruders[str(position)].quality = node.getContainer()
  768. if empty_quality_changes:
  769. self._global_container_stack.extruders[str(position)].qualityChanges = self._empty_quality_changes_container
  770. self.activeQualityGroupChanged.emit()
  771. self.activeQualityChangesGroupChanged.emit()
  772. def _setQualityChangesGroup(self, quality_changes_group):
  773. quality_type = quality_changes_group.quality_type
  774. quality_group_dict = self._quality_manager.getQualityGroups(self._global_container_stack)
  775. quality_group = quality_group_dict[quality_type]
  776. quality_changes_container = self._empty_quality_changes_container
  777. quality_container = self._empty_quality_changes_container
  778. if quality_changes_group.node_for_global:
  779. quality_changes_container = quality_changes_group.node_for_global.getContainer()
  780. if quality_group.node_for_global:
  781. quality_container = quality_group.node_for_global.getContainer()
  782. self._global_container_stack.quality = quality_container
  783. self._global_container_stack.qualityChanges = quality_changes_container
  784. for position, extruder in self._global_container_stack.extruders.items():
  785. quality_changes_node = quality_changes_group.nodes_for_extruders.get(position)
  786. quality_node = quality_group.nodes_for_extruders.get(position)
  787. quality_changes_container = self._empty_quality_changes_container
  788. quality_container = self._empty_quality_container
  789. if quality_changes_node:
  790. quality_changes_container = quality_changes_node.getContainer()
  791. if quality_node:
  792. quality_container = quality_node.getContainer()
  793. extruder.quality = quality_container
  794. extruder.qualityChanges = quality_changes_container
  795. self._current_quality_group = quality_group
  796. self._current_quality_changes_group = quality_changes_group
  797. self.activeQualityGroupChanged.emit()
  798. self.activeQualityChangesGroupChanged.emit()
  799. def _setVariantNode(self, position, container_node):
  800. self._global_container_stack.extruders[position].variant = container_node.getContainer()
  801. self.activeVariantChanged.emit()
  802. def _setGlobalVariant(self, container_node):
  803. self._global_container_stack.variant = container_node.getContainer()
  804. def _setMaterial(self, position, container_node = None):
  805. if container_node:
  806. self._global_container_stack.extruders[position].material = container_node.getContainer()
  807. root_material_id = container_node.metadata["base_file"]
  808. root_material_name = container_node.getContainer().getName()
  809. else:
  810. self._global_container_stack.extruders[position].material = self._empty_material_container
  811. root_material_id = None
  812. root_material_name = None
  813. # The _current_root_material_id is used in the MaterialMenu to see which material is selected
  814. if root_material_id != self._current_root_material_id[position]:
  815. self._current_root_material_id[position] = root_material_id
  816. self._current_root_material_name[position] = root_material_name
  817. self.rootMaterialChanged.emit()
  818. def activeMaterialsCompatible(self):
  819. # check material - variant compatibility
  820. if Util.parseBool(self._global_container_stack.getMetaDataEntry("has_materials", False)):
  821. for position, extruder in self._global_container_stack.extruders.items():
  822. if extruder.isEnabled and not extruder.material.getMetaDataEntry("compatible"):
  823. return False
  824. if not extruder.material.getMetaDataEntry("compatible"):
  825. return False
  826. return True
  827. ## Update current quality type and machine after setting material
  828. def _updateQualityWithMaterial(self):
  829. Logger.log("i", "Updating quality/quality_changes due to material change")
  830. current_quality_type = None
  831. if self._current_quality_group:
  832. current_quality_type = self._current_quality_group.quality_type
  833. candidate_quality_groups = self._quality_manager.getQualityGroups(self._global_container_stack)
  834. available_quality_types = {qt for qt, g in candidate_quality_groups.items() if g.is_available}
  835. Logger.log("d", "Current quality type = [%s]", current_quality_type)
  836. if not self.activeMaterialsCompatible():
  837. Logger.log("i", "Active materials are not compatible, setting all qualities to empty (Not Supported).")
  838. self._setEmptyQuality()
  839. return
  840. if not available_quality_types:
  841. Logger.log("i", "No available quality types found, setting all qualities to empty (Not Supported).")
  842. self._setEmptyQuality()
  843. return
  844. if current_quality_type in available_quality_types:
  845. Logger.log("i", "Current available quality type [%s] is available, applying changes.", current_quality_type)
  846. self._setQualityGroup(candidate_quality_groups[current_quality_type], empty_quality_changes = False)
  847. return
  848. # The current quality type is not available so we use the preferred quality type if it's available,
  849. # otherwise use one of the available quality types.
  850. quality_type = sorted(list(available_quality_types))[0]
  851. preferred_quality_type = self._global_container_stack.getMetaDataEntry("preferred_quality_type")
  852. if preferred_quality_type in available_quality_types:
  853. quality_type = preferred_quality_type
  854. Logger.log("i", "The current quality type [%s] is not available, switching to [%s] instead",
  855. current_quality_type, quality_type)
  856. self._setQualityGroup(candidate_quality_groups[quality_type], empty_quality_changes = True)
  857. def _updateMaterialWithVariant(self, position: Optional[str]):
  858. if position is None:
  859. position_list = list(self._global_container_stack.extruders.keys())
  860. else:
  861. position_list = [position]
  862. for position in position_list:
  863. extruder = self._global_container_stack.extruders[position]
  864. current_material_base_name = extruder.material.getMetaDataEntry("base_file")
  865. current_variant_name = extruder.variant.getMetaDataEntry("name")
  866. material_diameter = self._global_container_stack.getProperty("material_diameter", "value")
  867. candidate_materials = self._material_manager.getAvailableMaterials(
  868. self._global_container_stack.definition.getId(),
  869. current_variant_name,
  870. material_diameter)
  871. if not candidate_materials:
  872. self._setMaterial(position, container_node = None)
  873. continue
  874. if current_material_base_name in candidate_materials:
  875. new_material = candidate_materials[current_material_base_name]
  876. self._setMaterial(position, new_material)
  877. continue
  878. @pyqtSlot("QVariant")
  879. def setGlobalVariant(self, container_node):
  880. self.blurSettings.emit()
  881. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  882. self._setGlobalVariant(container_node)
  883. self._updateMaterialWithVariant(None) # Update all materials
  884. self._updateQualityWithMaterial()
  885. @pyqtSlot(str, "QVariant")
  886. def setMaterial(self, position, container_node):
  887. position = str(position)
  888. self.blurSettings.emit()
  889. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  890. self._setMaterial(position, container_node)
  891. self._updateQualityWithMaterial()
  892. @pyqtSlot(str, "QVariant")
  893. def setVariantGroup(self, position, container_node):
  894. position = str(position)
  895. self.blurSettings.emit()
  896. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  897. self._setVariantNode(position, container_node)
  898. self._updateMaterialWithVariant(position)
  899. self._updateQualityWithMaterial()
  900. @pyqtSlot(QObject)
  901. def setQualityGroup(self, quality_group, no_dialog = False):
  902. self.blurSettings.emit()
  903. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  904. self._setQualityGroup(quality_group)
  905. # See if we need to show the Discard or Keep changes screen
  906. if not no_dialog and self.hasUserSettings and Preferences.getInstance().getValue("cura/active_mode") == 1:
  907. self._application.discardOrKeepProfileChanges()
  908. @pyqtProperty(QObject, fset = setQualityGroup, notify = activeQualityGroupChanged)
  909. def activeQualityGroup(self):
  910. return self._current_quality_group
  911. @pyqtSlot(QObject)
  912. def setQualityChangesGroup(self, quality_changes_group, no_dialog = False):
  913. self.blurSettings.emit()
  914. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  915. self._setQualityChangesGroup(quality_changes_group)
  916. # See if we need to show the Discard or Keep changes screen
  917. if not no_dialog and self.hasUserSettings and Preferences.getInstance().getValue("cura/active_mode") == 1:
  918. self._application.discardOrKeepProfileChanges()
  919. @pyqtProperty(QObject, fset = setQualityChangesGroup, notify = activeQualityChangesGroupChanged)
  920. def activeQualityChangesGroup(self):
  921. return self._current_quality_changes_group
  922. @pyqtProperty(str, notify = activeQualityGroupChanged)
  923. def activeQualityOrQualityChangesName(self):
  924. name = self._empty_quality_container.getName()
  925. if self._current_quality_changes_group:
  926. name = self._current_quality_changes_group.name
  927. elif self._current_quality_group:
  928. name = self._current_quality_group.name
  929. return name