MachineManager.py 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  1. # Copyright (c) 2017 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. #Type hinting.
  4. from typing import Union, List, Dict
  5. from UM.Signal import Signal
  6. from PyQt5.QtCore import QObject, pyqtProperty, pyqtSignal, QTimer
  7. from UM.FlameProfiler import pyqtSlot
  8. from PyQt5.QtWidgets import QMessageBox
  9. from UM import Util
  10. from UM.Application import Application
  11. from UM.Preferences import Preferences
  12. from UM.Logger import Logger
  13. from UM.Message import Message
  14. from UM.Decorators import deprecated
  15. from UM.Settings.ContainerRegistry import ContainerRegistry
  16. from UM.Settings.ContainerStack import ContainerStack
  17. from UM.Settings.InstanceContainer import InstanceContainer
  18. from UM.Settings.SettingFunction import SettingFunction
  19. from UM.Signal import postponeSignals, CompressTechnique
  20. import UM.FlameProfiler
  21. from cura.QualityManager import QualityManager
  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. from cura.Settings.ProfilesModel import ProfilesModel
  28. from typing import TYPE_CHECKING, Optional
  29. if TYPE_CHECKING:
  30. from UM.Settings.DefinitionContainer import DefinitionContainer
  31. from cura.Settings.CuraContainerStack import CuraContainerStack
  32. from cura.Settings.GlobalStack import GlobalStack
  33. class MachineManager(QObject):
  34. def __init__(self, parent = None):
  35. super().__init__(parent)
  36. self._active_container_stack = None # type: CuraContainerStack
  37. self._global_container_stack = None # type: GlobalStack
  38. # Used to store the new containers until after confirming the dialog
  39. self._new_variant_container = None
  40. self._new_buildplate_container = None
  41. self._new_material_container = None
  42. self._new_quality_containers = []
  43. self._error_check_timer = QTimer()
  44. self._error_check_timer.setInterval(250)
  45. self._error_check_timer.setSingleShot(True)
  46. self._error_check_timer.timeout.connect(self._updateStacksHaveErrors)
  47. self._instance_container_timer = QTimer()
  48. self._instance_container_timer.setInterval(250)
  49. self._instance_container_timer.setSingleShot(True)
  50. self._instance_container_timer.timeout.connect(self.__emitChangedSignals)
  51. Application.getInstance().globalContainerStackChanged.connect(self._onGlobalContainerChanged)
  52. Application.getInstance().getContainerRegistry().containerLoadComplete.connect(self._onInstanceContainersChanged)
  53. self._connected_to_profiles_model = False
  54. ## When the global container is changed, active material probably needs to be updated.
  55. self.globalContainerChanged.connect(self.activeMaterialChanged)
  56. self.globalContainerChanged.connect(self.activeVariantChanged)
  57. self.globalContainerChanged.connect(self.activeQualityChanged)
  58. self._stacks_have_errors = None
  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. # when a user closed dialog check if any delayed material or variant changes need to be applied
  74. Application.getInstance().onDiscardOrKeepProfileChangesClosed.connect(self._executeDelayedActiveContainerStackChanges)
  75. Preferences.getInstance().addPreference("cura/active_machine", "")
  76. self._global_event_keys = set()
  77. active_machine_id = Preferences.getInstance().getValue("cura/active_machine")
  78. self._printer_output_devices = []
  79. Application.getInstance().getOutputDeviceManager().outputDevicesChanged.connect(self._onOutputDevicesChanged)
  80. # There might already be some output devices by the time the signal is connected
  81. self._onOutputDevicesChanged()
  82. if active_machine_id != "" and ContainerRegistry.getInstance().findContainerStacksMetadata(id = active_machine_id):
  83. # An active machine was saved, so restore it.
  84. self.setActiveMachine(active_machine_id)
  85. # Make sure _active_container_stack is properly initiated
  86. ExtruderManager.getInstance().setActiveExtruderIndex(0)
  87. self._auto_materials_changed = {}
  88. self._auto_hotends_changed = {}
  89. self._material_incompatible_message = Message(catalog.i18nc("@info:status",
  90. "The selected material is incompatible with the selected machine or configuration."),
  91. title = catalog.i18nc("@info:title", "Incompatible Material"))
  92. containers = ContainerRegistry.getInstance().findInstanceContainers(id = self.activeMaterialId)
  93. if containers:
  94. containers[0].nameChanged.connect(self._onMaterialNameChanged)
  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. globalValueChanged = pyqtSignal() # Emitted whenever a value inside global container is changed.
  101. activeStackValueChanged = pyqtSignal() # Emitted whenever a value inside the active stack is changed.
  102. activeStackValidationChanged = pyqtSignal() # Emitted whenever a validation inside active container is changed
  103. stacksValidationChanged = pyqtSignal() # Emitted whenever a validation is changed
  104. blurSettings = pyqtSignal() # Emitted to force fields in the advanced sidebar to un-focus, so they update properly
  105. outputDevicesChanged = pyqtSignal()
  106. def _onOutputDevicesChanged(self) -> None:
  107. for printer_output_device in self._printer_output_devices:
  108. printer_output_device.hotendIdChanged.disconnect(self._onHotendIdChanged)
  109. printer_output_device.materialIdChanged.disconnect(self._onMaterialIdChanged)
  110. self._printer_output_devices = []
  111. for printer_output_device in Application.getInstance().getOutputDeviceManager().getOutputDevices():
  112. if isinstance(printer_output_device, PrinterOutputDevice):
  113. self._printer_output_devices.append(printer_output_device)
  114. printer_output_device.hotendIdChanged.connect(self._onHotendIdChanged)
  115. printer_output_device.materialIdChanged.connect(self._onMaterialIdChanged)
  116. self.outputDevicesChanged.emit()
  117. @property
  118. def newVariant(self):
  119. return self._new_variant_container
  120. @property
  121. def newBuildplate(self):
  122. return self._new_buildplate_container
  123. @property
  124. def newMaterial(self):
  125. return self._new_material_container
  126. @pyqtProperty("QVariantList", notify = outputDevicesChanged)
  127. def printerOutputDevices(self):
  128. return self._printer_output_devices
  129. @pyqtProperty(int, constant=True)
  130. def totalNumberOfSettings(self) -> int:
  131. return len(ContainerRegistry.getInstance().findDefinitionContainers(id = "fdmprinter")[0].getAllKeys())
  132. def _onHotendIdChanged(self):
  133. if not self._global_container_stack or not self._printer_output_devices:
  134. return
  135. active_printer_model = self._printer_output_devices[0].activePrinter
  136. if not active_printer_model:
  137. return
  138. change_found = False
  139. machine_id = self.activeMachineId
  140. extruders = sorted(ExtruderManager.getInstance().getMachineExtruders(machine_id),
  141. key=lambda k: k.getMetaDataEntry("position"))
  142. for extruder_model, extruder in zip(active_printer_model.extruders, extruders):
  143. containers = ContainerRegistry.getInstance().findInstanceContainersMetadata(type="variant",
  144. definition=self._global_container_stack.definition.getId(),
  145. name=extruder_model.hotendID)
  146. if containers:
  147. # The hotend ID is known.
  148. machine_id = self.activeMachineId
  149. if extruder.variant.getName() != extruder_model.hotendID:
  150. change_found = True
  151. self._auto_hotends_changed[extruder.getMetaDataEntry("position")] = containers[0]["id"]
  152. if change_found:
  153. # A change was found, let the output device handle this.
  154. self._printer_output_devices[0].materialHotendChangedMessage(self._materialHotendChangedCallback)
  155. def _onMaterialIdChanged(self):
  156. if not self._global_container_stack or not self._printer_output_devices:
  157. return
  158. active_printer_model = self._printer_output_devices[0].activePrinter
  159. if not active_printer_model:
  160. return
  161. change_found = False
  162. machine_id = self.activeMachineId
  163. extruders = sorted(ExtruderManager.getInstance().getMachineExtruders(machine_id),
  164. key=lambda k: k.getMetaDataEntry("position"))
  165. for extruder_model, extruder in zip(active_printer_model.extruders, extruders):
  166. if extruder_model.activeMaterial is None:
  167. continue
  168. containers = ContainerRegistry.getInstance().findInstanceContainersMetadata(type="material",
  169. definition=self._global_container_stack.definition.getId(),
  170. GUID=extruder_model.activeMaterial.guid)
  171. if containers:
  172. # The material is known.
  173. if extruder.material.getMetaDataEntry("GUID") != extruder_model.activeMaterial.guid:
  174. change_found = True
  175. if self._global_container_stack.definition.getMetaDataEntry("has_variants") and extruder.variant:
  176. variant_id = self.getQualityVariantId(self._global_container_stack.definition,
  177. extruder.variant)
  178. for container in containers:
  179. if container.get("variant") == variant_id:
  180. self._auto_materials_changed[extruder.getMetaDataEntry("position")] = container["id"]
  181. break
  182. else:
  183. # Just use the first result we found.
  184. self._auto_materials_changed[extruder.getMetaDataEntry("position")] = containers[0]["id"]
  185. if change_found:
  186. # A change was found, let the output device handle this.
  187. self._printer_output_devices[0].materialHotendChangedMessage(self._materialHotendChangedCallback)
  188. def _materialHotendChangedCallback(self, button):
  189. if button == QMessageBox.No:
  190. self._auto_materials_changed = {}
  191. self._auto_hotends_changed = {}
  192. return
  193. self._autoUpdateMaterials()
  194. self._autoUpdateHotends()
  195. def _autoUpdateMaterials(self):
  196. extruder_manager = ExtruderManager.getInstance()
  197. for position in self._auto_materials_changed:
  198. material_id = self._auto_materials_changed[position]
  199. old_index = extruder_manager.activeExtruderIndex
  200. if old_index != int(position):
  201. extruder_manager.setActiveExtruderIndex(int(position))
  202. else:
  203. old_index = None
  204. Logger.log("d", "Setting material of hotend %s to %s" % (position, material_id))
  205. self.setActiveMaterial(material_id)
  206. if old_index is not None:
  207. extruder_manager.setActiveExtruderIndex(old_index)
  208. self._auto_materials_changed = {} #Processed all of them now.
  209. def _autoUpdateHotends(self):
  210. extruder_manager = ExtruderManager.getInstance()
  211. for position in self._auto_hotends_changed:
  212. hotend_id = self._auto_hotends_changed[position]
  213. old_index = extruder_manager.activeExtruderIndex
  214. if old_index != int(position):
  215. extruder_manager.setActiveExtruderIndex(int(position))
  216. else:
  217. old_index = None
  218. Logger.log("d", "Setting hotend variant of hotend %s to %s" % (position, hotend_id))
  219. self.setActiveVariant(hotend_id)
  220. if old_index is not None:
  221. extruder_manager.setActiveExtruderIndex(old_index)
  222. self._auto_hotends_changed = {} # Processed all of them now.
  223. def _onGlobalContainerChanged(self):
  224. if self._global_container_stack:
  225. try:
  226. self._global_container_stack.nameChanged.disconnect(self._onMachineNameChanged)
  227. except TypeError: # pyQtSignal gives a TypeError when disconnecting from something that was already disconnected.
  228. pass
  229. try:
  230. self._global_container_stack.containersChanged.disconnect(self._onInstanceContainersChanged)
  231. except TypeError:
  232. pass
  233. try:
  234. self._global_container_stack.propertyChanged.disconnect(self._onPropertyChanged)
  235. except TypeError:
  236. pass
  237. for extruder_stack in ExtruderManager.getInstance().getActiveExtruderStacks():
  238. extruder_stack.propertyChanged.disconnect(self._onPropertyChanged)
  239. extruder_stack.containersChanged.disconnect(self._onInstanceContainersChanged)
  240. # update the local global container stack reference
  241. self._global_container_stack = Application.getInstance().getGlobalContainerStack()
  242. self.globalContainerChanged.emit()
  243. # after switching the global stack we reconnect all the signals and set the variant and material references
  244. if self._global_container_stack:
  245. Preferences.getInstance().setValue("cura/active_machine", self._global_container_stack.getId())
  246. self._global_container_stack.nameChanged.connect(self._onMachineNameChanged)
  247. self._global_container_stack.containersChanged.connect(self._onInstanceContainersChanged)
  248. self._global_container_stack.propertyChanged.connect(self._onPropertyChanged)
  249. # Global stack can have only a variant if it is a buildplate
  250. global_variant = self._global_container_stack.variant
  251. if global_variant != self._empty_variant_container:
  252. if global_variant.getMetaDataEntry("hardware_type") != "buildplate":
  253. self._global_container_stack.setVariant(self._empty_variant_container)
  254. # set the global material to empty as we now use the extruder stack at all times - CURA-4482
  255. global_material = self._global_container_stack.material
  256. if global_material != self._empty_material_container:
  257. self._global_container_stack.setMaterial(self._empty_material_container)
  258. # Listen for changes on all extruder stacks
  259. for extruder_stack in ExtruderManager.getInstance().getActiveExtruderStacks():
  260. extruder_stack.propertyChanged.connect(self._onPropertyChanged)
  261. extruder_stack.containersChanged.connect(self._onInstanceContainersChanged)
  262. self._error_check_timer.start()
  263. ## Update self._stacks_valid according to _checkStacksForErrors and emit if change.
  264. def _updateStacksHaveErrors(self):
  265. old_stacks_have_errors = self._stacks_have_errors
  266. self._stacks_have_errors = self._checkStacksHaveErrors()
  267. if old_stacks_have_errors != self._stacks_have_errors:
  268. self.stacksValidationChanged.emit()
  269. Application.getInstance().stacksValidationFinished.emit()
  270. def _onActiveExtruderStackChanged(self):
  271. self.blurSettings.emit() # Ensure no-one has focus.
  272. old_active_container_stack = self._active_container_stack
  273. self._active_container_stack = ExtruderManager.getInstance().getActiveExtruderStack()
  274. self._error_check_timer.start()
  275. if old_active_container_stack != self._active_container_stack:
  276. # Many methods and properties related to the active quality actually depend
  277. # on _active_container_stack. If it changes, then the properties change.
  278. self.activeQualityChanged.emit()
  279. def __emitChangedSignals(self):
  280. self.activeQualityChanged.emit()
  281. self.activeVariantChanged.emit()
  282. self.activeMaterialChanged.emit()
  283. self._updateStacksHaveErrors() # Prevents unwanted re-slices after changing machine
  284. self._error_check_timer.start()
  285. def _onProfilesModelChanged(self, *args):
  286. self.__emitChangedSignals()
  287. def _onInstanceContainersChanged(self, container):
  288. # This should not trigger the ProfilesModel to be created, or there will be an infinite recursion
  289. if not self._connected_to_profiles_model and ProfilesModel.hasInstance():
  290. # This triggers updating the qualityModel in SidebarSimple whenever ProfilesModel is updated
  291. Logger.log("d", "Connecting profiles model...")
  292. ProfilesModel.getInstance().itemsChanged.connect(self._onProfilesModelChanged)
  293. self._connected_to_profiles_model = True
  294. self._instance_container_timer.start()
  295. def _onPropertyChanged(self, key: str, property_name: str):
  296. if property_name == "value":
  297. # Notify UI items, such as the "changed" star in profile pull down menu.
  298. self.activeStackValueChanged.emit()
  299. elif property_name == "validationState":
  300. self._error_check_timer.start()
  301. @pyqtSlot(str)
  302. def setActiveMachine(self, stack_id: str) -> None:
  303. self.blurSettings.emit() # Ensure no-one has focus.
  304. self._cancelDelayedActiveContainerStackChanges()
  305. container_registry = ContainerRegistry.getInstance()
  306. containers = container_registry.findContainerStacks(id = stack_id)
  307. if containers:
  308. Application.getInstance().setGlobalContainerStack(containers[0])
  309. self.__emitChangedSignals()
  310. @pyqtSlot(str, str)
  311. def addMachine(self, name: str, definition_id: str) -> None:
  312. new_stack = CuraStackBuilder.createMachine(name, definition_id)
  313. if new_stack:
  314. # Instead of setting the global container stack here, we set the active machine and so the signals are emitted
  315. self.setActiveMachine(new_stack.getId())
  316. else:
  317. Logger.log("w", "Failed creating a new machine!")
  318. def _checkStacksHaveErrors(self) -> bool:
  319. if self._global_container_stack is None: #No active machine.
  320. return False
  321. if self._global_container_stack.hasErrors():
  322. return True
  323. for stack in ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()):
  324. if stack.hasErrors():
  325. return True
  326. return False
  327. ## Remove all instances from the top instanceContainer (effectively removing all user-changed settings)
  328. @pyqtSlot()
  329. def clearUserSettings(self):
  330. if not self._active_container_stack:
  331. return
  332. self.blurSettings.emit()
  333. user_settings = self._active_container_stack.getTop()
  334. user_settings.clear()
  335. ## Check if the global_container has instances in the user container
  336. @pyqtProperty(bool, notify = activeStackValueChanged)
  337. def hasUserSettings(self) -> bool:
  338. if not self._global_container_stack:
  339. return False
  340. if self._global_container_stack.getTop().findInstances():
  341. return True
  342. stacks = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
  343. for stack in stacks:
  344. if stack.getTop().findInstances():
  345. return True
  346. return False
  347. @pyqtProperty(int, notify = activeStackValueChanged)
  348. def numUserSettings(self) -> int:
  349. if not self._global_container_stack:
  350. return 0
  351. num_user_settings = 0
  352. num_user_settings += len(self._global_container_stack.getTop().findInstances())
  353. stacks = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
  354. for stack in stacks:
  355. num_user_settings += len(stack.getTop().findInstances())
  356. return num_user_settings
  357. ## Delete a user setting from the global stack and all extruder stacks.
  358. # \param key \type{str} the name of the key to delete
  359. @pyqtSlot(str)
  360. def clearUserSettingAllCurrentStacks(self, key: str):
  361. if not self._global_container_stack:
  362. return
  363. send_emits_containers = []
  364. top_container = self._global_container_stack.getTop()
  365. top_container.removeInstance(key, postpone_emit=True)
  366. send_emits_containers.append(top_container)
  367. linked = not self._global_container_stack.getProperty(key, "settable_per_extruder") or \
  368. self._global_container_stack.getProperty(key, "limit_to_extruder") != "-1"
  369. if not linked:
  370. stack = ExtruderManager.getInstance().getActiveExtruderStack()
  371. stacks = [stack]
  372. else:
  373. stacks = ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId())
  374. for stack in stacks:
  375. if stack is not None:
  376. container = stack.getTop()
  377. container.removeInstance(key, postpone_emit=True)
  378. send_emits_containers.append(container)
  379. for container in send_emits_containers:
  380. container.sendPostponedEmits()
  381. ## Check if none of the stacks contain error states
  382. # Note that the _stacks_have_errors is cached due to performance issues
  383. # Calling _checkStack(s)ForErrors on every change is simply too expensive
  384. @pyqtProperty(bool, notify = stacksValidationChanged)
  385. def stacksHaveErrors(self) -> bool:
  386. return bool(self._stacks_have_errors)
  387. @pyqtProperty(str, notify = activeStackChanged)
  388. def activeUserProfileId(self) -> str:
  389. if self._active_container_stack:
  390. return self._active_container_stack.getTop().getId()
  391. return ""
  392. @pyqtProperty(str, notify = globalContainerChanged)
  393. def activeMachineName(self) -> str:
  394. if self._global_container_stack:
  395. return self._global_container_stack.getName()
  396. return ""
  397. @pyqtProperty(str, notify = globalContainerChanged)
  398. def activeMachineId(self) -> str:
  399. if self._global_container_stack:
  400. return self._global_container_stack.getId()
  401. return ""
  402. @pyqtProperty(QObject, notify = globalContainerChanged)
  403. def activeMachine(self) -> Optional["GlobalStack"]:
  404. return self._global_container_stack
  405. @pyqtProperty(str, notify = activeStackChanged)
  406. def activeStackId(self) -> str:
  407. if self._active_container_stack:
  408. return self._active_container_stack.getId()
  409. return ""
  410. @pyqtProperty(str, notify = activeMaterialChanged)
  411. def activeMaterialName(self) -> str:
  412. if self._active_container_stack:
  413. material = self._active_container_stack.material
  414. if material:
  415. return material.getName()
  416. return ""
  417. @pyqtProperty("QVariantList", notify=activeVariantChanged)
  418. def activeVariantNames(self) -> List[str]:
  419. result = []
  420. active_stacks = ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks()
  421. if active_stacks is not None:
  422. for stack in active_stacks:
  423. variant_container = stack.variant
  424. if variant_container and variant_container != self._empty_variant_container:
  425. result.append(variant_container.getName())
  426. return result
  427. @pyqtProperty("QVariantList", notify = activeMaterialChanged)
  428. def activeMaterialNames(self) -> List[str]:
  429. result = []
  430. active_stacks = ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks()
  431. if active_stacks is not None:
  432. for stack in active_stacks:
  433. material_container = stack.material
  434. if material_container and material_container != self._empty_material_container:
  435. result.append(material_container.getName())
  436. return result
  437. @pyqtProperty(str, notify=activeMaterialChanged)
  438. def activeMaterialId(self) -> str:
  439. if self._active_container_stack:
  440. material = self._active_container_stack.material
  441. if material:
  442. return material.getId()
  443. return ""
  444. @pyqtProperty("QVariantMap", notify = activeVariantChanged)
  445. def allActiveVariantIds(self) -> Dict[str, str]:
  446. result = {}
  447. active_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  448. if active_stacks is not None: #If we have a global stack.
  449. for stack in active_stacks:
  450. variant_container = stack.variant
  451. if not variant_container:
  452. continue
  453. result[stack.getId()] = variant_container.getId()
  454. return result
  455. ## Gets a dict with the active materials ids set in all extruder stacks and the global stack
  456. # (when there is one extruder, the material is set in the global stack)
  457. #
  458. # \return The material ids in all stacks
  459. @pyqtProperty("QVariantMap", notify = activeMaterialChanged)
  460. def allActiveMaterialIds(self) -> Dict[str, str]:
  461. result = {}
  462. active_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  463. if active_stacks is not None: # If we have extruder stacks
  464. for stack in active_stacks:
  465. material_container = stack.material
  466. if not material_container:
  467. continue
  468. result[stack.getId()] = material_container.getId()
  469. return result
  470. ## Gets the layer height of the currently active quality profile.
  471. #
  472. # This is indicated together with the name of the active quality profile.
  473. #
  474. # \return The layer height of the currently active quality profile. If
  475. # there is no quality profile, this returns 0.
  476. @pyqtProperty(float, notify=activeQualityChanged)
  477. def activeQualityLayerHeight(self) -> float:
  478. if not self._global_container_stack:
  479. return 0
  480. quality_changes = self._global_container_stack.qualityChanges
  481. if quality_changes:
  482. value = self._global_container_stack.getRawProperty("layer_height", "value", skip_until_container = quality_changes.getId())
  483. if isinstance(value, SettingFunction):
  484. value = value(self._global_container_stack)
  485. return value
  486. quality = self._global_container_stack.quality
  487. if quality:
  488. value = self._global_container_stack.getRawProperty("layer_height", "value", skip_until_container = quality.getId())
  489. if isinstance(value, SettingFunction):
  490. value = value(self._global_container_stack)
  491. return value
  492. return 0 # No quality profile.
  493. ## Get the Material ID associated with the currently active material
  494. # \returns MaterialID (string) if found, empty string otherwise
  495. @pyqtProperty(str, notify=activeQualityChanged)
  496. def activeQualityMaterialId(self) -> str:
  497. if self._active_container_stack:
  498. quality = self._active_container_stack.quality
  499. if quality:
  500. material_id = quality.getMetaDataEntry("material")
  501. if material_id:
  502. # if the currently active machine inherits its qualities from a different machine
  503. # definition, make sure to return a material that is relevant to that machine definition
  504. definition_id = self.activeDefinitionId
  505. quality_definition_id = self.activeQualityDefinitionId
  506. if definition_id != quality_definition_id:
  507. material_id = material_id.replace(definition_id, quality_definition_id, 1)
  508. return material_id
  509. return ""
  510. @pyqtProperty(str, notify=activeQualityChanged)
  511. def activeQualityName(self) -> str:
  512. if self._active_container_stack and self._global_container_stack:
  513. quality = self._global_container_stack.qualityChanges
  514. if quality and not isinstance(quality, type(self._empty_quality_changes_container)):
  515. return quality.getName()
  516. quality = self._active_container_stack.quality
  517. if quality:
  518. return quality.getName()
  519. return ""
  520. @pyqtProperty(str, notify=activeQualityChanged)
  521. def activeQualityId(self) -> str:
  522. if self._active_container_stack:
  523. quality = self._active_container_stack.quality
  524. if isinstance(quality, type(self._empty_quality_container)):
  525. return ""
  526. quality_changes = self._active_container_stack.qualityChanges
  527. if quality and quality_changes:
  528. if isinstance(quality_changes, type(self._empty_quality_changes_container)):
  529. # It's a built-in profile
  530. return quality.getId()
  531. else:
  532. # Custom profile
  533. return quality_changes.getId()
  534. return ""
  535. @pyqtProperty(str, notify=activeQualityChanged)
  536. def globalQualityId(self) -> str:
  537. if self._global_container_stack:
  538. quality = self._global_container_stack.qualityChanges
  539. if quality and not isinstance(quality, type(self._empty_quality_changes_container)):
  540. return quality.getId()
  541. quality = self._global_container_stack.quality
  542. if quality:
  543. return quality.getId()
  544. return ""
  545. @pyqtProperty(str, notify=activeVariantChanged)
  546. def globalVariantId(self) -> str:
  547. if self._global_container_stack:
  548. variant = self._global_container_stack.variant
  549. if variant and not isinstance(variant, type(self._empty_variant_container)):
  550. return variant.getId()
  551. return ""
  552. @pyqtProperty(str, notify = activeQualityChanged)
  553. def activeQualityType(self) -> str:
  554. if self._active_container_stack:
  555. quality = self._active_container_stack.quality
  556. if quality:
  557. return quality.getMetaDataEntry("quality_type")
  558. return ""
  559. @pyqtProperty(bool, notify = activeQualityChanged)
  560. def isActiveQualitySupported(self) -> bool:
  561. if self._active_container_stack:
  562. quality = self._active_container_stack.quality
  563. if quality:
  564. return Util.parseBool(quality.getMetaDataEntry("supported", True))
  565. return False
  566. ## Returns whether there is anything unsupported in the current set-up.
  567. #
  568. # The current set-up signifies the global stack and all extruder stacks,
  569. # so this indicates whether there is any container in any of the container
  570. # stacks that is not marked as supported.
  571. @pyqtProperty(bool, notify = activeQualityChanged)
  572. def isCurrentSetupSupported(self) -> bool:
  573. if not self._global_container_stack:
  574. return False
  575. for stack in [self._global_container_stack] + list(self._global_container_stack.extruders.values()):
  576. for container in stack.getContainers():
  577. if not container:
  578. return False
  579. if not Util.parseBool(container.getMetaDataEntry("supported", True)):
  580. return False
  581. return True
  582. ## Get the Quality ID associated with the currently active extruder
  583. # Note that this only returns the "quality", not the "quality_changes"
  584. # \returns QualityID (string) if found, empty string otherwise
  585. # \sa activeQualityId()
  586. # \todo Ideally, this method would be named activeQualityId(), and the other one
  587. # would be named something like activeQualityOrQualityChanges() for consistency
  588. @pyqtProperty(str, notify = activeQualityChanged)
  589. def activeQualityContainerId(self) -> str:
  590. # We're using the active stack instead of the global stack in case the list of qualities differs per extruder
  591. if self._global_container_stack:
  592. quality = self._active_container_stack.quality
  593. if quality:
  594. return quality.getId()
  595. return ""
  596. @pyqtProperty(str, notify = activeQualityChanged)
  597. def activeQualityChangesId(self) -> str:
  598. if self._active_container_stack:
  599. quality_changes = self._active_container_stack.qualityChanges
  600. if quality_changes and not isinstance(quality_changes, type(self._empty_quality_changes_container)):
  601. return quality_changes.getId()
  602. return ""
  603. ## Check if a container is read_only
  604. @pyqtSlot(str, result = bool)
  605. def isReadOnly(self, container_id: str) -> bool:
  606. return ContainerRegistry.getInstance().isReadOnly(container_id)
  607. ## Copy the value of the setting of the current extruder to all other extruders as well as the global container.
  608. @pyqtSlot(str)
  609. def copyValueToExtruders(self, key: str):
  610. new_value = self._active_container_stack.getProperty(key, "value")
  611. extruder_stacks = [stack for stack in ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId())]
  612. # check in which stack the value has to be replaced
  613. for extruder_stack in extruder_stacks:
  614. if extruder_stack != self._active_container_stack and extruder_stack.getProperty(key, "value") != new_value:
  615. extruder_stack.userChanges.setProperty(key, "value", new_value) # TODO: nested property access, should be improved
  616. ## Set the active material by switching out a container
  617. # Depending on from/to material+current variant, a quality profile is chosen and set.
  618. @pyqtSlot(str)
  619. def setActiveMaterial(self, material_id: str, always_discard_changes = False):
  620. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  621. containers = ContainerRegistry.getInstance().findInstanceContainers(id = material_id)
  622. if not containers or not self._active_container_stack:
  623. return
  624. material_container = containers[0]
  625. Logger.log("d", "Attempting to change the active material to %s", material_id)
  626. old_material = self._active_container_stack.material
  627. old_quality = self._active_container_stack.quality
  628. old_quality_type = None
  629. if old_quality and old_quality.getId() != self._empty_quality_container.getId():
  630. old_quality_type = old_quality.getMetaDataEntry("quality_type")
  631. old_quality_changes = self._active_container_stack.qualityChanges
  632. if not old_material:
  633. Logger.log("w", "While trying to set the active material, no material was found to replace it.")
  634. return
  635. if old_quality_changes and isinstance(old_quality_changes, type(self._empty_quality_changes_container)):
  636. old_quality_changes = None
  637. self.blurSettings.emit()
  638. old_material.nameChanged.disconnect(self._onMaterialNameChanged)
  639. self._new_material_container = material_container # self._active_container_stack will be updated with a delay
  640. Logger.log("d", "Active material changed")
  641. material_container.nameChanged.connect(self._onMaterialNameChanged)
  642. if material_container.getMetaDataEntry("compatible") == False:
  643. self._material_incompatible_message.show()
  644. else:
  645. self._material_incompatible_message.hide()
  646. quality_type = None
  647. new_quality_id = None
  648. if old_quality:
  649. new_quality_id = old_quality.getId()
  650. quality_type = old_quality.getMetaDataEntry("quality_type")
  651. if old_quality_changes:
  652. quality_type = old_quality_changes.getMetaDataEntry("quality_type")
  653. new_quality_id = old_quality_changes.getId()
  654. global_stack = Application.getInstance().getGlobalContainerStack()
  655. if global_stack:
  656. quality_manager = QualityManager.getInstance()
  657. candidate_quality = None
  658. if quality_type:
  659. candidate_quality = quality_manager.findQualityByQualityType(quality_type,
  660. quality_manager.getWholeMachineDefinition(global_stack.definition),
  661. [material_container.getMetaData()])
  662. if not candidate_quality or candidate_quality.getId() == self._empty_quality_changes_container:
  663. Logger.log("d", "Attempting to find fallback quality")
  664. # Fall back to a quality (which must be compatible with all other extruders)
  665. new_qualities = quality_manager.findAllUsableQualitiesForMachineAndExtruders(
  666. self._global_container_stack, ExtruderManager.getInstance().getExtruderStacks())
  667. quality_types = sorted([q.getMetaDataEntry("quality_type") for q in new_qualities], reverse = True)
  668. quality_type_to_use = None
  669. if quality_types:
  670. # try to use the same quality as before, otherwise the first one in the quality_types
  671. quality_type_to_use = quality_types[0]
  672. if old_quality_type is not None and old_quality_type in quality_type_to_use:
  673. quality_type_to_use = old_quality_type
  674. new_quality = None
  675. for q in new_qualities:
  676. if quality_type_to_use is not None and q.getMetaDataEntry("quality_type") == quality_type_to_use:
  677. new_quality = q
  678. break
  679. if new_quality is not None:
  680. new_quality_id = new_quality.getId() # Just pick the first available one
  681. else:
  682. Logger.log("w", "No quality profile found that matches the current machine and extruders.")
  683. else:
  684. if not old_quality_changes:
  685. new_quality_id = candidate_quality.getId()
  686. self.setActiveQuality(new_quality_id, always_discard_changes = always_discard_changes)
  687. @pyqtSlot(str)
  688. def setActiveVariant(self, variant_id: str, always_discard_changes = False):
  689. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  690. containers = ContainerRegistry.getInstance().findInstanceContainers(id = variant_id)
  691. if not containers or not self._active_container_stack:
  692. return
  693. Logger.log("d", "Attempting to change the active variant to %s", variant_id)
  694. old_variant = self._active_container_stack.variant
  695. old_material = self._active_container_stack.material
  696. if old_variant:
  697. self.blurSettings.emit()
  698. self._new_variant_container = containers[0] # self._active_container_stack will be updated with a delay
  699. Logger.log("d", "Active variant changed to {active_variant_id}".format(active_variant_id = containers[0].getId()))
  700. preferred_material_name = None
  701. if old_material:
  702. preferred_material_name = old_material.getName()
  703. preferred_material_id = self._updateMaterialContainer(self._global_container_stack.definition, self._global_container_stack, containers[0], preferred_material_name).id
  704. self.setActiveMaterial(preferred_material_id, always_discard_changes = always_discard_changes)
  705. else:
  706. Logger.log("w", "While trying to set the active variant, no variant was found to replace.")
  707. @pyqtSlot(str)
  708. def setActiveVariantBuildplate(self, variant_buildplate_id: str):
  709. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  710. containers = ContainerRegistry.getInstance().findInstanceContainers(id = variant_buildplate_id)
  711. if not containers or not self._global_container_stack:
  712. return
  713. Logger.log("d", "Attempting to change the active buildplate to %s", variant_buildplate_id)
  714. old_buildplate = self._global_container_stack.variant
  715. if old_buildplate:
  716. self.blurSettings.emit()
  717. self._new_buildplate_container = containers[0] # self._active_container_stack will be updated with a delay
  718. Logger.log("d", "Active buildplate changed to {active_variant_buildplate_id}".format(active_variant_buildplate_id = containers[0].getId()))
  719. # Force set the active quality as it is so the values are updated
  720. self.setActiveMaterial(self._active_container_stack.material.getId())
  721. else:
  722. Logger.log("w", "While trying to set the active buildplate, no buildplate was found to replace.")
  723. ## set the active quality
  724. # \param quality_id The quality_id of either a quality or a quality_changes
  725. @pyqtSlot(str)
  726. def setActiveQuality(self, quality_id: str, always_discard_changes = False):
  727. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  728. self.blurSettings.emit()
  729. Logger.log("d", "Attempting to change the active quality to %s", quality_id)
  730. containers = ContainerRegistry.getInstance().findInstanceContainersMetadata(id = quality_id)
  731. if not containers or not self._global_container_stack:
  732. return
  733. # Quality profile come in two flavours: type=quality and type=quality_changes
  734. # If we found a quality_changes profile then look up its parent quality profile.
  735. container_type = containers[0].get("type")
  736. quality_name = containers[0]["name"]
  737. quality_type = containers[0].get("quality_type")
  738. # Get quality container and optionally the quality_changes container.
  739. if container_type == "quality":
  740. new_quality_settings_list = self.determineQualityAndQualityChangesForQualityType(quality_type)
  741. elif container_type == "quality_changes":
  742. new_quality_settings_list = self._determineQualityAndQualityChangesForQualityChanges(quality_name)
  743. else:
  744. Logger.log("e", "Tried to set quality to a container that is not of the right type: {container_id}".format(container_id = containers[0]["id"]))
  745. return
  746. # Check if it was at all possible to find new settings
  747. if new_quality_settings_list is None:
  748. return
  749. # check if any of the stacks have a not supported profile
  750. # if that is the case, all stacks should have a not supported state (otherwise it will show quality_type normal)
  751. has_not_supported_quality = False
  752. # check all stacks for not supported
  753. for setting_info in new_quality_settings_list:
  754. if setting_info["quality"].getMetaDataEntry("quality_type") == "not_supported":
  755. has_not_supported_quality = True
  756. break
  757. # set all stacks to not supported if that's the case
  758. if has_not_supported_quality:
  759. for setting_info in new_quality_settings_list:
  760. setting_info["quality"] = self._empty_quality_container
  761. self._new_quality_containers.clear()
  762. # store the upcoming quality profile changes per stack for later execution
  763. # this prevents re-slicing before the user has made a choice in the discard or keep dialog
  764. # (see _executeDelayedActiveContainerStackChanges)
  765. for setting_info in new_quality_settings_list:
  766. stack = setting_info["stack"]
  767. stack_quality = setting_info["quality"]
  768. stack_quality_changes = setting_info["quality_changes"]
  769. self._new_quality_containers.append({
  770. "stack": stack,
  771. "quality": stack_quality,
  772. "quality_changes": stack_quality_changes
  773. })
  774. Logger.log("d", "Active quality changed")
  775. # show the keep/discard dialog after the containers have been switched. Otherwise, the default values on
  776. # the dialog will be the those before the switching.
  777. self._executeDelayedActiveContainerStackChanges()
  778. if self.hasUserSettings and Preferences.getInstance().getValue("cura/active_mode") == 1 and not always_discard_changes:
  779. Application.getInstance().discardOrKeepProfileChanges()
  780. ## Used to update material and variant in the active container stack with a delay.
  781. # This delay prevents the stack from triggering a lot of signals (eventually resulting in slicing)
  782. # before the user decided to keep or discard any of their changes using the dialog.
  783. # The Application.onDiscardOrKeepProfileChangesClosed signal triggers this method.
  784. def _executeDelayedActiveContainerStackChanges(self):
  785. Logger.log("d", "Applying configuration changes...")
  786. if self._new_variant_container is not None:
  787. self._active_container_stack.variant = self._new_variant_container
  788. self._new_variant_container = None
  789. if self._new_buildplate_container is not None:
  790. self._global_container_stack.variant = self._new_buildplate_container
  791. self._new_buildplate_container = None
  792. if self._new_material_container is not None:
  793. self._active_container_stack.material = self._new_material_container
  794. self._new_material_container = None
  795. # apply the new quality to all stacks
  796. if self._new_quality_containers:
  797. for new_quality in self._new_quality_containers:
  798. self._replaceQualityOrQualityChangesInStack(new_quality["stack"], new_quality["quality"], postpone_emit = True)
  799. self._replaceQualityOrQualityChangesInStack(new_quality["stack"], new_quality["quality_changes"], postpone_emit = True)
  800. for new_quality in self._new_quality_containers:
  801. new_quality["stack"].nameChanged.connect(self._onQualityNameChanged)
  802. new_quality["stack"].sendPostponedEmits() # Send the signals that were postponed in _replaceQualityOrQualityChangesInStack
  803. self._new_quality_containers.clear()
  804. Logger.log("d", "New configuration applied")
  805. ## Cancel set changes for material and variant in the active container stack.
  806. # Used for ignoring any changes when switching between printers (setActiveMachine)
  807. def _cancelDelayedActiveContainerStackChanges(self):
  808. self._new_material_container = None
  809. self._new_buildplate_container = None
  810. self._new_variant_container = None
  811. ## Determine the quality and quality changes settings for the current machine for a quality name.
  812. #
  813. # \param quality_name \type{str} the name of the quality.
  814. # \return \type{List[Dict]} with keys "stack", "quality" and "quality_changes".
  815. @UM.FlameProfiler.profile
  816. def determineQualityAndQualityChangesForQualityType(self, quality_type: str) -> List[Dict[str, Union["CuraContainerStack", InstanceContainer]]]:
  817. quality_manager = QualityManager.getInstance()
  818. result = []
  819. empty_quality_changes = self._empty_quality_changes_container
  820. global_container_stack = self._global_container_stack
  821. if not global_container_stack:
  822. return []
  823. global_machine_definition = quality_manager.getParentMachineDefinition(global_container_stack.definition)
  824. extruder_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  825. # find qualities for extruders
  826. for extruder_stack in extruder_stacks:
  827. material_metadata = extruder_stack.material.getMetaData()
  828. # TODO: fix this
  829. if self._new_material_container and extruder_stack.getId() == self._active_container_stack.getId():
  830. material_metadata = self._new_material_container.getMetaData()
  831. quality = quality_manager.findQualityByQualityType(quality_type, global_machine_definition, [material_metadata])
  832. if not quality:
  833. # No quality profile is found for this quality type.
  834. quality = self._empty_quality_container
  835. result.append({
  836. "stack": extruder_stack,
  837. "quality": quality,
  838. "quality_changes": empty_quality_changes
  839. })
  840. # also find a global quality for the machine
  841. global_quality = quality_manager.findQualityByQualityType(quality_type, global_machine_definition, [], global_quality = "True")
  842. # if there is not global quality but we're using a single extrusion machine, copy the quality of the first extruder - CURA-4482
  843. if not global_quality and len(extruder_stacks) == 1:
  844. global_quality = result[0]["quality"]
  845. # if there is still no global quality, set it to empty (not supported)
  846. if not global_quality:
  847. global_quality = self._empty_quality_container
  848. result.append({
  849. "stack": global_container_stack,
  850. "quality": global_quality,
  851. "quality_changes": empty_quality_changes
  852. })
  853. return result
  854. ## Determine the quality and quality changes settings for the current machine for a quality changes name.
  855. #
  856. # \param quality_changes_name \type{str} the name of the quality changes.
  857. # \return \type{List[Dict]} with keys "stack", "quality" and "quality_changes".
  858. def _determineQualityAndQualityChangesForQualityChanges(self, quality_changes_name: str) -> Optional[List[Dict[str, Union["CuraContainerStack", InstanceContainer]]]]:
  859. result = []
  860. quality_manager = QualityManager.getInstance()
  861. global_container_stack = self._global_container_stack
  862. global_machine_definition = quality_manager.getParentMachineDefinition(global_container_stack.definition)
  863. quality_changes_profiles = quality_manager.findQualityChangesByName(quality_changes_name, global_machine_definition)
  864. global_quality_changes = [qcp for qcp in quality_changes_profiles if qcp.getMetaDataEntry("extruder") is None]
  865. if global_quality_changes:
  866. global_quality_changes = global_quality_changes[0]
  867. else:
  868. Logger.log("e", "Could not find the global quality changes container with name %s", quality_changes_name)
  869. return None
  870. # For the global stack, find a quality which matches the quality_type in
  871. # the quality changes profile and also satisfies any material constraints.
  872. quality_type = global_quality_changes.getMetaDataEntry("quality_type")
  873. extruder_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  874. # append the extruder quality changes
  875. for extruder_stack in extruder_stacks:
  876. extruder_definition = quality_manager.getParentMachineDefinition(extruder_stack.definition)
  877. quality_changes_list = [qcp for qcp in quality_changes_profiles if qcp.getMetaDataEntry("extruder") == extruder_definition.getId()]
  878. if quality_changes_list:
  879. quality_changes = quality_changes_list[0]
  880. else:
  881. quality_changes = global_quality_changes
  882. if not quality_changes:
  883. quality_changes = self._empty_quality_changes_container
  884. material_metadata = extruder_stack.material.getMetaData()
  885. if self._new_material_container and self._active_container_stack.getId() == extruder_stack.getId():
  886. material_metadata = self._new_material_container.getMetaData()
  887. quality = quality_manager.findQualityByQualityType(quality_type, global_machine_definition, [material_metadata])
  888. if not quality:
  889. # No quality profile found for this quality type.
  890. quality = self._empty_quality_container
  891. result.append({
  892. "stack": extruder_stack,
  893. "quality": quality,
  894. "quality_changes": quality_changes
  895. })
  896. # append the global quality changes
  897. global_quality = quality_manager.findQualityByQualityType(quality_type, global_machine_definition, global_quality = "True")
  898. # if there is not global quality but we're using a single extrusion machine, copy the quality of the first extruder - CURA-4482
  899. if not global_quality and len(extruder_stacks) == 1:
  900. global_quality = result[0]["quality"]
  901. # if still no global quality changes are found we set it to empty (not supported)
  902. if not global_quality:
  903. global_quality = self._empty_quality_container
  904. result.append({
  905. "stack": global_container_stack,
  906. "quality": global_quality,
  907. "quality_changes": global_quality_changes
  908. })
  909. return result
  910. def _replaceQualityOrQualityChangesInStack(self, stack: "CuraContainerStack", container: "InstanceContainer", postpone_emit = False):
  911. # Disconnect the signal handling from the old container.
  912. container_type = container.getMetaDataEntry("type")
  913. if container_type == "quality":
  914. stack.quality.nameChanged.disconnect(self._onQualityNameChanged)
  915. stack.setQuality(container, postpone_emit = postpone_emit)
  916. stack.quality.nameChanged.connect(self._onQualityNameChanged)
  917. elif container_type == "quality_changes" or container_type is None:
  918. # If the container is an empty container, we need to change the quality_changes.
  919. # Quality can never be set to empty.
  920. stack.qualityChanges.nameChanged.disconnect(self._onQualityNameChanged)
  921. stack.setQualityChanges(container, postpone_emit = postpone_emit)
  922. stack.qualityChanges.nameChanged.connect(self._onQualityNameChanged)
  923. self._onQualityNameChanged()
  924. @pyqtProperty(str, notify = activeVariantChanged)
  925. def activeVariantName(self) -> str:
  926. if self._active_container_stack:
  927. variant = self._active_container_stack.variant
  928. if variant:
  929. return variant.getName()
  930. return ""
  931. @pyqtProperty(str, notify = activeVariantChanged)
  932. def activeVariantId(self) -> str:
  933. if self._active_container_stack:
  934. variant = self._active_container_stack.variant
  935. if variant:
  936. return variant.getId()
  937. return ""
  938. @pyqtProperty(str, notify = activeVariantChanged)
  939. def activeVariantBuildplateName(self) -> str:
  940. if self._global_container_stack:
  941. variant = self._global_container_stack.variant
  942. if variant:
  943. return variant.getName()
  944. return ""
  945. @pyqtProperty(str, notify = globalContainerChanged)
  946. def activeDefinitionId(self) -> str:
  947. if self._global_container_stack:
  948. return self._global_container_stack.definition.id
  949. return ""
  950. @pyqtProperty(str, notify=globalContainerChanged)
  951. def activeDefinitionName(self) -> str:
  952. if self._global_container_stack:
  953. return self._global_container_stack.definition.getName()
  954. return ""
  955. ## Get the Definition ID to use to select quality profiles for the currently active machine
  956. # \returns DefinitionID (string) if found, empty string otherwise
  957. # \sa getQualityDefinitionId
  958. @pyqtProperty(str, notify = globalContainerChanged)
  959. def activeQualityDefinitionId(self) -> str:
  960. if self._global_container_stack:
  961. return self.getQualityDefinitionId(self._global_container_stack.definition)
  962. return ""
  963. ## Get the Definition ID to use to select quality profiles for machines of the specified definition
  964. # This is normally the id of the definition itself, but machines can specify a different definition to inherit qualities from
  965. # \param definition (DefinitionContainer) machine definition
  966. # \returns DefinitionID (string) if found, empty string otherwise
  967. def getQualityDefinitionId(self, definition: "DefinitionContainer") -> str:
  968. return QualityManager.getInstance().getParentMachineDefinition(definition).getId()
  969. ## Get the Variant ID to use to select quality profiles for the currently active variant
  970. # \returns VariantID (string) if found, empty string otherwise
  971. # \sa getQualityVariantId
  972. @pyqtProperty(str, notify = activeVariantChanged)
  973. def activeQualityVariantId(self) -> str:
  974. if self._active_container_stack:
  975. variant = self._active_container_stack.variant
  976. if variant:
  977. return self.getQualityVariantId(self._global_container_stack.definition, variant)
  978. return ""
  979. ## Get the Variant ID to use to select quality profiles for variants of the specified definitions
  980. # This is normally the id of the variant itself, but machines can specify a different definition
  981. # to inherit qualities from, which has consequences for the variant to use as well
  982. # \param definition (DefinitionContainer) machine definition
  983. # \param variant (InstanceContainer) variant definition
  984. # \returns VariantID (string) if found, empty string otherwise
  985. def getQualityVariantId(self, definition: "DefinitionContainer", variant: "InstanceContainer") -> str:
  986. variant_id = variant.getId()
  987. definition_id = definition.getId()
  988. quality_definition_id = self.getQualityDefinitionId(definition)
  989. if definition_id != quality_definition_id:
  990. variant_id = variant_id.replace(definition_id, quality_definition_id, 1)
  991. return variant_id
  992. ## Gets how the active definition calls variants
  993. # Caveat: per-definition-variant-title is currently not translated (though the fallback is)
  994. @pyqtProperty(str, notify = globalContainerChanged)
  995. def activeDefinitionVariantsName(self) -> str:
  996. fallback_title = catalog.i18nc("@label", "Nozzle")
  997. if self._global_container_stack:
  998. return self._global_container_stack.definition.getMetaDataEntry("variants_name", fallback_title)
  999. return fallback_title
  1000. @pyqtSlot(str, str)
  1001. def renameMachine(self, machine_id: str, new_name: str):
  1002. container_registry = ContainerRegistry.getInstance()
  1003. machine_stack = container_registry.findContainerStacks(id = machine_id)
  1004. if machine_stack:
  1005. new_name = container_registry.createUniqueName("machine", machine_stack[0].getName(), new_name, machine_stack[0].definition.getName())
  1006. machine_stack[0].setName(new_name)
  1007. self.globalContainerChanged.emit()
  1008. @pyqtSlot(str)
  1009. def removeMachine(self, machine_id: str):
  1010. # If the machine that is being removed is the currently active machine, set another machine as the active machine.
  1011. activate_new_machine = (self._global_container_stack and self._global_container_stack.getId() == machine_id)
  1012. # activate a new machine before removing a machine because this is safer
  1013. if activate_new_machine:
  1014. machine_stacks = ContainerRegistry.getInstance().findContainerStacksMetadata(type = "machine")
  1015. other_machine_stacks = [s for s in machine_stacks if s["id"] != machine_id]
  1016. if other_machine_stacks:
  1017. self.setActiveMachine(other_machine_stacks[0]["id"])
  1018. ExtruderManager.getInstance().removeMachineExtruders(machine_id)
  1019. containers = ContainerRegistry.getInstance().findInstanceContainersMetadata(type = "user", machine = machine_id)
  1020. for container in containers:
  1021. ContainerRegistry.getInstance().removeContainer(container["id"])
  1022. ContainerRegistry.getInstance().removeContainer(machine_id)
  1023. @pyqtProperty(bool, notify = globalContainerChanged)
  1024. def hasMaterials(self) -> bool:
  1025. if self._global_container_stack:
  1026. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_materials", False))
  1027. return False
  1028. @pyqtProperty(bool, notify = globalContainerChanged)
  1029. def hasVariants(self) -> bool:
  1030. if self._global_container_stack:
  1031. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_variants", False))
  1032. return False
  1033. @pyqtProperty(bool, notify = globalContainerChanged)
  1034. def hasVariantBuildplates(self) -> bool:
  1035. if self._global_container_stack:
  1036. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_variant_buildplates", False))
  1037. return False
  1038. ## The selected buildplate is compatible if it is compatible with all the materials in all the extruders
  1039. @pyqtProperty(bool, notify = activeMaterialChanged)
  1040. def variantBuildplateCompatible(self) -> bool:
  1041. if not self._global_container_stack:
  1042. return True
  1043. buildplate_compatible = True # It is compatible by default
  1044. extruder_stacks = self._global_container_stack.extruders.values()
  1045. for stack in extruder_stacks:
  1046. material_container = stack.material
  1047. if material_container == self._empty_material_container:
  1048. continue
  1049. if material_container.getMetaDataEntry("buildplate_compatible"):
  1050. buildplate_compatible = buildplate_compatible and material_container.getMetaDataEntry("buildplate_compatible")[self.activeVariantBuildplateName]
  1051. return buildplate_compatible
  1052. ## The selected buildplate is usable if it is usable for all materials OR it is compatible for one but not compatible
  1053. # for the other material but the buildplate is still usable
  1054. @pyqtProperty(bool, notify = activeMaterialChanged)
  1055. def variantBuildplateUsable(self) -> bool:
  1056. if not self._global_container_stack:
  1057. return True
  1058. # Here the next formula is being calculated:
  1059. # result = (not (material_left_compatible and material_right_compatible)) and
  1060. # (material_left_compatible or material_left_usable) and
  1061. # (material_right_compatible or material_right_usable)
  1062. result = not self.variantBuildplateCompatible
  1063. extruder_stacks = self._global_container_stack.extruders.values()
  1064. for stack in extruder_stacks:
  1065. material_container = stack.material
  1066. if material_container == self._empty_material_container:
  1067. continue
  1068. buildplate_compatible = material_container.getMetaDataEntry("buildplate_compatible")[self.activeVariantBuildplateName] if material_container.getMetaDataEntry("buildplate_compatible") else True
  1069. buildplate_usable = material_container.getMetaDataEntry("buildplate_recommended")[self.activeVariantBuildplateName] if material_container.getMetaDataEntry("buildplate_recommended") else True
  1070. result = result and (buildplate_compatible or buildplate_usable)
  1071. return result
  1072. ## Property to indicate if a machine has "specialized" material profiles.
  1073. # Some machines have their own material profiles that "override" the default catch all profiles.
  1074. @pyqtProperty(bool, notify = globalContainerChanged)
  1075. def filterMaterialsByMachine(self) -> bool:
  1076. if self._global_container_stack:
  1077. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_machine_materials", False))
  1078. return False
  1079. ## Property to indicate if a machine has "specialized" quality profiles.
  1080. # Some machines have their own quality profiles that "override" the default catch all profiles.
  1081. @pyqtProperty(bool, notify = globalContainerChanged)
  1082. def filterQualityByMachine(self) -> bool:
  1083. if self._global_container_stack:
  1084. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_machine_quality", False))
  1085. return False
  1086. ## Get the Definition ID of a machine (specified by ID)
  1087. # \param machine_id string machine id to get the definition ID of
  1088. # \returns DefinitionID (string) if found, None otherwise
  1089. @pyqtSlot(str, result = str)
  1090. def getDefinitionByMachineId(self, machine_id: str) -> str:
  1091. containers = ContainerRegistry.getInstance().findContainerStacks(id = machine_id)
  1092. if containers:
  1093. return containers[0].definition.getId()
  1094. @staticmethod
  1095. def createMachineManager():
  1096. return MachineManager()
  1097. @deprecated("Use ExtruderStack.material = ... and it won't be necessary", "2.7")
  1098. def _updateMaterialContainer(self, definition: "DefinitionContainer", stack: "ContainerStack", variant_container: Optional["InstanceContainer"] = None, preferred_material_name: Optional[str] = None) -> InstanceContainer:
  1099. if not definition.getMetaDataEntry("has_materials"):
  1100. return self._empty_material_container
  1101. approximate_material_diameter = str(round(stack.getProperty("material_diameter", "value")))
  1102. search_criteria = { "type": "material", "approximate_diameter": approximate_material_diameter }
  1103. if definition.getMetaDataEntry("has_machine_materials"):
  1104. search_criteria["definition"] = self.getQualityDefinitionId(definition)
  1105. if definition.getMetaDataEntry("has_variants") and variant_container:
  1106. search_criteria["variant"] = self.getQualityVariantId(definition, variant_container)
  1107. else:
  1108. search_criteria["definition"] = "fdmprinter"
  1109. if preferred_material_name:
  1110. search_criteria["name"] = preferred_material_name
  1111. else:
  1112. preferred_material = definition.getMetaDataEntry("preferred_material")
  1113. if preferred_material:
  1114. search_criteria["id"] = preferred_material
  1115. containers = ContainerRegistry.getInstance().findInstanceContainers(**search_criteria)
  1116. if containers:
  1117. return containers[0]
  1118. if "variant" in search_criteria or "id" in search_criteria:
  1119. # If a material by this name can not be found, try a wider set of search criteria
  1120. search_criteria.pop("variant", None)
  1121. search_criteria.pop("id", None)
  1122. containers = ContainerRegistry.getInstance().findInstanceContainers(**search_criteria)
  1123. if containers:
  1124. return containers[0]
  1125. Logger.log("w", "Unable to find a material container with provided criteria, returning an empty one instead.")
  1126. return self._empty_material_container
  1127. def _onMachineNameChanged(self):
  1128. self.globalContainerChanged.emit()
  1129. def _onMaterialNameChanged(self):
  1130. self.activeMaterialChanged.emit()
  1131. def _onQualityNameChanged(self):
  1132. self.activeQualityChanged.emit()
  1133. def _getContainerChangedSignals(self) -> List[Signal]:
  1134. stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  1135. stacks.append(self._global_container_stack)
  1136. return [ s.containersChanged for s in stacks ]