MachineManager.py 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629
  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.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._default_extruder_position = "0" # to be updated when extruders are switched on and off
  52. self._instance_container_timer = QTimer() # type: QTimer
  53. self._instance_container_timer.setInterval(250)
  54. self._instance_container_timer.setSingleShot(True)
  55. self._instance_container_timer.timeout.connect(self.__emitChangedSignals)
  56. self._application = application
  57. self._container_registry = self._application.getContainerRegistry()
  58. self._application.globalContainerStackChanged.connect(self._onGlobalContainerChanged)
  59. self._container_registry.containerLoadComplete.connect(self._onContainersChanged)
  60. # When the global container is changed, active material probably needs to be updated.
  61. self.globalContainerChanged.connect(self.activeMaterialChanged)
  62. self.globalContainerChanged.connect(self.activeVariantChanged)
  63. self.globalContainerChanged.connect(self.activeQualityChanged)
  64. self.globalContainerChanged.connect(self.activeQualityChangesGroupChanged)
  65. self.globalContainerChanged.connect(self.activeQualityGroupChanged)
  66. self._stacks_have_errors = None # type: Optional[bool]
  67. self._onGlobalContainerChanged()
  68. extruder_manager = self._application.getExtruderManager()
  69. extruder_manager.activeExtruderChanged.connect(self._onActiveExtruderStackChanged)
  70. self._onActiveExtruderStackChanged()
  71. extruder_manager.activeExtruderChanged.connect(self.activeMaterialChanged)
  72. extruder_manager.activeExtruderChanged.connect(self.activeVariantChanged)
  73. extruder_manager.activeExtruderChanged.connect(self.activeQualityChanged)
  74. self.globalContainerChanged.connect(self.activeStackChanged)
  75. self.globalValueChanged.connect(self.activeStackValueChanged)
  76. ExtruderManager.getInstance().activeExtruderChanged.connect(self.activeStackChanged)
  77. self.activeStackChanged.connect(self.activeStackValueChanged)
  78. self._application.getPreferences().addPreference("cura/active_machine", "")
  79. self._printer_output_devices = [] # type: List[PrinterOutputDevice]
  80. self._application.getOutputDeviceManager().outputDevicesChanged.connect(self._onOutputDevicesChanged)
  81. # There might already be some output devices by the time the signal is connected
  82. self._onOutputDevicesChanged()
  83. self._current_printer_configuration = PrinterConfigurationModel() # Indicates the current configuration setup in this printer
  84. self.activeMaterialChanged.connect(self._onCurrentConfigurationChanged)
  85. self.activeVariantChanged.connect(self._onCurrentConfigurationChanged)
  86. # Force to compute the current configuration
  87. self._onCurrentConfigurationChanged()
  88. self._application.callLater(self.setInitialActiveMachine)
  89. containers = CuraContainerRegistry.getInstance().findInstanceContainers(id = self.activeMaterialId) # type: List[InstanceContainer]
  90. if containers:
  91. containers[0].nameChanged.connect(self._onMaterialNameChanged)
  92. self.rootMaterialChanged.connect(self._onRootMaterialChanged)
  93. # Emit the printerConnectedStatusChanged when either globalContainerChanged or outputDevicesChanged are emitted
  94. self.globalContainerChanged.connect(self.printerConnectedStatusChanged)
  95. self.outputDevicesChanged.connect(self.printerConnectedStatusChanged)
  96. activeQualityGroupChanged = pyqtSignal()
  97. activeQualityChangesGroupChanged = pyqtSignal()
  98. globalContainerChanged = pyqtSignal() # Emitted whenever the global stack is changed (ie: when changing between printers, changing a global profile, but not when changing a value)
  99. activeMaterialChanged = pyqtSignal()
  100. activeVariantChanged = pyqtSignal()
  101. activeQualityChanged = pyqtSignal()
  102. activeIntentChanged = pyqtSignal()
  103. activeStackChanged = pyqtSignal() # Emitted whenever the active stack is changed (ie: when changing between extruders, changing a profile, but not when changing a value)
  104. extruderChanged = pyqtSignal()
  105. globalValueChanged = pyqtSignal() # Emitted whenever a value inside global container is changed.
  106. activeStackValueChanged = pyqtSignal() # Emitted whenever a value inside the active stack is changed.
  107. activeStackValidationChanged = pyqtSignal() # Emitted whenever a validation inside active container is changed
  108. stacksValidationChanged = pyqtSignal() # Emitted whenever a validation is changed
  109. numberExtrudersEnabledChanged = pyqtSignal() # Emitted when the number of extruders that are enabled changed
  110. blurSettings = pyqtSignal() # Emitted to force fields in the advanced sidebar to un-focus, so they update properly
  111. outputDevicesChanged = pyqtSignal()
  112. currentConfigurationChanged = pyqtSignal() # Emitted every time the current configurations of the machine changes
  113. printerConnectedStatusChanged = pyqtSignal() # Emitted every time the active machine change or the outputdevices change
  114. rootMaterialChanged = pyqtSignal()
  115. discoveredPrintersChanged = pyqtSignal()
  116. def setInitialActiveMachine(self) -> None:
  117. active_machine_id = self._application.getPreferences().getValue("cura/active_machine")
  118. if active_machine_id != "" and CuraContainerRegistry.getInstance().findContainerStacksMetadata(id = active_machine_id):
  119. # An active machine was saved, so restore it.
  120. self.setActiveMachine(active_machine_id)
  121. def _onOutputDevicesChanged(self) -> None:
  122. self._printer_output_devices = []
  123. for printer_output_device in self._application.getOutputDeviceManager().getOutputDevices():
  124. if isinstance(printer_output_device, PrinterOutputDevice):
  125. self._printer_output_devices.append(printer_output_device)
  126. self.outputDevicesChanged.emit()
  127. @pyqtProperty(QObject, notify = currentConfigurationChanged)
  128. def currentConfiguration(self) -> PrinterConfigurationModel:
  129. return self._current_printer_configuration
  130. def _onCurrentConfigurationChanged(self) -> None:
  131. if not self._global_container_stack:
  132. return
  133. # Create the configuration model with the current data in Cura
  134. self._current_printer_configuration.printerType = self._global_container_stack.definition.getName()
  135. self._current_printer_configuration.extruderConfigurations = []
  136. for extruder in self._global_container_stack.extruders.values():
  137. extruder_configuration = ExtruderConfigurationModel()
  138. # For compare just the GUID is needed at this moment
  139. mat_type = extruder.material.getMetaDataEntry("material") if extruder.material != empty_material_container else None
  140. mat_guid = extruder.material.getMetaDataEntry("GUID") if extruder.material != empty_material_container else None
  141. mat_color = extruder.material.getMetaDataEntry("color_name") if extruder.material != empty_material_container else None
  142. mat_brand = extruder.material.getMetaDataEntry("brand") if extruder.material != empty_material_container else None
  143. mat_name = extruder.material.getMetaDataEntry("name") if extruder.material != empty_material_container else None
  144. material_model = MaterialOutputModel(mat_guid, mat_type, mat_color, mat_brand, mat_name)
  145. extruder_configuration.position = int(extruder.getMetaDataEntry("position"))
  146. extruder_configuration.material = material_model
  147. extruder_configuration.hotendID = extruder.variant.getName() if extruder.variant != empty_variant_container else None
  148. self._current_printer_configuration.extruderConfigurations.append(extruder_configuration)
  149. # An empty build plate configuration from the network printer is presented as an empty string, so use "" for an
  150. # empty build plate.
  151. self._current_printer_configuration.buildplateConfiguration = self._global_container_stack.getProperty("machine_buildplate_type", "value") if self._global_container_stack.variant != empty_variant_container else ""
  152. self.currentConfigurationChanged.emit()
  153. @pyqtSlot(QObject, result = bool)
  154. def matchesConfiguration(self, configuration: PrinterConfigurationModel) -> bool:
  155. return self._current_printer_configuration == configuration
  156. @pyqtProperty("QVariantList", notify = outputDevicesChanged)
  157. def printerOutputDevices(self) -> List[PrinterOutputDevice]:
  158. return self._printer_output_devices
  159. @pyqtProperty(int, constant=True)
  160. def totalNumberOfSettings(self) -> int:
  161. general_definition_containers = CuraContainerRegistry.getInstance().findDefinitionContainers(id = "fdmprinter")
  162. if not general_definition_containers:
  163. return 0
  164. return len(general_definition_containers[0].getAllKeys())
  165. def _onGlobalContainerChanged(self) -> None:
  166. if self._global_container_stack:
  167. try:
  168. self._global_container_stack.nameChanged.disconnect(self._onMachineNameChanged)
  169. except TypeError: # pyQtSignal gives a TypeError when disconnecting from something that was already disconnected.
  170. pass
  171. try:
  172. self._global_container_stack.containersChanged.disconnect(self._onContainersChanged)
  173. except TypeError:
  174. pass
  175. try:
  176. self._global_container_stack.propertyChanged.disconnect(self._onPropertyChanged)
  177. except TypeError:
  178. pass
  179. for extruder_stack in ExtruderManager.getInstance().getActiveExtruderStacks():
  180. extruder_stack.propertyChanged.disconnect(self._onPropertyChanged)
  181. extruder_stack.containersChanged.disconnect(self._onContainersChanged)
  182. # Update the local global container stack reference
  183. self._global_container_stack = self._application.getGlobalContainerStack()
  184. if self._global_container_stack:
  185. self.updateDefaultExtruder()
  186. self.updateNumberExtrudersEnabled()
  187. self.globalContainerChanged.emit()
  188. # After switching the global stack we reconnect all the signals and set the variant and material references
  189. if self._global_container_stack:
  190. self._application.getPreferences().setValue("cura/active_machine", self._global_container_stack.getId())
  191. self._global_container_stack.nameChanged.connect(self._onMachineNameChanged)
  192. self._global_container_stack.containersChanged.connect(self._onContainersChanged)
  193. self._global_container_stack.propertyChanged.connect(self._onPropertyChanged)
  194. # Global stack can have only a variant if it is a buildplate
  195. global_variant = self._global_container_stack.variant
  196. if global_variant != empty_variant_container:
  197. if global_variant.getMetaDataEntry("hardware_type") != "buildplate":
  198. self._global_container_stack.setVariant(empty_variant_container)
  199. # Set the global material to empty as we now use the extruder stack at all times - CURA-4482
  200. global_material = self._global_container_stack.material
  201. if global_material != empty_material_container:
  202. self._global_container_stack.setMaterial(empty_material_container)
  203. # Listen for changes on all extruder stacks
  204. for extruder_stack in ExtruderManager.getInstance().getActiveExtruderStacks():
  205. extruder_stack.propertyChanged.connect(self._onPropertyChanged)
  206. extruder_stack.containersChanged.connect(self._onContainersChanged)
  207. self.activeQualityGroupChanged.emit()
  208. def _onActiveExtruderStackChanged(self) -> None:
  209. self.blurSettings.emit() # Ensure no-one has focus.
  210. self._active_container_stack = ExtruderManager.getInstance().getActiveExtruderStack()
  211. def __emitChangedSignals(self) -> None:
  212. self.activeQualityChanged.emit()
  213. self.activeVariantChanged.emit()
  214. self.activeMaterialChanged.emit()
  215. self.activeIntentChanged.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. global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  478. if not global_stack:
  479. return ""
  480. return global_stack.quality.getMetaDataEntry("quality_type")
  481. @pyqtProperty(bool, notify = activeQualityGroupChanged)
  482. def isActiveQualitySupported(self) -> bool:
  483. global_container_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  484. if not global_container_stack:
  485. return False
  486. if not self.activeQualityGroup:
  487. return False
  488. return self.activeQualityGroup.is_available
  489. @pyqtProperty(bool, notify = activeQualityGroupChanged)
  490. def isActiveQualityExperimental(self) -> bool:
  491. global_container_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  492. if not global_container_stack:
  493. return False
  494. return Util.parseBool(global_container_stack.quality.getMetaDataEntry("is_experimental", False))
  495. @pyqtProperty(str, notify=activeIntentChanged)
  496. def activeIntentCategory(self):
  497. if not self._active_container_stack:
  498. return ""
  499. intent_category = self._active_container_stack.intent.getMetaDataEntry("intent_category")
  500. return intent_category
  501. ## Returns whether there is anything unsupported in the current set-up.
  502. #
  503. # The current set-up signifies the global stack and all extruder stacks,
  504. # so this indicates whether there is any container in any of the container
  505. # stacks that is not marked as supported.
  506. @pyqtProperty(bool, notify = activeQualityChanged)
  507. def isCurrentSetupSupported(self) -> bool:
  508. if not self._global_container_stack:
  509. return False
  510. for stack in [self._global_container_stack] + list(self._global_container_stack.extruders.values()):
  511. for container in stack.getContainers():
  512. if not container:
  513. return False
  514. if not Util.parseBool(container.getMetaDataEntry("supported", True)):
  515. return False
  516. return True
  517. ## Copy the value of the setting of the current extruder to all other extruders as well as the global container.
  518. @pyqtSlot(str)
  519. def copyValueToExtruders(self, key: str) -> None:
  520. if self._active_container_stack is None or self._global_container_stack is None:
  521. return
  522. new_value = self._active_container_stack.getProperty(key, "value")
  523. extruder_stacks = [stack for stack in ExtruderManager.getInstance().getActiveExtruderStacks()]
  524. # Check in which stack the value has to be replaced
  525. for extruder_stack in extruder_stacks:
  526. if extruder_stack != self._active_container_stack and extruder_stack.getProperty(key, "value") != new_value:
  527. extruder_stack.userChanges.setProperty(key, "value", new_value) # TODO: nested property access, should be improved
  528. ## Copy the value of all manually changed settings of the current extruder to all other extruders.
  529. @pyqtSlot()
  530. def copyAllValuesToExtruders(self) -> None:
  531. if self._active_container_stack is None or self._global_container_stack is None:
  532. return
  533. extruder_stacks = list(self._global_container_stack.extruders.values())
  534. for extruder_stack in extruder_stacks:
  535. if extruder_stack != self._active_container_stack:
  536. for key in self._active_container_stack.userChanges.getAllKeys():
  537. new_value = self._active_container_stack.getProperty(key, "value")
  538. # Check if the value has to be replaced
  539. extruder_stack.userChanges.setProperty(key, "value", new_value)
  540. @pyqtProperty(str, notify = activeVariantChanged)
  541. @deprecated("use Cura.MachineManager.activeStack.variant.name instead", "4.1")
  542. def activeVariantName(self) -> str:
  543. if self._active_container_stack:
  544. variant = self._active_container_stack.variant
  545. if variant:
  546. return variant.getName()
  547. return ""
  548. @pyqtProperty(str, notify = activeVariantChanged)
  549. @deprecated("use Cura.MachineManager.activeStack.variant.id instead", "4.1")
  550. def activeVariantId(self) -> str:
  551. if self._active_container_stack:
  552. variant = self._active_container_stack.variant
  553. if variant:
  554. return variant.getId()
  555. return ""
  556. @pyqtProperty(str, notify = activeVariantChanged)
  557. @deprecated("use Cura.MachineManager.activeMachine.variant.name instead", "4.1")
  558. def activeVariantBuildplateName(self) -> str:
  559. if self._global_container_stack:
  560. variant = self._global_container_stack.variant
  561. if variant:
  562. return variant.getName()
  563. return ""
  564. @pyqtProperty(str, notify = globalContainerChanged)
  565. @deprecated("use Cura.MachineManager.activeMachine.definition.id instead", "4.1")
  566. def activeDefinitionId(self) -> str:
  567. if self._global_container_stack:
  568. return self._global_container_stack.definition.id
  569. return ""
  570. ## Get the Definition ID to use to select quality profiles for the currently active machine
  571. # \returns DefinitionID (string) if found, empty string otherwise
  572. @pyqtProperty(str, notify = globalContainerChanged)
  573. def activeQualityDefinitionId(self) -> str:
  574. global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  575. if not global_stack:
  576. return ""
  577. return ContainerTree.getInstance().machines[global_stack.definition.getId()].quality_definition
  578. ## Gets how the active definition calls variants
  579. # Caveat: per-definition-variant-title is currently not translated (though the fallback is)
  580. @pyqtProperty(str, notify = globalContainerChanged)
  581. def activeDefinitionVariantsName(self) -> str:
  582. fallback_title = catalog.i18nc("@label", "Nozzle")
  583. if self._global_container_stack:
  584. return self._global_container_stack.definition.getMetaDataEntry("variants_name", fallback_title)
  585. return fallback_title
  586. @pyqtSlot(str, str)
  587. def renameMachine(self, machine_id: str, new_name: str) -> None:
  588. container_registry = CuraContainerRegistry.getInstance()
  589. machine_stack = container_registry.findContainerStacks(id = machine_id)
  590. if machine_stack:
  591. new_name = container_registry.createUniqueName("machine", machine_stack[0].getName(), new_name, machine_stack[0].definition.getName())
  592. machine_stack[0].setName(new_name)
  593. self.globalContainerChanged.emit()
  594. @pyqtSlot(str)
  595. def removeMachine(self, machine_id: str) -> None:
  596. Logger.log("i", "Attempting to remove a machine with the id [%s]", machine_id)
  597. # If the machine that is being removed is the currently active machine, set another machine as the active machine.
  598. activate_new_machine = (self._global_container_stack and self._global_container_stack.getId() == machine_id)
  599. # Activate a new machine before removing a machine because this is safer
  600. if activate_new_machine:
  601. machine_stacks = CuraContainerRegistry.getInstance().findContainerStacksMetadata(type = "machine")
  602. other_machine_stacks = [s for s in machine_stacks if s["id"] != machine_id]
  603. if other_machine_stacks:
  604. self.setActiveMachine(other_machine_stacks[0]["id"])
  605. metadata = CuraContainerRegistry.getInstance().findContainerStacksMetadata(id = machine_id)[0]
  606. ExtruderManager.getInstance().removeMachineExtruders(machine_id)
  607. containers = CuraContainerRegistry.getInstance().findInstanceContainersMetadata(type = "user", machine = machine_id)
  608. for container in containers:
  609. CuraContainerRegistry.getInstance().removeContainer(container["id"])
  610. CuraContainerRegistry.getInstance().removeContainer(machine_id)
  611. # If the printer that is being removed is a network printer, the hidden printers have to be also removed
  612. group_id = metadata.get("group_id", None)
  613. if group_id:
  614. metadata_filter = {"group_id": group_id}
  615. hidden_containers = CuraContainerRegistry.getInstance().findContainerStacks(type = "machine", **metadata_filter)
  616. if hidden_containers:
  617. # This reuses the method and remove all printers recursively
  618. self.removeMachine(hidden_containers[0].getId())
  619. @pyqtProperty(bool, notify = globalContainerChanged)
  620. @deprecated("use Cura.MachineManager.activeMachine.hasMaterials instead", "4.2")
  621. def hasMaterials(self) -> bool:
  622. if self._global_container_stack:
  623. return self._global_container_stack.hasMaterials
  624. return False
  625. @pyqtProperty(bool, notify = globalContainerChanged)
  626. @deprecated("use Cura.MachineManager.activeMachine.hasVariants instead", "4.2")
  627. def hasVariants(self) -> bool:
  628. if self._global_container_stack:
  629. return self._global_container_stack.hasVariants
  630. return False
  631. @pyqtProperty(bool, notify = globalContainerChanged)
  632. @deprecated("use Cura.MachineManager.activeMachine.hasVariantBuildplates instead", "4.2")
  633. def hasVariantBuildplates(self) -> bool:
  634. if self._global_container_stack:
  635. return self._global_container_stack.hasVariantBuildplates
  636. return False
  637. ## The selected buildplate is compatible if it is compatible with all the materials in all the extruders
  638. @pyqtProperty(bool, notify = activeMaterialChanged)
  639. def variantBuildplateCompatible(self) -> bool:
  640. if not self._global_container_stack:
  641. return True
  642. buildplate_compatible = True # It is compatible by default
  643. extruder_stacks = self._global_container_stack.extruders.values()
  644. for stack in extruder_stacks:
  645. if not stack.isEnabled:
  646. continue
  647. material_container = stack.material
  648. if material_container == empty_material_container:
  649. continue
  650. if material_container.getMetaDataEntry("buildplate_compatible"):
  651. buildplate_compatible = buildplate_compatible and material_container.getMetaDataEntry("buildplate_compatible")[self.activeVariantBuildplateName]
  652. return buildplate_compatible
  653. ## The selected buildplate is usable if it is usable for all materials OR it is compatible for one but not compatible
  654. # for the other material but the buildplate is still usable
  655. @pyqtProperty(bool, notify = activeMaterialChanged)
  656. def variantBuildplateUsable(self) -> bool:
  657. if not self._global_container_stack:
  658. return True
  659. # Here the next formula is being calculated:
  660. # result = (not (material_left_compatible and material_right_compatible)) and
  661. # (material_left_compatible or material_left_usable) and
  662. # (material_right_compatible or material_right_usable)
  663. result = not self.variantBuildplateCompatible
  664. extruder_stacks = self._global_container_stack.extruders.values()
  665. for stack in extruder_stacks:
  666. material_container = stack.material
  667. if material_container == empty_material_container:
  668. continue
  669. buildplate_compatible = material_container.getMetaDataEntry("buildplate_compatible")[self.activeVariantBuildplateName] if material_container.getMetaDataEntry("buildplate_compatible") else True
  670. buildplate_usable = material_container.getMetaDataEntry("buildplate_recommended")[self.activeVariantBuildplateName] if material_container.getMetaDataEntry("buildplate_recommended") else True
  671. result = result and (buildplate_compatible or buildplate_usable)
  672. return result
  673. ## Get the Definition ID of a machine (specified by ID)
  674. # \param machine_id string machine id to get the definition ID of
  675. # \returns DefinitionID if found, None otherwise
  676. @pyqtSlot(str, result = str)
  677. def getDefinitionByMachineId(self, machine_id: str) -> Optional[str]:
  678. containers = CuraContainerRegistry.getInstance().findContainerStacks(id = machine_id)
  679. if containers:
  680. return containers[0].definition.getId()
  681. return None
  682. def getIncompatibleSettingsOnEnabledExtruders(self, container: InstanceContainer) -> List[str]:
  683. if self._global_container_stack is None:
  684. return []
  685. extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  686. result = [] # type: List[str]
  687. for setting_instance in container.findInstances():
  688. setting_key = setting_instance.definition.key
  689. if not self._global_container_stack.getProperty(setting_key, "type") in ("extruder", "optional_extruder"):
  690. continue
  691. old_value = container.getProperty(setting_key, "value")
  692. if isinstance(old_value, SettingFunction):
  693. old_value = old_value(self._global_container_stack)
  694. if int(old_value) < 0:
  695. continue
  696. if int(old_value) >= extruder_count or not self._global_container_stack.extruders[str(old_value)].isEnabled:
  697. result.append(setting_key)
  698. Logger.log("d", "Reset setting [%s] in [%s] because its old value [%s] is no longer valid", setting_key, container, old_value)
  699. return result
  700. ## Update extruder number to a valid value when the number of extruders are changed, or when an extruder is changed
  701. def correctExtruderSettings(self) -> None:
  702. if self._global_container_stack is None:
  703. return
  704. for setting_key in self.getIncompatibleSettingsOnEnabledExtruders(self._global_container_stack.userChanges):
  705. self._global_container_stack.userChanges.removeInstance(setting_key)
  706. add_user_changes = self.getIncompatibleSettingsOnEnabledExtruders(self._global_container_stack.qualityChanges)
  707. for setting_key in add_user_changes:
  708. # Apply quality changes that are incompatible to user changes, so we do not change the quality changes itself.
  709. self._global_container_stack.userChanges.setProperty(setting_key, "value", self._default_extruder_position)
  710. if add_user_changes:
  711. caution_message = Message(
  712. 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)),
  713. lifetime = 0,
  714. title = catalog.i18nc("@info:title", "Settings updated"))
  715. caution_message.show()
  716. ## Set the amount of extruders on the active machine (global stack)
  717. # \param extruder_count int the number of extruders to set
  718. def setActiveMachineExtruderCount(self, extruder_count: int) -> None:
  719. if self._global_container_stack is None:
  720. return
  721. extruder_manager = self._application.getExtruderManager()
  722. definition_changes_container = self._global_container_stack.definitionChanges
  723. if not self._global_container_stack or definition_changes_container == empty_definition_changes_container:
  724. return
  725. previous_extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  726. if extruder_count == previous_extruder_count:
  727. return
  728. definition_changes_container.setProperty("machine_extruder_count", "value", extruder_count)
  729. self.updateDefaultExtruder()
  730. self.updateNumberExtrudersEnabled()
  731. self.correctExtruderSettings()
  732. # Check to see if any objects are set to print with an extruder that will no longer exist
  733. root_node = self._application.getController().getScene().getRoot()
  734. for node in DepthFirstIterator(root_node):
  735. if node.getMeshData():
  736. extruder_nr = node.callDecoration("getActiveExtruderPosition")
  737. if extruder_nr is not None and int(extruder_nr) > extruder_count - 1:
  738. extruder = extruder_manager.getExtruderStack(extruder_count - 1)
  739. if extruder is not None:
  740. node.callDecoration("setActiveExtruder", extruder.getId())
  741. else:
  742. Logger.log("w", "Could not find extruder to set active.")
  743. # Make sure one of the extruder stacks is active
  744. extruder_manager.setActiveExtruderIndex(0)
  745. # Move settable_per_extruder values out of the global container
  746. # After CURA-4482 this should not be the case anymore, but we still want to support older project files.
  747. global_user_container = self._global_container_stack.userChanges
  748. for setting_instance in global_user_container.findInstances():
  749. setting_key = setting_instance.definition.key
  750. settable_per_extruder = self._global_container_stack.getProperty(setting_key, "settable_per_extruder")
  751. if settable_per_extruder:
  752. limit_to_extruder = int(self._global_container_stack.getProperty(setting_key, "limit_to_extruder"))
  753. extruder_position = max(0, limit_to_extruder)
  754. extruder_stack = self.getExtruder(extruder_position)
  755. if extruder_stack:
  756. extruder_stack.userChanges.setProperty(setting_key, "value", global_user_container.getProperty(setting_key, "value"))
  757. else:
  758. Logger.log("e", "Unable to find extruder on position %s", extruder_position)
  759. global_user_container.removeInstance(setting_key)
  760. # Signal that the global stack has changed
  761. self._application.globalContainerStackChanged.emit()
  762. self.forceUpdateAllSettings()
  763. @pyqtSlot(int, result = QObject)
  764. def getExtruder(self, position: int) -> Optional[ExtruderStack]:
  765. return self._getExtruder(position)
  766. # This is a workaround for the deprecated decorator and the pyqtSlot not playing well together.
  767. @deprecated("use Cura.MachineManager.activeMachine.extruders instead", "4.2")
  768. def _getExtruder(self, position) -> Optional[ExtruderStack]:
  769. if self._global_container_stack:
  770. return self._global_container_stack.extruders.get(str(position))
  771. return None
  772. def updateDefaultExtruder(self) -> None:
  773. if self._global_container_stack is None:
  774. return
  775. extruder_items = sorted(self._global_container_stack.extruders.items())
  776. old_position = self._default_extruder_position
  777. new_default_position = "0"
  778. for position, extruder in extruder_items:
  779. if extruder.isEnabled:
  780. new_default_position = position
  781. break
  782. if new_default_position != old_position:
  783. self._default_extruder_position = new_default_position
  784. self.extruderChanged.emit()
  785. def updateNumberExtrudersEnabled(self) -> None:
  786. if self._global_container_stack is None:
  787. return
  788. definition_changes_container = self._global_container_stack.definitionChanges
  789. machine_extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  790. extruder_count = 0
  791. for position, extruder in self._global_container_stack.extruders.items():
  792. if extruder.isEnabled and int(position) < machine_extruder_count:
  793. extruder_count += 1
  794. if self.numberExtrudersEnabled != extruder_count:
  795. definition_changes_container.setProperty("extruders_enabled_count", "value", extruder_count)
  796. self.numberExtrudersEnabledChanged.emit()
  797. @pyqtProperty(int, notify = numberExtrudersEnabledChanged)
  798. def numberExtrudersEnabled(self) -> int:
  799. if self._global_container_stack is None:
  800. return 1
  801. return self._global_container_stack.definitionChanges.getProperty("extruders_enabled_count", "value")
  802. @pyqtProperty(str, notify = extruderChanged)
  803. def defaultExtruderPosition(self) -> str:
  804. return self._default_extruder_position
  805. ## This will fire the propertiesChanged for all settings so they will be updated in the front-end
  806. @pyqtSlot()
  807. def forceUpdateAllSettings(self) -> None:
  808. if self._global_container_stack is None:
  809. return
  810. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  811. property_names = ["value", "resolve", "validationState"]
  812. for container in [self._global_container_stack] + list(self._global_container_stack.extruders.values()):
  813. for setting_key in container.getAllKeys():
  814. container.propertiesChanged.emit(setting_key, property_names)
  815. @pyqtSlot(int, bool)
  816. def setExtruderEnabled(self, position: int, enabled: bool) -> None:
  817. extruder = self.getExtruder(position)
  818. if not extruder or self._global_container_stack is None:
  819. Logger.log("w", "Could not find extruder on position %s", position)
  820. return
  821. extruder.setEnabled(enabled)
  822. self.updateDefaultExtruder()
  823. self.updateNumberExtrudersEnabled()
  824. self.correctExtruderSettings()
  825. # In case this extruder is being disabled and it's the currently selected one, switch to the default extruder
  826. if not enabled and position == ExtruderManager.getInstance().activeExtruderIndex:
  827. ExtruderManager.getInstance().setActiveExtruderIndex(int(self._default_extruder_position))
  828. # Ensure that the quality profile is compatible with current combination, or choose a compatible one if available
  829. self._updateQualityWithMaterial()
  830. self.extruderChanged.emit()
  831. # Update material compatibility color
  832. self.activeQualityGroupChanged.emit()
  833. # Update items in SettingExtruder
  834. ExtruderManager.getInstance().extrudersChanged.emit(self._global_container_stack.getId())
  835. # Make sure the front end reflects changes
  836. self.forceUpdateAllSettings()
  837. # Also trigger the build plate compatibility to update
  838. self.activeMaterialChanged.emit()
  839. def _onMachineNameChanged(self) -> None:
  840. self.globalContainerChanged.emit()
  841. def _onMaterialNameChanged(self) -> None:
  842. self.activeMaterialChanged.emit()
  843. def _getContainerChangedSignals(self) -> List[Signal]:
  844. if self._global_container_stack is None:
  845. return []
  846. stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  847. stacks.append(self._global_container_stack)
  848. return [ s.containersChanged for s in stacks ]
  849. @pyqtSlot(str, str, str)
  850. def setSettingForAllExtruders(self, setting_name: str, property_name: str, property_value: str) -> None:
  851. if self._global_container_stack is None:
  852. return
  853. for key, extruder in self._global_container_stack.extruders.items():
  854. container = extruder.userChanges
  855. container.setProperty(setting_name, property_name, property_value)
  856. ## Reset all setting properties of a setting for all extruders.
  857. # \param setting_name The ID of the setting to reset.
  858. @pyqtSlot(str)
  859. def resetSettingForAllExtruders(self, setting_name: str) -> None:
  860. if self._global_container_stack is None:
  861. return
  862. for key, extruder in self._global_container_stack.extruders.items():
  863. container = extruder.userChanges
  864. container.removeInstance(setting_name)
  865. @pyqtProperty("QVariantList", notify = globalContainerChanged)
  866. @deprecated("use Cura.MachineManager.activeMachine.extruders instead", "4.2")
  867. def currentExtruderPositions(self) -> List[str]:
  868. if self._global_container_stack is None:
  869. return []
  870. return sorted(list(self._global_container_stack.extruders.keys()))
  871. ## Update _current_root_material_id when the current root material was changed.
  872. def _onRootMaterialChanged(self) -> None:
  873. self._current_root_material_id = {}
  874. changed = False
  875. if self._global_container_stack:
  876. for position in self._global_container_stack.extruders:
  877. material_id = self._global_container_stack.extruders[position].material.getMetaDataEntry("base_file")
  878. if position not in self._current_root_material_id or material_id != self._current_root_material_id[position]:
  879. changed = True
  880. self._current_root_material_id[position] = material_id
  881. if changed:
  882. self.activeMaterialChanged.emit()
  883. @pyqtProperty("QVariant", notify = rootMaterialChanged)
  884. def currentRootMaterialId(self) -> Dict[str, str]:
  885. return self._current_root_material_id
  886. ## Return the variant names in the extruder stack(s).
  887. ## For the variant in the global stack, use activeVariantBuildplateName
  888. @pyqtProperty("QVariant", notify = activeVariantChanged)
  889. def activeVariantNames(self) -> Dict[str, str]:
  890. result = {}
  891. active_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  892. for stack in active_stacks:
  893. variant_container = stack.variant
  894. position = stack.getMetaDataEntry("position")
  895. if variant_container and variant_container != empty_variant_container:
  896. result[position] = variant_container.getName()
  897. return result
  898. # Sets all quality and quality_changes containers to empty_quality and empty_quality_changes containers
  899. # for all stacks in the currently active machine.
  900. #
  901. def _setEmptyQuality(self) -> None:
  902. if self._global_container_stack is None:
  903. return
  904. self._global_container_stack.quality = empty_quality_container
  905. self._global_container_stack.qualityChanges = empty_quality_changes_container
  906. for extruder in self._global_container_stack.extruders.values():
  907. extruder.quality = empty_quality_container
  908. extruder.qualityChanges = empty_quality_changes_container
  909. self.activeQualityGroupChanged.emit()
  910. self.activeQualityChangesGroupChanged.emit()
  911. def _setQualityGroup(self, quality_group: Optional["QualityGroup"], empty_quality_changes: bool = True) -> None:
  912. if self._global_container_stack is None:
  913. return
  914. if quality_group is None:
  915. self._setEmptyQuality()
  916. return
  917. if quality_group.node_for_global is None or quality_group.node_for_global.container is None:
  918. return
  919. for node in quality_group.nodes_for_extruders.values():
  920. if node.container is None:
  921. return
  922. # Set quality and quality_changes for the GlobalStack
  923. self._global_container_stack.quality = quality_group.node_for_global.container
  924. if empty_quality_changes:
  925. self._global_container_stack.qualityChanges = empty_quality_changes_container
  926. # Set quality and quality_changes for each ExtruderStack
  927. for position, node in quality_group.nodes_for_extruders.items():
  928. self._global_container_stack.extruders[str(position)].quality = node.container
  929. if empty_quality_changes:
  930. self._global_container_stack.extruders[str(position)].qualityChanges = empty_quality_changes_container
  931. self.activeQualityGroupChanged.emit()
  932. self.activeQualityChangesGroupChanged.emit()
  933. def _fixQualityChangesGroupToNotSupported(self, quality_changes_group: "QualityChangesGroup") -> None:
  934. metadatas = [quality_changes_group.metadata_for_global] + list(quality_changes_group.metadata_per_extruder.values())
  935. for metadata in metadatas:
  936. metadata["quality_type"] = "not_supported" # This actually changes the metadata of the container since they are stored by reference!
  937. quality_changes_group.quality_type = "not_supported"
  938. quality_changes_group.intent_category = "default"
  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": # Find the quality group that the quality changes was based on.
  947. quality_group = ContainerTree.getInstance().getCurrentQualityGroups().get(quality_type)
  948. if quality_group is None:
  949. self._fixQualityChangesGroupToNotSupported(quality_changes_group)
  950. container_registry = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry()
  951. quality_changes_container = empty_quality_changes_container
  952. quality_container = empty_quality_container # type: InstanceContainer
  953. if quality_changes_group.metadata_for_global:
  954. global_containers = container_registry.findContainers(id = quality_changes_group.metadata_for_global["id"])
  955. if global_containers:
  956. quality_changes_container = global_containers[0]
  957. if quality_changes_group.metadata_for_global:
  958. containers = container_registry.findContainers(id = quality_changes_group.metadata_for_global["id"])
  959. if containers:
  960. quality_changes_container = cast(InstanceContainer, containers[0])
  961. if quality_group is not None and quality_group.node_for_global and quality_group.node_for_global.container:
  962. quality_container = quality_group.node_for_global.container
  963. self._global_container_stack.quality = quality_container
  964. self._global_container_stack.qualityChanges = quality_changes_container
  965. for position, extruder in self._global_container_stack.extruders.items():
  966. quality_node = None
  967. if quality_group is not None:
  968. quality_node = quality_group.nodes_for_extruders.get(position)
  969. quality_changes_container = empty_quality_changes_container
  970. quality_container = empty_quality_container
  971. quality_changes_metadata = quality_changes_group.metadata_per_extruder.get(int(position))
  972. if quality_changes_metadata:
  973. containers = container_registry.findContainers(id = quality_changes_metadata["id"])
  974. if containers:
  975. quality_changes_container = cast(InstanceContainer, containers[0])
  976. if quality_node and quality_node.container:
  977. quality_container = quality_node.container
  978. extruder.quality = quality_container
  979. extruder.qualityChanges = quality_changes_container
  980. self.setIntentByCategory(quality_changes_group.intent_category)
  981. self.activeQualityGroupChanged.emit()
  982. self.activeQualityChangesGroupChanged.emit()
  983. def _setVariantNode(self, position: str, variant_node: "VariantNode") -> None:
  984. if self._global_container_stack is None:
  985. return
  986. self._global_container_stack.extruders[position].variant = variant_node.container
  987. self.activeVariantChanged.emit()
  988. def _setGlobalVariant(self, container_node: "ContainerNode") -> None:
  989. if self._global_container_stack is None:
  990. return
  991. self._global_container_stack.variant = container_node.container
  992. if not self._global_container_stack.variant:
  993. self._global_container_stack.variant = self._application.empty_variant_container
  994. def _setMaterial(self, position: str, material_node: Optional["MaterialNode"] = None) -> None:
  995. if self._global_container_stack is None:
  996. return
  997. if material_node and material_node.container:
  998. material_container = material_node.container
  999. self._global_container_stack.extruders[position].material = material_container
  1000. root_material_id = material_container.getMetaDataEntry("base_file", None)
  1001. else:
  1002. self._global_container_stack.extruders[position].material = empty_material_container
  1003. root_material_id = None
  1004. # The _current_root_material_id is used in the MaterialMenu to see which material is selected
  1005. if root_material_id != self._current_root_material_id[position]:
  1006. self._current_root_material_id[position] = root_material_id
  1007. self.rootMaterialChanged.emit()
  1008. def activeMaterialsCompatible(self) -> bool:
  1009. # Check material - variant compatibility
  1010. if self._global_container_stack is not None:
  1011. if Util.parseBool(self._global_container_stack.getMetaDataEntry("has_materials", False)):
  1012. for position, extruder in self._global_container_stack.extruders.items():
  1013. if not extruder.isEnabled:
  1014. continue
  1015. if not extruder.material.getMetaDataEntry("compatible"):
  1016. return False
  1017. return True
  1018. ## Update current quality type and machine after setting material
  1019. def _updateQualityWithMaterial(self, *args: Any) -> None:
  1020. global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  1021. if global_stack is None:
  1022. return
  1023. Logger.log("d", "Updating quality/quality_changes due to material change")
  1024. current_quality_type = global_stack.quality.getMetaDataEntry("quality_type")
  1025. candidate_quality_groups = ContainerTree.getInstance().getCurrentQualityGroups()
  1026. available_quality_types = {qt for qt, g in candidate_quality_groups.items() if g.is_available}
  1027. Logger.log("d", "Current quality type = [%s]", current_quality_type)
  1028. if not self.activeMaterialsCompatible():
  1029. if current_quality_type is not None:
  1030. Logger.log("i", "Active materials are not compatible, setting all qualities to empty (Not Supported).")
  1031. self._setEmptyQuality()
  1032. return
  1033. if not available_quality_types:
  1034. if global_stack.qualityChanges == empty_quality_changes_container:
  1035. Logger.log("i", "No available quality types found, setting all qualities to empty (Not Supported).")
  1036. self._setEmptyQuality()
  1037. return
  1038. if current_quality_type in available_quality_types:
  1039. Logger.log("i", "Current available quality type [%s] is available, applying changes.", current_quality_type)
  1040. self._setQualityGroup(candidate_quality_groups[current_quality_type], empty_quality_changes = False)
  1041. return
  1042. # The current quality type is not available so we use the preferred quality type if it's available,
  1043. # otherwise use one of the available quality types.
  1044. quality_type = sorted(list(available_quality_types))[0]
  1045. if self._global_container_stack is None:
  1046. Logger.log("e", "Global stack not present!")
  1047. return
  1048. preferred_quality_type = self._global_container_stack.getMetaDataEntry("preferred_quality_type")
  1049. if preferred_quality_type in available_quality_types:
  1050. quality_type = preferred_quality_type
  1051. Logger.log("i", "The current quality type [%s] is not available, switching to [%s] instead",
  1052. current_quality_type, quality_type)
  1053. self._setQualityGroup(candidate_quality_groups[quality_type], empty_quality_changes = True)
  1054. ## Update the material profile in the current stacks when the variant is
  1055. # changed.
  1056. # \param position The extruder stack to update. If provided with None, all
  1057. # extruder stacks will be updated.
  1058. def updateMaterialWithVariant(self, position: Optional[str]) -> None:
  1059. if self._global_container_stack is None:
  1060. return
  1061. if position is None:
  1062. position_list = list(self._global_container_stack.extruders.keys())
  1063. else:
  1064. position_list = [position]
  1065. for position_item in position_list:
  1066. extruder = self._global_container_stack.extruders[position_item]
  1067. current_material_base_name = extruder.material.getMetaDataEntry("base_file")
  1068. current_nozzle_name = None
  1069. if extruder.variant.getId() != empty_variant_container.getId():
  1070. current_nozzle_name = extruder.variant.getMetaDataEntry("name")
  1071. # If we can keep the current material after the switch, try to do so.
  1072. nozzle_node = ContainerTree.getInstance().machines[self._global_container_stack.definition.getId()].variants[current_nozzle_name]
  1073. candidate_materials = nozzle_node.materials
  1074. if current_material_base_name in candidate_materials: # The current material is also available after the switch. Retain it.
  1075. new_material = candidate_materials[current_material_base_name]
  1076. self._setMaterial(position_item, new_material)
  1077. else:
  1078. # The current material is not available, find the preferred one.
  1079. material_diameter = self._global_container_stack.extruders[position].getCompatibleMaterialDiameter()
  1080. approximate_material_diameter = round(material_diameter)
  1081. material_node = nozzle_node.preferredMaterial(approximate_material_diameter)
  1082. self._setMaterial(position_item, material_node)
  1083. ## Given a printer definition name, select the right machine instance. In case it doesn't exist, create a new
  1084. # instance with the same network key.
  1085. @pyqtSlot(str)
  1086. def switchPrinterType(self, machine_name: str) -> None:
  1087. Logger.log("i", "Attempting to switch the printer type to [%s]", machine_name)
  1088. # Don't switch if the user tries to change to the same type of printer
  1089. if self._global_container_stack is None or self.activeMachineDefinitionName == machine_name:
  1090. return
  1091. # Get the definition id corresponding to this machine name
  1092. machine_definition_id = CuraContainerRegistry.getInstance().findDefinitionContainers(name = machine_name)[0].getId()
  1093. # Try to find a machine with the same network key
  1094. metadata_filter = {"group_id": self._global_container_stack.getMetaDataEntry("group_id"),
  1095. "um_network_key": self.activeMachineNetworkKey(),
  1096. }
  1097. new_machine = self.getMachine(machine_definition_id, metadata_filter = metadata_filter)
  1098. # If there is no machine, then create a new one and set it to the non-hidden instance
  1099. if not new_machine:
  1100. new_machine = CuraStackBuilder.createMachine(machine_definition_id + "_sync", machine_definition_id)
  1101. if not new_machine:
  1102. return
  1103. new_machine.setMetaDataEntry("group_id", self._global_container_stack.getMetaDataEntry("group_id"))
  1104. new_machine.setMetaDataEntry("um_network_key", self.activeMachineNetworkKey())
  1105. new_machine.setMetaDataEntry("group_name", self.activeMachineNetworkGroupName)
  1106. new_machine.setMetaDataEntry("connection_type", self._global_container_stack.getMetaDataEntry("connection_type"))
  1107. else:
  1108. Logger.log("i", "Found a %s with the key %s. Let's use it!", machine_name, self.activeMachineNetworkKey())
  1109. # Set the current printer instance to hidden (the metadata entry must exist)
  1110. new_machine.setMetaDataEntry("hidden", False)
  1111. self._global_container_stack.setMetaDataEntry("hidden", True)
  1112. self.setActiveMachine(new_machine.getId())
  1113. @pyqtSlot(QObject)
  1114. def applyRemoteConfiguration(self, configuration: PrinterConfigurationModel) -> None:
  1115. if self._global_container_stack is None:
  1116. return
  1117. self.blurSettings.emit()
  1118. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1119. self.switchPrinterType(configuration.printerType)
  1120. disabled_used_extruder_position_set = set()
  1121. extruders_to_disable = set()
  1122. # If an extruder that's currently used to print a model gets disabled due to the syncing, we need to show
  1123. # a message explaining why.
  1124. need_to_show_message = False
  1125. for extruder_configuration in configuration.extruderConfigurations:
  1126. # We support "" or None, since the cloud uses None instead of empty strings
  1127. extruder_has_hotend = extruder_configuration.hotendID and extruder_configuration.hotendID != ""
  1128. extruder_has_material = extruder_configuration.material.guid and extruder_configuration.material.guid != ""
  1129. # If the machine doesn't have a hotend or material, disable this extruder
  1130. if not extruder_has_hotend or not extruder_has_material:
  1131. extruders_to_disable.add(extruder_configuration.position)
  1132. # If there's no material and/or nozzle on the printer, enable the first extruder and disable the rest.
  1133. if len(extruders_to_disable) == len(self._global_container_stack.extruders):
  1134. extruders_to_disable.remove(min(extruders_to_disable))
  1135. for extruder_configuration in configuration.extruderConfigurations:
  1136. position = str(extruder_configuration.position)
  1137. # If the machine doesn't have a hotend or material, disable this extruder
  1138. if int(position) in extruders_to_disable:
  1139. self._global_container_stack.extruders[position].setEnabled(False)
  1140. need_to_show_message = True
  1141. disabled_used_extruder_position_set.add(int(position))
  1142. else:
  1143. machine_node = ContainerTree.getInstance().machines.get(self._global_container_stack.definition.getId())
  1144. variant_node = machine_node.variants.get(extruder_configuration.hotendID)
  1145. if variant_node:
  1146. self._setVariantNode(position, variant_node)
  1147. else:
  1148. self._global_container_stack.extruders[position].variant = empty_variant_container
  1149. material_container_node = MaterialManager.getInstance().getMaterialNodeByType(self._global_container_stack,
  1150. position,
  1151. extruder_configuration.hotendID,
  1152. configuration.buildplateConfiguration,
  1153. extruder_configuration.material.guid)
  1154. if material_container_node:
  1155. self._setMaterial(position, material_container_node)
  1156. else:
  1157. self._global_container_stack.extruders[position].material = empty_material_container
  1158. self._global_container_stack.extruders[position].setEnabled(True)
  1159. self.updateMaterialWithVariant(position)
  1160. self.updateDefaultExtruder()
  1161. self.updateNumberExtrudersEnabled()
  1162. self._updateQualityWithMaterial()
  1163. if need_to_show_message:
  1164. msg_str = "{extruders} is disabled because there is no material loaded. Please load a material or use custom configurations."
  1165. # Show human-readable extruder names such as "Extruder Left", "Extruder Front" instead of "Extruder 1, 2, 3".
  1166. extruder_names = []
  1167. for extruder_position in sorted(disabled_used_extruder_position_set):
  1168. extruder_stack = self._global_container_stack.extruders[str(extruder_position)]
  1169. extruder_name = extruder_stack.definition.getName()
  1170. extruder_names.append(extruder_name)
  1171. extruders_str = ", ".join(extruder_names)
  1172. msg_str = msg_str.format(extruders = extruders_str)
  1173. message = Message(catalog.i18nc("@info:status", msg_str),
  1174. title = catalog.i18nc("@info:title", "Extruder(s) Disabled"))
  1175. message.show()
  1176. # See if we need to show the Discard or Keep changes screen
  1177. if self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1178. self._application.discardOrKeepProfileChanges()
  1179. @pyqtSlot("QVariant")
  1180. def setGlobalVariant(self, container_node: "ContainerNode") -> None:
  1181. self.blurSettings.emit()
  1182. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1183. self._setGlobalVariant(container_node)
  1184. self.updateMaterialWithVariant(None) # Update all materials
  1185. self._updateQualityWithMaterial()
  1186. @pyqtSlot(str, str)
  1187. def setMaterialById(self, position: str, root_material_id: str) -> None:
  1188. if self._global_container_stack is None:
  1189. return
  1190. buildplate_name = None
  1191. if self._global_container_stack.variant.getId() != "empty_variant":
  1192. buildplate_name = self._global_container_stack.variant.getName()
  1193. machine_definition_id = self._global_container_stack.definition.id
  1194. position = str(position)
  1195. extruder_stack = self._global_container_stack.extruders[position]
  1196. nozzle_name = extruder_stack.variant.getName()
  1197. material_diameter = extruder_stack.getApproximateMaterialDiameter()
  1198. material_node = MaterialManager.getInstance().getMaterialNode(machine_definition_id, nozzle_name, buildplate_name,
  1199. material_diameter, root_material_id)
  1200. self.setMaterial(position, material_node)
  1201. ## Global_stack: if you want to provide your own global_stack instead of the current active one
  1202. # if you update an active machine, special measures have to be taken.
  1203. @pyqtSlot(str, "QVariant")
  1204. def setMaterial(self, position: str, container_node, global_stack: Optional["GlobalStack"] = None) -> None:
  1205. if global_stack is not None and global_stack != self._global_container_stack:
  1206. global_stack.extruders[position].material = container_node.container
  1207. return
  1208. position = str(position)
  1209. self.blurSettings.emit()
  1210. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1211. self._setMaterial(position, container_node)
  1212. self._updateQualityWithMaterial()
  1213. # See if we need to show the Discard or Keep changes screen
  1214. if self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1215. self._application.discardOrKeepProfileChanges()
  1216. @pyqtSlot(str, str)
  1217. def setVariantByName(self, position: str, variant_name: str) -> None:
  1218. if self._global_container_stack is None:
  1219. return
  1220. machine_definition_id = self._global_container_stack.definition.id
  1221. variant_node = self._variant_manager.getVariantNode(machine_definition_id, variant_name)
  1222. self.setVariant(position, variant_node)
  1223. @pyqtSlot(str, "QVariant")
  1224. def setVariant(self, position: str, variant_node: "VariantNode") -> None:
  1225. position = str(position)
  1226. self.blurSettings.emit()
  1227. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1228. self._setVariantNode(position, variant_node)
  1229. self.updateMaterialWithVariant(position)
  1230. self._updateQualityWithMaterial()
  1231. # See if we need to show the Discard or Keep changes screen
  1232. if self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1233. self._application.discardOrKeepProfileChanges()
  1234. @pyqtSlot(str)
  1235. def setQualityGroupByQualityType(self, quality_type: str) -> None:
  1236. if self._global_container_stack is None:
  1237. return
  1238. # Get all the quality groups for this global stack and filter out by quality_type
  1239. self.setQualityGroup(ContainerTree.getInstance().getCurrentQualityGroups()[quality_type])
  1240. ## Optionally provide global_stack if you want to use your own
  1241. # The active global_stack is treated differently.
  1242. @pyqtSlot(QObject)
  1243. def setQualityGroup(self, quality_group: "QualityGroup", no_dialog: bool = False, global_stack: Optional["GlobalStack"] = None) -> None:
  1244. if global_stack is not None and global_stack != self._global_container_stack:
  1245. if quality_group is None:
  1246. Logger.log("e", "Could not set quality group because quality group is None")
  1247. return
  1248. if quality_group.node_for_global is None:
  1249. Logger.log("e", "Could not set quality group [%s] because it has no node_for_global", str(quality_group))
  1250. return
  1251. # This is not changing the quality for the active machine !!!!!!!!
  1252. global_stack.quality = quality_group.node_for_global.container
  1253. for extruder_nr, extruder_stack in global_stack.extruders.items():
  1254. quality_container = empty_quality_container
  1255. if extruder_nr in quality_group.nodes_for_extruders:
  1256. container = quality_group.nodes_for_extruders[extruder_nr].container
  1257. quality_container = container if container is not None else quality_container
  1258. extruder_stack.quality = quality_container
  1259. return
  1260. self.blurSettings.emit()
  1261. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1262. self._setQualityGroup(quality_group)
  1263. # See if we need to show the Discard or Keep changes screen
  1264. if not no_dialog and self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1265. self._application.discardOrKeepProfileChanges()
  1266. ## Change the intent category of the current printer.
  1267. #
  1268. # All extruders can change their profiles. If an intent profile is
  1269. # available with the desired intent category, that one will get chosen.
  1270. # Otherwise the intent profile will be left to the empty profile, which
  1271. # represents the "default" intent category.
  1272. # \param intent_category The intent category to change to.
  1273. def setIntentByCategory(self, intent_category: str) -> None:
  1274. global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  1275. if global_stack is None:
  1276. return
  1277. container_tree = ContainerTree.getInstance()
  1278. for extruder in global_stack.extruderList:
  1279. definition_id = global_stack.definition.getId()
  1280. variant_name = extruder.variant.getName()
  1281. material_base_file = extruder.material.getMetaDataEntry("base_file")
  1282. quality_id = extruder.quality.getId()
  1283. quality_node = container_tree.machines[definition_id].variants[variant_name].materials[material_base_file].qualities[quality_id]
  1284. for intent_node in quality_node.intents.values():
  1285. if intent_node.intent_category == intent_category: # Found an intent with the correct category.
  1286. extruder.intent = intent_node.container
  1287. break
  1288. else: # No intent had the correct category.
  1289. extruder.intent = empty_intent_container
  1290. @pyqtProperty(QObject, fset = setQualityGroup, notify = activeQualityGroupChanged)
  1291. def activeQualityGroup(self) -> Optional["QualityGroup"]:
  1292. global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  1293. if not global_stack or global_stack.quality == empty_quality_container:
  1294. return None
  1295. return ContainerTree.getInstance().getCurrentQualityGroups().get(self.activeQualityType)
  1296. @pyqtSlot(QObject)
  1297. def setQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup", no_dialog: bool = False) -> None:
  1298. self.blurSettings.emit()
  1299. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1300. self._setQualityChangesGroup(quality_changes_group)
  1301. # See if we need to show the Discard or Keep changes screen
  1302. if not no_dialog and self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1303. self._application.discardOrKeepProfileChanges()
  1304. @pyqtSlot()
  1305. def resetToUseDefaultQuality(self) -> None:
  1306. if self._global_container_stack is None:
  1307. return
  1308. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1309. self._setQualityGroup(self.activeQualityGroup)
  1310. for stack in [self._global_container_stack] + list(self._global_container_stack.extruders.values()):
  1311. stack.userChanges.clear()
  1312. @pyqtProperty(QObject, fset = setQualityChangesGroup, notify = activeQualityChangesGroupChanged)
  1313. def activeQualityChangesGroup(self) -> Optional["QualityChangesGroup"]:
  1314. global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  1315. if not global_stack or global_stack.qualityChanges == empty_quality_changes_container:
  1316. return None
  1317. candidate_groups = ContainerTree.getInstance().getCurrentQualityChangesGroups()
  1318. for group in candidate_groups: # Match on the container ID of the global stack to find the quality changes group belonging to the active configuration.
  1319. if group.node_for_global and group.node_for_global.container_id == global_stack.qualityChanges.getId():
  1320. return group
  1321. return None
  1322. @pyqtProperty(bool, notify = activeQualityChangesGroupChanged)
  1323. def hasCustomQuality(self) -> bool:
  1324. global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  1325. return global_stack is None or global_stack.qualityChanges != empty_quality_changes_container
  1326. @pyqtProperty(str, notify = activeQualityGroupChanged)
  1327. def activeQualityOrQualityChangesName(self) -> str:
  1328. global_container_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  1329. if not global_container_stack:
  1330. return empty_quality_container.getName()
  1331. if global_container_stack.qualityChanges != empty_quality_changes_container:
  1332. return global_container_stack.qualityChanges.getName()
  1333. return global_container_stack.quality.getName()
  1334. @pyqtProperty(bool, notify = activeQualityGroupChanged)
  1335. def hasNotSupportedQuality(self) -> bool:
  1336. global_container_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  1337. return (not global_container_stack is None) and global_container_stack.quality == empty_quality_container and global_container_stack.qualityChanges == empty_quality_changes_container
  1338. def _updateUponMaterialMetadataChange(self) -> None:
  1339. if self._global_container_stack is None:
  1340. return
  1341. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1342. self.updateMaterialWithVariant(None)
  1343. self._updateQualityWithMaterial()
  1344. ## This function will translate any printer type name to an abbreviated printer type name
  1345. @pyqtSlot(str, result = str)
  1346. def getAbbreviatedMachineName(self, machine_type_name: str) -> str:
  1347. abbr_machine = ""
  1348. for word in re.findall(r"[\w']+", machine_type_name):
  1349. if word.lower() == "ultimaker":
  1350. abbr_machine += "UM"
  1351. elif word.isdigit():
  1352. abbr_machine += word
  1353. else:
  1354. stripped_word = "".join(char for char in unicodedata.normalize("NFD", word.upper()) if unicodedata.category(char) != "Mn")
  1355. # - use only the first character if the word is too long (> 3 characters)
  1356. # - use the whole word if it's not too long (<= 3 characters)
  1357. if len(stripped_word) > 3:
  1358. stripped_word = stripped_word[0]
  1359. abbr_machine += stripped_word
  1360. return abbr_machine
  1361. # Gets all machines that belong to the given group_id.
  1362. def getMachinesInGroup(self, group_id: str) -> List["GlobalStack"]:
  1363. return self._container_registry.findContainerStacks(type = "machine", group_id = group_id)