MachineManager.py 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659
  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. discoveredPrintersChanged = pyqtSignal()
  124. def setInitialActiveMachine(self) -> None:
  125. active_machine_id = self._application.getPreferences().getValue("cura/active_machine")
  126. if active_machine_id != "" and CuraContainerRegistry.getInstance().findContainerStacksMetadata(id = active_machine_id):
  127. # An active machine was saved, so restore it.
  128. self.setActiveMachine(active_machine_id)
  129. def _onOutputDevicesChanged(self) -> None:
  130. self._printer_output_devices = []
  131. for printer_output_device in self._application.getOutputDeviceManager().getOutputDevices():
  132. if isinstance(printer_output_device, PrinterOutputDevice):
  133. self._printer_output_devices.append(printer_output_device)
  134. self.outputDevicesChanged.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)
  312. @pyqtSlot(str, str)
  313. def addMachine(self, definition_id: str, name: Optional[str] = None) -> None:
  314. if name is None:
  315. definitions = CuraContainerRegistry.getInstance().findDefinitionContainers(id = definition_id)
  316. if definitions:
  317. name = definitions[0].getName()
  318. else:
  319. name = definition_id
  320. new_stack = CuraStackBuilder.createMachine(cast(str, name), definition_id)
  321. if new_stack:
  322. # Instead of setting the global container stack here, we set the active machine and so the signals are emitted
  323. self.setActiveMachine(new_stack.getId())
  324. else:
  325. Logger.log("w", "Failed creating a new machine!")
  326. def _checkStacksHaveErrors(self) -> bool:
  327. time_start = time.time()
  328. if self._global_container_stack is None: #No active machine.
  329. return False
  330. if self._global_container_stack.hasErrors():
  331. Logger.log("d", "Checking global stack for errors took %0.2f s and we found an error" % (time.time() - time_start))
  332. return True
  333. # Not a very pretty solution, but the extruder manager doesn't really know how many extruders there are
  334. machine_extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  335. extruder_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  336. count = 1 # We start with the global stack
  337. for stack in extruder_stacks:
  338. md = stack.getMetaData()
  339. if "position" in md and int(md["position"]) >= machine_extruder_count:
  340. continue
  341. count += 1
  342. if stack.hasErrors():
  343. 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)))
  344. return True
  345. Logger.log("d", "Checking %s stacks for errors took %.2f s" % (count, time.time() - time_start))
  346. return False
  347. ## Check if the global_container has instances in the user container
  348. @pyqtProperty(bool, notify = activeStackValueChanged)
  349. def hasUserSettings(self) -> bool:
  350. if not self._global_container_stack:
  351. return False
  352. if self._global_container_stack.getTop().getNumInstances() != 0:
  353. return True
  354. stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  355. for stack in stacks:
  356. if stack.getTop().getNumInstances() != 0:
  357. return True
  358. return False
  359. @pyqtProperty(int, notify = activeStackValueChanged)
  360. def numUserSettings(self) -> int:
  361. if not self._global_container_stack:
  362. return 0
  363. num_user_settings = 0
  364. num_user_settings += self._global_container_stack.getTop().getNumInstances()
  365. stacks = self._global_container_stack.extruderList
  366. for stack in stacks:
  367. num_user_settings += stack.getTop().getNumInstances()
  368. return num_user_settings
  369. ## Delete a user setting from the global stack and all extruder stacks.
  370. # \param key \type{str} the name of the key to delete
  371. @pyqtSlot(str)
  372. def clearUserSettingAllCurrentStacks(self, key: str) -> None:
  373. if not self._global_container_stack:
  374. return
  375. send_emits_containers = []
  376. top_container = self._global_container_stack.getTop()
  377. top_container.removeInstance(key, postpone_emit=True)
  378. send_emits_containers.append(top_container)
  379. linked = not self._global_container_stack.getProperty(key, "settable_per_extruder") or \
  380. self._global_container_stack.getProperty(key, "limit_to_extruder") != "-1"
  381. if not linked:
  382. stack = ExtruderManager.getInstance().getActiveExtruderStack()
  383. stacks = [stack]
  384. else:
  385. stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  386. for stack in stacks:
  387. if stack is not None:
  388. container = stack.getTop()
  389. container.removeInstance(key, postpone_emit=True)
  390. send_emits_containers.append(container)
  391. for container in send_emits_containers:
  392. container.sendPostponedEmits()
  393. ## Check if none of the stacks contain error states
  394. # Note that the _stacks_have_errors is cached due to performance issues
  395. # Calling _checkStack(s)ForErrors on every change is simply too expensive
  396. @pyqtProperty(bool, notify = stacksValidationChanged)
  397. def stacksHaveErrors(self) -> bool:
  398. return bool(self._stacks_have_errors)
  399. @pyqtProperty(str, notify = globalContainerChanged)
  400. def activeMachineDefinitionName(self) -> str:
  401. if self._global_container_stack:
  402. return self._global_container_stack.definition.getName()
  403. return ""
  404. @pyqtProperty(str, notify = globalContainerChanged)
  405. def activeMachineName(self) -> str:
  406. if self._global_container_stack:
  407. return self._global_container_stack.getMetaDataEntry("group_name", self._global_container_stack.getName())
  408. return ""
  409. @pyqtProperty(str, notify = globalContainerChanged)
  410. def activeMachineId(self) -> str:
  411. if self._global_container_stack:
  412. return self._global_container_stack.getId()
  413. return ""
  414. @pyqtProperty(str, notify = globalContainerChanged)
  415. def activeMachineFirmwareVersion(self) -> str:
  416. if not self._printer_output_devices:
  417. return ""
  418. return self._printer_output_devices[0].firmwareVersion
  419. @pyqtProperty(str, notify = globalContainerChanged)
  420. def activeMachineAddress(self) -> str:
  421. if not self._printer_output_devices:
  422. return ""
  423. return self._printer_output_devices[0].address
  424. @pyqtProperty(bool, notify = printerConnectedStatusChanged)
  425. def printerConnected(self) -> bool:
  426. return bool(self._printer_output_devices)
  427. @pyqtProperty(bool, notify = printerConnectedStatusChanged)
  428. def activeMachineHasRemoteConnection(self) -> bool:
  429. if self._global_container_stack:
  430. has_remote_connection = False
  431. for connection_type in self._global_container_stack.configuredConnectionTypes:
  432. has_remote_connection |= connection_type in [ConnectionType.NetworkConnection.value,
  433. ConnectionType.CloudConnection.value]
  434. return has_remote_connection
  435. return False
  436. @pyqtProperty("QVariantList", notify=globalContainerChanged)
  437. def activeMachineConfiguredConnectionTypes(self):
  438. if self._global_container_stack:
  439. return self._global_container_stack.configuredConnectionTypes
  440. return []
  441. @pyqtProperty(bool, notify = printerConnectedStatusChanged)
  442. def activeMachineIsGroup(self) -> bool:
  443. return bool(self._printer_output_devices) and len(self._printer_output_devices[0].printers) > 1
  444. @pyqtProperty(bool, notify = printerConnectedStatusChanged)
  445. def activeMachineHasNetworkConnection(self) -> bool:
  446. # A network connection is only available if any output device is actually a network connected device.
  447. return any(d.connectionType == ConnectionType.NetworkConnection for d in self._printer_output_devices)
  448. @pyqtProperty(bool, notify = printerConnectedStatusChanged)
  449. def activeMachineHasCloudConnection(self) -> bool:
  450. # A cloud connection is only available if any output device actually is a cloud connected device.
  451. return any(d.connectionType == ConnectionType.CloudConnection for d in self._printer_output_devices)
  452. @pyqtProperty(bool, notify = printerConnectedStatusChanged)
  453. def activeMachineIsUsingCloudConnection(self) -> bool:
  454. return self.activeMachineHasCloudConnection and not self.activeMachineHasNetworkConnection
  455. def activeMachineNetworkKey(self) -> str:
  456. if self._global_container_stack:
  457. return self._global_container_stack.getMetaDataEntry("um_network_key", "")
  458. return ""
  459. @pyqtProperty(str, notify = printerConnectedStatusChanged)
  460. def activeMachineNetworkGroupName(self) -> str:
  461. if self._global_container_stack:
  462. return self._global_container_stack.getMetaDataEntry("group_name", "")
  463. return ""
  464. @pyqtProperty(QObject, notify = globalContainerChanged)
  465. def activeMachine(self) -> Optional["GlobalStack"]:
  466. return self._global_container_stack
  467. @pyqtProperty(str, notify = activeStackChanged)
  468. def activeStackId(self) -> str:
  469. if self._active_container_stack:
  470. return self._active_container_stack.getId()
  471. return ""
  472. @pyqtProperty(QObject, notify = activeStackChanged)
  473. def activeStack(self) -> Optional["ExtruderStack"]:
  474. return self._active_container_stack
  475. @pyqtProperty(str, notify=activeMaterialChanged)
  476. def activeMaterialId(self) -> str:
  477. if self._active_container_stack:
  478. material = self._active_container_stack.material
  479. if material:
  480. return material.getId()
  481. return ""
  482. ## Gets a dict with the active materials ids set in all extruder stacks and the global stack
  483. # (when there is one extruder, the material is set in the global stack)
  484. #
  485. # \return The material ids in all stacks
  486. @pyqtProperty("QVariantMap", notify = activeMaterialChanged)
  487. def allActiveMaterialIds(self) -> Dict[str, str]:
  488. result = {}
  489. active_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  490. for stack in active_stacks:
  491. material_container = stack.material
  492. if not material_container:
  493. continue
  494. result[stack.getId()] = material_container.getId()
  495. return result
  496. ## Gets the layer height of the currently active quality profile.
  497. #
  498. # This is indicated together with the name of the active quality profile.
  499. #
  500. # \return The layer height of the currently active quality profile. If
  501. # there is no quality profile, this returns 0.
  502. @pyqtProperty(float, notify = activeQualityGroupChanged)
  503. def activeQualityLayerHeight(self) -> float:
  504. if not self._global_container_stack:
  505. return 0
  506. if self._current_quality_changes_group:
  507. value = self._global_container_stack.getRawProperty("layer_height", "value", skip_until_container = self._global_container_stack.qualityChanges.getId())
  508. if isinstance(value, SettingFunction):
  509. value = value(self._global_container_stack)
  510. return value
  511. elif self._current_quality_group:
  512. value = self._global_container_stack.getRawProperty("layer_height", "value", skip_until_container = self._global_container_stack.quality.getId())
  513. if isinstance(value, SettingFunction):
  514. value = value(self._global_container_stack)
  515. return value
  516. return 0
  517. @pyqtProperty(str, notify = activeVariantChanged)
  518. def globalVariantName(self) -> str:
  519. if self._global_container_stack:
  520. variant = self._global_container_stack.variant
  521. if variant and not isinstance(variant, type(empty_variant_container)):
  522. return variant.getName()
  523. return ""
  524. @pyqtProperty(str, notify = activeQualityGroupChanged)
  525. def activeQualityType(self) -> str:
  526. quality_type = ""
  527. if self._active_container_stack:
  528. if self._current_quality_group:
  529. quality_type = self._current_quality_group.quality_type
  530. return quality_type
  531. @pyqtProperty(bool, notify = activeQualityGroupChanged)
  532. def isActiveQualitySupported(self) -> bool:
  533. is_supported = False
  534. if self._global_container_stack:
  535. if self._current_quality_group:
  536. is_supported = self._current_quality_group.is_available
  537. return is_supported
  538. @pyqtProperty(bool, notify = activeQualityGroupChanged)
  539. def isActiveQualityExperimental(self) -> bool:
  540. is_experimental = False
  541. if self._global_container_stack:
  542. if self._current_quality_group:
  543. is_experimental = self._current_quality_group.is_experimental
  544. return is_experimental
  545. ## Returns whether there is anything unsupported in the current set-up.
  546. #
  547. # The current set-up signifies the global stack and all extruder stacks,
  548. # so this indicates whether there is any container in any of the container
  549. # stacks that is not marked as supported.
  550. @pyqtProperty(bool, notify = activeQualityChanged)
  551. def isCurrentSetupSupported(self) -> bool:
  552. if not self._global_container_stack:
  553. return False
  554. for stack in [self._global_container_stack] + list(self._global_container_stack.extruders.values()):
  555. for container in stack.getContainers():
  556. if not container:
  557. return False
  558. if not Util.parseBool(container.getMetaDataEntry("supported", True)):
  559. return False
  560. return True
  561. ## Check if a container is read_only
  562. @pyqtSlot(str, result = bool)
  563. def isReadOnly(self, container_id: str) -> bool:
  564. return CuraContainerRegistry.getInstance().isReadOnly(container_id)
  565. ## Copy the value of the setting of the current extruder to all other extruders as well as the global container.
  566. @pyqtSlot(str)
  567. def copyValueToExtruders(self, key: str) -> None:
  568. if self._active_container_stack is None or self._global_container_stack is None:
  569. return
  570. new_value = self._active_container_stack.getProperty(key, "value")
  571. extruder_stacks = [stack for stack in ExtruderManager.getInstance().getActiveExtruderStacks()]
  572. # Check in which stack the value has to be replaced
  573. for extruder_stack in extruder_stacks:
  574. if extruder_stack != self._active_container_stack and extruder_stack.getProperty(key, "value") != new_value:
  575. extruder_stack.userChanges.setProperty(key, "value", new_value) # TODO: nested property access, should be improved
  576. ## Copy the value of all manually changed settings of the current extruder to all other extruders.
  577. @pyqtSlot()
  578. def copyAllValuesToExtruders(self) -> None:
  579. if self._active_container_stack is None or self._global_container_stack is None:
  580. return
  581. extruder_stacks = list(self._global_container_stack.extruders.values())
  582. for extruder_stack in extruder_stacks:
  583. if extruder_stack != self._active_container_stack:
  584. for key in self._active_container_stack.userChanges.getAllKeys():
  585. new_value = self._active_container_stack.getProperty(key, "value")
  586. # Check if the value has to be replaced
  587. extruder_stack.userChanges.setProperty(key, "value", new_value)
  588. @pyqtProperty(str, notify = activeVariantChanged)
  589. def activeVariantName(self) -> str:
  590. if self._active_container_stack:
  591. variant = self._active_container_stack.variant
  592. if variant:
  593. return variant.getName()
  594. return ""
  595. @pyqtProperty(str, notify = activeVariantChanged)
  596. def activeVariantId(self) -> str:
  597. if self._active_container_stack:
  598. variant = self._active_container_stack.variant
  599. if variant:
  600. return variant.getId()
  601. return ""
  602. @pyqtProperty(str, notify = activeVariantChanged)
  603. def activeVariantBuildplateName(self) -> str:
  604. if self._global_container_stack:
  605. variant = self._global_container_stack.variant
  606. if variant:
  607. return variant.getName()
  608. return ""
  609. @pyqtProperty(str, notify = globalContainerChanged)
  610. def activeDefinitionId(self) -> str:
  611. if self._global_container_stack:
  612. return self._global_container_stack.definition.id
  613. return ""
  614. ## Get the Definition ID to use to select quality profiles for the currently active machine
  615. # \returns DefinitionID (string) if found, empty string otherwise
  616. @pyqtProperty(str, notify = globalContainerChanged)
  617. def activeQualityDefinitionId(self) -> str:
  618. if self._global_container_stack:
  619. return getMachineDefinitionIDForQualitySearch(self._global_container_stack.definition)
  620. return ""
  621. ## Gets how the active definition calls variants
  622. # Caveat: per-definition-variant-title is currently not translated (though the fallback is)
  623. @pyqtProperty(str, notify = globalContainerChanged)
  624. def activeDefinitionVariantsName(self) -> str:
  625. fallback_title = catalog.i18nc("@label", "Nozzle")
  626. if self._global_container_stack:
  627. return self._global_container_stack.definition.getMetaDataEntry("variants_name", fallback_title)
  628. return fallback_title
  629. @pyqtSlot(str, str)
  630. def renameMachine(self, machine_id: str, new_name: str) -> None:
  631. container_registry = CuraContainerRegistry.getInstance()
  632. machine_stack = container_registry.findContainerStacks(id = machine_id)
  633. if machine_stack:
  634. new_name = container_registry.createUniqueName("machine", machine_stack[0].getName(), new_name, machine_stack[0].definition.getName())
  635. machine_stack[0].setName(new_name)
  636. self.globalContainerChanged.emit()
  637. @pyqtSlot(str)
  638. def removeMachine(self, machine_id: str) -> None:
  639. # If the machine that is being removed is the currently active machine, set another machine as the active machine.
  640. activate_new_machine = (self._global_container_stack and self._global_container_stack.getId() == machine_id)
  641. # Activate a new machine before removing a machine because this is safer
  642. if activate_new_machine:
  643. machine_stacks = CuraContainerRegistry.getInstance().findContainerStacksMetadata(type = "machine")
  644. other_machine_stacks = [s for s in machine_stacks if s["id"] != machine_id]
  645. if other_machine_stacks:
  646. self.setActiveMachine(other_machine_stacks[0]["id"])
  647. metadata = CuraContainerRegistry.getInstance().findContainerStacksMetadata(id = machine_id)[0]
  648. network_key = metadata.get("um_network_key", None)
  649. ExtruderManager.getInstance().removeMachineExtruders(machine_id)
  650. containers = CuraContainerRegistry.getInstance().findInstanceContainersMetadata(type = "user", machine = machine_id)
  651. for container in containers:
  652. CuraContainerRegistry.getInstance().removeContainer(container["id"])
  653. CuraContainerRegistry.getInstance().removeContainer(machine_id)
  654. # If the printer that is being removed is a network printer, the hidden printers have to be also removed
  655. if network_key:
  656. metadata_filter = {"um_network_key": network_key}
  657. hidden_containers = CuraContainerRegistry.getInstance().findContainerStacks(type = "machine", **metadata_filter)
  658. if hidden_containers:
  659. # This reuses the method and remove all printers recursively
  660. self.removeMachine(hidden_containers[0].getId())
  661. @pyqtProperty(bool, notify = globalContainerChanged)
  662. def hasMaterials(self) -> bool:
  663. if self._global_container_stack:
  664. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_materials", False))
  665. return False
  666. @pyqtProperty(bool, notify = globalContainerChanged)
  667. def hasVariants(self) -> bool:
  668. if self._global_container_stack:
  669. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_variants", False))
  670. return False
  671. @pyqtProperty(bool, notify = globalContainerChanged)
  672. def hasVariantBuildplates(self) -> bool:
  673. if self._global_container_stack:
  674. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_variant_buildplates", False))
  675. return False
  676. ## The selected buildplate is compatible if it is compatible with all the materials in all the extruders
  677. @pyqtProperty(bool, notify = activeMaterialChanged)
  678. def variantBuildplateCompatible(self) -> bool:
  679. if not self._global_container_stack:
  680. return True
  681. buildplate_compatible = True # It is compatible by default
  682. extruder_stacks = self._global_container_stack.extruders.values()
  683. for stack in extruder_stacks:
  684. if not stack.isEnabled:
  685. continue
  686. material_container = stack.material
  687. if material_container == empty_material_container:
  688. continue
  689. if material_container.getMetaDataEntry("buildplate_compatible"):
  690. buildplate_compatible = buildplate_compatible and material_container.getMetaDataEntry("buildplate_compatible")[self.activeVariantBuildplateName]
  691. return buildplate_compatible
  692. ## The selected buildplate is usable if it is usable for all materials OR it is compatible for one but not compatible
  693. # for the other material but the buildplate is still usable
  694. @pyqtProperty(bool, notify = activeMaterialChanged)
  695. def variantBuildplateUsable(self) -> bool:
  696. if not self._global_container_stack:
  697. return True
  698. # Here the next formula is being calculated:
  699. # result = (not (material_left_compatible and material_right_compatible)) and
  700. # (material_left_compatible or material_left_usable) and
  701. # (material_right_compatible or material_right_usable)
  702. result = not self.variantBuildplateCompatible
  703. extruder_stacks = self._global_container_stack.extruders.values()
  704. for stack in extruder_stacks:
  705. material_container = stack.material
  706. if material_container == empty_material_container:
  707. continue
  708. buildplate_compatible = material_container.getMetaDataEntry("buildplate_compatible")[self.activeVariantBuildplateName] if material_container.getMetaDataEntry("buildplate_compatible") else True
  709. buildplate_usable = material_container.getMetaDataEntry("buildplate_recommended")[self.activeVariantBuildplateName] if material_container.getMetaDataEntry("buildplate_recommended") else True
  710. result = result and (buildplate_compatible or buildplate_usable)
  711. return result
  712. ## Get the Definition ID of a machine (specified by ID)
  713. # \param machine_id string machine id to get the definition ID of
  714. # \returns DefinitionID if found, None otherwise
  715. @pyqtSlot(str, result = str)
  716. def getDefinitionByMachineId(self, machine_id: str) -> Optional[str]:
  717. containers = CuraContainerRegistry.getInstance().findContainerStacks(id = machine_id)
  718. if containers:
  719. return containers[0].definition.getId()
  720. return None
  721. def getIncompatibleSettingsOnEnabledExtruders(self, container: InstanceContainer) -> List[str]:
  722. if self._global_container_stack is None:
  723. return []
  724. extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  725. result = [] # type: List[str]
  726. for setting_instance in container.findInstances():
  727. setting_key = setting_instance.definition.key
  728. setting_enabled = self._global_container_stack.getProperty(setting_key, "enabled")
  729. if not setting_enabled:
  730. # A setting is not visible anymore
  731. result.append(setting_key)
  732. Logger.log("d", "Reset setting [%s] from [%s] because the setting is no longer enabled", setting_key, container)
  733. continue
  734. if not self._global_container_stack.getProperty(setting_key, "type") in ("extruder", "optional_extruder"):
  735. continue
  736. old_value = container.getProperty(setting_key, "value")
  737. if int(old_value) < 0:
  738. continue
  739. if int(old_value) >= extruder_count or not self._global_container_stack.extruders[str(old_value)].isEnabled:
  740. result.append(setting_key)
  741. Logger.log("d", "Reset setting [%s] in [%s] because its old value [%s] is no longer valid", setting_key, container, old_value)
  742. return result
  743. ## Update extruder number to a valid value when the number of extruders are changed, or when an extruder is changed
  744. def correctExtruderSettings(self) -> None:
  745. if self._global_container_stack is None:
  746. return
  747. for setting_key in self.getIncompatibleSettingsOnEnabledExtruders(self._global_container_stack.userChanges):
  748. self._global_container_stack.userChanges.removeInstance(setting_key)
  749. add_user_changes = self.getIncompatibleSettingsOnEnabledExtruders(self._global_container_stack.qualityChanges)
  750. for setting_key in add_user_changes:
  751. # Apply quality changes that are incompatible to user changes, so we do not change the quality changes itself.
  752. self._global_container_stack.userChanges.setProperty(setting_key, "value", self._default_extruder_position)
  753. if add_user_changes:
  754. caution_message = Message(catalog.i18nc(
  755. "@info:generic",
  756. "Settings have been changed to match the current availability of extruders: [%s]" % ", ".join(add_user_changes)),
  757. lifetime = 0,
  758. title = catalog.i18nc("@info:title", "Settings updated"))
  759. caution_message.show()
  760. ## Set the amount of extruders on the active machine (global stack)
  761. # \param extruder_count int the number of extruders to set
  762. def setActiveMachineExtruderCount(self, extruder_count: int) -> None:
  763. if self._global_container_stack is None:
  764. return
  765. extruder_manager = self._application.getExtruderManager()
  766. definition_changes_container = self._global_container_stack.definitionChanges
  767. if not self._global_container_stack or definition_changes_container == empty_definition_changes_container:
  768. return
  769. previous_extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  770. if extruder_count == previous_extruder_count:
  771. return
  772. definition_changes_container.setProperty("machine_extruder_count", "value", extruder_count)
  773. self.updateDefaultExtruder()
  774. self.updateNumberExtrudersEnabled()
  775. self.correctExtruderSettings()
  776. # Check to see if any objects are set to print with an extruder that will no longer exist
  777. root_node = self._application.getController().getScene().getRoot()
  778. for node in DepthFirstIterator(root_node): #type: ignore #Ignore type error because iter() should get called automatically by Python syntax.
  779. if node.getMeshData():
  780. extruder_nr = node.callDecoration("getActiveExtruderPosition")
  781. if extruder_nr is not None and int(extruder_nr) > extruder_count - 1:
  782. extruder = extruder_manager.getExtruderStack(extruder_count - 1)
  783. if extruder is not None:
  784. node.callDecoration("setActiveExtruder", extruder.getId())
  785. else:
  786. Logger.log("w", "Could not find extruder to set active.")
  787. # Make sure one of the extruder stacks is active
  788. extruder_manager.setActiveExtruderIndex(0)
  789. # Move settable_per_extruder values out of the global container
  790. # After CURA-4482 this should not be the case anymore, but we still want to support older project files.
  791. global_user_container = self._global_container_stack.userChanges
  792. for setting_instance in global_user_container.findInstances():
  793. setting_key = setting_instance.definition.key
  794. settable_per_extruder = self._global_container_stack.getProperty(setting_key, "settable_per_extruder")
  795. if settable_per_extruder:
  796. limit_to_extruder = int(self._global_container_stack.getProperty(setting_key, "limit_to_extruder"))
  797. extruder_position = max(0, limit_to_extruder)
  798. extruder_stack = self.getExtruder(extruder_position)
  799. if extruder_stack:
  800. extruder_stack.userChanges.setProperty(setting_key, "value", global_user_container.getProperty(setting_key, "value"))
  801. else:
  802. Logger.log("e", "Unable to find extruder on position %s", extruder_position)
  803. global_user_container.removeInstance(setting_key)
  804. # Signal that the global stack has changed
  805. self._application.globalContainerStackChanged.emit()
  806. self.forceUpdateAllSettings()
  807. @pyqtSlot(int, result = QObject)
  808. def getExtruder(self, position: int) -> Optional[ExtruderStack]:
  809. if self._global_container_stack:
  810. return self._global_container_stack.extruders.get(str(position))
  811. return None
  812. def updateDefaultExtruder(self) -> None:
  813. if self._global_container_stack is None:
  814. return
  815. extruder_items = sorted(self._global_container_stack.extruders.items())
  816. old_position = self._default_extruder_position
  817. new_default_position = "0"
  818. for position, extruder in extruder_items:
  819. if extruder.isEnabled:
  820. new_default_position = position
  821. break
  822. if new_default_position != old_position:
  823. self._default_extruder_position = new_default_position
  824. self.extruderChanged.emit()
  825. def updateNumberExtrudersEnabled(self) -> None:
  826. if self._global_container_stack is None:
  827. return
  828. definition_changes_container = self._global_container_stack.definitionChanges
  829. machine_extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  830. extruder_count = 0
  831. for position, extruder in self._global_container_stack.extruders.items():
  832. if extruder.isEnabled and int(position) < machine_extruder_count:
  833. extruder_count += 1
  834. if self.numberExtrudersEnabled != extruder_count:
  835. definition_changes_container.setProperty("extruders_enabled_count", "value", extruder_count)
  836. self.numberExtrudersEnabledChanged.emit()
  837. @pyqtProperty(int, notify = numberExtrudersEnabledChanged)
  838. def numberExtrudersEnabled(self) -> int:
  839. if self._global_container_stack is None:
  840. return 1
  841. return self._global_container_stack.definitionChanges.getProperty("extruders_enabled_count", "value")
  842. @pyqtProperty(str, notify = extruderChanged)
  843. def defaultExtruderPosition(self) -> str:
  844. return self._default_extruder_position
  845. ## This will fire the propertiesChanged for all settings so they will be updated in the front-end
  846. @pyqtSlot()
  847. def forceUpdateAllSettings(self) -> None:
  848. if self._global_container_stack is None:
  849. return
  850. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  851. property_names = ["value", "resolve", "validationState"]
  852. for container in [self._global_container_stack] + list(self._global_container_stack.extruders.values()):
  853. for setting_key in container.getAllKeys():
  854. container.propertiesChanged.emit(setting_key, property_names)
  855. @pyqtSlot(int, bool)
  856. def setExtruderEnabled(self, position: int, enabled: bool) -> None:
  857. extruder = self.getExtruder(position)
  858. if not extruder or self._global_container_stack is None:
  859. Logger.log("w", "Could not find extruder on position %s", position)
  860. return
  861. extruder.setEnabled(enabled)
  862. self.updateDefaultExtruder()
  863. self.updateNumberExtrudersEnabled()
  864. self.correctExtruderSettings()
  865. # In case this extruder is being disabled and it's the currently selected one, switch to the default extruder
  866. if not enabled and position == ExtruderManager.getInstance().activeExtruderIndex:
  867. ExtruderManager.getInstance().setActiveExtruderIndex(int(self._default_extruder_position))
  868. # Ensure that the quality profile is compatible with current combination, or choose a compatible one if available
  869. self._updateQualityWithMaterial()
  870. self.extruderChanged.emit()
  871. # Update material compatibility color
  872. self.activeQualityGroupChanged.emit()
  873. # Update items in SettingExtruder
  874. ExtruderManager.getInstance().extrudersChanged.emit(self._global_container_stack.getId())
  875. # Make sure the front end reflects changes
  876. self.forceUpdateAllSettings()
  877. # Also trigger the build plate compatibility to update
  878. self.activeMaterialChanged.emit()
  879. def _onMachineNameChanged(self) -> None:
  880. self.globalContainerChanged.emit()
  881. def _onMaterialNameChanged(self) -> None:
  882. self.activeMaterialChanged.emit()
  883. def _onQualityNameChanged(self) -> None:
  884. self.activeQualityChanged.emit()
  885. def _getContainerChangedSignals(self) -> List[Signal]:
  886. if self._global_container_stack is None:
  887. return []
  888. stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  889. stacks.append(self._global_container_stack)
  890. return [ s.containersChanged for s in stacks ]
  891. @pyqtSlot(str, str, str)
  892. def setSettingForAllExtruders(self, setting_name: str, property_name: str, property_value: str) -> None:
  893. if self._global_container_stack is None:
  894. return
  895. for key, extruder in self._global_container_stack.extruders.items():
  896. container = extruder.userChanges
  897. container.setProperty(setting_name, property_name, property_value)
  898. ## Reset all setting properties of a setting for all extruders.
  899. # \param setting_name The ID of the setting to reset.
  900. @pyqtSlot(str)
  901. def resetSettingForAllExtruders(self, setting_name: str) -> None:
  902. if self._global_container_stack is None:
  903. return
  904. for key, extruder in self._global_container_stack.extruders.items():
  905. container = extruder.userChanges
  906. container.removeInstance(setting_name)
  907. @pyqtProperty("QVariantList", notify = globalContainerChanged)
  908. def currentExtruderPositions(self) -> List[str]:
  909. if self._global_container_stack is None:
  910. return []
  911. return sorted(list(self._global_container_stack.extruders.keys()))
  912. ## Update _current_root_material_id when the current root material was changed.
  913. def _onRootMaterialChanged(self) -> None:
  914. self._current_root_material_id = {}
  915. if self._global_container_stack:
  916. for position in self._global_container_stack.extruders:
  917. self._current_root_material_id[position] = self._global_container_stack.extruders[position].material.getMetaDataEntry("base_file")
  918. @pyqtProperty("QVariant", notify = rootMaterialChanged)
  919. def currentRootMaterialId(self) -> Dict[str, str]:
  920. return self._current_root_material_id
  921. ## Return the variant names in the extruder stack(s).
  922. ## For the variant in the global stack, use activeVariantBuildplateName
  923. @pyqtProperty("QVariant", notify = activeVariantChanged)
  924. def activeVariantNames(self) -> Dict[str, str]:
  925. result = {}
  926. active_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  927. for stack in active_stacks:
  928. variant_container = stack.variant
  929. position = stack.getMetaDataEntry("position")
  930. if variant_container and variant_container != empty_variant_container:
  931. result[position] = variant_container.getName()
  932. return result
  933. # Sets all quality and quality_changes containers to empty_quality and empty_quality_changes containers
  934. # for all stacks in the currently active machine.
  935. #
  936. def _setEmptyQuality(self) -> None:
  937. if self._global_container_stack is None:
  938. return
  939. self._current_quality_group = None
  940. self._current_quality_changes_group = None
  941. self._global_container_stack.quality = empty_quality_container
  942. self._global_container_stack.qualityChanges = empty_quality_changes_container
  943. for extruder in self._global_container_stack.extruders.values():
  944. extruder.quality = empty_quality_container
  945. extruder.qualityChanges = empty_quality_changes_container
  946. self.activeQualityGroupChanged.emit()
  947. self.activeQualityChangesGroupChanged.emit()
  948. def _setQualityGroup(self, quality_group: Optional["QualityGroup"], empty_quality_changes: bool = True) -> None:
  949. if self._global_container_stack is None:
  950. return
  951. if quality_group is None:
  952. self._setEmptyQuality()
  953. return
  954. if quality_group.node_for_global is None or quality_group.node_for_global.getContainer() is None:
  955. return
  956. for node in quality_group.nodes_for_extruders.values():
  957. if node.getContainer() is None:
  958. return
  959. self._current_quality_group = quality_group
  960. if empty_quality_changes:
  961. self._current_quality_changes_group = None
  962. # Set quality and quality_changes for the GlobalStack
  963. self._global_container_stack.quality = quality_group.node_for_global.getContainer()
  964. if empty_quality_changes:
  965. self._global_container_stack.qualityChanges = empty_quality_changes_container
  966. # Set quality and quality_changes for each ExtruderStack
  967. for position, node in quality_group.nodes_for_extruders.items():
  968. self._global_container_stack.extruders[str(position)].quality = node.getContainer()
  969. if empty_quality_changes:
  970. self._global_container_stack.extruders[str(position)].qualityChanges = empty_quality_changes_container
  971. self.activeQualityGroupChanged.emit()
  972. self.activeQualityChangesGroupChanged.emit()
  973. def _fixQualityChangesGroupToNotSupported(self, quality_changes_group: "QualityChangesGroup") -> None:
  974. nodes = [quality_changes_group.node_for_global] + list(quality_changes_group.nodes_for_extruders.values())
  975. containers = [n.getContainer() for n in nodes if n is not None]
  976. for container in containers:
  977. if container:
  978. container.setMetaDataEntry("quality_type", "not_supported")
  979. quality_changes_group.quality_type = "not_supported"
  980. def _setQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup") -> None:
  981. if self._global_container_stack is None:
  982. return # Can't change that.
  983. quality_type = quality_changes_group.quality_type
  984. # A custom quality can be created based on "not supported".
  985. # In that case, do not set quality containers to empty.
  986. quality_group = None
  987. if quality_type != "not_supported":
  988. quality_group_dict = self._quality_manager.getQualityGroups(self._global_container_stack)
  989. quality_group = quality_group_dict.get(quality_type)
  990. if quality_group is None:
  991. self._fixQualityChangesGroupToNotSupported(quality_changes_group)
  992. quality_changes_container = empty_quality_changes_container
  993. quality_container = empty_quality_container # type: Optional[InstanceContainer]
  994. if quality_changes_group.node_for_global and quality_changes_group.node_for_global.getContainer():
  995. quality_changes_container = cast(InstanceContainer, quality_changes_group.node_for_global.getContainer())
  996. if quality_group is not None and quality_group.node_for_global and quality_group.node_for_global.getContainer():
  997. quality_container = quality_group.node_for_global.getContainer()
  998. self._global_container_stack.quality = quality_container
  999. self._global_container_stack.qualityChanges = quality_changes_container
  1000. for position, extruder in self._global_container_stack.extruders.items():
  1001. quality_changes_node = quality_changes_group.nodes_for_extruders.get(position)
  1002. quality_node = None
  1003. if quality_group is not None:
  1004. quality_node = quality_group.nodes_for_extruders.get(position)
  1005. quality_changes_container = empty_quality_changes_container
  1006. quality_container = empty_quality_container
  1007. if quality_changes_node and quality_changes_node.getContainer():
  1008. quality_changes_container = cast(InstanceContainer, quality_changes_node.getContainer())
  1009. if quality_node and quality_node.getContainer():
  1010. quality_container = quality_node.getContainer()
  1011. extruder.quality = quality_container
  1012. extruder.qualityChanges = quality_changes_container
  1013. self._current_quality_group = quality_group
  1014. self._current_quality_changes_group = quality_changes_group
  1015. self.activeQualityGroupChanged.emit()
  1016. self.activeQualityChangesGroupChanged.emit()
  1017. def _setVariantNode(self, position: str, container_node: "ContainerNode") -> None:
  1018. if container_node.getContainer() is None or self._global_container_stack is None:
  1019. return
  1020. self._global_container_stack.extruders[position].variant = container_node.getContainer()
  1021. self.activeVariantChanged.emit()
  1022. def _setGlobalVariant(self, container_node: "ContainerNode") -> None:
  1023. if self._global_container_stack is None:
  1024. return
  1025. self._global_container_stack.variant = container_node.getContainer()
  1026. if not self._global_container_stack.variant:
  1027. self._global_container_stack.variant = self._application.empty_variant_container
  1028. def _setMaterial(self, position: str, container_node: Optional["ContainerNode"] = None) -> None:
  1029. if self._global_container_stack is None:
  1030. return
  1031. if container_node and container_node.getContainer():
  1032. self._global_container_stack.extruders[position].material = container_node.getContainer()
  1033. root_material_id = container_node.getMetaDataEntry("base_file", None)
  1034. else:
  1035. self._global_container_stack.extruders[position].material = empty_material_container
  1036. root_material_id = None
  1037. # The _current_root_material_id is used in the MaterialMenu to see which material is selected
  1038. if root_material_id != self._current_root_material_id[position]:
  1039. self._current_root_material_id[position] = root_material_id
  1040. self.rootMaterialChanged.emit()
  1041. def activeMaterialsCompatible(self) -> bool:
  1042. # Check material - variant compatibility
  1043. if self._global_container_stack is not None:
  1044. if Util.parseBool(self._global_container_stack.getMetaDataEntry("has_materials", False)):
  1045. for position, extruder in self._global_container_stack.extruders.items():
  1046. if extruder.isEnabled and not extruder.material.getMetaDataEntry("compatible"):
  1047. return False
  1048. if not extruder.material.getMetaDataEntry("compatible"):
  1049. return False
  1050. return True
  1051. ## Update current quality type and machine after setting material
  1052. def _updateQualityWithMaterial(self, *args: Any) -> None:
  1053. if self._global_container_stack is None:
  1054. return
  1055. Logger.log("i", "Updating quality/quality_changes due to material change")
  1056. current_quality_type = None
  1057. if self._current_quality_group:
  1058. current_quality_type = self._current_quality_group.quality_type
  1059. candidate_quality_groups = self._quality_manager.getQualityGroups(self._global_container_stack)
  1060. available_quality_types = {qt for qt, g in candidate_quality_groups.items() if g.is_available}
  1061. Logger.log("d", "Current quality type = [%s]", current_quality_type)
  1062. if not self.activeMaterialsCompatible():
  1063. if current_quality_type is not None:
  1064. Logger.log("i", "Active materials are not compatible, setting all qualities to empty (Not Supported).")
  1065. self._setEmptyQuality()
  1066. return
  1067. if not available_quality_types:
  1068. if self._current_quality_changes_group is None:
  1069. Logger.log("i", "No available quality types found, setting all qualities to empty (Not Supported).")
  1070. self._setEmptyQuality()
  1071. return
  1072. if current_quality_type in available_quality_types:
  1073. Logger.log("i", "Current available quality type [%s] is available, applying changes.", current_quality_type)
  1074. self._setQualityGroup(candidate_quality_groups[current_quality_type], empty_quality_changes = False)
  1075. return
  1076. # The current quality type is not available so we use the preferred quality type if it's available,
  1077. # otherwise use one of the available quality types.
  1078. quality_type = sorted(list(available_quality_types))[0]
  1079. preferred_quality_type = self._global_container_stack.getMetaDataEntry("preferred_quality_type")
  1080. if preferred_quality_type in available_quality_types:
  1081. quality_type = preferred_quality_type
  1082. Logger.log("i", "The current quality type [%s] is not available, switching to [%s] instead",
  1083. current_quality_type, quality_type)
  1084. self._setQualityGroup(candidate_quality_groups[quality_type], empty_quality_changes = True)
  1085. def updateMaterialWithVariant(self, position: Optional[str]) -> None:
  1086. if self._global_container_stack is None:
  1087. return
  1088. if position is None:
  1089. position_list = list(self._global_container_stack.extruders.keys())
  1090. else:
  1091. position_list = [position]
  1092. buildplate_name = None
  1093. if self._global_container_stack.variant.getId() != "empty_variant":
  1094. buildplate_name = self._global_container_stack.variant.getName()
  1095. for position_item in position_list:
  1096. extruder = self._global_container_stack.extruders[position_item]
  1097. current_material_base_name = extruder.material.getMetaDataEntry("base_file")
  1098. current_nozzle_name = None
  1099. if extruder.variant.getId() != empty_variant_container.getId():
  1100. current_nozzle_name = extruder.variant.getMetaDataEntry("name")
  1101. material_diameter = extruder.getCompatibleMaterialDiameter()
  1102. candidate_materials = self._material_manager.getAvailableMaterials(
  1103. self._global_container_stack.definition,
  1104. current_nozzle_name,
  1105. buildplate_name,
  1106. material_diameter)
  1107. if not candidate_materials:
  1108. self._setMaterial(position_item, container_node = None)
  1109. continue
  1110. if current_material_base_name in candidate_materials:
  1111. new_material = candidate_materials[current_material_base_name]
  1112. self._setMaterial(position_item, new_material)
  1113. continue
  1114. # The current material is not available, find the preferred one
  1115. material_node = self._material_manager.getDefaultMaterial(self._global_container_stack, position_item, current_nozzle_name)
  1116. if material_node is not None:
  1117. self._setMaterial(position_item, material_node)
  1118. ## Given a printer definition name, select the right machine instance. In case it doesn't exist, create a new
  1119. # instance with the same network key.
  1120. @pyqtSlot(str)
  1121. def switchPrinterType(self, machine_name: str) -> None:
  1122. # Don't switch if the user tries to change to the same type of printer
  1123. if self._global_container_stack is None or self.activeMachineDefinitionName == machine_name:
  1124. return
  1125. # Get the definition id corresponding to this machine name
  1126. machine_definition_id = CuraContainerRegistry.getInstance().findDefinitionContainers(name = machine_name)[0].getId()
  1127. # Try to find a machine with the same network key
  1128. new_machine = self.getMachine(machine_definition_id, metadata_filter = {"um_network_key": self.activeMachineNetworkKey()})
  1129. # If there is no machine, then create a new one and set it to the non-hidden instance
  1130. if not new_machine:
  1131. new_machine = CuraStackBuilder.createMachine(machine_definition_id + "_sync", machine_definition_id)
  1132. if not new_machine:
  1133. return
  1134. new_machine.setMetaDataEntry("um_network_key", self.activeMachineNetworkKey())
  1135. new_machine.setMetaDataEntry("group_name", self.activeMachineNetworkGroupName)
  1136. new_machine.setMetaDataEntry("hidden", False)
  1137. new_machine.setMetaDataEntry("connection_type", self._global_container_stack.getMetaDataEntry("connection_type"))
  1138. else:
  1139. Logger.log("i", "Found a %s with the key %s. Let's use it!", machine_name, self.activeMachineNetworkKey())
  1140. new_machine.setMetaDataEntry("hidden", False)
  1141. # Set the current printer instance to hidden (the metadata entry must exist)
  1142. self._global_container_stack.setMetaDataEntry("hidden", True)
  1143. self.setActiveMachine(new_machine.getId())
  1144. @pyqtSlot(QObject)
  1145. def applyRemoteConfiguration(self, configuration: ConfigurationModel) -> None:
  1146. if self._global_container_stack is None:
  1147. return
  1148. self.blurSettings.emit()
  1149. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1150. self.switchPrinterType(configuration.printerType)
  1151. disabled_used_extruder_position_set = set()
  1152. extruders_to_disable = set()
  1153. # If an extruder that's currently used to print a model gets disabled due to the syncing, we need to show
  1154. # a message explaining why.
  1155. need_to_show_message = False
  1156. for extruder_configuration in configuration.extruderConfigurations:
  1157. extruder_has_hotend = extruder_configuration.hotendID != ""
  1158. extruder_has_material = extruder_configuration.material.guid != ""
  1159. # If the machine doesn't have a hotend or material, disable this extruder
  1160. if not extruder_has_hotend or not extruder_has_material:
  1161. extruders_to_disable.add(extruder_configuration.position)
  1162. # If there's no material and/or nozzle on the printer, enable the first extruder and disable the rest.
  1163. if len(extruders_to_disable) == len(self._global_container_stack.extruders):
  1164. extruders_to_disable.remove(min(extruders_to_disable))
  1165. for extruder_configuration in configuration.extruderConfigurations:
  1166. position = str(extruder_configuration.position)
  1167. # If the machine doesn't have a hotend or material, disable this extruder
  1168. if int(position) in extruders_to_disable:
  1169. self._global_container_stack.extruders[position].setEnabled(False)
  1170. need_to_show_message = True
  1171. disabled_used_extruder_position_set.add(int(position))
  1172. else:
  1173. variant_container_node = self._variant_manager.getVariantNode(self._global_container_stack.definition.getId(),
  1174. extruder_configuration.hotendID)
  1175. material_container_node = self._material_manager.getMaterialNodeByType(self._global_container_stack,
  1176. position,
  1177. extruder_configuration.hotendID,
  1178. configuration.buildplateConfiguration,
  1179. extruder_configuration.material.guid)
  1180. if variant_container_node:
  1181. self._setVariantNode(position, variant_container_node)
  1182. else:
  1183. self._global_container_stack.extruders[position].variant = empty_variant_container
  1184. if material_container_node:
  1185. self._setMaterial(position, material_container_node)
  1186. else:
  1187. self._global_container_stack.extruders[position].material = empty_material_container
  1188. self._global_container_stack.extruders[position].setEnabled(True)
  1189. self.updateMaterialWithVariant(position)
  1190. self.updateNumberExtrudersEnabled()
  1191. if configuration.buildplateConfiguration is not None:
  1192. global_variant_container_node = self._variant_manager.getBuildplateVariantNode(self._global_container_stack.definition.getId(), configuration.buildplateConfiguration)
  1193. if global_variant_container_node:
  1194. self._setGlobalVariant(global_variant_container_node)
  1195. else:
  1196. self._global_container_stack.variant = empty_variant_container
  1197. else:
  1198. self._global_container_stack.variant = empty_variant_container
  1199. self._updateQualityWithMaterial()
  1200. if need_to_show_message:
  1201. msg_str = "{extruders} is disabled because there is no material loaded. Please load a material or use custom configurations."
  1202. # Show human-readable extruder names such as "Extruder Left", "Extruder Front" instead of "Extruder 1, 2, 3".
  1203. extruder_names = []
  1204. for extruder_position in sorted(disabled_used_extruder_position_set):
  1205. extruder_stack = self._global_container_stack.extruders[str(extruder_position)]
  1206. extruder_name = extruder_stack.definition.getName()
  1207. extruder_names.append(extruder_name)
  1208. extruders_str = ", ".join(extruder_names)
  1209. msg_str = msg_str.format(extruders = extruders_str)
  1210. message = Message(catalog.i18nc("@info:status", msg_str),
  1211. title = catalog.i18nc("@info:title", "Extruder(s) Disabled"))
  1212. message.show()
  1213. # See if we need to show the Discard or Keep changes screen
  1214. if self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1215. self._application.discardOrKeepProfileChanges()
  1216. ## Find all container stacks that has the pair 'key = value' in its metadata and replaces the value with 'new_value'
  1217. def replaceContainersMetadata(self, key: str, value: str, new_value: str) -> None:
  1218. machines = CuraContainerRegistry.getInstance().findContainerStacks(type = "machine")
  1219. for machine in machines:
  1220. if machine.getMetaDataEntry(key) == value:
  1221. machine.setMetaDataEntry(key, new_value)
  1222. ## This method checks if the name of the group stored in the definition container is correct.
  1223. # 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
  1224. # then all the container stacks are updated, both the current and the hidden ones.
  1225. def checkCorrectGroupName(self, device_id: str, group_name: str) -> None:
  1226. if self._global_container_stack and device_id == self.activeMachineNetworkKey():
  1227. # Check if the group_name is correct. If not, update all the containers connected to the same printer
  1228. if self.activeMachineNetworkGroupName != group_name:
  1229. metadata_filter = {"um_network_key": self.activeMachineNetworkKey()}
  1230. containers = CuraContainerRegistry.getInstance().findContainerStacks(type = "machine", **metadata_filter)
  1231. for container in containers:
  1232. container.setMetaDataEntry("group_name", group_name)
  1233. ## This method checks if there is an instance connected to the given network_key
  1234. def existNetworkInstances(self, network_key: str) -> bool:
  1235. metadata_filter = {"um_network_key": network_key}
  1236. containers = CuraContainerRegistry.getInstance().findContainerStacks(type = "machine", **metadata_filter)
  1237. return bool(containers)
  1238. @pyqtSlot("QVariant")
  1239. def setGlobalVariant(self, container_node: "ContainerNode") -> None:
  1240. self.blurSettings.emit()
  1241. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1242. self._setGlobalVariant(container_node)
  1243. self.updateMaterialWithVariant(None) # Update all materials
  1244. self._updateQualityWithMaterial()
  1245. @pyqtSlot(str, str)
  1246. def setMaterialById(self, position: str, root_material_id: str) -> None:
  1247. if self._global_container_stack is None:
  1248. return
  1249. buildplate_name = None
  1250. if self._global_container_stack.variant.getId() != "empty_variant":
  1251. buildplate_name = self._global_container_stack.variant.getName()
  1252. machine_definition_id = self._global_container_stack.definition.id
  1253. position = str(position)
  1254. extruder_stack = self._global_container_stack.extruders[position]
  1255. nozzle_name = extruder_stack.variant.getName()
  1256. material_diameter = extruder_stack.getApproximateMaterialDiameter()
  1257. material_node = self._material_manager.getMaterialNode(machine_definition_id, nozzle_name, buildplate_name,
  1258. material_diameter, root_material_id)
  1259. self.setMaterial(position, material_node)
  1260. ## Global_stack: if you want to provide your own global_stack instead of the current active one
  1261. # if you update an active machine, special measures have to be taken.
  1262. @pyqtSlot(str, "QVariant")
  1263. def setMaterial(self, position: str, container_node, global_stack: Optional["GlobalStack"] = None) -> None:
  1264. if global_stack is not None and global_stack != self._global_container_stack:
  1265. global_stack.extruders[position].material = container_node.getContainer()
  1266. return
  1267. position = str(position)
  1268. self.blurSettings.emit()
  1269. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1270. self._setMaterial(position, container_node)
  1271. self._updateQualityWithMaterial()
  1272. # See if we need to show the Discard or Keep changes screen
  1273. if self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1274. self._application.discardOrKeepProfileChanges()
  1275. @pyqtSlot(str, str)
  1276. def setVariantByName(self, position: str, variant_name: str) -> None:
  1277. if self._global_container_stack is None:
  1278. return
  1279. machine_definition_id = self._global_container_stack.definition.id
  1280. variant_node = self._variant_manager.getVariantNode(machine_definition_id, variant_name)
  1281. self.setVariant(position, variant_node)
  1282. @pyqtSlot(str, "QVariant")
  1283. def setVariant(self, position: str, container_node: "ContainerNode") -> None:
  1284. position = str(position)
  1285. self.blurSettings.emit()
  1286. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1287. self._setVariantNode(position, container_node)
  1288. self.updateMaterialWithVariant(position)
  1289. self._updateQualityWithMaterial()
  1290. # See if we need to show the Discard or Keep changes screen
  1291. if self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1292. self._application.discardOrKeepProfileChanges()
  1293. @pyqtSlot(str)
  1294. def setQualityGroupByQualityType(self, quality_type: str) -> None:
  1295. if self._global_container_stack is None:
  1296. return
  1297. # Get all the quality groups for this global stack and filter out by quality_type
  1298. quality_group_dict = self._quality_manager.getQualityGroups(self._global_container_stack)
  1299. quality_group = quality_group_dict[quality_type]
  1300. self.setQualityGroup(quality_group)
  1301. ## Optionally provide global_stack if you want to use your own
  1302. # The active global_stack is treated differently.
  1303. @pyqtSlot(QObject)
  1304. def setQualityGroup(self, quality_group: "QualityGroup", no_dialog: bool = False, global_stack: Optional["GlobalStack"] = None) -> None:
  1305. if global_stack is not None and global_stack != self._global_container_stack:
  1306. if quality_group is None:
  1307. Logger.log("e", "Could not set quality group because quality group is None")
  1308. return
  1309. if quality_group.node_for_global is None:
  1310. Logger.log("e", "Could not set quality group [%s] because it has no node_for_global", str(quality_group))
  1311. return
  1312. # This is not changing the quality for the active machine !!!!!!!!
  1313. global_stack.quality = quality_group.node_for_global.getContainer()
  1314. for extruder_nr, extruder_stack in global_stack.extruders.items():
  1315. quality_container = empty_quality_container
  1316. if extruder_nr in quality_group.nodes_for_extruders:
  1317. container = quality_group.nodes_for_extruders[extruder_nr].getContainer()
  1318. quality_container = container if container is not None else quality_container
  1319. extruder_stack.quality = quality_container
  1320. return
  1321. self.blurSettings.emit()
  1322. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1323. self._setQualityGroup(quality_group)
  1324. # See if we need to show the Discard or Keep changes screen
  1325. if not no_dialog and self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1326. self._application.discardOrKeepProfileChanges()
  1327. @pyqtProperty(QObject, fset = setQualityGroup, notify = activeQualityGroupChanged)
  1328. def activeQualityGroup(self) -> Optional["QualityGroup"]:
  1329. return self._current_quality_group
  1330. @pyqtSlot(QObject)
  1331. def setQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup", no_dialog: bool = False) -> None:
  1332. self.blurSettings.emit()
  1333. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1334. self._setQualityChangesGroup(quality_changes_group)
  1335. # See if we need to show the Discard or Keep changes screen
  1336. if not no_dialog and self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1337. self._application.discardOrKeepProfileChanges()
  1338. @pyqtSlot()
  1339. def resetToUseDefaultQuality(self) -> None:
  1340. if self._global_container_stack is None:
  1341. return
  1342. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1343. self._setQualityGroup(self._current_quality_group)
  1344. for stack in [self._global_container_stack] + list(self._global_container_stack.extruders.values()):
  1345. stack.userChanges.clear()
  1346. @pyqtProperty(QObject, fset = setQualityChangesGroup, notify = activeQualityChangesGroupChanged)
  1347. def activeQualityChangesGroup(self) -> Optional["QualityChangesGroup"]:
  1348. return self._current_quality_changes_group
  1349. @pyqtProperty(bool, notify = activeQualityChangesGroupChanged)
  1350. def hasCustomQuality(self) -> bool:
  1351. return self._current_quality_changes_group is not None
  1352. @pyqtProperty(str, notify = activeQualityGroupChanged)
  1353. def activeQualityOrQualityChangesName(self) -> str:
  1354. name = empty_quality_container.getName()
  1355. if self._current_quality_changes_group:
  1356. name = self._current_quality_changes_group.name
  1357. elif self._current_quality_group:
  1358. name = self._current_quality_group.name
  1359. return name
  1360. @pyqtProperty(bool, notify = activeQualityGroupChanged)
  1361. def hasNotSupportedQuality(self) -> bool:
  1362. return self._current_quality_group is None and self._current_quality_changes_group is None
  1363. def _updateUponMaterialMetadataChange(self) -> None:
  1364. if self._global_container_stack is None:
  1365. return
  1366. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1367. self.updateMaterialWithVariant(None)
  1368. self._updateQualityWithMaterial()
  1369. ## This function will translate any printer type name to an abbreviated printer type name
  1370. @pyqtSlot(str, result = str)
  1371. def getAbbreviatedMachineName(self, machine_type_name: str) -> str:
  1372. abbr_machine = ""
  1373. for word in re.findall(r"[\w']+", machine_type_name):
  1374. if word.lower() == "ultimaker":
  1375. abbr_machine += "UM"
  1376. elif word.isdigit():
  1377. abbr_machine += word
  1378. else:
  1379. stripped_word = "".join(char for char in unicodedata.normalize("NFD", word.upper()) if unicodedata.category(char) != "Mn")
  1380. # - use only the first character if the word is too long (> 3 characters)
  1381. # - use the whole word if it's not too long (<= 3 characters)
  1382. if len(stripped_word) > 3:
  1383. stripped_word = stripped_word[0]
  1384. abbr_machine += stripped_word
  1385. return abbr_machine