MachineManager.py 91 KB

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