MachineManager.py 91 KB

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