MachineManager.py 88 KB

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