MachineManager.py 90 KB

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