MachineManager.py 71 KB

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