MachineManager.py 86 KB

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