MachineManager.py 73 KB

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