MachineManager.py 64 KB

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