MachineManager.py 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import time
  4. import re
  5. import unicodedata
  6. from typing import Any, List, Dict, TYPE_CHECKING, Optional, cast
  7. from PyQt5.QtCore import QObject, pyqtProperty, pyqtSignal, QTimer
  8. from UM.ConfigurationErrorMessage import ConfigurationErrorMessage
  9. from UM.Decorators import deprecated
  10. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  11. from UM.Settings.InstanceContainer import InstanceContainer
  12. from UM.Settings.Interfaces import ContainerInterface
  13. from UM.Signal import Signal
  14. from UM.FlameProfiler import pyqtSlot
  15. from UM import Util
  16. from UM.Logger import Logger
  17. from UM.Message import Message
  18. from UM.Settings.SettingFunction import SettingFunction
  19. from UM.Signal import postponeSignals, CompressTechnique
  20. import cura.CuraApplication # Imported like this to prevent circular references.
  21. from cura.Machines.ContainerNode import ContainerNode
  22. from cura.Machines.ContainerTree import ContainerTree
  23. from cura.PrinterOutput.PrinterOutputDevice import PrinterOutputDevice, ConnectionType
  24. from cura.PrinterOutput.Models.PrinterConfigurationModel import PrinterConfigurationModel
  25. from cura.PrinterOutput.Models.ExtruderConfigurationModel import ExtruderConfigurationModel
  26. from cura.PrinterOutput.Models.MaterialOutputModel import MaterialOutputModel
  27. from cura.Settings.CuraContainerRegistry import CuraContainerRegistry
  28. from cura.Settings.ExtruderManager import ExtruderManager
  29. from cura.Settings.ExtruderStack import ExtruderStack
  30. from cura.Settings.cura_empty_instance_containers import (empty_definition_changes_container, empty_variant_container,
  31. empty_material_container, empty_quality_container,
  32. empty_quality_changes_container, empty_intent_container)
  33. from .CuraStackBuilder import CuraStackBuilder
  34. from UM.i18n import i18nCatalog
  35. catalog = i18nCatalog("cura")
  36. from cura.Settings.GlobalStack import GlobalStack
  37. if TYPE_CHECKING:
  38. from cura.CuraApplication import CuraApplication
  39. from cura.Machines.MaterialNode import MaterialNode
  40. from cura.Machines.QualityChangesGroup import QualityChangesGroup
  41. from cura.Machines.QualityGroup import QualityGroup
  42. from cura.Machines.VariantNode import VariantNode
  43. class MachineManager(QObject):
  44. def __init__(self, application: "CuraApplication", parent: Optional["QObject"] = None) -> None:
  45. super().__init__(parent)
  46. self._active_container_stack = None # type: Optional[ExtruderStack]
  47. self._global_container_stack = None # type: Optional[GlobalStack]
  48. self._current_root_material_id = {} # type: Dict[str, str]
  49. self._default_extruder_position = "0" # to be updated when extruders are switched on and off
  50. self._instance_container_timer = QTimer() # type: QTimer
  51. self._instance_container_timer.setInterval(250)
  52. self._instance_container_timer.setSingleShot(True)
  53. self._instance_container_timer.timeout.connect(self.__emitChangedSignals)
  54. self._application = application
  55. self._container_registry = self._application.getContainerRegistry()
  56. self._application.globalContainerStackChanged.connect(self._onGlobalContainerChanged)
  57. self._container_registry.containerLoadComplete.connect(self._onContainersChanged)
  58. # When the global container is changed, active material probably needs to be updated.
  59. self.globalContainerChanged.connect(self.activeMaterialChanged)
  60. self.globalContainerChanged.connect(self.activeVariantChanged)
  61. self.globalContainerChanged.connect(self.activeQualityChanged)
  62. self.globalContainerChanged.connect(self.activeQualityChangesGroupChanged)
  63. self.globalContainerChanged.connect(self.activeQualityGroupChanged)
  64. self._stacks_have_errors = None # type: Optional[bool]
  65. self._onGlobalContainerChanged()
  66. extruder_manager = self._application.getExtruderManager()
  67. extruder_manager.activeExtruderChanged.connect(self._onActiveExtruderStackChanged)
  68. self._onActiveExtruderStackChanged()
  69. extruder_manager.activeExtruderChanged.connect(self.activeMaterialChanged)
  70. extruder_manager.activeExtruderChanged.connect(self.activeVariantChanged)
  71. extruder_manager.activeExtruderChanged.connect(self.activeQualityChanged)
  72. self.globalContainerChanged.connect(self.activeStackChanged)
  73. self.globalValueChanged.connect(self.activeStackValueChanged)
  74. ExtruderManager.getInstance().activeExtruderChanged.connect(self.activeStackChanged)
  75. self.activeStackChanged.connect(self.activeStackValueChanged)
  76. self._application.getPreferences().addPreference("cura/active_machine", "")
  77. self._printer_output_devices = [] # type: List[PrinterOutputDevice]
  78. self._application.getOutputDeviceManager().outputDevicesChanged.connect(self._onOutputDevicesChanged)
  79. # There might already be some output devices by the time the signal is connected
  80. self._onOutputDevicesChanged()
  81. self._current_printer_configuration = PrinterConfigurationModel() # Indicates the current configuration setup in this printer
  82. self.activeMaterialChanged.connect(self._onCurrentConfigurationChanged)
  83. self.activeVariantChanged.connect(self._onCurrentConfigurationChanged)
  84. # Force to compute the current configuration
  85. self._onCurrentConfigurationChanged()
  86. self._application.callLater(self.setInitialActiveMachine)
  87. containers = CuraContainerRegistry.getInstance().findInstanceContainers(id = self.activeMaterialId) # type: List[InstanceContainer]
  88. if containers:
  89. containers[0].nameChanged.connect(self._onMaterialNameChanged)
  90. self.rootMaterialChanged.connect(self._onRootMaterialChanged)
  91. # Emit the printerConnectedStatusChanged when either globalContainerChanged or outputDevicesChanged are emitted
  92. self.globalContainerChanged.connect(self.printerConnectedStatusChanged)
  93. self.outputDevicesChanged.connect(self.printerConnectedStatusChanged)
  94. activeQualityGroupChanged = pyqtSignal()
  95. activeQualityChangesGroupChanged = pyqtSignal()
  96. globalContainerChanged = pyqtSignal() # Emitted whenever the global stack is changed (ie: when changing between printers, changing a global profile, but not when changing a value)
  97. activeMaterialChanged = pyqtSignal()
  98. activeVariantChanged = pyqtSignal()
  99. activeQualityChanged = pyqtSignal()
  100. activeIntentChanged = pyqtSignal()
  101. activeStackChanged = pyqtSignal() # Emitted whenever the active stack is changed (ie: when changing between extruders, changing a profile, but not when changing a value)
  102. extruderChanged = pyqtSignal()
  103. globalValueChanged = pyqtSignal() # Emitted whenever a value inside global container is changed.
  104. activeStackValueChanged = pyqtSignal() # Emitted whenever a value inside the active stack is changed.
  105. activeStackValidationChanged = pyqtSignal() # Emitted whenever a validation inside active container is changed
  106. stacksValidationChanged = pyqtSignal() # Emitted whenever a validation is changed
  107. numberExtrudersEnabledChanged = pyqtSignal() # Emitted when the number of extruders that are enabled changed
  108. blurSettings = pyqtSignal() # Emitted to force fields in the advanced sidebar to un-focus, so they update properly
  109. outputDevicesChanged = pyqtSignal()
  110. currentConfigurationChanged = pyqtSignal() # Emitted every time the current configurations of the machine changes
  111. printerConnectedStatusChanged = pyqtSignal() # Emitted every time the active machine change or the outputdevices change
  112. rootMaterialChanged = pyqtSignal()
  113. discoveredPrintersChanged = pyqtSignal()
  114. def setInitialActiveMachine(self) -> None:
  115. active_machine_id = self._application.getPreferences().getValue("cura/active_machine")
  116. if active_machine_id != "" and CuraContainerRegistry.getInstance().findContainerStacksMetadata(id = active_machine_id):
  117. # An active machine was saved, so restore it.
  118. self.setActiveMachine(active_machine_id)
  119. def _onOutputDevicesChanged(self) -> None:
  120. self._printer_output_devices = []
  121. for printer_output_device in self._application.getOutputDeviceManager().getOutputDevices():
  122. if isinstance(printer_output_device, PrinterOutputDevice):
  123. self._printer_output_devices.append(printer_output_device)
  124. self.outputDevicesChanged.emit()
  125. @pyqtProperty(QObject, notify = currentConfigurationChanged)
  126. def currentConfiguration(self) -> PrinterConfigurationModel:
  127. return self._current_printer_configuration
  128. def _onCurrentConfigurationChanged(self) -> None:
  129. if not self._global_container_stack:
  130. return
  131. # Create the configuration model with the current data in Cura
  132. self._current_printer_configuration.printerType = self._global_container_stack.definition.getName()
  133. self._current_printer_configuration.extruderConfigurations = []
  134. for extruder in self._global_container_stack.extruders.values():
  135. extruder_configuration = ExtruderConfigurationModel()
  136. # For compare just the GUID is needed at this moment
  137. mat_type = extruder.material.getMetaDataEntry("material") if extruder.material != empty_material_container else None
  138. mat_guid = extruder.material.getMetaDataEntry("GUID") if extruder.material != empty_material_container else None
  139. mat_color = extruder.material.getMetaDataEntry("color_name") if extruder.material != empty_material_container else None
  140. mat_brand = extruder.material.getMetaDataEntry("brand") if extruder.material != empty_material_container else None
  141. mat_name = extruder.material.getMetaDataEntry("name") if extruder.material != empty_material_container else None
  142. material_model = MaterialOutputModel(mat_guid, mat_type, mat_color, mat_brand, mat_name)
  143. extruder_configuration.position = int(extruder.getMetaDataEntry("position"))
  144. extruder_configuration.material = material_model
  145. extruder_configuration.hotendID = extruder.variant.getName() if extruder.variant != empty_variant_container else None
  146. self._current_printer_configuration.extruderConfigurations.append(extruder_configuration)
  147. # An empty build plate configuration from the network printer is presented as an empty string, so use "" for an
  148. # empty build plate.
  149. self._current_printer_configuration.buildplateConfiguration = self._global_container_stack.getProperty("machine_buildplate_type", "value") if self._global_container_stack.variant != empty_variant_container else ""
  150. self.currentConfigurationChanged.emit()
  151. @pyqtSlot(QObject, result = bool)
  152. def matchesConfiguration(self, configuration: PrinterConfigurationModel) -> bool:
  153. return self._current_printer_configuration == configuration
  154. @pyqtProperty("QVariantList", notify = outputDevicesChanged)
  155. def printerOutputDevices(self) -> List[PrinterOutputDevice]:
  156. return self._printer_output_devices
  157. @pyqtProperty(int, constant=True)
  158. def totalNumberOfSettings(self) -> int:
  159. general_definition_containers = CuraContainerRegistry.getInstance().findDefinitionContainers(id = "fdmprinter")
  160. if not general_definition_containers:
  161. return 0
  162. return len(general_definition_containers[0].getAllKeys())
  163. def _onGlobalContainerChanged(self) -> None:
  164. if self._global_container_stack:
  165. try:
  166. self._global_container_stack.nameChanged.disconnect(self._onMachineNameChanged)
  167. except TypeError: # pyQtSignal gives a TypeError when disconnecting from something that was already disconnected.
  168. pass
  169. try:
  170. self._global_container_stack.containersChanged.disconnect(self._onContainersChanged)
  171. except TypeError:
  172. pass
  173. try:
  174. self._global_container_stack.propertyChanged.disconnect(self._onPropertyChanged)
  175. except TypeError:
  176. pass
  177. for extruder_stack in ExtruderManager.getInstance().getActiveExtruderStacks():
  178. extruder_stack.propertyChanged.disconnect(self._onPropertyChanged)
  179. extruder_stack.containersChanged.disconnect(self._onContainersChanged)
  180. # Update the local global container stack reference
  181. self._global_container_stack = self._application.getGlobalContainerStack()
  182. if self._global_container_stack:
  183. self.updateDefaultExtruder()
  184. self.updateNumberExtrudersEnabled()
  185. self.globalContainerChanged.emit()
  186. # After switching the global stack we reconnect all the signals and set the variant and material references
  187. if self._global_container_stack:
  188. self._application.getPreferences().setValue("cura/active_machine", self._global_container_stack.getId())
  189. self._global_container_stack.nameChanged.connect(self._onMachineNameChanged)
  190. self._global_container_stack.containersChanged.connect(self._onContainersChanged)
  191. self._global_container_stack.propertyChanged.connect(self._onPropertyChanged)
  192. # Global stack can have only a variant if it is a buildplate
  193. global_variant = self._global_container_stack.variant
  194. if global_variant != empty_variant_container:
  195. if global_variant.getMetaDataEntry("hardware_type") != "buildplate":
  196. self._global_container_stack.setVariant(empty_variant_container)
  197. # Set the global material to empty as we now use the extruder stack at all times - CURA-4482
  198. global_material = self._global_container_stack.material
  199. if global_material != empty_material_container:
  200. self._global_container_stack.setMaterial(empty_material_container)
  201. # Listen for changes on all extruder stacks
  202. for extruder_stack in ExtruderManager.getInstance().getActiveExtruderStacks():
  203. extruder_stack.propertyChanged.connect(self._onPropertyChanged)
  204. extruder_stack.containersChanged.connect(self._onContainersChanged)
  205. self.activeQualityGroupChanged.emit()
  206. def _onActiveExtruderStackChanged(self) -> None:
  207. self.blurSettings.emit() # Ensure no-one has focus.
  208. if self._active_container_stack is not None:
  209. self._active_container_stack.pyqtContainersChanged.disconnect(self.activeStackChanged) # Unplug from the old one.
  210. self._active_container_stack = ExtruderManager.getInstance().getActiveExtruderStack()
  211. if self._active_container_stack is not None:
  212. self._active_container_stack.pyqtContainersChanged.connect(self.activeStackChanged) # Plug into the new one.
  213. def __emitChangedSignals(self) -> None:
  214. self.activeQualityChanged.emit()
  215. self.activeVariantChanged.emit()
  216. self.activeMaterialChanged.emit()
  217. self.activeIntentChanged.emit()
  218. self.rootMaterialChanged.emit()
  219. self.numberExtrudersEnabledChanged.emit()
  220. def _onContainersChanged(self, container: ContainerInterface) -> None:
  221. self._instance_container_timer.start()
  222. def _onPropertyChanged(self, key: str, property_name: str) -> None:
  223. if property_name == "value":
  224. # Notify UI items, such as the "changed" star in profile pull down menu.
  225. self.activeStackValueChanged.emit()
  226. @pyqtSlot(str)
  227. def setActiveMachine(self, stack_id: str) -> None:
  228. self.blurSettings.emit() # Ensure no-one has focus.
  229. container_registry = CuraContainerRegistry.getInstance()
  230. containers = container_registry.findContainerStacks(id = stack_id)
  231. if not containers:
  232. return
  233. global_stack = containers[0]
  234. # Make sure that the default machine actions for this machine have been added
  235. self._application.getMachineActionManager().addDefaultMachineActions(global_stack)
  236. ExtruderManager.getInstance().fixSingleExtrusionMachineExtruderDefinition(global_stack)
  237. if not global_stack.isValid():
  238. # Mark global stack as invalid
  239. ConfigurationErrorMessage.getInstance().addFaultyContainers(global_stack.getId())
  240. return # We're done here
  241. self._global_container_stack = global_stack
  242. self._application.setGlobalContainerStack(global_stack)
  243. ExtruderManager.getInstance()._globalContainerStackChanged()
  244. self._onGlobalContainerChanged()
  245. # Switch to the first enabled extruder
  246. self.updateDefaultExtruder()
  247. default_extruder_position = int(self.defaultExtruderPosition)
  248. ExtruderManager.getInstance().setActiveExtruderIndex(default_extruder_position)
  249. self.__emitChangedSignals()
  250. ## Given a definition id, return the machine with this id.
  251. # Optional: add a list of keys and values to filter the list of machines with the given definition id
  252. # \param definition_id \type{str} definition id that needs to look for
  253. # \param metadata_filter \type{dict} list of metadata keys and values used for filtering
  254. @staticmethod
  255. def getMachine(definition_id: str, metadata_filter: Optional[Dict[str, str]] = None) -> Optional["GlobalStack"]:
  256. if metadata_filter is None:
  257. metadata_filter = {}
  258. machines = CuraContainerRegistry.getInstance().findContainerStacks(type = "machine", **metadata_filter)
  259. for machine in machines:
  260. if machine.definition.getId() == definition_id:
  261. return cast(GlobalStack, machine)
  262. return None
  263. @pyqtSlot(str)
  264. @pyqtSlot(str, str)
  265. def addMachine(self, definition_id: str, name: Optional[str] = None) -> None:
  266. Logger.log("i", "Trying to add a machine with the definition id [%s]", definition_id)
  267. if name is None:
  268. definitions = CuraContainerRegistry.getInstance().findDefinitionContainers(id = definition_id)
  269. if definitions:
  270. name = definitions[0].getName()
  271. else:
  272. name = definition_id
  273. new_stack = CuraStackBuilder.createMachine(cast(str, name), definition_id)
  274. if new_stack:
  275. # Instead of setting the global container stack here, we set the active machine and so the signals are emitted
  276. self.setActiveMachine(new_stack.getId())
  277. else:
  278. Logger.log("w", "Failed creating a new machine!")
  279. def _checkStacksHaveErrors(self) -> bool:
  280. time_start = time.time()
  281. if self._global_container_stack is None: #No active machine.
  282. return False
  283. if self._global_container_stack.hasErrors():
  284. Logger.log("d", "Checking global stack for errors took %0.2f s and we found an error" % (time.time() - time_start))
  285. return True
  286. # Not a very pretty solution, but the extruder manager doesn't really know how many extruders there are
  287. machine_extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  288. extruder_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  289. count = 1 # We start with the global stack
  290. for stack in extruder_stacks:
  291. md = stack.getMetaData()
  292. if "position" in md and int(md["position"]) >= machine_extruder_count:
  293. continue
  294. count += 1
  295. if stack.hasErrors():
  296. 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)))
  297. return True
  298. Logger.log("d", "Checking %s stacks for errors took %.2f s" % (count, time.time() - time_start))
  299. return False
  300. ## Check if the global_container has instances in the user container
  301. @pyqtProperty(bool, notify = activeStackValueChanged)
  302. def hasUserSettings(self) -> bool:
  303. if not self._global_container_stack:
  304. return False
  305. if self._global_container_stack.getTop().getNumInstances() != 0:
  306. return True
  307. stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  308. for stack in stacks:
  309. if stack.getTop().getNumInstances() != 0:
  310. return True
  311. return False
  312. @pyqtProperty(int, notify = activeStackValueChanged)
  313. def numUserSettings(self) -> int:
  314. if not self._global_container_stack:
  315. return 0
  316. num_user_settings = 0
  317. num_user_settings += self._global_container_stack.getTop().getNumInstances()
  318. stacks = self._global_container_stack.extruderList
  319. for stack in stacks:
  320. num_user_settings += stack.getTop().getNumInstances()
  321. return num_user_settings
  322. ## Delete a user setting from the global stack and all extruder stacks.
  323. # \param key \type{str} the name of the key to delete
  324. @pyqtSlot(str)
  325. def clearUserSettingAllCurrentStacks(self, key: str) -> None:
  326. Logger.log("i", "Clearing the setting [%s] from all stacks", key)
  327. if not self._global_container_stack:
  328. return
  329. send_emits_containers = []
  330. top_container = self._global_container_stack.getTop()
  331. top_container.removeInstance(key, postpone_emit=True)
  332. send_emits_containers.append(top_container)
  333. linked = not self._global_container_stack.getProperty(key, "settable_per_extruder") or \
  334. self._global_container_stack.getProperty(key, "limit_to_extruder") != "-1"
  335. if not linked:
  336. stack = ExtruderManager.getInstance().getActiveExtruderStack()
  337. stacks = [stack]
  338. else:
  339. stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  340. for stack in stacks:
  341. if stack is not None:
  342. container = stack.getTop()
  343. container.removeInstance(key, postpone_emit=True)
  344. send_emits_containers.append(container)
  345. for container in send_emits_containers:
  346. container.sendPostponedEmits()
  347. ## Check if none of the stacks contain error states
  348. # Note that the _stacks_have_errors is cached due to performance issues
  349. # Calling _checkStack(s)ForErrors on every change is simply too expensive
  350. @pyqtProperty(bool, notify = stacksValidationChanged)
  351. def stacksHaveErrors(self) -> bool:
  352. return bool(self._stacks_have_errors)
  353. @pyqtProperty(str, notify = globalContainerChanged)
  354. @deprecated("use Cura.MachineManager.activeMachine.definition.name instead", "4.1")
  355. def activeMachineDefinitionName(self) -> str:
  356. if self._global_container_stack:
  357. return self._global_container_stack.definition.getName()
  358. return ""
  359. @pyqtProperty(str, notify = globalContainerChanged)
  360. @deprecated("use Cura.MachineManager.activeMachine.name instead", "4.1")
  361. def activeMachineName(self) -> str:
  362. if self._global_container_stack:
  363. return self._global_container_stack.getMetaDataEntry("group_name", self._global_container_stack.getName())
  364. return ""
  365. @pyqtProperty(str, notify = globalContainerChanged)
  366. @deprecated("use Cura.MachineManager.activeMachine.id instead", "4.1")
  367. def activeMachineId(self) -> str:
  368. if self._global_container_stack:
  369. return self._global_container_stack.getId()
  370. return ""
  371. @pyqtProperty(str, notify = globalContainerChanged)
  372. def activeMachineFirmwareVersion(self) -> str:
  373. if not self._printer_output_devices:
  374. return ""
  375. return self._printer_output_devices[0].firmwareVersion
  376. @pyqtProperty(str, notify = globalContainerChanged)
  377. def activeMachineAddress(self) -> str:
  378. if not self._printer_output_devices:
  379. return ""
  380. return self._printer_output_devices[0].address
  381. @pyqtProperty(bool, notify = printerConnectedStatusChanged)
  382. def printerConnected(self) -> bool:
  383. return bool(self._printer_output_devices)
  384. @pyqtProperty(bool, notify = printerConnectedStatusChanged)
  385. @deprecated("use Cura.MachineManager.activeMachine.configuredConnectionTypes instead", "4.2")
  386. def activeMachineHasRemoteConnection(self) -> bool:
  387. if self._global_container_stack:
  388. has_remote_connection = False
  389. for connection_type in self._global_container_stack.configuredConnectionTypes:
  390. has_remote_connection |= connection_type in [ConnectionType.NetworkConnection.value,
  391. ConnectionType.CloudConnection.value]
  392. return has_remote_connection
  393. return False
  394. @pyqtProperty("QVariantList", notify=globalContainerChanged)
  395. @deprecated("use Cura.MachineManager.activeMachine.configuredConnectionTypes instead", "4.1")
  396. def activeMachineConfiguredConnectionTypes(self):
  397. if self._global_container_stack:
  398. return self._global_container_stack.configuredConnectionTypes
  399. return []
  400. @pyqtProperty(bool, notify = printerConnectedStatusChanged)
  401. def activeMachineIsGroup(self) -> bool:
  402. return bool(self._printer_output_devices) and len(self._printer_output_devices[0].printers) > 1
  403. @pyqtProperty(bool, notify = printerConnectedStatusChanged)
  404. def activeMachineHasNetworkConnection(self) -> bool:
  405. # A network connection is only available if any output device is actually a network connected device.
  406. return any(d.connectionType == ConnectionType.NetworkConnection for d in self._printer_output_devices)
  407. @pyqtProperty(bool, notify = printerConnectedStatusChanged)
  408. def activeMachineHasCloudConnection(self) -> bool:
  409. # A cloud connection is only available if any output device actually is a cloud connected device.
  410. return any(d.connectionType == ConnectionType.CloudConnection for d in self._printer_output_devices)
  411. @pyqtProperty(bool, notify = printerConnectedStatusChanged)
  412. def activeMachineIsUsingCloudConnection(self) -> bool:
  413. return self.activeMachineHasCloudConnection and not self.activeMachineHasNetworkConnection
  414. def activeMachineNetworkKey(self) -> str:
  415. if self._global_container_stack:
  416. return self._global_container_stack.getMetaDataEntry("um_network_key", "")
  417. return ""
  418. @pyqtProperty(str, notify = printerConnectedStatusChanged)
  419. def activeMachineNetworkGroupName(self) -> str:
  420. if self._global_container_stack:
  421. return self._global_container_stack.getMetaDataEntry("group_name", "")
  422. return ""
  423. @pyqtProperty(QObject, notify = globalContainerChanged)
  424. def activeMachine(self) -> Optional["GlobalStack"]:
  425. return self._global_container_stack
  426. @pyqtProperty(str, notify = activeStackChanged)
  427. def activeStackId(self) -> str:
  428. if self._active_container_stack:
  429. return self._active_container_stack.getId()
  430. return ""
  431. @pyqtProperty(QObject, notify = activeStackChanged)
  432. def activeStack(self) -> Optional["ExtruderStack"]:
  433. return self._active_container_stack
  434. @pyqtProperty(str, notify = activeMaterialChanged)
  435. def activeMaterialId(self) -> str:
  436. if self._active_container_stack:
  437. material = self._active_container_stack.material
  438. if material:
  439. return material.getId()
  440. return ""
  441. ## Gets a dict with the active materials ids set in all extruder stacks and the global stack
  442. # (when there is one extruder, the material is set in the global stack)
  443. #
  444. # \return The material ids in all stacks
  445. @pyqtProperty("QVariantMap", notify = activeMaterialChanged)
  446. @deprecated("use Cura.MachineManager.activeStack.extruders instead.", "4.3")
  447. def allActiveMaterialIds(self) -> Dict[str, str]:
  448. result = {}
  449. active_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  450. for stack in active_stacks:
  451. material_container = stack.material
  452. if not material_container:
  453. continue
  454. result[stack.getId()] = material_container.getId()
  455. return result
  456. ## Gets the layer height of the currently active quality profile.
  457. #
  458. # This is indicated together with the name of the active quality profile.
  459. #
  460. # \return The layer height of the currently active quality profile. If
  461. # there is no quality profile, this returns the default layer height.
  462. @pyqtProperty(float, notify = activeQualityGroupChanged)
  463. def activeQualityLayerHeight(self) -> float:
  464. if not self._global_container_stack:
  465. return 0
  466. value = self._global_container_stack.getRawProperty("layer_height", "value", skip_until_container = self._global_container_stack.qualityChanges.getId())
  467. if isinstance(value, SettingFunction):
  468. value = value(self._global_container_stack)
  469. return value
  470. @pyqtProperty(str, notify = activeVariantChanged)
  471. def globalVariantName(self) -> str:
  472. if self._global_container_stack:
  473. variant = self._global_container_stack.variant
  474. if variant and not isinstance(variant, type(empty_variant_container)):
  475. return variant.getName()
  476. return ""
  477. @pyqtProperty(str, notify = activeQualityGroupChanged)
  478. def activeQualityType(self) -> str:
  479. global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  480. if not global_stack:
  481. return ""
  482. return global_stack.quality.getMetaDataEntry("quality_type")
  483. @pyqtProperty(bool, notify = activeQualityGroupChanged)
  484. def isActiveQualitySupported(self) -> bool:
  485. global_container_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  486. if not global_container_stack:
  487. return False
  488. if not self.activeQualityGroup:
  489. return False
  490. return self.activeQualityGroup.is_available
  491. @pyqtProperty(bool, notify = activeQualityGroupChanged)
  492. def isActiveQualityExperimental(self) -> bool:
  493. global_container_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  494. if not global_container_stack:
  495. return False
  496. return Util.parseBool(global_container_stack.quality.getMetaDataEntry("is_experimental", False))
  497. @pyqtProperty(str, notify=activeIntentChanged)
  498. def activeIntentCategory(self):
  499. if not self._active_container_stack:
  500. return ""
  501. intent_category = self._active_container_stack.intent.getMetaDataEntry("intent_category")
  502. return intent_category
  503. ## Returns whether there is anything unsupported in the current set-up.
  504. #
  505. # The current set-up signifies the global stack and all extruder stacks,
  506. # so this indicates whether there is any container in any of the container
  507. # stacks that is not marked as supported.
  508. @pyqtProperty(bool, notify = activeQualityChanged)
  509. def isCurrentSetupSupported(self) -> bool:
  510. if not self._global_container_stack:
  511. return False
  512. for stack in [self._global_container_stack] + list(self._global_container_stack.extruders.values()):
  513. for container in stack.getContainers():
  514. if not container:
  515. return False
  516. if not Util.parseBool(container.getMetaDataEntry("supported", True)):
  517. return False
  518. return True
  519. ## Copy the value of the setting of the current extruder to all other extruders as well as the global container.
  520. @pyqtSlot(str)
  521. def copyValueToExtruders(self, key: str) -> None:
  522. if self._active_container_stack is None or self._global_container_stack is None:
  523. return
  524. new_value = self._active_container_stack.getProperty(key, "value")
  525. extruder_stacks = [stack for stack in ExtruderManager.getInstance().getActiveExtruderStacks()]
  526. # Check in which stack the value has to be replaced
  527. for extruder_stack in extruder_stacks:
  528. if extruder_stack != self._active_container_stack and extruder_stack.getProperty(key, "value") != new_value:
  529. extruder_stack.userChanges.setProperty(key, "value", new_value) # TODO: nested property access, should be improved
  530. ## Copy the value of all manually changed settings of the current extruder to all other extruders.
  531. @pyqtSlot()
  532. def copyAllValuesToExtruders(self) -> None:
  533. if self._active_container_stack is None or self._global_container_stack is None:
  534. return
  535. extruder_stacks = list(self._global_container_stack.extruders.values())
  536. for extruder_stack in extruder_stacks:
  537. if extruder_stack != self._active_container_stack:
  538. for key in self._active_container_stack.userChanges.getAllKeys():
  539. new_value = self._active_container_stack.getProperty(key, "value")
  540. # Check if the value has to be replaced
  541. extruder_stack.userChanges.setProperty(key, "value", new_value)
  542. @pyqtProperty(str, notify = activeVariantChanged)
  543. @deprecated("use Cura.MachineManager.activeStack.variant.name instead", "4.1")
  544. def activeVariantName(self) -> str:
  545. if self._active_container_stack:
  546. variant = self._active_container_stack.variant
  547. if variant:
  548. return variant.getName()
  549. return ""
  550. @pyqtProperty(str, notify = activeVariantChanged)
  551. @deprecated("use Cura.MachineManager.activeStack.variant.id instead", "4.1")
  552. def activeVariantId(self) -> str:
  553. if self._active_container_stack:
  554. variant = self._active_container_stack.variant
  555. if variant:
  556. return variant.getId()
  557. return ""
  558. @pyqtProperty(str, notify = activeVariantChanged)
  559. @deprecated("use Cura.MachineManager.activeMachine.variant.name instead", "4.1")
  560. def activeVariantBuildplateName(self) -> str:
  561. if self._global_container_stack:
  562. variant = self._global_container_stack.variant
  563. if variant:
  564. return variant.getName()
  565. return ""
  566. @pyqtProperty(str, notify = globalContainerChanged)
  567. @deprecated("use Cura.MachineManager.activeMachine.definition.id instead", "4.1")
  568. def activeDefinitionId(self) -> str:
  569. if self._global_container_stack:
  570. return self._global_container_stack.definition.id
  571. return ""
  572. ## Get the Definition ID to use to select quality profiles for the currently active machine
  573. # \returns DefinitionID (string) if found, empty string otherwise
  574. @pyqtProperty(str, notify = globalContainerChanged)
  575. def activeQualityDefinitionId(self) -> str:
  576. global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  577. if not global_stack:
  578. return ""
  579. return ContainerTree.getInstance().machines[global_stack.definition.getId()].quality_definition
  580. ## Gets how the active definition calls variants
  581. # Caveat: per-definition-variant-title is currently not translated (though the fallback is)
  582. @pyqtProperty(str, notify = globalContainerChanged)
  583. def activeDefinitionVariantsName(self) -> str:
  584. fallback_title = catalog.i18nc("@label", "Nozzle")
  585. if self._global_container_stack:
  586. return self._global_container_stack.definition.getMetaDataEntry("variants_name", fallback_title)
  587. return fallback_title
  588. @pyqtSlot(str, str)
  589. def renameMachine(self, machine_id: str, new_name: str) -> None:
  590. container_registry = CuraContainerRegistry.getInstance()
  591. machine_stack = container_registry.findContainerStacks(id = machine_id)
  592. if machine_stack:
  593. new_name = container_registry.createUniqueName("machine", machine_stack[0].getName(), new_name, machine_stack[0].definition.getName())
  594. machine_stack[0].setName(new_name)
  595. self.globalContainerChanged.emit()
  596. @pyqtSlot(str)
  597. def removeMachine(self, machine_id: str) -> None:
  598. Logger.log("i", "Attempting to remove a machine with the id [%s]", machine_id)
  599. # If the machine that is being removed is the currently active machine, set another machine as the active machine.
  600. activate_new_machine = (self._global_container_stack and self._global_container_stack.getId() == machine_id)
  601. # Activate a new machine before removing a machine because this is safer
  602. if activate_new_machine:
  603. machine_stacks = CuraContainerRegistry.getInstance().findContainerStacksMetadata(type = "machine")
  604. other_machine_stacks = [s for s in machine_stacks if s["id"] != machine_id]
  605. if other_machine_stacks:
  606. self.setActiveMachine(other_machine_stacks[0]["id"])
  607. metadata = CuraContainerRegistry.getInstance().findContainerStacksMetadata(id = machine_id)[0]
  608. ExtruderManager.getInstance().removeMachineExtruders(machine_id)
  609. containers = CuraContainerRegistry.getInstance().findInstanceContainersMetadata(type = "user", machine = machine_id)
  610. for container in containers:
  611. CuraContainerRegistry.getInstance().removeContainer(container["id"])
  612. CuraContainerRegistry.getInstance().removeContainer(machine_id)
  613. # If the printer that is being removed is a network printer, the hidden printers have to be also removed
  614. group_id = metadata.get("group_id", None)
  615. if group_id:
  616. metadata_filter = {"group_id": group_id}
  617. hidden_containers = CuraContainerRegistry.getInstance().findContainerStacks(type = "machine", **metadata_filter)
  618. if hidden_containers:
  619. # This reuses the method and remove all printers recursively
  620. self.removeMachine(hidden_containers[0].getId())
  621. @pyqtProperty(bool, notify = globalContainerChanged)
  622. @deprecated("use Cura.MachineManager.activeMachine.hasMaterials instead", "4.2")
  623. def hasMaterials(self) -> bool:
  624. if self._global_container_stack:
  625. return self._global_container_stack.hasMaterials
  626. return False
  627. @pyqtProperty(bool, notify = globalContainerChanged)
  628. @deprecated("use Cura.MachineManager.activeMachine.hasVariants instead", "4.2")
  629. def hasVariants(self) -> bool:
  630. if self._global_container_stack:
  631. return self._global_container_stack.hasVariants
  632. return False
  633. @pyqtProperty(bool, notify = globalContainerChanged)
  634. @deprecated("use Cura.MachineManager.activeMachine.hasVariantBuildplates instead", "4.2")
  635. def hasVariantBuildplates(self) -> bool:
  636. if self._global_container_stack:
  637. return self._global_container_stack.hasVariantBuildplates
  638. return False
  639. ## The selected buildplate is compatible if it is compatible with all the materials in all the extruders
  640. @pyqtProperty(bool, notify = activeMaterialChanged)
  641. def variantBuildplateCompatible(self) -> bool:
  642. if not self._global_container_stack:
  643. return True
  644. buildplate_compatible = True # It is compatible by default
  645. extruder_stacks = self._global_container_stack.extruders.values()
  646. for stack in extruder_stacks:
  647. if not stack.isEnabled:
  648. continue
  649. material_container = stack.material
  650. if material_container == empty_material_container:
  651. continue
  652. if material_container.getMetaDataEntry("buildplate_compatible"):
  653. buildplate_compatible = buildplate_compatible and material_container.getMetaDataEntry("buildplate_compatible")[self.activeVariantBuildplateName]
  654. return buildplate_compatible
  655. ## The selected buildplate is usable if it is usable for all materials OR it is compatible for one but not compatible
  656. # for the other material but the buildplate is still usable
  657. @pyqtProperty(bool, notify = activeMaterialChanged)
  658. def variantBuildplateUsable(self) -> bool:
  659. if not self._global_container_stack:
  660. return True
  661. # Here the next formula is being calculated:
  662. # result = (not (material_left_compatible and material_right_compatible)) and
  663. # (material_left_compatible or material_left_usable) and
  664. # (material_right_compatible or material_right_usable)
  665. result = not self.variantBuildplateCompatible
  666. extruder_stacks = self._global_container_stack.extruders.values()
  667. for stack in extruder_stacks:
  668. material_container = stack.material
  669. if material_container == empty_material_container:
  670. continue
  671. buildplate_compatible = material_container.getMetaDataEntry("buildplate_compatible")[self.activeVariantBuildplateName] if material_container.getMetaDataEntry("buildplate_compatible") else True
  672. buildplate_usable = material_container.getMetaDataEntry("buildplate_recommended")[self.activeVariantBuildplateName] if material_container.getMetaDataEntry("buildplate_recommended") else True
  673. result = result and (buildplate_compatible or buildplate_usable)
  674. return result
  675. ## Get the Definition ID of a machine (specified by ID)
  676. # \param machine_id string machine id to get the definition ID of
  677. # \returns DefinitionID if found, None otherwise
  678. @pyqtSlot(str, result = str)
  679. def getDefinitionByMachineId(self, machine_id: str) -> Optional[str]:
  680. containers = CuraContainerRegistry.getInstance().findContainerStacks(id = machine_id)
  681. if containers:
  682. return containers[0].definition.getId()
  683. return None
  684. def getIncompatibleSettingsOnEnabledExtruders(self, container: InstanceContainer) -> List[str]:
  685. if self._global_container_stack is None:
  686. return []
  687. extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  688. result = [] # type: List[str]
  689. for setting_instance in container.findInstances():
  690. setting_key = setting_instance.definition.key
  691. if not self._global_container_stack.getProperty(setting_key, "type") in ("extruder", "optional_extruder"):
  692. continue
  693. old_value = container.getProperty(setting_key, "value")
  694. if isinstance(old_value, SettingFunction):
  695. old_value = old_value(self._global_container_stack)
  696. if int(old_value) < 0:
  697. continue
  698. if int(old_value) >= extruder_count or not self._global_container_stack.extruders[str(old_value)].isEnabled:
  699. result.append(setting_key)
  700. Logger.log("d", "Reset setting [%s] in [%s] because its old value [%s] is no longer valid", setting_key, container, old_value)
  701. return result
  702. ## Update extruder number to a valid value when the number of extruders are changed, or when an extruder is changed
  703. def correctExtruderSettings(self) -> None:
  704. if self._global_container_stack is None:
  705. return
  706. for setting_key in self.getIncompatibleSettingsOnEnabledExtruders(self._global_container_stack.userChanges):
  707. self._global_container_stack.userChanges.removeInstance(setting_key)
  708. add_user_changes = self.getIncompatibleSettingsOnEnabledExtruders(self._global_container_stack.qualityChanges)
  709. for setting_key in add_user_changes:
  710. # Apply quality changes that are incompatible to user changes, so we do not change the quality changes itself.
  711. self._global_container_stack.userChanges.setProperty(setting_key, "value", self._default_extruder_position)
  712. if add_user_changes:
  713. caution_message = Message(
  714. catalog.i18nc("@info:message Followed by a list of settings.", "Settings have been changed to match the current availability of extruders:") + " [{settings_list}]".format(settings_list = ", ".join(add_user_changes)),
  715. lifetime = 0,
  716. title = catalog.i18nc("@info:title", "Settings updated"))
  717. caution_message.show()
  718. ## Set the amount of extruders on the active machine (global stack)
  719. # \param extruder_count int the number of extruders to set
  720. def setActiveMachineExtruderCount(self, extruder_count: int) -> None:
  721. if self._global_container_stack is None:
  722. return
  723. extruder_manager = self._application.getExtruderManager()
  724. definition_changes_container = self._global_container_stack.definitionChanges
  725. if not self._global_container_stack or definition_changes_container == empty_definition_changes_container:
  726. return
  727. previous_extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  728. if extruder_count == previous_extruder_count:
  729. return
  730. definition_changes_container.setProperty("machine_extruder_count", "value", extruder_count)
  731. self.updateDefaultExtruder()
  732. self.updateNumberExtrudersEnabled()
  733. self.correctExtruderSettings()
  734. # Check to see if any objects are set to print with an extruder that will no longer exist
  735. root_node = self._application.getController().getScene().getRoot()
  736. for node in DepthFirstIterator(root_node):
  737. if node.getMeshData():
  738. extruder_nr = node.callDecoration("getActiveExtruderPosition")
  739. if extruder_nr is not None and int(extruder_nr) > extruder_count - 1:
  740. extruder = extruder_manager.getExtruderStack(extruder_count - 1)
  741. if extruder is not None:
  742. node.callDecoration("setActiveExtruder", extruder.getId())
  743. else:
  744. Logger.log("w", "Could not find extruder to set active.")
  745. # Make sure one of the extruder stacks is active
  746. extruder_manager.setActiveExtruderIndex(0)
  747. # Move settable_per_extruder values out of the global container
  748. # After CURA-4482 this should not be the case anymore, but we still want to support older project files.
  749. global_user_container = self._global_container_stack.userChanges
  750. for setting_instance in global_user_container.findInstances():
  751. setting_key = setting_instance.definition.key
  752. settable_per_extruder = self._global_container_stack.getProperty(setting_key, "settable_per_extruder")
  753. if settable_per_extruder:
  754. limit_to_extruder = int(self._global_container_stack.getProperty(setting_key, "limit_to_extruder"))
  755. extruder_position = max(0, limit_to_extruder)
  756. extruder_stack = self.getExtruder(extruder_position)
  757. if extruder_stack:
  758. extruder_stack.userChanges.setProperty(setting_key, "value", global_user_container.getProperty(setting_key, "value"))
  759. else:
  760. Logger.log("e", "Unable to find extruder on position %s", extruder_position)
  761. global_user_container.removeInstance(setting_key)
  762. # Signal that the global stack has changed
  763. self._application.globalContainerStackChanged.emit()
  764. self.forceUpdateAllSettings()
  765. @pyqtSlot(int, result = QObject)
  766. def getExtruder(self, position: int) -> Optional[ExtruderStack]:
  767. return self._getExtruder(position)
  768. # This is a workaround for the deprecated decorator and the pyqtSlot not playing well together.
  769. @deprecated("use Cura.MachineManager.activeMachine.extruders instead", "4.2")
  770. def _getExtruder(self, position) -> Optional[ExtruderStack]:
  771. if self._global_container_stack:
  772. return self._global_container_stack.extruders.get(str(position))
  773. return None
  774. def updateDefaultExtruder(self) -> None:
  775. if self._global_container_stack is None:
  776. return
  777. extruder_items = sorted(self._global_container_stack.extruders.items())
  778. old_position = self._default_extruder_position
  779. new_default_position = "0"
  780. for position, extruder in extruder_items:
  781. if extruder.isEnabled:
  782. new_default_position = position
  783. break
  784. if new_default_position != old_position:
  785. self._default_extruder_position = new_default_position
  786. self.extruderChanged.emit()
  787. def updateNumberExtrudersEnabled(self) -> None:
  788. if self._global_container_stack is None:
  789. return
  790. definition_changes_container = self._global_container_stack.definitionChanges
  791. machine_extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  792. extruder_count = 0
  793. for position, extruder in self._global_container_stack.extruders.items():
  794. if extruder.isEnabled and int(position) < machine_extruder_count:
  795. extruder_count += 1
  796. if self.numberExtrudersEnabled != extruder_count:
  797. definition_changes_container.setProperty("extruders_enabled_count", "value", extruder_count)
  798. self.numberExtrudersEnabledChanged.emit()
  799. @pyqtProperty(int, notify = numberExtrudersEnabledChanged)
  800. def numberExtrudersEnabled(self) -> int:
  801. if self._global_container_stack is None:
  802. return 1
  803. return self._global_container_stack.definitionChanges.getProperty("extruders_enabled_count", "value")
  804. @pyqtProperty(str, notify = extruderChanged)
  805. def defaultExtruderPosition(self) -> str:
  806. return self._default_extruder_position
  807. ## This will fire the propertiesChanged for all settings so they will be updated in the front-end
  808. @pyqtSlot()
  809. def forceUpdateAllSettings(self) -> None:
  810. if self._global_container_stack is None:
  811. return
  812. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  813. property_names = ["value", "resolve", "validationState"]
  814. for container in [self._global_container_stack] + list(self._global_container_stack.extruders.values()):
  815. for setting_key in container.getAllKeys():
  816. container.propertiesChanged.emit(setting_key, property_names)
  817. @pyqtSlot(int, bool)
  818. def setExtruderEnabled(self, position: int, enabled: bool) -> None:
  819. extruder = self.getExtruder(position)
  820. if not extruder or self._global_container_stack is None:
  821. Logger.log("w", "Could not find extruder on position %s", position)
  822. return
  823. extruder.setEnabled(enabled)
  824. self.updateDefaultExtruder()
  825. self.updateNumberExtrudersEnabled()
  826. self.correctExtruderSettings()
  827. # In case this extruder is being disabled and it's the currently selected one, switch to the default extruder
  828. if not enabled and position == ExtruderManager.getInstance().activeExtruderIndex:
  829. ExtruderManager.getInstance().setActiveExtruderIndex(int(self._default_extruder_position))
  830. # Ensure that the quality profile is compatible with current combination, or choose a compatible one if available
  831. self._updateQualityWithMaterial()
  832. self.extruderChanged.emit()
  833. # Update material compatibility color
  834. self.activeQualityGroupChanged.emit()
  835. # Update items in SettingExtruder
  836. ExtruderManager.getInstance().extrudersChanged.emit(self._global_container_stack.getId())
  837. # Make sure the front end reflects changes
  838. self.forceUpdateAllSettings()
  839. # Also trigger the build plate compatibility to update
  840. self.activeMaterialChanged.emit()
  841. def _onMachineNameChanged(self) -> None:
  842. self.globalContainerChanged.emit()
  843. def _onMaterialNameChanged(self) -> None:
  844. self.activeMaterialChanged.emit()
  845. def _getContainerChangedSignals(self) -> List[Signal]:
  846. if self._global_container_stack is None:
  847. return []
  848. stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  849. stacks.append(self._global_container_stack)
  850. return [ s.containersChanged for s in stacks ]
  851. @pyqtSlot(str, str, str)
  852. def setSettingForAllExtruders(self, setting_name: str, property_name: str, property_value: str) -> None:
  853. if self._global_container_stack is None:
  854. return
  855. for key, extruder in self._global_container_stack.extruders.items():
  856. container = extruder.userChanges
  857. container.setProperty(setting_name, property_name, property_value)
  858. ## Reset all setting properties of a setting for all extruders.
  859. # \param setting_name The ID of the setting to reset.
  860. @pyqtSlot(str)
  861. def resetSettingForAllExtruders(self, setting_name: str) -> None:
  862. if self._global_container_stack is None:
  863. return
  864. for key, extruder in self._global_container_stack.extruders.items():
  865. container = extruder.userChanges
  866. container.removeInstance(setting_name)
  867. @pyqtProperty("QVariantList", notify = globalContainerChanged)
  868. @deprecated("use Cura.MachineManager.activeMachine.extruders instead", "4.2")
  869. def currentExtruderPositions(self) -> List[str]:
  870. if self._global_container_stack is None:
  871. return []
  872. return sorted(list(self._global_container_stack.extruders.keys()))
  873. ## Update _current_root_material_id when the current root material was changed.
  874. def _onRootMaterialChanged(self) -> None:
  875. self._current_root_material_id = {}
  876. changed = False
  877. if self._global_container_stack:
  878. for position in self._global_container_stack.extruders:
  879. material_id = self._global_container_stack.extruders[position].material.getMetaDataEntry("base_file")
  880. if position not in self._current_root_material_id or material_id != self._current_root_material_id[position]:
  881. changed = True
  882. self._current_root_material_id[position] = material_id
  883. if changed:
  884. self.activeMaterialChanged.emit()
  885. @pyqtProperty("QVariant", notify = rootMaterialChanged)
  886. def currentRootMaterialId(self) -> Dict[str, str]:
  887. return self._current_root_material_id
  888. ## Return the variant names in the extruder stack(s).
  889. ## For the variant in the global stack, use activeVariantBuildplateName
  890. @pyqtProperty("QVariant", notify = activeVariantChanged)
  891. def activeVariantNames(self) -> Dict[str, str]:
  892. result = {}
  893. active_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  894. for stack in active_stacks:
  895. variant_container = stack.variant
  896. position = stack.getMetaDataEntry("position")
  897. if variant_container and variant_container != empty_variant_container:
  898. result[position] = variant_container.getName()
  899. return result
  900. # Sets all quality and quality_changes containers to empty_quality and empty_quality_changes containers
  901. # for all stacks in the currently active machine.
  902. #
  903. def _setEmptyQuality(self) -> None:
  904. if self._global_container_stack is None:
  905. return
  906. self._global_container_stack.quality = empty_quality_container
  907. self._global_container_stack.qualityChanges = empty_quality_changes_container
  908. for extruder in self._global_container_stack.extruders.values():
  909. extruder.quality = empty_quality_container
  910. extruder.qualityChanges = empty_quality_changes_container
  911. self.activeQualityGroupChanged.emit()
  912. self.activeQualityChangesGroupChanged.emit()
  913. def _setQualityGroup(self, quality_group: Optional["QualityGroup"], empty_quality_changes: bool = True) -> None:
  914. if self._global_container_stack is None:
  915. return
  916. if quality_group is None:
  917. self._setEmptyQuality()
  918. return
  919. if quality_group.node_for_global is None or quality_group.node_for_global.container is None:
  920. return
  921. for node in quality_group.nodes_for_extruders.values():
  922. if node.container is None:
  923. return
  924. # Set quality and quality_changes for the GlobalStack
  925. self._global_container_stack.quality = quality_group.node_for_global.container
  926. if empty_quality_changes:
  927. self._global_container_stack.qualityChanges = empty_quality_changes_container
  928. # Set quality and quality_changes for each ExtruderStack
  929. for position, node in quality_group.nodes_for_extruders.items():
  930. self._global_container_stack.extruders[str(position)].quality = node.container
  931. if empty_quality_changes:
  932. self._global_container_stack.extruders[str(position)].qualityChanges = empty_quality_changes_container
  933. self.activeQualityGroupChanged.emit()
  934. self.activeQualityChangesGroupChanged.emit()
  935. def _fixQualityChangesGroupToNotSupported(self, quality_changes_group: "QualityChangesGroup") -> None:
  936. metadatas = [quality_changes_group.metadata_for_global] + list(quality_changes_group.metadata_per_extruder.values())
  937. for metadata in metadatas:
  938. metadata["quality_type"] = "not_supported" # This actually changes the metadata of the container since they are stored by reference!
  939. quality_changes_group.quality_type = "not_supported"
  940. quality_changes_group.intent_category = "default"
  941. def _setQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup") -> None:
  942. if self._global_container_stack is None:
  943. return # Can't change that.
  944. quality_type = quality_changes_group.quality_type
  945. # A custom quality can be created based on "not supported".
  946. # In that case, do not set quality containers to empty.
  947. quality_group = None
  948. if quality_type != "not_supported": # Find the quality group that the quality changes was based on.
  949. quality_group = ContainerTree.getInstance().getCurrentQualityGroups().get(quality_type)
  950. if quality_group is None:
  951. self._fixQualityChangesGroupToNotSupported(quality_changes_group)
  952. container_registry = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry()
  953. quality_changes_container = empty_quality_changes_container
  954. quality_container = empty_quality_container # type: InstanceContainer
  955. if quality_changes_group.metadata_for_global:
  956. global_containers = container_registry.findContainers(id = quality_changes_group.metadata_for_global["id"])
  957. if global_containers:
  958. quality_changes_container = global_containers[0]
  959. if quality_changes_group.metadata_for_global:
  960. containers = container_registry.findContainers(id = quality_changes_group.metadata_for_global["id"])
  961. if containers:
  962. quality_changes_container = cast(InstanceContainer, containers[0])
  963. if quality_group is not None and quality_group.node_for_global and quality_group.node_for_global.container:
  964. quality_container = quality_group.node_for_global.container
  965. self._global_container_stack.quality = quality_container
  966. self._global_container_stack.qualityChanges = quality_changes_container
  967. for position, extruder in self._global_container_stack.extruders.items():
  968. quality_node = None
  969. if quality_group is not None:
  970. quality_node = quality_group.nodes_for_extruders.get(int(position))
  971. quality_changes_container = empty_quality_changes_container
  972. quality_container = empty_quality_container
  973. quality_changes_metadata = quality_changes_group.metadata_per_extruder.get(int(position))
  974. if quality_changes_metadata:
  975. containers = container_registry.findContainers(id = quality_changes_metadata["id"])
  976. if containers:
  977. quality_changes_container = cast(InstanceContainer, containers[0])
  978. if quality_node and quality_node.container:
  979. quality_container = quality_node.container
  980. extruder.quality = quality_container
  981. extruder.qualityChanges = quality_changes_container
  982. self.setIntentByCategory(quality_changes_group.intent_category)
  983. self.activeQualityGroupChanged.emit()
  984. self.activeQualityChangesGroupChanged.emit()
  985. def _setVariantNode(self, position: str, variant_node: "VariantNode") -> None:
  986. if self._global_container_stack is None:
  987. return
  988. self._global_container_stack.extruders[position].variant = variant_node.container
  989. self.activeVariantChanged.emit()
  990. def _setGlobalVariant(self, container_node: "ContainerNode") -> None:
  991. if self._global_container_stack is None:
  992. return
  993. self._global_container_stack.variant = container_node.container
  994. if not self._global_container_stack.variant:
  995. self._global_container_stack.variant = self._application.empty_variant_container
  996. def _setMaterial(self, position: str, material_node: Optional["MaterialNode"] = None) -> None:
  997. if self._global_container_stack is None:
  998. return
  999. if material_node and material_node.container:
  1000. material_container = material_node.container
  1001. self._global_container_stack.extruders[position].material = material_container
  1002. root_material_id = material_container.getMetaDataEntry("base_file", None)
  1003. else:
  1004. self._global_container_stack.extruders[position].material = empty_material_container
  1005. root_material_id = None
  1006. # The _current_root_material_id is used in the MaterialMenu to see which material is selected
  1007. if root_material_id != self._current_root_material_id[position]:
  1008. self._current_root_material_id[position] = root_material_id
  1009. self.rootMaterialChanged.emit()
  1010. def activeMaterialsCompatible(self) -> bool:
  1011. # Check material - variant compatibility
  1012. if self._global_container_stack is not None:
  1013. if Util.parseBool(self._global_container_stack.getMetaDataEntry("has_materials", False)):
  1014. for position, extruder in self._global_container_stack.extruders.items():
  1015. if not extruder.isEnabled:
  1016. continue
  1017. if not extruder.material.getMetaDataEntry("compatible"):
  1018. return False
  1019. return True
  1020. ## Update current quality type and machine after setting material
  1021. def _updateQualityWithMaterial(self, *args: Any) -> None:
  1022. global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  1023. if global_stack is None:
  1024. return
  1025. Logger.log("d", "Updating quality/quality_changes due to material change")
  1026. current_quality_type = global_stack.quality.getMetaDataEntry("quality_type")
  1027. candidate_quality_groups = ContainerTree.getInstance().getCurrentQualityGroups()
  1028. available_quality_types = {qt for qt, g in candidate_quality_groups.items() if g.is_available}
  1029. Logger.log("d", "Current quality type = [%s]", current_quality_type)
  1030. if not self.activeMaterialsCompatible():
  1031. if current_quality_type is not None:
  1032. Logger.log("i", "Active materials are not compatible, setting all qualities to empty (Not Supported).")
  1033. self._setEmptyQuality()
  1034. return
  1035. if not available_quality_types:
  1036. if global_stack.qualityChanges == empty_quality_changes_container:
  1037. Logger.log("i", "No available quality types found, setting all qualities to empty (Not Supported).")
  1038. self._setEmptyQuality()
  1039. return
  1040. if current_quality_type in available_quality_types:
  1041. Logger.log("i", "Current available quality type [%s] is available, applying changes.", current_quality_type)
  1042. self._setQualityGroup(candidate_quality_groups[current_quality_type], empty_quality_changes = False)
  1043. return
  1044. # The current quality type is not available so we use the preferred quality type if it's available,
  1045. # otherwise use one of the available quality types.
  1046. quality_type = sorted(list(available_quality_types))[0]
  1047. if self._global_container_stack is None:
  1048. Logger.log("e", "Global stack not present!")
  1049. return
  1050. preferred_quality_type = self._global_container_stack.getMetaDataEntry("preferred_quality_type")
  1051. if preferred_quality_type in available_quality_types:
  1052. quality_type = preferred_quality_type
  1053. Logger.log("i", "The current quality type [%s] is not available, switching to [%s] instead",
  1054. current_quality_type, quality_type)
  1055. self._setQualityGroup(candidate_quality_groups[quality_type], empty_quality_changes = True)
  1056. ## Update the material profile in the current stacks when the variant is
  1057. # changed.
  1058. # \param position The extruder stack to update. If provided with None, all
  1059. # extruder stacks will be updated.
  1060. def updateMaterialWithVariant(self, position: Optional[str]) -> None:
  1061. if self._global_container_stack is None:
  1062. return
  1063. if position is None:
  1064. position_list = list(self._global_container_stack.extruders.keys())
  1065. else:
  1066. position_list = [position]
  1067. for position_item in position_list:
  1068. extruder = self._global_container_stack.extruders[position_item]
  1069. current_material_base_name = extruder.material.getMetaDataEntry("base_file")
  1070. current_nozzle_name = None
  1071. if extruder.variant.getId() != empty_variant_container.getId():
  1072. current_nozzle_name = extruder.variant.getMetaDataEntry("name")
  1073. # If we can keep the current material after the switch, try to do so.
  1074. nozzle_node = ContainerTree.getInstance().machines[self._global_container_stack.definition.getId()].variants[current_nozzle_name]
  1075. candidate_materials = nozzle_node.materials
  1076. if current_material_base_name in candidate_materials: # The current material is also available after the switch. Retain it.
  1077. new_material = candidate_materials[current_material_base_name]
  1078. self._setMaterial(position_item, new_material)
  1079. else:
  1080. # The current material is not available, find the preferred one.
  1081. material_diameter = self._global_container_stack.extruders[position].getCompatibleMaterialDiameter()
  1082. approximate_material_diameter = round(material_diameter)
  1083. material_node = nozzle_node.preferredMaterial(approximate_material_diameter)
  1084. self._setMaterial(position_item, material_node)
  1085. ## Given a printer definition name, select the right machine instance. In case it doesn't exist, create a new
  1086. # instance with the same network key.
  1087. @pyqtSlot(str)
  1088. def switchPrinterType(self, machine_name: str) -> None:
  1089. Logger.log("i", "Attempting to switch the printer type to [%s]", machine_name)
  1090. # Don't switch if the user tries to change to the same type of printer
  1091. if self._global_container_stack is None or self.activeMachineDefinitionName == machine_name:
  1092. return
  1093. # Get the definition id corresponding to this machine name
  1094. machine_definition_id = CuraContainerRegistry.getInstance().findDefinitionContainers(name = machine_name)[0].getId()
  1095. # Try to find a machine with the same network key
  1096. metadata_filter = {"group_id": self._global_container_stack.getMetaDataEntry("group_id")}
  1097. new_machine = self.getMachine(machine_definition_id, metadata_filter = metadata_filter)
  1098. # If there is no machine, then create a new one and set it to the non-hidden instance
  1099. if not new_machine:
  1100. new_machine = CuraStackBuilder.createMachine(machine_definition_id + "_sync", machine_definition_id)
  1101. if not new_machine:
  1102. return
  1103. for metadata_key in self._global_container_stack.getMetaData():
  1104. if metadata_key in new_machine.getMetaData():
  1105. continue # Don't copy the already preset stuff.
  1106. new_machine.setMetaDataEntry(metadata_key, self._global_container_stack.getMetaDataEntry(metadata_key))
  1107. else:
  1108. Logger.log("i", "Found a %s with the key %s. Let's use it!", machine_name, self.activeMachineNetworkKey())
  1109. # Set the current printer instance to hidden (the metadata entry must exist)
  1110. new_machine.setMetaDataEntry("hidden", False)
  1111. self._global_container_stack.setMetaDataEntry("hidden", True)
  1112. self.setActiveMachine(new_machine.getId())
  1113. @pyqtSlot(QObject)
  1114. def applyRemoteConfiguration(self, configuration: PrinterConfigurationModel) -> None:
  1115. if self._global_container_stack is None:
  1116. return
  1117. self.blurSettings.emit()
  1118. container_registry = CuraContainerRegistry.getInstance()
  1119. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1120. self.switchPrinterType(configuration.printerType)
  1121. disabled_used_extruder_position_set = set()
  1122. extruders_to_disable = set()
  1123. # If an extruder that's currently used to print a model gets disabled due to the syncing, we need to show
  1124. # a message explaining why.
  1125. need_to_show_message = False
  1126. for extruder_configuration in configuration.extruderConfigurations:
  1127. # We support "" or None, since the cloud uses None instead of empty strings
  1128. extruder_has_hotend = extruder_configuration.hotendID and extruder_configuration.hotendID != ""
  1129. extruder_has_material = extruder_configuration.material.guid and extruder_configuration.material.guid != ""
  1130. # If the machine doesn't have a hotend or material, disable this extruder
  1131. if not extruder_has_hotend or not extruder_has_material:
  1132. extruders_to_disable.add(extruder_configuration.position)
  1133. # If there's no material and/or nozzle on the printer, enable the first extruder and disable the rest.
  1134. if len(extruders_to_disable) == len(self._global_container_stack.extruders):
  1135. extruders_to_disable.remove(min(extruders_to_disable))
  1136. for extruder_configuration in configuration.extruderConfigurations:
  1137. position = str(extruder_configuration.position)
  1138. # If the machine doesn't have a hotend or material, disable this extruder
  1139. if int(position) in extruders_to_disable:
  1140. self._global_container_stack.extruders[position].setEnabled(False)
  1141. need_to_show_message = True
  1142. disabled_used_extruder_position_set.add(int(position))
  1143. else:
  1144. machine_node = ContainerTree.getInstance().machines.get(self._global_container_stack.definition.getId())
  1145. variant_node = machine_node.variants.get(extruder_configuration.hotendID)
  1146. self._setVariantNode(position, variant_node)
  1147. # Find the material profile that the printer has stored.
  1148. # This might find one of the duplicates if the user duplicated the material to sync with. But that's okay; both have this GUID so both are correct.
  1149. approximate_diameter = int(self._global_container_stack.extruderList[int(position)].getApproximateMaterialDiameter())
  1150. materials_with_guid = container_registry.findInstanceContainersMetadata(guid = extruder_configuration.material.guid, approximate_diameter = approximate_diameter)
  1151. material_container_node = variant_node.preferredMaterial(approximate_diameter)
  1152. if materials_with_guid: # We also have the material profile that the printer wants to share.
  1153. base_file = materials_with_guid[0]["base_file"]
  1154. material_container_node = variant_node.materials.get(base_file, default = material_container_node) # If Cura thinks that the selected material is not available for this printer, revert to the preferred material.
  1155. self._setMaterial(position, material_container_node)
  1156. self._global_container_stack.extruders[position].setEnabled(True)
  1157. self.updateMaterialWithVariant(position)
  1158. self.updateDefaultExtruder()
  1159. self.updateNumberExtrudersEnabled()
  1160. self._updateQualityWithMaterial()
  1161. if need_to_show_message:
  1162. msg_str = "{extruders} is disabled because there is no material loaded. Please load a material or use custom configurations."
  1163. # Show human-readable extruder names such as "Extruder Left", "Extruder Front" instead of "Extruder 1, 2, 3".
  1164. extruder_names = []
  1165. for extruder_position in sorted(disabled_used_extruder_position_set):
  1166. extruder_stack = self._global_container_stack.extruders[str(extruder_position)]
  1167. extruder_name = extruder_stack.definition.getName()
  1168. extruder_names.append(extruder_name)
  1169. extruders_str = ", ".join(extruder_names)
  1170. msg_str = msg_str.format(extruders = extruders_str)
  1171. message = Message(catalog.i18nc("@info:status", msg_str),
  1172. title = catalog.i18nc("@info:title", "Extruder(s) Disabled"))
  1173. message.show()
  1174. # See if we need to show the Discard or Keep changes screen
  1175. if self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1176. self._application.discardOrKeepProfileChanges()
  1177. @pyqtSlot("QVariant")
  1178. def setGlobalVariant(self, container_node: "ContainerNode") -> None:
  1179. self.blurSettings.emit()
  1180. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1181. self._setGlobalVariant(container_node)
  1182. self.updateMaterialWithVariant(None) # Update all materials
  1183. self._updateQualityWithMaterial()
  1184. @pyqtSlot(str, str)
  1185. def setMaterialById(self, position: str, root_material_id: str) -> None:
  1186. if self._global_container_stack is None:
  1187. return
  1188. buildplate_name = None
  1189. if self._global_container_stack.variant.getId() != "empty_variant":
  1190. buildplate_name = self._global_container_stack.variant.getName()
  1191. machine_definition_id = self._global_container_stack.definition.id
  1192. position = str(position)
  1193. extruder_stack = self._global_container_stack.extruders[position]
  1194. nozzle_name = extruder_stack.variant.getName()
  1195. material_diameter = extruder_stack.getApproximateMaterialDiameter()
  1196. material_node = ContainerTree.getInstance().machines[machine_definition_id].variants[nozzle_name].materials[root_material_id]
  1197. self.setMaterial(position, material_node)
  1198. ## Global_stack: if you want to provide your own global_stack instead of the current active one
  1199. # if you update an active machine, special measures have to be taken.
  1200. @pyqtSlot(str, "QVariant")
  1201. def setMaterial(self, position: str, container_node, global_stack: Optional["GlobalStack"] = None) -> None:
  1202. if global_stack is not None and global_stack != self._global_container_stack:
  1203. global_stack.extruders[position].material = container_node.container
  1204. return
  1205. position = str(position)
  1206. self.blurSettings.emit()
  1207. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1208. self._setMaterial(position, container_node)
  1209. self._updateQualityWithMaterial()
  1210. # See if we need to show the Discard or Keep changes screen
  1211. if self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1212. self._application.discardOrKeepProfileChanges()
  1213. @pyqtSlot(str, str)
  1214. def setVariantByName(self, position: str, variant_name: str) -> None:
  1215. if self._global_container_stack is None:
  1216. return
  1217. machine_definition_id = self._global_container_stack.definition.id
  1218. variant_node = self._variant_manager.getVariantNode(machine_definition_id, variant_name)
  1219. self.setVariant(position, variant_node)
  1220. @pyqtSlot(str, "QVariant")
  1221. def setVariant(self, position: str, variant_node: "VariantNode") -> None:
  1222. position = str(position)
  1223. self.blurSettings.emit()
  1224. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1225. self._setVariantNode(position, variant_node)
  1226. self.updateMaterialWithVariant(position)
  1227. self._updateQualityWithMaterial()
  1228. # See if we need to show the Discard or Keep changes screen
  1229. if self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1230. self._application.discardOrKeepProfileChanges()
  1231. @pyqtSlot(str)
  1232. def setQualityGroupByQualityType(self, quality_type: str) -> None:
  1233. if self._global_container_stack is None:
  1234. return
  1235. # Get all the quality groups for this global stack and filter out by quality_type
  1236. self.setQualityGroup(ContainerTree.getInstance().getCurrentQualityGroups()[quality_type])
  1237. ## Optionally provide global_stack if you want to use your own
  1238. # The active global_stack is treated differently.
  1239. @pyqtSlot(QObject)
  1240. def setQualityGroup(self, quality_group: "QualityGroup", no_dialog: bool = False, global_stack: Optional["GlobalStack"] = None) -> None:
  1241. if global_stack is not None and global_stack != self._global_container_stack:
  1242. if quality_group is None:
  1243. Logger.log("e", "Could not set quality group because quality group is None")
  1244. return
  1245. if quality_group.node_for_global is None:
  1246. Logger.log("e", "Could not set quality group [%s] because it has no node_for_global", str(quality_group))
  1247. return
  1248. # This is not changing the quality for the active machine !!!!!!!!
  1249. global_stack.quality = quality_group.node_for_global.container
  1250. for extruder_nr, extruder_stack in global_stack.extruders.items():
  1251. quality_container = empty_quality_container
  1252. if extruder_nr in quality_group.nodes_for_extruders:
  1253. container = quality_group.nodes_for_extruders[extruder_nr].container
  1254. quality_container = container if container is not None else quality_container
  1255. extruder_stack.quality = quality_container
  1256. return
  1257. self.blurSettings.emit()
  1258. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1259. self._setQualityGroup(quality_group)
  1260. # See if we need to show the Discard or Keep changes screen
  1261. if not no_dialog and self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1262. self._application.discardOrKeepProfileChanges()
  1263. ## Change the intent category of the current printer.
  1264. #
  1265. # All extruders can change their profiles. If an intent profile is
  1266. # available with the desired intent category, that one will get chosen.
  1267. # Otherwise the intent profile will be left to the empty profile, which
  1268. # represents the "default" intent category.
  1269. # \param intent_category The intent category to change to.
  1270. def setIntentByCategory(self, intent_category: str) -> None:
  1271. global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  1272. if global_stack is None:
  1273. return
  1274. container_tree = ContainerTree.getInstance()
  1275. for extruder in global_stack.extruderList:
  1276. definition_id = global_stack.definition.getId()
  1277. variant_name = extruder.variant.getName()
  1278. material_base_file = extruder.material.getMetaDataEntry("base_file")
  1279. quality_id = extruder.quality.getId()
  1280. quality_node = container_tree.machines[definition_id].variants[variant_name].materials[material_base_file].qualities[quality_id]
  1281. for intent_node in quality_node.intents.values():
  1282. if intent_node.intent_category == intent_category: # Found an intent with the correct category.
  1283. extruder.intent = intent_node.container
  1284. break
  1285. else: # No intent had the correct category.
  1286. extruder.intent = empty_intent_container
  1287. @pyqtProperty(QObject, fset = setQualityGroup, notify = activeQualityGroupChanged)
  1288. def activeQualityGroup(self) -> Optional["QualityGroup"]:
  1289. global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  1290. if not global_stack or global_stack.quality == empty_quality_container:
  1291. return None
  1292. return ContainerTree.getInstance().getCurrentQualityGroups().get(self.activeQualityType)
  1293. @pyqtSlot(QObject)
  1294. def setQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup", no_dialog: bool = False) -> None:
  1295. self.blurSettings.emit()
  1296. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1297. self._setQualityChangesGroup(quality_changes_group)
  1298. # See if we need to show the Discard or Keep changes screen
  1299. if not no_dialog and self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1300. self._application.discardOrKeepProfileChanges()
  1301. @pyqtSlot()
  1302. def resetToUseDefaultQuality(self) -> None:
  1303. if self._global_container_stack is None:
  1304. return
  1305. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1306. self._setQualityGroup(self.activeQualityGroup)
  1307. for stack in [self._global_container_stack] + list(self._global_container_stack.extruders.values()):
  1308. stack.userChanges.clear()
  1309. @pyqtProperty(QObject, fset = setQualityChangesGroup, notify = activeQualityChangesGroupChanged)
  1310. def activeQualityChangesGroup(self) -> Optional["QualityChangesGroup"]:
  1311. global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  1312. if not global_stack or global_stack.qualityChanges == empty_quality_changes_container:
  1313. return None
  1314. for group in ContainerTree.getInstance().getCurrentQualityChangesGroups(): # Match on the container ID of the global stack to find the quality changes group belonging to the active configuration.
  1315. if group.metadata_for_global and group.metadata_for_global["id"] == global_stack.qualityChanges.getId():
  1316. return group
  1317. return None
  1318. @pyqtProperty(bool, notify = activeQualityChangesGroupChanged)
  1319. def hasCustomQuality(self) -> bool:
  1320. global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  1321. return global_stack is None or global_stack.qualityChanges != empty_quality_changes_container
  1322. @pyqtProperty(str, notify = activeQualityGroupChanged)
  1323. def activeQualityOrQualityChangesName(self) -> str:
  1324. global_container_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  1325. if not global_container_stack:
  1326. return empty_quality_container.getName()
  1327. if global_container_stack.qualityChanges != empty_quality_changes_container:
  1328. return global_container_stack.qualityChanges.getName()
  1329. return global_container_stack.quality.getName()
  1330. @pyqtProperty(bool, notify = activeQualityGroupChanged)
  1331. def hasNotSupportedQuality(self) -> bool:
  1332. global_container_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  1333. return (not global_container_stack is None) and global_container_stack.quality == empty_quality_container and global_container_stack.qualityChanges == empty_quality_changes_container
  1334. def _updateUponMaterialMetadataChange(self) -> None:
  1335. if self._global_container_stack is None:
  1336. return
  1337. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1338. self.updateMaterialWithVariant(None)
  1339. self._updateQualityWithMaterial()
  1340. ## This function will translate any printer type name to an abbreviated printer type name
  1341. @pyqtSlot(str, result = str)
  1342. def getAbbreviatedMachineName(self, machine_type_name: str) -> str:
  1343. abbr_machine = ""
  1344. for word in re.findall(r"[\w']+", machine_type_name):
  1345. if word.lower() == "ultimaker":
  1346. abbr_machine += "UM"
  1347. elif word.isdigit():
  1348. abbr_machine += word
  1349. else:
  1350. stripped_word = "".join(char for char in unicodedata.normalize("NFD", word.upper()) if unicodedata.category(char) != "Mn")
  1351. # - use only the first character if the word is too long (> 3 characters)
  1352. # - use the whole word if it's not too long (<= 3 characters)
  1353. if len(stripped_word) > 3:
  1354. stripped_word = stripped_word[0]
  1355. abbr_machine += stripped_word
  1356. return abbr_machine
  1357. # Gets all machines that belong to the given group_id.
  1358. def getMachinesInGroup(self, group_id: str) -> List["GlobalStack"]:
  1359. return self._container_registry.findContainerStacks(type = "machine", group_id = group_id)