MachineManager.py 51 KB

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