MachineManager.py 72 KB

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