MachineManager.py 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876
  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. @pyqtProperty(bool, notify = currentConfigurationChanged)
  679. def variantCoreUsableForFactor4(self) -> bool:
  680. """The selected core is usable if it is in second extruder of Factor4
  681. """
  682. result = True
  683. if not self._global_container_stack:
  684. return result
  685. if self.activeMachine.definition.id != "ultimaker_factor4":
  686. return result
  687. for extruder_container in self._global_container_stack.extruderList:
  688. if extruder_container.definition.id.startswith("ultimaker_factor4_extruder_right"):
  689. if extruder_container.material == empty_material_container:
  690. return True
  691. if extruder_container.variant.id.startswith("ultimaker_factor4_bb"):
  692. return False
  693. return True
  694. @pyqtSlot(str, result = str)
  695. def getDefinitionByMachineId(self, machine_id: str) -> Optional[str]:
  696. """Get the Definition ID of a machine (specified by ID)
  697. :param machine_id: string machine id to get the definition ID of
  698. :returns: DefinitionID if found, None otherwise
  699. """
  700. containers = CuraContainerRegistry.getInstance().findContainerStacks(id = machine_id)
  701. if containers:
  702. return containers[0].definition.getId()
  703. return None
  704. def getIncompatibleSettingsOnEnabledExtruders(self, container: InstanceContainer) -> List[str]:
  705. if self._global_container_stack is None:
  706. return []
  707. extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  708. result = [] # type: List[str]
  709. for setting_instance in container.findInstances():
  710. setting_key = setting_instance.definition.key
  711. if not self._global_container_stack.getProperty(setting_key, "type") in ("extruder", "optional_extruder"):
  712. continue
  713. old_value = container.getProperty(setting_key, "value")
  714. if isinstance(old_value, SettingFunction):
  715. old_value = old_value(self._global_container_stack)
  716. if int(old_value) < 0:
  717. continue
  718. if int(old_value) >= extruder_count or not self._global_container_stack.extruderList[int(old_value)].isEnabled:
  719. result.append(setting_key)
  720. Logger.log("d", "Reset setting [%s] in [%s] because its old value [%s] is no longer valid", setting_key, container, old_value)
  721. return result
  722. def correctExtruderSettings(self) -> None:
  723. """Update extruder number to a valid value when the number of extruders are changed, or when an extruder is changed"""
  724. if self._global_container_stack is None:
  725. return
  726. for setting_key in self.getIncompatibleSettingsOnEnabledExtruders(self._global_container_stack.userChanges):
  727. self._global_container_stack.userChanges.removeInstance(setting_key)
  728. add_user_changes = self.getIncompatibleSettingsOnEnabledExtruders(self._global_container_stack.qualityChanges)
  729. for setting_key in add_user_changes:
  730. # Apply quality changes that are incompatible to user changes, so we do not change the quality changes itself.
  731. self._global_container_stack.userChanges.setProperty(setting_key, "value", self._default_extruder_position)
  732. if add_user_changes:
  733. caution_message = Message(
  734. catalog.i18nc("@info:message Followed by a list of settings.",
  735. "Settings have been changed to match the current availability of extruders:") + " [{settings_list}]".format(settings_list = ", ".join(add_user_changes)),
  736. title = catalog.i18nc("@info:title", "Settings updated"))
  737. caution_message.show()
  738. def correctPrintSequence(self) -> None:
  739. """
  740. Sets the Print Sequence setting to "all-at-once" when there are more than one enabled extruders.
  741. This setting has to be explicitly changed whenever we have more than one enabled extruders to make sure that the
  742. Cura UI is properly updated to reset all the UI elements changes that occur due to the one-at-a-time mode (such
  743. as the reduced build volume, the different convex hulls of the objects etc.).
  744. """
  745. setting_key = "print_sequence"
  746. new_value = "all_at_once"
  747. if self._global_container_stack is None \
  748. or self._global_container_stack.getProperty(setting_key, "value") == new_value \
  749. or self._global_container_stack.definitionChanges.getProperty("extruders_enabled_count", "value") is None \
  750. or self._global_container_stack.definitionChanges.getProperty("extruders_enabled_count", "value") < 2:
  751. return
  752. user_changes_container = self._global_container_stack.userChanges
  753. quality_changes_container = self._global_container_stack.qualityChanges
  754. print_sequence_quality_changes = quality_changes_container.getProperty(setting_key, "value")
  755. print_sequence_user_changes = user_changes_container.getProperty(setting_key, "value")
  756. # If the user changes container has a value and its the incorrect value, then reset the setting in the user
  757. # changes (so that the circular revert-changes arrow will now show up in the interface)
  758. if print_sequence_user_changes and print_sequence_user_changes != new_value:
  759. user_changes_container.removeInstance(setting_key)
  760. Logger.log("d", "Resetting '{}' in container '{}' because there are more than 1 enabled extruders.".format(setting_key, user_changes_container))
  761. # If the print sequence doesn't exist in either the user changes or the quality changes (yet it still has the
  762. # wrong value in the global stack), or it exists in the quality changes and it has the wrong value, then set it
  763. # in the user changes
  764. elif (not print_sequence_quality_changes and not print_sequence_user_changes) \
  765. or (print_sequence_quality_changes and print_sequence_quality_changes != new_value):
  766. user_changes_container.setProperty(setting_key, "value", new_value)
  767. Logger.log("d", "Setting '{}' in '{}' to '{}' because there are more than 1 enabled extruders.".format(setting_key, user_changes_container, new_value))
  768. def setActiveMachineExtruderCount(self, extruder_count: int) -> None:
  769. """Set the amount of extruders on the active machine (global stack)
  770. :param extruder_count: int the number of extruders to set
  771. """
  772. if self._global_container_stack is None:
  773. return
  774. extruder_manager = self._application.getExtruderManager()
  775. definition_changes_container = self._global_container_stack.definitionChanges
  776. if not self._global_container_stack or definition_changes_container == empty_definition_changes_container:
  777. return
  778. previous_extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  779. if extruder_count == previous_extruder_count:
  780. return
  781. definition_changes_container.setProperty("machine_extruder_count", "value", extruder_count)
  782. self.updateDefaultExtruder()
  783. self.numberExtrudersEnabledChanged.emit()
  784. self.correctExtruderSettings()
  785. # Check to see if any objects are set to print with an extruder that will no longer exist
  786. root_node = self._application.getController().getScene().getRoot()
  787. for node in DepthFirstIterator(root_node):
  788. if node.getMeshData():
  789. extruder_nr = node.callDecoration("getActiveExtruderPosition")
  790. if extruder_nr is not None and int(extruder_nr) > extruder_count - 1:
  791. extruder = extruder_manager.getExtruderStack(extruder_count - 1)
  792. if extruder is not None:
  793. node.callDecoration("setActiveExtruder", extruder.getId())
  794. else:
  795. Logger.log("w", "Could not find extruder to set active.")
  796. # Make sure one of the extruder stacks is active
  797. extruder_manager.setActiveExtruderIndex(0)
  798. # Move settable_per_extruder values out of the global container
  799. # After CURA-4482 this should not be the case anymore, but we still want to support older project files.
  800. global_user_container = self._global_container_stack.userChanges
  801. for setting_instance in global_user_container.findInstances():
  802. setting_key = setting_instance.definition.key
  803. settable_per_extruder = self._global_container_stack.getProperty(setting_key, "settable_per_extruder")
  804. if settable_per_extruder:
  805. limit_to_extruder = int(self._global_container_stack.getProperty(setting_key, "limit_to_extruder"))
  806. extruder_position = max(0, limit_to_extruder)
  807. extruder_stack = self._global_container_stack.extruderList[extruder_position]
  808. if extruder_stack:
  809. extruder_stack.userChanges.setProperty(setting_key, "value", global_user_container.getProperty(setting_key, "value"))
  810. else:
  811. Logger.log("e", "Unable to find extruder on position %s", extruder_position)
  812. global_user_container.removeInstance(setting_key)
  813. # Signal that the global stack has changed
  814. self._application.globalContainerStackChanged.emit()
  815. self.forceUpdateAllSettings()
  816. def updateDefaultExtruder(self) -> None:
  817. if self._global_container_stack is None:
  818. return
  819. old_position = self._default_extruder_position
  820. new_default_position = "0"
  821. for extruder in self._global_container_stack.extruderList:
  822. if extruder.isEnabled:
  823. new_default_position = extruder.getMetaDataEntry("position", "0")
  824. break
  825. if new_default_position != old_position:
  826. self._default_extruder_position = new_default_position
  827. self.extruderChanged.emit()
  828. def updateNumberExtrudersEnabled(self) -> None:
  829. if self._global_container_stack is None:
  830. return
  831. definition_changes_container = self._global_container_stack.definitionChanges
  832. machine_extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  833. extruder_count = 0
  834. for position, extruder in enumerate(self._global_container_stack.extruderList):
  835. if extruder.isEnabled and int(position) < machine_extruder_count:
  836. extruder_count += 1
  837. if self._global_container_stack.definitionChanges.getProperty("extruders_enabled_count", "value") != extruder_count:
  838. definition_changes_container.setProperty("extruders_enabled_count", "value", extruder_count)
  839. self.numberExtrudersEnabledChanged.emit()
  840. @pyqtProperty(int, notify = numberExtrudersEnabledChanged)
  841. def numberExtrudersEnabled(self) -> int:
  842. if self._global_container_stack is None:
  843. return 1
  844. extruders_enabled_count = self._global_container_stack.definitionChanges.getProperty("extruders_enabled_count", "value")
  845. if extruders_enabled_count is None:
  846. extruders_enabled_count = len(self._global_container_stack.extruderList)
  847. return extruders_enabled_count
  848. @pyqtProperty(str, notify = extruderChanged)
  849. def defaultExtruderPosition(self) -> str:
  850. return self._default_extruder_position
  851. @pyqtSlot()
  852. def forceUpdateAllSettings(self) -> None:
  853. """This will fire the propertiesChanged for all settings so they will be updated in the front-end"""
  854. if self._global_container_stack is None:
  855. return
  856. property_names = ["value", "resolve", "validationState"]
  857. for container in [self._global_container_stack] + self._global_container_stack.extruderList:
  858. for setting_key in container.getAllKeys():
  859. container.propertiesChanged.emit(setting_key, property_names)
  860. @pyqtSlot(int, bool)
  861. def setExtruderEnabled(self, position: int, enabled: bool) -> None:
  862. if self._global_container_stack is None or position >= len(self._global_container_stack.extruderList):
  863. Logger.log("w", "Could not find extruder on position %s.", position)
  864. return
  865. extruder = self._global_container_stack.extruderList[position]
  866. extruder.setEnabled(enabled)
  867. self.updateDefaultExtruder()
  868. self.updateNumberExtrudersEnabled()
  869. self.correctExtruderSettings()
  870. # Ensure that the quality profile is compatible with current combination, or choose a compatible one if available
  871. self._updateQualityWithMaterial()
  872. self.extruderChanged.emit()
  873. # Update material compatibility color
  874. self.activeQualityGroupChanged.emit()
  875. # Update items in SettingExtruder
  876. ExtruderManager.getInstance().extrudersChanged.emit(self._global_container_stack.getId())
  877. # Also trigger the build plate compatibility to update
  878. self.activeMaterialChanged.emit()
  879. self.activeIntentChanged.emit()
  880. # Force an update of resolve values
  881. property_names = ["resolve", "validationState"]
  882. for setting_key in self._global_container_stack.getAllKeys():
  883. self._global_container_stack.propertiesChanged.emit(setting_key, property_names)
  884. def _onMaterialNameChanged(self) -> None:
  885. self.activeMaterialChanged.emit()
  886. def _getContainerChangedSignals(self) -> List[Signal]:
  887. """Get the signals that signal that the containers changed for all stacks.
  888. This includes the global stack and all extruder stacks. So if any
  889. container changed anywhere.
  890. """
  891. if self._global_container_stack is None:
  892. return []
  893. return [s.containersChanged for s in self._global_container_stack.extruderList + [self._global_container_stack]]
  894. @pyqtSlot(str, str, str)
  895. def setSettingForAllExtruders(self, setting_name: str, property_name: str, property_value: str) -> None:
  896. if self._global_container_stack is None:
  897. return
  898. for extruder in self._global_container_stack.extruderList:
  899. container = extruder.userChanges
  900. container.setProperty(setting_name, property_name, property_value)
  901. @pyqtSlot(str)
  902. def resetSettingForAllExtruders(self, setting_name: str) -> None:
  903. """Reset all setting properties of a setting for all extruders.
  904. :param setting_name: The ID of the setting to reset.
  905. """
  906. if self._global_container_stack is None:
  907. return
  908. for extruder in self._global_container_stack.extruderList:
  909. container = extruder.userChanges
  910. container.removeInstance(setting_name)
  911. def _onRootMaterialChanged(self) -> None:
  912. """Update _current_root_material_id when the current root material was changed."""
  913. self._current_root_material_id = {}
  914. changed = False
  915. if self._global_container_stack:
  916. for extruder in self._global_container_stack.extruderList:
  917. material_id = extruder.material.getMetaDataEntry("base_file")
  918. position = extruder.getMetaDataEntry("position")
  919. if position not in self._current_root_material_id or material_id != self._current_root_material_id[position]:
  920. changed = True
  921. self._current_root_material_id[position] = material_id
  922. if changed:
  923. self.activeMaterialChanged.emit()
  924. @pyqtProperty("QVariant", notify = rootMaterialChanged)
  925. def currentRootMaterialId(self) -> Dict[str, str]:
  926. return self._current_root_material_id
  927. # Sets all quality and quality_changes containers to empty_quality and empty_quality_changes containers
  928. # for all stacks in the currently active machine.
  929. #
  930. def _setEmptyQuality(self) -> None:
  931. if self._global_container_stack is None:
  932. return
  933. self._global_container_stack.quality = empty_quality_container
  934. self._global_container_stack.qualityChanges = empty_quality_changes_container
  935. for extruder in self._global_container_stack.extruderList:
  936. extruder.quality = empty_quality_container
  937. extruder.qualityChanges = empty_quality_changes_container
  938. self.activeQualityGroupChanged.emit()
  939. self.activeQualityChangesGroupChanged.emit()
  940. self._updateIntentWithQuality()
  941. def _setQualityGroup(self, quality_group: Optional["QualityGroup"], empty_quality_changes: bool = True) -> None:
  942. if self._global_container_stack is None:
  943. return
  944. if quality_group is None:
  945. self._setEmptyQuality()
  946. return
  947. if quality_group.node_for_global is None or quality_group.node_for_global.container is None:
  948. return
  949. for node in quality_group.nodes_for_extruders.values():
  950. if node.container is None:
  951. return
  952. # Set quality and quality_changes for the GlobalStack
  953. self._global_container_stack.quality = quality_group.node_for_global.container
  954. if empty_quality_changes:
  955. self._global_container_stack.qualityChanges = empty_quality_changes_container
  956. # Set quality and quality_changes for each ExtruderStack
  957. for position, node in quality_group.nodes_for_extruders.items():
  958. self._global_container_stack.extruderList[position].quality = node.container
  959. if empty_quality_changes:
  960. self._global_container_stack.extruderList[position].qualityChanges = empty_quality_changes_container
  961. self.activeQualityGroupChanged.emit()
  962. self.activeQualityChangesGroupChanged.emit()
  963. self._updateIntentWithQuality()
  964. def _fixQualityChangesGroupToNotSupported(self, quality_changes_group: "QualityChangesGroup") -> None:
  965. metadatas = [quality_changes_group.metadata_for_global] + list(quality_changes_group.metadata_per_extruder.values())
  966. for metadata in metadatas:
  967. metadata["quality_type"] = "not_supported" # This actually changes the metadata of the container since they are stored by reference!
  968. quality_changes_group.quality_type = "not_supported"
  969. quality_changes_group.intent_category = "default"
  970. def _setQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup") -> None:
  971. if self._global_container_stack is None:
  972. return # Can't change that.
  973. quality_type = quality_changes_group.quality_type
  974. # A custom quality can be created based on "not supported".
  975. # In that case, do not set quality containers to empty.
  976. quality_group = None
  977. if quality_type != "not_supported": # Find the quality group that the quality changes was based on.
  978. quality_group = ContainerTree.getInstance().getCurrentQualityGroups().get(quality_type)
  979. if quality_group is None:
  980. self._fixQualityChangesGroupToNotSupported(quality_changes_group)
  981. container_registry = self._application.getContainerRegistry()
  982. quality_changes_container = empty_quality_changes_container
  983. quality_container = empty_quality_container # type: InstanceContainer
  984. if quality_changes_group.metadata_for_global:
  985. global_containers = container_registry.findContainers(id = quality_changes_group.metadata_for_global["id"])
  986. if global_containers:
  987. quality_changes_container = global_containers[0]
  988. if quality_changes_group.metadata_for_global:
  989. containers = container_registry.findContainers(id = quality_changes_group.metadata_for_global["id"])
  990. if containers:
  991. quality_changes_container = cast(InstanceContainer, containers[0])
  992. if quality_group is not None and quality_group.node_for_global and quality_group.node_for_global.container:
  993. quality_container = quality_group.node_for_global.container
  994. self._global_container_stack.quality = quality_container
  995. self._global_container_stack.qualityChanges = quality_changes_container
  996. for position, extruder in enumerate(self._global_container_stack.extruderList):
  997. quality_node = None
  998. if quality_group is not None:
  999. quality_node = quality_group.nodes_for_extruders.get(position)
  1000. quality_changes_container = empty_quality_changes_container
  1001. quality_container = empty_quality_container
  1002. quality_changes_metadata = quality_changes_group.metadata_per_extruder.get(position)
  1003. if quality_changes_metadata:
  1004. containers = container_registry.findContainers(id = quality_changes_metadata["id"])
  1005. if containers:
  1006. quality_changes_container = cast(InstanceContainer, containers[0])
  1007. if quality_node and quality_node.container:
  1008. quality_container = quality_node.container
  1009. extruder.quality = quality_container
  1010. extruder.qualityChanges = quality_changes_container
  1011. self.setIntentByCategory(quality_changes_group.intent_category)
  1012. self._reCalculateNumUserSettings()
  1013. self.correctExtruderSettings()
  1014. self.activeQualityGroupChanged.emit()
  1015. self.activeQualityChangesGroupChanged.emit()
  1016. def _setVariantNode(self, position: str, variant_node: "VariantNode") -> None:
  1017. if self._global_container_stack is None:
  1018. return
  1019. self._global_container_stack.extruderList[int(position)].variant = variant_node.container
  1020. self.activeVariantChanged.emit()
  1021. def _setGlobalVariant(self, container_node: "ContainerNode") -> None:
  1022. if self._global_container_stack is None:
  1023. return
  1024. self._global_container_stack.variant = container_node.container
  1025. if not self._global_container_stack.variant:
  1026. self._global_container_stack.variant = self._application.empty_variant_container
  1027. def _setMaterial(self, position: str, material_node: Optional["MaterialNode"] = None) -> None:
  1028. if self._global_container_stack is None:
  1029. return
  1030. if material_node and material_node.container:
  1031. material_container = material_node.container
  1032. self._global_container_stack.extruderList[int(position)].material = material_container
  1033. root_material_id = material_container.getMetaDataEntry("base_file", None)
  1034. else:
  1035. self._global_container_stack.extruderList[int(position)].material = empty_material_container
  1036. root_material_id = None
  1037. # The _current_root_material_id is used in the MaterialMenu to see which material is selected
  1038. if position not in self._current_root_material_id or root_material_id != self._current_root_material_id[position]:
  1039. self._current_root_material_id[position] = root_material_id
  1040. self.rootMaterialChanged.emit()
  1041. def activeMaterialsCompatible(self) -> bool:
  1042. # Check material - variant compatibility
  1043. if self._global_container_stack is not None:
  1044. if Util.parseBool(self._global_container_stack.getMetaDataEntry("has_materials", False)):
  1045. for extruder in self._global_container_stack.extruderList:
  1046. if not extruder.isEnabled:
  1047. continue
  1048. if not extruder.material.getMetaDataEntry("compatible"):
  1049. return False
  1050. return True
  1051. def _updateQualityWithMaterial(self, *args: Any) -> None:
  1052. """Update current quality type and machine after setting material"""
  1053. global_stack = self._application.getGlobalContainerStack()
  1054. if global_stack is None:
  1055. return
  1056. Logger.log("d", "Updating quality/quality_changes due to material change")
  1057. current_quality_type = global_stack.quality.getMetaDataEntry("quality_type")
  1058. candidate_quality_groups = ContainerTree.getInstance().getCurrentQualityGroups()
  1059. available_quality_types = {qt for qt, g in candidate_quality_groups.items() if g.is_available}
  1060. Logger.log("d", "Current quality type = [%s]", current_quality_type)
  1061. if not self.activeMaterialsCompatible():
  1062. if current_quality_type is not None:
  1063. Logger.log("i", "Active materials are not compatible, setting all qualities to empty (Not Supported).")
  1064. self._setEmptyQuality()
  1065. return
  1066. if not available_quality_types:
  1067. Logger.log("i", "No available quality types found, setting all qualities to empty (Not Supported).")
  1068. self._setEmptyQuality()
  1069. return
  1070. if current_quality_type in available_quality_types:
  1071. Logger.log("i", "Current available quality type [%s] is available, applying changes.", current_quality_type)
  1072. self._setQualityGroup(candidate_quality_groups[current_quality_type], empty_quality_changes = False)
  1073. return
  1074. # The current quality type is not available so we use the preferred quality type if it's available,
  1075. # otherwise use one of the available quality types.
  1076. quality_type = sorted(list(available_quality_types))[0]
  1077. if self._global_container_stack is None:
  1078. Logger.log("e", "Global stack not present!")
  1079. return
  1080. preferred_quality_type = self._global_container_stack.getMetaDataEntry("preferred_quality_type")
  1081. if preferred_quality_type in available_quality_types:
  1082. quality_type = preferred_quality_type
  1083. Logger.log("i", "The current quality type [%s] is not available, switching to [%s] instead",
  1084. current_quality_type, quality_type)
  1085. self._setQualityGroup(candidate_quality_groups[quality_type], empty_quality_changes = True)
  1086. def _updateIntentWithQuality(self):
  1087. """Update the current intent after the quality changed"""
  1088. global_stack = self._application.getGlobalContainerStack()
  1089. if global_stack is None:
  1090. return
  1091. Logger.log("d", "Updating intent due to quality change")
  1092. category = "default"
  1093. for extruder in global_stack.extruderList:
  1094. if not extruder.isEnabled:
  1095. continue
  1096. current_category = extruder.intent.getMetaDataEntry("intent_category", "default")
  1097. if current_category != "default" and current_category != category:
  1098. category = current_category
  1099. continue
  1100. # It's also possible that the qualityChanges has an opinion about the intent_category.
  1101. # This is in the case that a QC was made on an intent, but none of the materials have that intent.
  1102. # If the user switches back, we do want the intent to be selected again.
  1103. #
  1104. # Do not ask empty quality changes for intent category.
  1105. if extruder.qualityChanges.getId() == empty_quality_changes_container.getId():
  1106. continue
  1107. current_category = extruder.qualityChanges.getMetaDataEntry("intent_category", "default")
  1108. if current_category != "default" and current_category != category:
  1109. category = current_category
  1110. self.setIntentByCategory(category)
  1111. @pyqtSlot()
  1112. def updateMaterialWithVariant(self, position: Optional[str] = None) -> None:
  1113. """Update the material profile in the current stacks when the variant is
  1114. changed.
  1115. :param position: The extruder stack to update. If provided with None, all
  1116. extruder stacks will be updated.
  1117. """
  1118. if self._global_container_stack is None:
  1119. return
  1120. if position is None:
  1121. position_list = [str(position) for position in range(len(self._global_container_stack.extruderList))]
  1122. else:
  1123. position_list = [position]
  1124. for position_item in position_list:
  1125. try:
  1126. extruder = self._global_container_stack.extruderList[int(position_item)]
  1127. except IndexError:
  1128. continue
  1129. current_material_base_name = extruder.material.getMetaDataEntry("base_file")
  1130. current_nozzle_name = extruder.variant.getMetaDataEntry("name")
  1131. # If we can keep the current material after the switch, try to do so.
  1132. nozzle_node = ContainerTree.getInstance().machines[self._global_container_stack.definition.getId()].variants[current_nozzle_name]
  1133. candidate_materials = nozzle_node.materials
  1134. old_approximate_material_diameter = int(extruder.material.getMetaDataEntry("approximate_diameter", default = 3))
  1135. new_approximate_material_diameter = int(self._global_container_stack.extruderList[int(position_item)].getApproximateMaterialDiameter())
  1136. # Only switch to the old candidate material if the approximate material diameter of the extruder stays the
  1137. # same.
  1138. if new_approximate_material_diameter == old_approximate_material_diameter and \
  1139. current_material_base_name in candidate_materials: # The current material is also available after the switch. Retain it.
  1140. new_material = candidate_materials[current_material_base_name]
  1141. self._setMaterial(position_item, new_material)
  1142. else:
  1143. # The current material is not available, find the preferred one.
  1144. approximate_material_diameter = int(self._global_container_stack.extruderList[int(position_item)].getApproximateMaterialDiameter())
  1145. material_node = nozzle_node.preferredMaterial(approximate_material_diameter)
  1146. self._setMaterial(position_item, material_node)
  1147. @pyqtSlot(str)
  1148. def switchPrinterType(self, machine_name: str) -> None:
  1149. """Given a printer definition name, select the right machine instance. In case it doesn't exist, create a new
  1150. instance with the same network key.
  1151. """
  1152. # Don't switch if the user tries to change to the same type of printer
  1153. if self._global_container_stack is None or self._global_container_stack.definition.name == machine_name:
  1154. return
  1155. Logger.log("i", "Attempting to switch the printer type to [%s]", machine_name)
  1156. # Get the definition id corresponding to this machine name
  1157. definitions = CuraContainerRegistry.getInstance().findDefinitionContainers(name=machine_name)
  1158. if not definitions:
  1159. Logger.log("e", "Unable to switch printer type since it could not be found!")
  1160. return
  1161. machine_definition_id = definitions[0].getId()
  1162. # Try to find a machine with the same network key
  1163. metadata_filter = {"group_id": self._global_container_stack.getMetaDataEntry("group_id")}
  1164. new_machine = self.getMachine(machine_definition_id, metadata_filter = metadata_filter)
  1165. # If there is no machine, then create a new one and set it to the non-hidden instance
  1166. if not new_machine:
  1167. new_machine = CuraStackBuilder.createMachine(machine_definition_id + "_sync", machine_definition_id)
  1168. if not new_machine:
  1169. Logger.log("e", "Failed to create new machine when switching configuration.")
  1170. return
  1171. for metadata_key in self._global_container_stack.getMetaData():
  1172. if metadata_key in new_machine.getMetaData():
  1173. continue # Don't copy the already preset stuff.
  1174. new_machine.setMetaDataEntry(metadata_key, self._global_container_stack.getMetaDataEntry(metadata_key))
  1175. # Special case, group_id should be overwritten!
  1176. new_machine.setMetaDataEntry("group_id", self._global_container_stack.getMetaDataEntry("group_id"))
  1177. else:
  1178. Logger.log("i", "Found a %s with the key %s. Let's use it!", machine_name, self.activeMachineNetworkKey())
  1179. # Set the current printer instance to hidden (the metadata entry must exist)
  1180. new_machine.setMetaDataEntry("hidden", False)
  1181. self._global_container_stack.setMetaDataEntry("hidden", True)
  1182. # The new_machine does not contain user changes (global or per-extruder user changes).
  1183. # Keep a temporary copy of the global and per-extruder user changes and transfer them to the user changes
  1184. # of the new machine after the new_machine becomes active.
  1185. global_user_changes = self._global_container_stack.userChanges
  1186. per_extruder_user_changes = [extruder_stack.userChanges for extruder_stack in self._global_container_stack.extruderList]
  1187. self.setActiveMachine(new_machine.getId())
  1188. # Apply the global and per-extruder userChanges to the new_machine (which is of different type than the
  1189. # previous one).
  1190. self._global_container_stack.setUserChanges(global_user_changes)
  1191. for i, user_changes in enumerate(per_extruder_user_changes):
  1192. if i >= len(self._global_container_stack.extruderList): # New printer has fewer extruders.
  1193. break
  1194. self._global_container_stack.extruderList[i].setUserChanges(per_extruder_user_changes[i])
  1195. @pyqtSlot(QObject)
  1196. def applyRemoteConfiguration(self, configuration: PrinterConfigurationModel) -> None:
  1197. if self._global_container_stack is None:
  1198. return
  1199. self.blurSettings.emit()
  1200. container_registry = CuraContainerRegistry.getInstance()
  1201. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1202. self.switchPrinterType(configuration.printerType)
  1203. extruders_to_disable = set()
  1204. # If an extruder that's currently used to print a model gets disabled due to the syncing, we need to show
  1205. # a message explaining why.
  1206. need_to_show_message = False
  1207. for extruder_configuration in configuration.extruderConfigurations:
  1208. # We support "" or None, since the cloud uses None instead of empty strings
  1209. extruder_has_hotend = extruder_configuration.hotendID not in ["", None]
  1210. extruder_has_material = extruder_configuration.material.guid not in [None, "", "00000000-0000-0000-0000-000000000000"]
  1211. # If the machine doesn't have a hotend or material, disable this extruder
  1212. if not extruder_has_hotend or not extruder_has_material:
  1213. extruders_to_disable.add(extruder_configuration.position)
  1214. # If there's no material and/or nozzle on the printer, enable the first extruder and disable the rest.
  1215. if len(extruders_to_disable) == len(self._global_container_stack.extruderList):
  1216. extruders_to_disable.remove(min(extruders_to_disable))
  1217. for extruder_configuration in configuration.extruderConfigurations:
  1218. position = str(extruder_configuration.position)
  1219. if int(position) >= len(self._global_container_stack.extruderList):
  1220. Logger.warning("Received a configuration for extruder {position}, which is out of bounds for this printer.".format(position=position))
  1221. 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.
  1222. # If the machine doesn't have a hotend or material, disable this extruder
  1223. if int(position) in extruders_to_disable:
  1224. self._global_container_stack.extruderList[int(position)].setEnabled(False)
  1225. need_to_show_message = True
  1226. else:
  1227. machine_node = ContainerTree.getInstance().machines.get(self._global_container_stack.definition.getId())
  1228. variant_node = machine_node.variants.get(extruder_configuration.hotendID)
  1229. if variant_node is None:
  1230. continue
  1231. self._setVariantNode(position, variant_node)
  1232. # Find the material profile that the printer has stored.
  1233. # 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.
  1234. approximate_diameter = int(self._global_container_stack.extruderList[int(position)].getApproximateMaterialDiameter())
  1235. materials_with_guid = container_registry.findInstanceContainersMetadata(GUID = extruder_configuration.material.guid, approximate_diameter = str(approximate_diameter), ignore_case = True)
  1236. material_container_node = variant_node.preferredMaterial(approximate_diameter)
  1237. if materials_with_guid: # We also have the material profile that the printer wants to share.
  1238. base_file = materials_with_guid[0]["base_file"]
  1239. material_container_node = variant_node.materials.get(base_file, material_container_node)
  1240. self._setMaterial(position, material_container_node)
  1241. self._global_container_stack.extruderList[int(position)].setEnabled(True)
  1242. self.updateMaterialWithVariant(position)
  1243. self.updateDefaultExtruder()
  1244. self.updateNumberExtrudersEnabled()
  1245. self._updateQualityWithMaterial()
  1246. if need_to_show_message:
  1247. msg_str = "{extruders} is disabled because there is no material loaded. Please load a material or use custom configurations."
  1248. # Show human-readable extruder names such as "Extruder Left", "Extruder Front" instead of "Extruder 1, 2, 3".
  1249. extruder_names = []
  1250. for extruder_position in sorted(extruders_to_disable):
  1251. extruder_stack = self._global_container_stack.extruderList[int(extruder_position)]
  1252. extruder_name = extruder_stack.definition.getName()
  1253. extruder_names.append(extruder_name)
  1254. extruders_str = ", ".join(extruder_names)
  1255. msg_str = msg_str.format(extruders = extruders_str)
  1256. message = Message(catalog.i18nc("@info:status", msg_str),
  1257. title = catalog.i18nc("@info:title", "Extruder(s) Disabled"))
  1258. message.show()
  1259. # See if we need to show the Discard or Keep changes screen
  1260. if self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1261. self._application.discardOrKeepProfileChanges()
  1262. @pyqtSlot("QVariant")
  1263. def setGlobalVariant(self, container_node: "ContainerNode") -> None:
  1264. self.blurSettings.emit()
  1265. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1266. self._setGlobalVariant(container_node)
  1267. self.updateMaterialWithVariant(None) # Update all materials
  1268. self._updateQualityWithMaterial()
  1269. @pyqtSlot(str, str, result = bool)
  1270. def setMaterialById(self, position: str, root_material_id: str) -> bool:
  1271. if self._global_container_stack is None:
  1272. return False
  1273. machine_definition_id = self._global_container_stack.definition.id
  1274. position = str(position)
  1275. extruder_stack = self._global_container_stack.extruderList[int(position)]
  1276. nozzle_name = extruder_stack.variant.getName()
  1277. materials = ContainerTree.getInstance().machines[machine_definition_id].variants[nozzle_name].materials
  1278. if root_material_id in materials:
  1279. self.setMaterial(position, materials[root_material_id])
  1280. return True
  1281. return False
  1282. @pyqtSlot(str, "QVariant")
  1283. def setMaterial(self, position: str, container_node, global_stack: Optional["GlobalStack"] = None) -> None:
  1284. """Global_stack: if you want to provide your own global_stack instead of the current active one
  1285. if you update an active machine, special measures have to be taken.
  1286. """
  1287. if global_stack is not None and global_stack != self._global_container_stack:
  1288. global_stack.extruderList[int(position)].material = container_node.container
  1289. return
  1290. position = str(position)
  1291. self.blurSettings.emit()
  1292. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1293. self._setMaterial(position, container_node)
  1294. self._updateQualityWithMaterial()
  1295. # See if we need to show the Discard or Keep changes screen
  1296. if self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1297. self._application.discardOrKeepProfileChanges()
  1298. @pyqtSlot(str, str)
  1299. def setVariantByName(self, position: str, variant_name: str) -> None:
  1300. if self._global_container_stack is None:
  1301. return
  1302. machine_definition_id = self._global_container_stack.definition.id
  1303. machine_node = ContainerTree.getInstance().machines.get(machine_definition_id)
  1304. variant_node = machine_node.variants.get(variant_name)
  1305. if variant_node is None:
  1306. Logger.error(f"There is no variant with the name {variant_name}.")
  1307. return
  1308. self.setVariant(position, variant_node)
  1309. @pyqtSlot(str, "QVariant")
  1310. def setVariant(self, position: str, variant_node: "VariantNode") -> None:
  1311. position = str(position)
  1312. self.blurSettings.emit()
  1313. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1314. self._setVariantNode(position, variant_node)
  1315. self.updateMaterialWithVariant(position)
  1316. self._updateQualityWithMaterial()
  1317. # See if we need to show the Discard or Keep changes screen
  1318. if self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1319. self._application.discardOrKeepProfileChanges()
  1320. @pyqtSlot(str)
  1321. def setQualityGroupByQualityType(self, quality_type: str) -> None:
  1322. if self._global_container_stack is None:
  1323. return
  1324. # Get all the quality groups for this global stack and filter out by quality_type
  1325. self.setQualityGroup(ContainerTree.getInstance().getCurrentQualityGroups()[quality_type])
  1326. @pyqtSlot(QObject)
  1327. def setQualityGroup(self, quality_group: "QualityGroup", no_dialog: bool = False, global_stack: Optional["GlobalStack"] = None) -> None:
  1328. """Optionally provide global_stack if you want to use your own
  1329. The active global_stack is treated differently.
  1330. """
  1331. if global_stack is not None and global_stack != self._global_container_stack:
  1332. if quality_group is None:
  1333. Logger.log("e", "Could not set quality group because quality group is None")
  1334. return
  1335. if quality_group.node_for_global is None:
  1336. Logger.log("e", "Could not set quality group [%s] because it has no node_for_global", str(quality_group))
  1337. return
  1338. # This is not changing the quality for the active machine !!!!!!!!
  1339. global_stack.quality = quality_group.node_for_global.container
  1340. for extruder_nr, extruder_stack in enumerate(global_stack.extruderList):
  1341. quality_container = empty_quality_container
  1342. if extruder_nr in quality_group.nodes_for_extruders:
  1343. container = quality_group.nodes_for_extruders[extruder_nr].container
  1344. quality_container = container if container is not None else quality_container
  1345. extruder_stack.quality = quality_container
  1346. return
  1347. self.blurSettings.emit()
  1348. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1349. self._setQualityGroup(quality_group)
  1350. # See if we need to show the Discard or Keep changes screen
  1351. if not no_dialog and self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1352. self._application.discardOrKeepProfileChanges()
  1353. # The display name map of currently active quality.
  1354. # The display name has 2 parts, a main part and a suffix part.
  1355. # This display name is:
  1356. # - For built-in qualities (quality/intent): the quality type name, such as "Fine", "Normal", etc.
  1357. # - For custom qualities: <custom_quality_name> - <intent_name> - <quality_type_name>
  1358. # Examples:
  1359. # - "my_profile - Fine" (only based on a default quality, no intent involved)
  1360. # - "my_profile - Engineering - Fine" (based on an intent)
  1361. @pyqtProperty("QList<QString>", notify = activeQualityDisplayNameChanged)
  1362. def activeQualityDisplayNameStringParts(self) -> List[str]:
  1363. return self.activeQualityDisplayNameMap().getStringParts()
  1364. @pyqtProperty("QList<QString>", notify = activeQualityDisplayNameChanged)
  1365. def activeQualityDisplayNameMainStringParts(self) -> List[str]:
  1366. return self.activeQualityDisplayNameMap().getMainStringParts()
  1367. @pyqtProperty("QList<QString>", notify = activeQualityDisplayNameChanged)
  1368. def activeQualityDisplayNameTailStringParts(self) -> List[str]:
  1369. return self.activeQualityDisplayNameMap().getTailStringParts()
  1370. def activeQualityDisplayNameMap(self) -> ActiveQuality:
  1371. global_stack = self._application.getGlobalContainerStack()
  1372. if global_stack is None:
  1373. return ActiveQuality()
  1374. return ActiveQuality(
  1375. profile = global_stack.quality.getName(),
  1376. intent_category = self.activeIntentCategory,
  1377. intent_name = IntentCategoryModel.translation(self.activeIntentCategory, "name", self.activeIntentCategory.title()),
  1378. custom_profile = self.activeQualityOrQualityChangesName if global_stack.qualityChanges is not empty_quality_changes_container else None,
  1379. layer_height = self.activeQualityLayerHeight if self.isActiveQualitySupported else None,
  1380. is_experimental = self.isActiveQualityExperimental and self.isActiveQualitySupported
  1381. )
  1382. @pyqtSlot(str)
  1383. def setIntentByCategory(self, intent_category: str) -> None:
  1384. """Change the intent category of the current printer.
  1385. All extruders can change their profiles. If an intent profile is
  1386. available with the desired intent category, that one will get chosen.
  1387. Otherwise the intent profile will be left to the empty profile, which
  1388. represents the "default" intent category.
  1389. :param intent_category: The intent category to change to.
  1390. """
  1391. global_stack = self._application.getGlobalContainerStack()
  1392. if global_stack is None:
  1393. return
  1394. container_tree = ContainerTree.getInstance()
  1395. for extruder in global_stack.extruderList:
  1396. definition_id = global_stack.definition.getId()
  1397. variant_name = extruder.variant.getName()
  1398. material_base_file = extruder.material.getMetaDataEntry("base_file")
  1399. quality_id = extruder.quality.getId()
  1400. if quality_id == empty_quality_container.getId():
  1401. extruder.intent = empty_intent_container
  1402. continue
  1403. # Yes, we can find this in a single line of code. This makes it easier to read and it has the benefit
  1404. # that it doesn't lump key errors together for the crashlogs
  1405. try:
  1406. machine_node = container_tree.machines[definition_id]
  1407. variant_node = machine_node.variants[variant_name]
  1408. material_node = variant_node.materials[material_base_file]
  1409. quality_node = material_node.qualities[quality_id]
  1410. except KeyError as e:
  1411. 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))
  1412. continue
  1413. for intent_node in quality_node.intents.values():
  1414. if intent_node.intent_category == intent_category: # Found an intent with the correct category.
  1415. extruder.intent = intent_node.container
  1416. break
  1417. else: # No intent had the correct category.
  1418. extruder.intent = empty_intent_container
  1419. @pyqtSlot()
  1420. def resetIntents(self) -> None:
  1421. """Reset the intent category of the current printer.
  1422. """
  1423. global_stack = self._application.getGlobalContainerStack()
  1424. if global_stack is None:
  1425. return
  1426. for extruder in global_stack.extruderList:
  1427. extruder.intent = empty_intent_container
  1428. def activeQualityGroup(self) -> Optional["QualityGroup"]:
  1429. """Get the currently activated quality group.
  1430. If no printer is added yet or the printer doesn't have quality profiles,
  1431. this returns ``None``.
  1432. :return: The currently active quality group.
  1433. """
  1434. global_stack = self._application.getGlobalContainerStack()
  1435. if not global_stack or global_stack.quality == empty_quality_container:
  1436. return None
  1437. return ContainerTree.getInstance().getCurrentQualityGroups().get(self.activeQualityType)
  1438. @pyqtProperty(str, notify = activeQualityGroupChanged)
  1439. def activeQualityGroupName(self) -> str:
  1440. """Get the name of the active quality group.
  1441. :return: The name of the active quality group.
  1442. """
  1443. quality_group = self.activeQualityGroup()
  1444. if quality_group is None:
  1445. return ""
  1446. return quality_group.getName()
  1447. @pyqtSlot(QObject)
  1448. def setQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup", no_dialog: bool = False) -> None:
  1449. self.blurSettings.emit()
  1450. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1451. self._setQualityChangesGroup(quality_changes_group)
  1452. # See if we need to show the Discard or Keep changes screen
  1453. if not no_dialog and self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1454. self._application.discardOrKeepProfileChanges()
  1455. @pyqtSlot()
  1456. def resetToUseDefaultQuality(self) -> None:
  1457. if self._global_container_stack is None:
  1458. return
  1459. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1460. self._setQualityGroup(self.activeQualityGroup())
  1461. for stack in [self._global_container_stack] + self._global_container_stack.extruderList:
  1462. stack.userChanges.clear()
  1463. @pyqtProperty(QObject, fset = setQualityChangesGroup, notify = activeQualityChangesGroupChanged)
  1464. def activeQualityChangesGroup(self) -> Optional["QualityChangesGroup"]:
  1465. global_stack = self._application.getGlobalContainerStack()
  1466. if global_stack is None or global_stack.qualityChanges == empty_quality_changes_container:
  1467. return None
  1468. all_group_list = ContainerTree.getInstance().getCurrentQualityChangesGroups()
  1469. the_group = None
  1470. 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.
  1471. if group.metadata_for_global and group.metadata_for_global["id"] == global_stack.qualityChanges.getId():
  1472. the_group = group
  1473. break
  1474. return the_group
  1475. @pyqtProperty(bool, notify = activeQualityChangesGroupChanged)
  1476. def hasCustomQuality(self) -> bool:
  1477. global_stack = self._application.getGlobalContainerStack()
  1478. return global_stack is None or global_stack.qualityChanges != empty_quality_changes_container
  1479. @pyqtProperty(str, notify = activeQualityGroupChanged)
  1480. def activeQualityOrQualityChangesName(self) -> str:
  1481. global_container_stack = self._application.getGlobalContainerStack()
  1482. if not global_container_stack:
  1483. return empty_quality_container.getName()
  1484. if global_container_stack.qualityChanges != empty_quality_changes_container:
  1485. return global_container_stack.qualityChanges.getName()
  1486. return global_container_stack.quality.getName()
  1487. @pyqtProperty(bool, notify = activeQualityGroupChanged)
  1488. def hasNotSupportedQuality(self) -> bool:
  1489. global_container_stack = self._application.getGlobalContainerStack()
  1490. return global_container_stack is not None\
  1491. and global_container_stack.quality == empty_quality_container \
  1492. and global_container_stack.qualityChanges == empty_quality_changes_container
  1493. @pyqtProperty(bool, notify = activeQualityGroupChanged)
  1494. def isActiveQualityCustom(self) -> bool:
  1495. global_stack = self._application.getGlobalContainerStack()
  1496. if global_stack is None:
  1497. return False
  1498. return global_stack.qualityChanges != empty_quality_changes_container
  1499. def updateUponMaterialMetadataChange(self) -> None:
  1500. if self._global_container_stack is None:
  1501. return
  1502. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1503. self.updateMaterialWithVariant(None)
  1504. self._updateQualityWithMaterial()
  1505. @pyqtSlot(str, result = str)
  1506. def getAbbreviatedMachineName(self, machine_type_name: str) -> str:
  1507. """This function will translate any printer type name to an abbreviated printer type name"""
  1508. abbr_machine = ""
  1509. for word in re.findall(r"[\w']+", machine_type_name):
  1510. if word.lower() == "ultimaker":
  1511. abbr_machine += "UM"
  1512. elif word.isdigit():
  1513. abbr_machine += word
  1514. else:
  1515. stripped_word = "".join(char for char in unicodedata.normalize("NFD", word.upper()) if unicodedata.category(char) != "Mn")
  1516. # - use only the first character if the word is too long (> 3 characters)
  1517. # - use the whole word if it's not too long (<= 3 characters)
  1518. if len(stripped_word) > 3:
  1519. stripped_word = stripped_word[0]
  1520. abbr_machine += stripped_word
  1521. return abbr_machine
  1522. @pyqtSlot(str, str, result = bool)
  1523. def intentCategoryHasQuality(self, intent_category: str, quality_type: str) -> bool:
  1524. """ Checks if there are any quality groups for active extruders that have an intent category """
  1525. quality_groups = ContainerTree.getInstance().getCurrentQualityGroups()
  1526. if quality_type in quality_groups:
  1527. quality_group = quality_groups[quality_type]
  1528. for node in quality_group.nodes_for_extruders.values():
  1529. if any(intent.intent_category == intent_category for intent in node.intents.values()):
  1530. return True
  1531. return False
  1532. @pyqtSlot(str, result = str)
  1533. def getDefaultQualityTypeForIntent(self, intent_category) -> str:
  1534. """ If there is an intent category for the default machine quality return it, otherwise return the first quality for this intent category """
  1535. machine = ContainerTree.getInstance().machines.get(self._global_container_stack.definition.getId())
  1536. if self.intentCategoryHasQuality(intent_category, machine.preferred_quality_type):
  1537. return machine.preferred_quality_type
  1538. for quality_type, quality_group in ContainerTree.getInstance().getCurrentQualityGroups().items():
  1539. for node in quality_group.nodes_for_extruders.values():
  1540. if any(intent.intent_category == intent_category for intent in node.intents.values()):
  1541. return quality_type
  1542. return ""