MachineManager.py 81 KB

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