MachineManager.py 94 KB

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