MachineManager.py 55 KB

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