MachineManager.py 66 KB

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