MachineManager.py 90 KB

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