MachineManager.py 96 KB

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