MachineManager.py 85 KB

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