MachineManager.py 85 KB

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