MachineManager.py 96 KB

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