MachineManager.py 85 KB

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