MachineManager.py 86 KB

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