MachineManager.py 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  1. # Copyright (c) 2017 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import collections
  4. import time
  5. #Type hinting.
  6. from typing import List, Dict, TYPE_CHECKING, Optional
  7. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  8. from UM.Signal import Signal
  9. from PyQt5.QtCore import QObject, pyqtProperty, pyqtSignal, QTimer
  10. from UM.FlameProfiler import pyqtSlot
  11. from UM import Util
  12. from UM.Application import Application
  13. from UM.Preferences import Preferences
  14. from UM.Logger import Logger
  15. from UM.Message import Message
  16. from UM.Settings.ContainerRegistry import ContainerRegistry
  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
  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.ExtruderManager import ExtruderManager
  25. from .CuraStackBuilder import CuraStackBuilder
  26. from UM.i18n import i18nCatalog
  27. catalog = i18nCatalog("cura")
  28. if TYPE_CHECKING:
  29. from cura.Settings.CuraContainerStack import CuraContainerStack
  30. from cura.Settings.GlobalStack import GlobalStack
  31. class MachineManager(QObject):
  32. def __init__(self, parent = None):
  33. super().__init__(parent)
  34. self._active_container_stack = None # type: CuraContainerStack
  35. self._global_container_stack = None # type: GlobalStack
  36. self._current_root_material_id = {}
  37. self._current_quality_group = None
  38. self._current_quality_changes_group = None
  39. self._default_extruder_position = "0" # to be updated when extruders are switched on and off
  40. self.machine_extruder_material_update_dict = collections.defaultdict(list)
  41. self._instance_container_timer = QTimer()
  42. self._instance_container_timer.setInterval(250)
  43. self._instance_container_timer.setSingleShot(True)
  44. self._instance_container_timer.timeout.connect(self.__emitChangedSignals)
  45. self._application = Application.getInstance()
  46. self._application.globalContainerStackChanged.connect(self._onGlobalContainerChanged)
  47. self._application.getContainerRegistry().containerLoadComplete.connect(self._onInstanceContainersChanged)
  48. ## When the global container is changed, active material probably needs to be updated.
  49. self.globalContainerChanged.connect(self.activeMaterialChanged)
  50. self.globalContainerChanged.connect(self.activeVariantChanged)
  51. self.globalContainerChanged.connect(self.activeQualityChanged)
  52. self.globalContainerChanged.connect(self.activeQualityChangesGroupChanged)
  53. self.globalContainerChanged.connect(self.activeQualityGroupChanged)
  54. self._stacks_have_errors = None # type:Optional[bool]
  55. self._empty_definition_changes_container = ContainerRegistry.getInstance().findContainers(id = "empty_definition_changes")[0]
  56. self._empty_variant_container = ContainerRegistry.getInstance().findContainers(id = "empty_variant")[0]
  57. self._empty_material_container = ContainerRegistry.getInstance().findContainers(id = "empty_material")[0]
  58. self._empty_quality_container = ContainerRegistry.getInstance().findContainers(id = "empty_quality")[0]
  59. self._empty_quality_changes_container = ContainerRegistry.getInstance().findContainers(id = "empty_quality_changes")[0]
  60. self._onGlobalContainerChanged()
  61. ExtruderManager.getInstance().activeExtruderChanged.connect(self._onActiveExtruderStackChanged)
  62. self._onActiveExtruderStackChanged()
  63. ExtruderManager.getInstance().activeExtruderChanged.connect(self.activeMaterialChanged)
  64. ExtruderManager.getInstance().activeExtruderChanged.connect(self.activeVariantChanged)
  65. ExtruderManager.getInstance().activeExtruderChanged.connect(self.activeQualityChanged)
  66. self.globalContainerChanged.connect(self.activeStackChanged)
  67. self.globalValueChanged.connect(self.activeStackValueChanged)
  68. ExtruderManager.getInstance().activeExtruderChanged.connect(self.activeStackChanged)
  69. self.activeStackChanged.connect(self.activeStackValueChanged)
  70. Preferences.getInstance().addPreference("cura/active_machine", "")
  71. self._global_event_keys = set()
  72. self._printer_output_devices = []
  73. Application.getInstance().getOutputDeviceManager().outputDevicesChanged.connect(self._onOutputDevicesChanged)
  74. # There might already be some output devices by the time the signal is connected
  75. self._onOutputDevicesChanged()
  76. self._current_printer_configuration = ConfigurationModel() # Indicates the current configuration setup in this printer
  77. self.activeMaterialChanged.connect(self._onCurrentConfigurationChanged)
  78. self.activeVariantChanged.connect(self._onCurrentConfigurationChanged)
  79. # Force to compute the current configuration
  80. self._onCurrentConfigurationChanged()
  81. self._application.callLater(self.setInitialActiveMachine)
  82. self._material_incompatible_message = Message(catalog.i18nc("@info:status",
  83. "The selected material is incompatible with the selected machine or configuration."),
  84. title = catalog.i18nc("@info:title", "Incompatible Material"))
  85. containers = ContainerRegistry.getInstance().findInstanceContainers(id = self.activeMaterialId)
  86. if containers:
  87. containers[0].nameChanged.connect(self._onMaterialNameChanged)
  88. self._material_manager = self._application.getMaterialManager()
  89. self._variant_manager = self._application.getVariantManager()
  90. self._quality_manager = self._application.getQualityManager()
  91. # When the materials lookup table gets updated, it can mean that a material has its name changed, which should
  92. # be reflected on the GUI. This signal emission makes sure that it happens.
  93. self._material_manager.materialsUpdated.connect(self.rootMaterialChanged)
  94. # When the materials get updated, it can be that an activated material's diameter gets changed. In that case,
  95. # a material update should be triggered to make sure that the machine still has compatible materials activated.
  96. self._material_manager.materialsUpdated.connect(self._updateUponMaterialMetadataChange)
  97. self.rootMaterialChanged.connect(self._onRootMaterialChanged)
  98. activeQualityGroupChanged = pyqtSignal()
  99. activeQualityChangesGroupChanged = pyqtSignal()
  100. globalContainerChanged = pyqtSignal() # Emitted whenever the global stack is changed (ie: when changing between printers, changing a global profile, but not when changing a value)
  101. activeMaterialChanged = pyqtSignal()
  102. activeVariantChanged = pyqtSignal()
  103. activeQualityChanged = pyqtSignal()
  104. activeStackChanged = pyqtSignal() # Emitted whenever the active stack is changed (ie: when changing between extruders, changing a profile, but not when changing a value)
  105. extruderChanged = pyqtSignal()
  106. globalValueChanged = pyqtSignal() # Emitted whenever a value inside global container is changed.
  107. activeStackValueChanged = pyqtSignal() # Emitted whenever a value inside the active stack is changed.
  108. activeStackValidationChanged = pyqtSignal() # Emitted whenever a validation inside active container is changed
  109. stacksValidationChanged = pyqtSignal() # Emitted whenever a validation is changed
  110. blurSettings = pyqtSignal() # Emitted to force fields in the advanced sidebar to un-focus, so they update properly
  111. outputDevicesChanged = pyqtSignal()
  112. currentConfigurationChanged = pyqtSignal() # Emitted every time the current configurations of the machine changes
  113. rootMaterialChanged = pyqtSignal()
  114. def setInitialActiveMachine(self):
  115. active_machine_id = Preferences.getInstance().getValue("cura/active_machine")
  116. if active_machine_id != "" and ContainerRegistry.getInstance().findContainerStacksMetadata(id = active_machine_id):
  117. # An active machine was saved, so restore it.
  118. self.setActiveMachine(active_machine_id)
  119. # Make sure _active_container_stack is properly initiated
  120. ExtruderManager.getInstance().setActiveExtruderIndex(0)
  121. def _onOutputDevicesChanged(self) -> None:
  122. self._printer_output_devices = []
  123. for printer_output_device in Application.getInstance().getOutputDeviceManager().getOutputDevices():
  124. if isinstance(printer_output_device, PrinterOutputDevice):
  125. self._printer_output_devices.append(printer_output_device)
  126. self.outputDevicesChanged.emit()
  127. @pyqtProperty(QObject, notify = currentConfigurationChanged)
  128. def currentConfiguration(self):
  129. return self._current_printer_configuration
  130. def _onCurrentConfigurationChanged(self) -> None:
  131. if not self._global_container_stack:
  132. return
  133. # Create the configuration model with the current data in Cura
  134. self._current_printer_configuration.printerType = self._global_container_stack.definition.getName()
  135. self._current_printer_configuration.extruderConfigurations = []
  136. for extruder in self._global_container_stack.extruders.values():
  137. extruder_configuration = ExtruderConfigurationModel()
  138. # For compare just the GUID is needed at this moment
  139. mat_type = extruder.material.getMetaDataEntry("material") if extruder.material != self._empty_material_container else None
  140. mat_guid = extruder.material.getMetaDataEntry("GUID") if extruder.material != self._empty_material_container else None
  141. mat_color = extruder.material.getMetaDataEntry("color_name") if extruder.material != self._empty_material_container else None
  142. mat_brand = extruder.material.getMetaDataEntry("brand") if extruder.material != self._empty_material_container else None
  143. mat_name = extruder.material.getMetaDataEntry("name") if extruder.material != self._empty_material_container else None
  144. material_model = MaterialOutputModel(mat_guid, mat_type, mat_color, mat_brand, mat_name)
  145. extruder_configuration.position = int(extruder.getMetaDataEntry("position"))
  146. extruder_configuration.material = material_model
  147. extruder_configuration.hotendID = extruder.variant.getName() if extruder.variant != self._empty_variant_container else None
  148. self._current_printer_configuration.extruderConfigurations.append(extruder_configuration)
  149. self._current_printer_configuration.buildplateConfiguration = self._global_container_stack.getProperty("machine_buildplate_type", "value") if self._global_container_stack.variant != self._empty_variant_container else None
  150. self.currentConfigurationChanged.emit()
  151. @pyqtSlot(QObject, result = bool)
  152. def matchesConfiguration(self, configuration: ConfigurationModel) -> bool:
  153. return self._current_printer_configuration == configuration
  154. @pyqtProperty("QVariantList", notify = outputDevicesChanged)
  155. def printerOutputDevices(self):
  156. return self._printer_output_devices
  157. @pyqtProperty(int, constant=True)
  158. def totalNumberOfSettings(self) -> int:
  159. return len(ContainerRegistry.getInstance().findDefinitionContainers(id = "fdmprinter")[0].getAllKeys())
  160. def _onGlobalContainerChanged(self) -> None:
  161. if self._global_container_stack:
  162. try:
  163. self._global_container_stack.nameChanged.disconnect(self._onMachineNameChanged)
  164. except TypeError: # pyQtSignal gives a TypeError when disconnecting from something that was already disconnected.
  165. pass
  166. try:
  167. self._global_container_stack.containersChanged.disconnect(self._onInstanceContainersChanged)
  168. except TypeError:
  169. pass
  170. try:
  171. self._global_container_stack.propertyChanged.disconnect(self._onPropertyChanged)
  172. except TypeError:
  173. pass
  174. for extruder_stack in ExtruderManager.getInstance().getActiveExtruderStacks():
  175. extruder_stack.propertyChanged.disconnect(self._onPropertyChanged)
  176. extruder_stack.containersChanged.disconnect(self._onInstanceContainersChanged)
  177. # Update the local global container stack reference
  178. self._global_container_stack = Application.getInstance().getGlobalContainerStack()
  179. if self._global_container_stack:
  180. self.updateDefaultExtruder()
  181. self.updateNumberExtrudersEnabled()
  182. self.globalContainerChanged.emit()
  183. # after switching the global stack we reconnect all the signals and set the variant and material references
  184. if self._global_container_stack:
  185. Preferences.getInstance().setValue("cura/active_machine", self._global_container_stack.getId())
  186. self._global_container_stack.nameChanged.connect(self._onMachineNameChanged)
  187. self._global_container_stack.containersChanged.connect(self._onInstanceContainersChanged)
  188. self._global_container_stack.propertyChanged.connect(self._onPropertyChanged)
  189. # Global stack can have only a variant if it is a buildplate
  190. global_variant = self._global_container_stack.variant
  191. if global_variant != self._empty_variant_container:
  192. if global_variant.getMetaDataEntry("hardware_type") != "buildplate":
  193. self._global_container_stack.setVariant(self._empty_variant_container)
  194. # set the global material to empty as we now use the extruder stack at all times - CURA-4482
  195. global_material = self._global_container_stack.material
  196. if global_material != self._empty_material_container:
  197. self._global_container_stack.setMaterial(self._empty_material_container)
  198. # Listen for changes on all extruder stacks
  199. for extruder_stack in ExtruderManager.getInstance().getActiveExtruderStacks():
  200. extruder_stack.propertyChanged.connect(self._onPropertyChanged)
  201. extruder_stack.containersChanged.connect(self._onInstanceContainersChanged)
  202. if self._global_container_stack.getId() in self.machine_extruder_material_update_dict:
  203. for func in self.machine_extruder_material_update_dict[self._global_container_stack.getId()]:
  204. Application.getInstance().callLater(func)
  205. del self.machine_extruder_material_update_dict[self._global_container_stack.getId()]
  206. self.activeQualityGroupChanged.emit()
  207. def _onActiveExtruderStackChanged(self) -> None:
  208. self.blurSettings.emit() # Ensure no-one has focus.
  209. old_active_container_stack = self._active_container_stack
  210. self._active_container_stack = ExtruderManager.getInstance().getActiveExtruderStack()
  211. if old_active_container_stack != self._active_container_stack:
  212. # Many methods and properties related to the active quality actually depend
  213. # on _active_container_stack. If it changes, then the properties change.
  214. self.activeQualityChanged.emit()
  215. def __emitChangedSignals(self) -> None:
  216. self.activeQualityChanged.emit()
  217. self.activeVariantChanged.emit()
  218. self.activeMaterialChanged.emit()
  219. self.rootMaterialChanged.emit()
  220. def _onInstanceContainersChanged(self, container) -> None:
  221. self._instance_container_timer.start()
  222. def _onPropertyChanged(self, key: str, property_name: str) -> None:
  223. if property_name == "value":
  224. # Notify UI items, such as the "changed" star in profile pull down menu.
  225. self.activeStackValueChanged.emit()
  226. ## Given a global_stack, make sure that it's all valid by searching for this quality group and applying it again
  227. def _initMachineState(self, global_stack):
  228. material_dict = {}
  229. for position, extruder in global_stack.extruders.items():
  230. material_dict[position] = extruder.material.getMetaDataEntry("base_file")
  231. self._current_root_material_id = material_dict
  232. global_quality = global_stack.quality
  233. quality_type = global_quality.getMetaDataEntry("quality_type")
  234. global_quality_changes = global_stack.qualityChanges
  235. global_quality_changes_name = global_quality_changes.getName()
  236. if global_quality_changes.getId() != "empty_quality_changes":
  237. quality_changes_groups = self._application._quality_manager.getQualityChangesGroups(global_stack)
  238. if global_quality_changes_name in quality_changes_groups:
  239. new_quality_changes_group = quality_changes_groups[global_quality_changes_name]
  240. self._setQualityChangesGroup(new_quality_changes_group)
  241. else:
  242. quality_groups = self._application._quality_manager.getQualityGroups(global_stack)
  243. if quality_type not in quality_groups:
  244. Logger.log("w", "Quality type [%s] not found in available qualities [%s]", quality_type, str(quality_groups.values()))
  245. self._setEmptyQuality()
  246. return
  247. new_quality_group = quality_groups[quality_type]
  248. self._setQualityGroup(new_quality_group, empty_quality_changes = True)
  249. @pyqtSlot(str)
  250. def setActiveMachine(self, stack_id: str) -> None:
  251. self.blurSettings.emit() # Ensure no-one has focus.
  252. container_registry = ContainerRegistry.getInstance()
  253. containers = container_registry.findContainerStacks(id = stack_id)
  254. if containers:
  255. global_stack = containers[0]
  256. ExtruderManager.getInstance().setActiveExtruderIndex(0) # Switch to first extruder
  257. self._global_container_stack = global_stack
  258. Application.getInstance().setGlobalContainerStack(global_stack)
  259. ExtruderManager.getInstance()._globalContainerStackChanged()
  260. self._initMachineState(containers[0])
  261. self._onGlobalContainerChanged()
  262. self.__emitChangedSignals()
  263. ## Given a definition id, return the machine with this id.
  264. # Optional: add a list of keys and values to filter the list of machines with the given definition id
  265. # \param definition_id \type{str} definition id that needs to look for
  266. # \param metadata_filter \type{dict} list of metadata keys and values used for filtering
  267. @staticmethod
  268. def getMachine(definition_id: str, metadata_filter: Dict[str, str] = None) -> Optional["GlobalStack"]:
  269. machines = ContainerRegistry.getInstance().findContainerStacks(type = "machine", **metadata_filter)
  270. for machine in machines:
  271. if machine.definition.getId() == definition_id:
  272. return machine
  273. return None
  274. @pyqtSlot(str, str)
  275. def addMachine(self, name: str, definition_id: str) -> None:
  276. new_stack = CuraStackBuilder.createMachine(name, definition_id)
  277. if new_stack:
  278. # Instead of setting the global container stack here, we set the active machine and so the signals are emitted
  279. self.setActiveMachine(new_stack.getId())
  280. else:
  281. Logger.log("w", "Failed creating a new machine!")
  282. def _checkStacksHaveErrors(self) -> bool:
  283. time_start = time.time()
  284. if self._global_container_stack is None: #No active machine.
  285. return False
  286. if self._global_container_stack.hasErrors():
  287. Logger.log("d", "Checking global stack for errors took %0.2f s and we found an error" % (time.time() - time_start))
  288. return True
  289. # Not a very pretty solution, but the extruder manager doesn't really know how many extruders there are
  290. machine_extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  291. extruder_stacks = ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId())
  292. count = 1 # we start with the global stack
  293. for stack in extruder_stacks:
  294. md = stack.getMetaData()
  295. if "position" in md and int(md["position"]) >= machine_extruder_count:
  296. continue
  297. count += 1
  298. if stack.hasErrors():
  299. 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)))
  300. return True
  301. Logger.log("d", "Checking %s stacks for errors took %.2f s" % (count, time.time() - time_start))
  302. return False
  303. ## Check if the global_container has instances in the user container
  304. @pyqtProperty(bool, notify = activeStackValueChanged)
  305. def hasUserSettings(self) -> bool:
  306. if not self._global_container_stack:
  307. return False
  308. if self._global_container_stack.getTop().findInstances():
  309. return True
  310. stacks = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
  311. for stack in stacks:
  312. if stack.getTop().findInstances():
  313. return True
  314. return False
  315. @pyqtProperty(int, notify = activeStackValueChanged)
  316. def numUserSettings(self) -> int:
  317. if not self._global_container_stack:
  318. return 0
  319. num_user_settings = 0
  320. num_user_settings += len(self._global_container_stack.getTop().findInstances())
  321. stacks = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
  322. for stack in stacks:
  323. num_user_settings += len(stack.getTop().findInstances())
  324. return num_user_settings
  325. ## Delete a user setting from the global stack and all extruder stacks.
  326. # \param key \type{str} the name of the key to delete
  327. @pyqtSlot(str)
  328. def clearUserSettingAllCurrentStacks(self, key: str) -> None:
  329. if not self._global_container_stack:
  330. return
  331. send_emits_containers = []
  332. top_container = self._global_container_stack.getTop()
  333. top_container.removeInstance(key, postpone_emit=True)
  334. send_emits_containers.append(top_container)
  335. linked = not self._global_container_stack.getProperty(key, "settable_per_extruder") or \
  336. self._global_container_stack.getProperty(key, "limit_to_extruder") != "-1"
  337. if not linked:
  338. stack = ExtruderManager.getInstance().getActiveExtruderStack()
  339. stacks = [stack]
  340. else:
  341. stacks = ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId())
  342. for stack in stacks:
  343. if stack is not None:
  344. container = stack.getTop()
  345. container.removeInstance(key, postpone_emit=True)
  346. send_emits_containers.append(container)
  347. for container in send_emits_containers:
  348. container.sendPostponedEmits()
  349. ## Check if none of the stacks contain error states
  350. # Note that the _stacks_have_errors is cached due to performance issues
  351. # Calling _checkStack(s)ForErrors on every change is simply too expensive
  352. @pyqtProperty(bool, notify = stacksValidationChanged)
  353. def stacksHaveErrors(self) -> bool:
  354. return bool(self._stacks_have_errors)
  355. @pyqtProperty(str, notify = globalContainerChanged)
  356. def activeMachineDefinitionName(self) -> str:
  357. if self._global_container_stack:
  358. return self._global_container_stack.definition.getName()
  359. return ""
  360. @pyqtProperty(str, notify = globalContainerChanged)
  361. def activeMachineName(self) -> str:
  362. if self._global_container_stack:
  363. return self._global_container_stack.getName()
  364. return ""
  365. @pyqtProperty(str, notify = globalContainerChanged)
  366. def activeMachineId(self) -> str:
  367. if self._global_container_stack:
  368. return self._global_container_stack.getId()
  369. return ""
  370. @pyqtProperty(str, notify = outputDevicesChanged)
  371. def activeMachineNetworkKey(self) -> str:
  372. if self._global_container_stack:
  373. return self._global_container_stack.getMetaDataEntry("um_network_key", "")
  374. return ""
  375. @pyqtProperty(str, notify = outputDevicesChanged)
  376. def activeMachineNetworkGroupName(self) -> str:
  377. if self._global_container_stack:
  378. return self._global_container_stack.getMetaDataEntry("connect_group_name", "")
  379. return ""
  380. @pyqtProperty(QObject, notify = globalContainerChanged)
  381. def activeMachine(self) -> Optional["GlobalStack"]:
  382. return self._global_container_stack
  383. @pyqtProperty(str, notify = activeStackChanged)
  384. def activeStackId(self) -> str:
  385. if self._active_container_stack:
  386. return self._active_container_stack.getId()
  387. return ""
  388. @pyqtProperty(QObject, notify = activeStackChanged)
  389. def activeStack(self) -> Optional["ExtruderStack"]:
  390. return self._active_container_stack
  391. @pyqtProperty(str, notify=activeMaterialChanged)
  392. def activeMaterialId(self) -> str:
  393. if self._active_container_stack:
  394. material = self._active_container_stack.material
  395. if material:
  396. return material.getId()
  397. return ""
  398. ## Gets a dict with the active materials ids set in all extruder stacks and the global stack
  399. # (when there is one extruder, the material is set in the global stack)
  400. #
  401. # \return The material ids in all stacks
  402. @pyqtProperty("QVariantMap", notify = activeMaterialChanged)
  403. def allActiveMaterialIds(self) -> Dict[str, str]:
  404. result = {}
  405. active_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  406. if active_stacks is not None: # If we have extruder stacks
  407. for stack in active_stacks:
  408. material_container = stack.material
  409. if not material_container:
  410. continue
  411. result[stack.getId()] = material_container.getId()
  412. return result
  413. ## Gets the layer height of the currently active quality profile.
  414. #
  415. # This is indicated together with the name of the active quality profile.
  416. #
  417. # \return The layer height of the currently active quality profile. If
  418. # there is no quality profile, this returns 0.
  419. @pyqtProperty(float, notify = activeQualityGroupChanged)
  420. def activeQualityLayerHeight(self) -> float:
  421. if not self._global_container_stack:
  422. return 0
  423. if self._current_quality_changes_group:
  424. value = self._global_container_stack.getRawProperty("layer_height", "value", skip_until_container = self._global_container_stack.qualityChanges.getId())
  425. if isinstance(value, SettingFunction):
  426. value = value(self._global_container_stack)
  427. return value
  428. elif self._current_quality_group:
  429. value = self._global_container_stack.getRawProperty("layer_height", "value", skip_until_container = self._global_container_stack.quality.getId())
  430. if isinstance(value, SettingFunction):
  431. value = value(self._global_container_stack)
  432. return value
  433. return 0
  434. @pyqtProperty(str, notify = activeVariantChanged)
  435. def globalVariantName(self) -> str:
  436. if self._global_container_stack:
  437. variant = self._global_container_stack.variant
  438. if variant and not isinstance(variant, type(self._empty_variant_container)):
  439. return variant.getName()
  440. return ""
  441. @pyqtProperty(str, notify = activeQualityGroupChanged)
  442. def activeQualityType(self) -> str:
  443. quality_type = ""
  444. if self._active_container_stack:
  445. if self._current_quality_group:
  446. quality_type = self._current_quality_group.quality_type
  447. return quality_type
  448. @pyqtProperty(bool, notify = activeQualityGroupChanged)
  449. def isActiveQualitySupported(self) -> bool:
  450. is_supported = False
  451. if self._global_container_stack:
  452. if self._current_quality_group:
  453. is_supported = self._current_quality_group.is_available
  454. return is_supported
  455. ## Returns whether there is anything unsupported in the current set-up.
  456. #
  457. # The current set-up signifies the global stack and all extruder stacks,
  458. # so this indicates whether there is any container in any of the container
  459. # stacks that is not marked as supported.
  460. @pyqtProperty(bool, notify = activeQualityChanged)
  461. def isCurrentSetupSupported(self) -> bool:
  462. if not self._global_container_stack:
  463. return False
  464. for stack in [self._global_container_stack] + list(self._global_container_stack.extruders.values()):
  465. for container in stack.getContainers():
  466. if not container:
  467. return False
  468. if not Util.parseBool(container.getMetaDataEntry("supported", True)):
  469. return False
  470. return True
  471. ## Check if a container is read_only
  472. @pyqtSlot(str, result = bool)
  473. def isReadOnly(self, container_id: str) -> bool:
  474. return ContainerRegistry.getInstance().isReadOnly(container_id)
  475. ## Copy the value of the setting of the current extruder to all other extruders as well as the global container.
  476. @pyqtSlot(str)
  477. def copyValueToExtruders(self, key: str):
  478. new_value = self._active_container_stack.getProperty(key, "value")
  479. extruder_stacks = [stack for stack in ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId())]
  480. # check in which stack the value has to be replaced
  481. for extruder_stack in extruder_stacks:
  482. if extruder_stack != self._active_container_stack and extruder_stack.getProperty(key, "value") != new_value:
  483. extruder_stack.userChanges.setProperty(key, "value", new_value) # TODO: nested property access, should be improved
  484. @pyqtProperty(str, notify = activeVariantChanged)
  485. def activeVariantName(self) -> str:
  486. if self._active_container_stack:
  487. variant = self._active_container_stack.variant
  488. if variant:
  489. return variant.getName()
  490. return ""
  491. @pyqtProperty(str, notify = activeVariantChanged)
  492. def activeVariantBuildplateName(self) -> str:
  493. if self._global_container_stack:
  494. variant = self._global_container_stack.variant
  495. if variant:
  496. return variant.getName()
  497. return ""
  498. @pyqtProperty(str, notify = globalContainerChanged)
  499. def activeDefinitionId(self) -> str:
  500. if self._global_container_stack:
  501. return self._global_container_stack.definition.id
  502. return ""
  503. ## Get the Definition ID to use to select quality profiles for the currently active machine
  504. # \returns DefinitionID (string) if found, empty string otherwise
  505. @pyqtProperty(str, notify = globalContainerChanged)
  506. def activeQualityDefinitionId(self) -> str:
  507. if self._global_container_stack:
  508. return getMachineDefinitionIDForQualitySearch(self._global_container_stack.definition)
  509. return ""
  510. ## Gets how the active definition calls variants
  511. # Caveat: per-definition-variant-title is currently not translated (though the fallback is)
  512. @pyqtProperty(str, notify = globalContainerChanged)
  513. def activeDefinitionVariantsName(self) -> str:
  514. fallback_title = catalog.i18nc("@label", "Nozzle")
  515. if self._global_container_stack:
  516. return self._global_container_stack.definition.getMetaDataEntry("variants_name", fallback_title)
  517. return fallback_title
  518. @pyqtSlot(str, str)
  519. def renameMachine(self, machine_id: str, new_name: str):
  520. container_registry = ContainerRegistry.getInstance()
  521. machine_stack = container_registry.findContainerStacks(id = machine_id)
  522. if machine_stack:
  523. new_name = container_registry.createUniqueName("machine", machine_stack[0].getName(), new_name, machine_stack[0].definition.getName())
  524. machine_stack[0].setName(new_name)
  525. self.globalContainerChanged.emit()
  526. @pyqtSlot(str)
  527. def removeMachine(self, machine_id: str):
  528. # If the machine that is being removed is the currently active machine, set another machine as the active machine.
  529. activate_new_machine = (self._global_container_stack and self._global_container_stack.getId() == machine_id)
  530. # activate a new machine before removing a machine because this is safer
  531. if activate_new_machine:
  532. machine_stacks = ContainerRegistry.getInstance().findContainerStacksMetadata(type = "machine")
  533. other_machine_stacks = [s for s in machine_stacks if s["id"] != machine_id]
  534. if other_machine_stacks:
  535. self.setActiveMachine(other_machine_stacks[0]["id"])
  536. metadata = ContainerRegistry.getInstance().findContainerStacksMetadata(id = machine_id)[0]
  537. network_key = metadata["um_network_key"] if "um_network_key" in metadata else None
  538. ExtruderManager.getInstance().removeMachineExtruders(machine_id)
  539. containers = ContainerRegistry.getInstance().findInstanceContainersMetadata(type = "user", machine = machine_id)
  540. for container in containers:
  541. ContainerRegistry.getInstance().removeContainer(container["id"])
  542. ContainerRegistry.getInstance().removeContainer(machine_id)
  543. # If the printer that is being removed is a network printer, the hidden printers have to be also removed
  544. if network_key:
  545. metadata_filter = {"um_network_key": network_key}
  546. hidden_containers = ContainerRegistry.getInstance().findContainerStacks(type = "machine", **metadata_filter)
  547. if hidden_containers:
  548. # This reuses the method and remove all printers recursively
  549. self.removeMachine(hidden_containers[0].getId())
  550. @pyqtProperty(bool, notify = globalContainerChanged)
  551. def hasMaterials(self) -> bool:
  552. if self._global_container_stack:
  553. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_materials", False))
  554. return False
  555. @pyqtProperty(bool, notify = globalContainerChanged)
  556. def hasVariants(self) -> bool:
  557. if self._global_container_stack:
  558. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_variants", False))
  559. return False
  560. @pyqtProperty(bool, notify = globalContainerChanged)
  561. def hasVariantBuildplates(self) -> bool:
  562. if self._global_container_stack:
  563. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_variant_buildplates", False))
  564. return False
  565. ## The selected buildplate is compatible if it is compatible with all the materials in all the extruders
  566. @pyqtProperty(bool, notify = activeMaterialChanged)
  567. def variantBuildplateCompatible(self) -> bool:
  568. if not self._global_container_stack:
  569. return True
  570. buildplate_compatible = True # It is compatible by default
  571. extruder_stacks = self._global_container_stack.extruders.values()
  572. for stack in extruder_stacks:
  573. if not stack.isEnabled:
  574. continue
  575. material_container = stack.material
  576. if material_container == self._empty_material_container:
  577. continue
  578. if material_container.getMetaDataEntry("buildplate_compatible"):
  579. buildplate_compatible = buildplate_compatible and material_container.getMetaDataEntry("buildplate_compatible")[self.activeVariantBuildplateName]
  580. return buildplate_compatible
  581. ## The selected buildplate is usable if it is usable for all materials OR it is compatible for one but not compatible
  582. # for the other material but the buildplate is still usable
  583. @pyqtProperty(bool, notify = activeMaterialChanged)
  584. def variantBuildplateUsable(self) -> bool:
  585. if not self._global_container_stack:
  586. return True
  587. # Here the next formula is being calculated:
  588. # result = (not (material_left_compatible and material_right_compatible)) and
  589. # (material_left_compatible or material_left_usable) and
  590. # (material_right_compatible or material_right_usable)
  591. result = not self.variantBuildplateCompatible
  592. extruder_stacks = self._global_container_stack.extruders.values()
  593. for stack in extruder_stacks:
  594. material_container = stack.material
  595. if material_container == self._empty_material_container:
  596. continue
  597. buildplate_compatible = material_container.getMetaDataEntry("buildplate_compatible")[self.activeVariantBuildplateName] if material_container.getMetaDataEntry("buildplate_compatible") else True
  598. buildplate_usable = material_container.getMetaDataEntry("buildplate_recommended")[self.activeVariantBuildplateName] if material_container.getMetaDataEntry("buildplate_recommended") else True
  599. result = result and (buildplate_compatible or buildplate_usable)
  600. return result
  601. ## Property to indicate if a machine has "specialized" material profiles.
  602. # Some machines have their own material profiles that "override" the default catch all profiles.
  603. @pyqtProperty(bool, notify = globalContainerChanged)
  604. def filterMaterialsByMachine(self) -> bool:
  605. if self._global_container_stack:
  606. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_machine_materials", False))
  607. return False
  608. ## Property to indicate if a machine has "specialized" quality profiles.
  609. # Some machines have their own quality profiles that "override" the default catch all profiles.
  610. @pyqtProperty(bool, notify = globalContainerChanged)
  611. def filterQualityByMachine(self) -> bool:
  612. if self._global_container_stack:
  613. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_machine_quality", False))
  614. return False
  615. ## Get the Definition ID of a machine (specified by ID)
  616. # \param machine_id string machine id to get the definition ID of
  617. # \returns DefinitionID (string) if found, None otherwise
  618. @pyqtSlot(str, result = str)
  619. def getDefinitionByMachineId(self, machine_id: str) -> str:
  620. containers = ContainerRegistry.getInstance().findContainerStacks(id = machine_id)
  621. if containers:
  622. return containers[0].definition.getId()
  623. def getIncompatibleSettingsOnEnabledExtruders(self, container):
  624. extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  625. result = []
  626. for setting_instance in container.findInstances():
  627. setting_key = setting_instance.definition.key
  628. setting_enabled = self._global_container_stack.getProperty(setting_key, "enabled")
  629. if not setting_enabled:
  630. # A setting is not visible anymore
  631. result.append(setting_key)
  632. Logger.log("d", "Reset setting [%s] from [%s] because the setting is no longer enabled", setting_key, container)
  633. continue
  634. if not self._global_container_stack.getProperty(setting_key, "type") in ("extruder", "optional_extruder"):
  635. continue
  636. old_value = container.getProperty(setting_key, "value")
  637. if int(old_value) >= extruder_count or not self._global_container_stack.extruders[str(old_value)].isEnabled:
  638. result.append(setting_key)
  639. Logger.log("d", "Reset setting [%s] in [%s] because its old value [%s] is no longer valid", setting_key, container, old_value)
  640. return result
  641. ## Update extruder number to a valid value when the number of extruders are changed, or when an extruder is changed
  642. def correctExtruderSettings(self):
  643. for setting_key in self.getIncompatibleSettingsOnEnabledExtruders(self._global_container_stack.userChanges):
  644. self._global_container_stack.userChanges.removeInstance(setting_key)
  645. add_user_changes = self.getIncompatibleSettingsOnEnabledExtruders(self._global_container_stack.qualityChanges)
  646. for setting_key in add_user_changes:
  647. # Apply quality changes that are incompatible to user changes, so we do not change the quality changes itself.
  648. self._global_container_stack.userChanges.setProperty(setting_key, "value", self._default_extruder_position)
  649. if add_user_changes:
  650. caution_message = Message(catalog.i18nc(
  651. "@info:generic",
  652. "Settings have been changed to match the current availability of extruders: [%s]" % ", ".join(add_user_changes)),
  653. lifetime=0,
  654. title = catalog.i18nc("@info:title", "Settings updated"))
  655. caution_message.show()
  656. ## Set the amount of extruders on the active machine (global stack)
  657. # \param extruder_count int the number of extruders to set
  658. def setActiveMachineExtruderCount(self, extruder_count):
  659. extruder_manager = Application.getInstance().getExtruderManager()
  660. definition_changes_container = self._global_container_stack.definitionChanges
  661. if not self._global_container_stack or definition_changes_container == self._empty_definition_changes_container:
  662. return
  663. previous_extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  664. if extruder_count == previous_extruder_count:
  665. return
  666. definition_changes_container.setProperty("machine_extruder_count", "value", extruder_count)
  667. self.updateDefaultExtruder()
  668. self.updateNumberExtrudersEnabled()
  669. self.correctExtruderSettings()
  670. # Check to see if any objects are set to print with an extruder that will no longer exist
  671. root_node = Application.getInstance().getController().getScene().getRoot()
  672. for node in DepthFirstIterator(root_node):
  673. if node.getMeshData():
  674. extruder_nr = node.callDecoration("getActiveExtruderPosition")
  675. if extruder_nr is not None and int(extruder_nr) > extruder_count - 1:
  676. node.callDecoration("setActiveExtruder", extruder_manager.getExtruderStack(extruder_count - 1).getId())
  677. # Make sure one of the extruder stacks is active
  678. extruder_manager.setActiveExtruderIndex(0)
  679. # Move settable_per_extruder values out of the global container
  680. # After CURA-4482 this should not be the case anymore, but we still want to support older project files.
  681. global_user_container = self._global_container_stack.userChanges
  682. # Make sure extruder_stacks exists
  683. extruder_stacks = []
  684. if previous_extruder_count == 1:
  685. extruder_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  686. global_user_container = self._global_container_stack.userChanges
  687. for setting_instance in global_user_container.findInstances():
  688. setting_key = setting_instance.definition.key
  689. settable_per_extruder = self._global_container_stack.getProperty(setting_key, "settable_per_extruder")
  690. if settable_per_extruder:
  691. limit_to_extruder = int(self._global_container_stack.getProperty(setting_key, "limit_to_extruder"))
  692. extruder_stack = extruder_stacks[max(0, limit_to_extruder)]
  693. extruder_stack.userChanges.setProperty(setting_key, "value", global_user_container.getProperty(setting_key, "value"))
  694. global_user_container.removeInstance(setting_key)
  695. # Signal that the global stack has changed
  696. Application.getInstance().globalContainerStackChanged.emit()
  697. self.forceUpdateAllSettings()
  698. @pyqtSlot(int, result = QObject)
  699. def getExtruder(self, position: int):
  700. extruder = None
  701. if self._global_container_stack:
  702. extruder = self._global_container_stack.extruders.get(str(position))
  703. return extruder
  704. def updateDefaultExtruder(self):
  705. extruder_items = sorted(self._global_container_stack.extruders.items())
  706. old_position = self._default_extruder_position
  707. new_default_position = "0"
  708. for position, extruder in extruder_items:
  709. if extruder.isEnabled:
  710. new_default_position = position
  711. break
  712. if new_default_position != old_position:
  713. self._default_extruder_position = new_default_position
  714. self.extruderChanged.emit()
  715. def updateNumberExtrudersEnabled(self):
  716. definition_changes_container = self._global_container_stack.definitionChanges
  717. extruder_count = 0
  718. for position, extruder in self._global_container_stack.extruders.items():
  719. if extruder.isEnabled:
  720. extruder_count += 1
  721. definition_changes_container.setProperty("extruders_enabled_count", "value", extruder_count)
  722. @pyqtProperty(str, notify = extruderChanged)
  723. def defaultExtruderPosition(self):
  724. return self._default_extruder_position
  725. ## This will fire the propertiesChanged for all settings so they will be updated in the front-end
  726. @pyqtSlot()
  727. def forceUpdateAllSettings(self):
  728. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  729. property_names = ["value", "resolve", "validationState"]
  730. for container in [self._global_container_stack] + list(self._global_container_stack.extruders.values()):
  731. for setting_key in container.getAllKeys():
  732. container.propertiesChanged.emit(setting_key, property_names)
  733. @pyqtSlot(int, bool)
  734. def setExtruderEnabled(self, position: int, enabled) -> None:
  735. extruder = self.getExtruder(position)
  736. extruder.setEnabled(enabled)
  737. self.updateDefaultExtruder()
  738. self.updateNumberExtrudersEnabled()
  739. self.correctExtruderSettings()
  740. # ensure that the quality profile is compatible with current combination, or choose a compatible one if available
  741. self._updateQualityWithMaterial()
  742. self.extruderChanged.emit()
  743. # update material compatibility color
  744. self.activeQualityGroupChanged.emit()
  745. # update items in SettingExtruder
  746. ExtruderManager.getInstance().extrudersChanged.emit(self._global_container_stack.getId())
  747. # Make sure the front end reflects changes
  748. self.forceUpdateAllSettings()
  749. def _onMachineNameChanged(self):
  750. self.globalContainerChanged.emit()
  751. def _onMaterialNameChanged(self):
  752. self.activeMaterialChanged.emit()
  753. def _onQualityNameChanged(self):
  754. self.activeQualityChanged.emit()
  755. def _getContainerChangedSignals(self) -> List[Signal]:
  756. stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  757. stacks.append(self._global_container_stack)
  758. return [ s.containersChanged for s in stacks ]
  759. @pyqtSlot(str, str, str)
  760. def setSettingForAllExtruders(self, setting_name: str, property_name: str, property_value: str):
  761. for key, extruder in self._global_container_stack.extruders.items():
  762. container = extruder.userChanges
  763. container.setProperty(setting_name, property_name, property_value)
  764. @pyqtProperty("QVariantList", notify = globalContainerChanged)
  765. def currentExtruderPositions(self):
  766. if self._global_container_stack is None:
  767. return []
  768. return sorted(list(self._global_container_stack.extruders.keys()))
  769. ## Update _current_root_material_id when the current root material was changed.
  770. def _onRootMaterialChanged(self):
  771. self._current_root_material_id = {}
  772. if self._global_container_stack:
  773. for position in self._global_container_stack.extruders:
  774. self._current_root_material_id[position] = self._global_container_stack.extruders[position].material.getMetaDataEntry("base_file")
  775. @pyqtProperty("QVariant", notify = rootMaterialChanged)
  776. def currentRootMaterialId(self):
  777. return self._current_root_material_id
  778. ## Return the variant names in the extruder stack(s).
  779. ## For the variant in the global stack, use activeVariantBuildplateName
  780. @pyqtProperty("QVariant", notify = activeVariantChanged)
  781. def activeVariantNames(self):
  782. result = {}
  783. active_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  784. if active_stacks is not None:
  785. for stack in active_stacks:
  786. variant_container = stack.variant
  787. position = stack.getMetaDataEntry("position")
  788. if variant_container and variant_container != self._empty_variant_container:
  789. result[position] = variant_container.getName()
  790. return result
  791. #
  792. # Sets all quality and quality_changes containers to empty_quality and empty_quality_changes containers
  793. # for all stacks in the currently active machine.
  794. #
  795. def _setEmptyQuality(self):
  796. self._current_quality_group = None
  797. self._current_quality_changes_group = None
  798. self._global_container_stack.quality = self._empty_quality_container
  799. self._global_container_stack.qualityChanges = self._empty_quality_changes_container
  800. for extruder in self._global_container_stack.extruders.values():
  801. extruder.quality = self._empty_quality_container
  802. extruder.qualityChanges = self._empty_quality_changes_container
  803. self.activeQualityGroupChanged.emit()
  804. self.activeQualityChangesGroupChanged.emit()
  805. def _setQualityGroup(self, quality_group, empty_quality_changes = True):
  806. self._current_quality_group = quality_group
  807. if empty_quality_changes:
  808. self._current_quality_changes_group = None
  809. # Set quality and quality_changes for the GlobalStack
  810. self._global_container_stack.quality = quality_group.node_for_global.getContainer()
  811. if empty_quality_changes:
  812. self._global_container_stack.qualityChanges = self._empty_quality_changes_container
  813. # Set quality and quality_changes for each ExtruderStack
  814. for position, node in quality_group.nodes_for_extruders.items():
  815. self._global_container_stack.extruders[str(position)].quality = node.getContainer()
  816. if empty_quality_changes:
  817. self._global_container_stack.extruders[str(position)].qualityChanges = self._empty_quality_changes_container
  818. self.activeQualityGroupChanged.emit()
  819. self.activeQualityChangesGroupChanged.emit()
  820. def _setQualityChangesGroup(self, quality_changes_group):
  821. quality_type = quality_changes_group.quality_type
  822. quality_group_dict = self._quality_manager.getQualityGroups(self._global_container_stack)
  823. quality_group = quality_group_dict[quality_type]
  824. quality_changes_container = self._empty_quality_changes_container
  825. quality_container = self._empty_quality_changes_container
  826. if quality_changes_group.node_for_global:
  827. quality_changes_container = quality_changes_group.node_for_global.getContainer()
  828. if quality_group.node_for_global:
  829. quality_container = quality_group.node_for_global.getContainer()
  830. self._global_container_stack.quality = quality_container
  831. self._global_container_stack.qualityChanges = quality_changes_container
  832. for position, extruder in self._global_container_stack.extruders.items():
  833. quality_changes_node = quality_changes_group.nodes_for_extruders.get(position)
  834. quality_node = quality_group.nodes_for_extruders.get(position)
  835. quality_changes_container = self._empty_quality_changes_container
  836. quality_container = self._empty_quality_container
  837. if quality_changes_node:
  838. quality_changes_container = quality_changes_node.getContainer()
  839. if quality_node:
  840. quality_container = quality_node.getContainer()
  841. extruder.quality = quality_container
  842. extruder.qualityChanges = quality_changes_container
  843. self._current_quality_group = quality_group
  844. self._current_quality_changes_group = quality_changes_group
  845. self.activeQualityGroupChanged.emit()
  846. self.activeQualityChangesGroupChanged.emit()
  847. def _setVariantNode(self, position, container_node):
  848. self._global_container_stack.extruders[position].variant = container_node.getContainer()
  849. self.activeVariantChanged.emit()
  850. def _setGlobalVariant(self, container_node):
  851. self._global_container_stack.variant = container_node.getContainer()
  852. def _setMaterial(self, position, container_node = None):
  853. if container_node:
  854. self._global_container_stack.extruders[position].material = container_node.getContainer()
  855. root_material_id = container_node.metadata["base_file"]
  856. else:
  857. self._global_container_stack.extruders[position].material = self._empty_material_container
  858. root_material_id = None
  859. # The _current_root_material_id is used in the MaterialMenu to see which material is selected
  860. if root_material_id != self._current_root_material_id[position]:
  861. self._current_root_material_id[position] = root_material_id
  862. self.rootMaterialChanged.emit()
  863. def activeMaterialsCompatible(self):
  864. # check material - variant compatibility
  865. if Util.parseBool(self._global_container_stack.getMetaDataEntry("has_materials", False)):
  866. for position, extruder in self._global_container_stack.extruders.items():
  867. if extruder.isEnabled and not extruder.material.getMetaDataEntry("compatible"):
  868. return False
  869. if not extruder.material.getMetaDataEntry("compatible"):
  870. return False
  871. return True
  872. ## Update current quality type and machine after setting material
  873. def _updateQualityWithMaterial(self, *args):
  874. Logger.log("i", "Updating quality/quality_changes due to material change")
  875. current_quality_type = None
  876. if self._current_quality_group:
  877. current_quality_type = self._current_quality_group.quality_type
  878. candidate_quality_groups = self._quality_manager.getQualityGroups(self._global_container_stack)
  879. available_quality_types = {qt for qt, g in candidate_quality_groups.items() if g.is_available}
  880. Logger.log("d", "Current quality type = [%s]", current_quality_type)
  881. if not self.activeMaterialsCompatible():
  882. Logger.log("i", "Active materials are not compatible, setting all qualities to empty (Not Supported).")
  883. self._setEmptyQuality()
  884. return
  885. if not available_quality_types:
  886. Logger.log("i", "No available quality types found, setting all qualities to empty (Not Supported).")
  887. self._setEmptyQuality()
  888. return
  889. if current_quality_type in available_quality_types:
  890. Logger.log("i", "Current available quality type [%s] is available, applying changes.", current_quality_type)
  891. self._setQualityGroup(candidate_quality_groups[current_quality_type], empty_quality_changes = False)
  892. return
  893. # The current quality type is not available so we use the preferred quality type if it's available,
  894. # otherwise use one of the available quality types.
  895. quality_type = sorted(list(available_quality_types))[0]
  896. preferred_quality_type = self._global_container_stack.getMetaDataEntry("preferred_quality_type")
  897. if preferred_quality_type in available_quality_types:
  898. quality_type = preferred_quality_type
  899. Logger.log("i", "The current quality type [%s] is not available, switching to [%s] instead",
  900. current_quality_type, quality_type)
  901. self._setQualityGroup(candidate_quality_groups[quality_type], empty_quality_changes = True)
  902. def _updateMaterialWithVariant(self, position: Optional[str]):
  903. if position is None:
  904. position_list = list(self._global_container_stack.extruders.keys())
  905. else:
  906. position_list = [position]
  907. for position in position_list:
  908. extruder = self._global_container_stack.extruders[position]
  909. current_material_base_name = extruder.material.getMetaDataEntry("base_file")
  910. current_variant_name = None
  911. if extruder.variant.getId() != self._empty_variant_container.getId():
  912. current_variant_name = extruder.variant.getMetaDataEntry("name")
  913. from UM.Settings.Interfaces import PropertyEvaluationContext
  914. from cura.Settings.CuraContainerStack import _ContainerIndexes
  915. context = PropertyEvaluationContext(extruder)
  916. context.context["evaluate_from_container_index"] = _ContainerIndexes.DefinitionChanges
  917. material_diameter = self._global_container_stack.getProperty("material_diameter", "value", context)
  918. candidate_materials = self._material_manager.getAvailableMaterials(
  919. self._global_container_stack.definition.getId(),
  920. current_variant_name,
  921. material_diameter)
  922. if not candidate_materials:
  923. self._setMaterial(position, container_node = None)
  924. continue
  925. if current_material_base_name in candidate_materials:
  926. new_material = candidate_materials[current_material_base_name]
  927. self._setMaterial(position, new_material)
  928. continue
  929. # The current material is not available, find the preferred one
  930. material_node = self._material_manager.getDefaultMaterial(self._global_container_stack, current_variant_name)
  931. if material_node is not None:
  932. self._setMaterial(position, material_node)
  933. ## Given a printer definition name, select the right machine instance. In case it doesn't exist, create a new
  934. # instance with the same network key.
  935. @pyqtSlot(str)
  936. def switchPrinterType(self, machine_name):
  937. # Don't switch if the user tries to change to the same type of printer
  938. if self.activeMachineDefinitionName == machine_name:
  939. return
  940. # Get the definition id corresponding to this machine name
  941. machine_definition_id = ContainerRegistry.getInstance().findDefinitionContainers(name = machine_name)[0].getId()
  942. # Try to find a machine with the same network key
  943. new_machine = self.getMachine(machine_definition_id, metadata_filter = {"um_network_key": self.activeMachineNetworkKey})
  944. # If there is no machine, then create a new one and set it to the non-hidden instance
  945. if not new_machine:
  946. new_machine = CuraStackBuilder.createMachine(machine_definition_id + "_sync", machine_definition_id)
  947. new_machine.addMetaDataEntry("um_network_key", self.activeMachineNetworkKey)
  948. new_machine.addMetaDataEntry("connect_group_name", self.activeMachineNetworkGroupName)
  949. new_machine.addMetaDataEntry("hidden", False)
  950. else:
  951. Logger.log("i", "Found a %s with the key %s. Let's use it!", machine_name, self.activeMachineNetworkKey)
  952. new_machine.setMetaDataEntry("hidden", False)
  953. # Set the current printer instance to hidden (the metadata entry must exist)
  954. self._global_container_stack.setMetaDataEntry("hidden", True)
  955. self.setActiveMachine(new_machine.getId())
  956. @pyqtSlot(QObject)
  957. def applyRemoteConfiguration(self, configuration: ConfigurationModel):
  958. self.blurSettings.emit()
  959. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  960. self.switchPrinterType(configuration.printerType)
  961. for extruder_configuration in configuration.extruderConfigurations:
  962. position = str(extruder_configuration.position)
  963. variant_container_node = self._variant_manager.getVariantNode(self._global_container_stack.definition.getId(), extruder_configuration.hotendID)
  964. material_container_node = self._material_manager.getMaterialNodeByType(self._global_container_stack, extruder_configuration.hotendID,extruder_configuration.material.guid)
  965. if variant_container_node:
  966. self._setVariantNode(position, variant_container_node)
  967. else:
  968. self._global_container_stack.extruders[position].variant = self._empty_variant_container
  969. if material_container_node:
  970. self._setMaterial(position, material_container_node)
  971. else:
  972. self._global_container_stack.extruders[position].material = self._empty_material_container
  973. self._updateMaterialWithVariant(position)
  974. if configuration.buildplateConfiguration is not None:
  975. global_variant_container_node = self._variant_manager.getBuildplateVariantNode(self._global_container_stack.definition.getId(), configuration.buildplateConfiguration)
  976. if global_variant_container_node:
  977. self._setGlobalVariant(global_variant_container_node)
  978. else:
  979. self._global_container_stack.variant = self._empty_variant_container
  980. else:
  981. self._global_container_stack.variant = self._empty_variant_container
  982. self._updateQualityWithMaterial()
  983. ## Find all container stacks that has the pair 'key = value' in its metadata and replaces the value with 'new_value'
  984. def replaceContainersMetadata(self, key: str, value: str, new_value: str):
  985. machines = ContainerRegistry.getInstance().findContainerStacks(type = "machine")
  986. for machine in machines:
  987. if machine.getMetaDataEntry(key) == value:
  988. machine.setMetaDataEntry(key, new_value)
  989. @pyqtSlot("QVariant")
  990. def setGlobalVariant(self, container_node):
  991. self.blurSettings.emit()
  992. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  993. self._setGlobalVariant(container_node)
  994. self._updateMaterialWithVariant(None) # Update all materials
  995. self._updateQualityWithMaterial()
  996. @pyqtSlot(str, "QVariant")
  997. def setMaterial(self, position, container_node):
  998. position = str(position)
  999. self.blurSettings.emit()
  1000. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1001. self._setMaterial(position, container_node)
  1002. self._updateQualityWithMaterial()
  1003. @pyqtSlot(str, "QVariant")
  1004. def setVariantGroup(self, position, container_node):
  1005. position = str(position)
  1006. self.blurSettings.emit()
  1007. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1008. self._setVariantNode(position, container_node)
  1009. self._updateMaterialWithVariant(position)
  1010. self._updateQualityWithMaterial()
  1011. @pyqtSlot(QObject)
  1012. def setQualityGroup(self, quality_group, no_dialog = False):
  1013. self.blurSettings.emit()
  1014. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1015. self._setQualityGroup(quality_group)
  1016. # See if we need to show the Discard or Keep changes screen
  1017. if not no_dialog and self.hasUserSettings and Preferences.getInstance().getValue("cura/active_mode") == 1:
  1018. self._application.discardOrKeepProfileChanges()
  1019. @pyqtProperty(QObject, fset = setQualityGroup, notify = activeQualityGroupChanged)
  1020. def activeQualityGroup(self):
  1021. return self._current_quality_group
  1022. @pyqtSlot(QObject)
  1023. def setQualityChangesGroup(self, quality_changes_group, no_dialog = False):
  1024. self.blurSettings.emit()
  1025. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1026. self._setQualityChangesGroup(quality_changes_group)
  1027. # See if we need to show the Discard or Keep changes screen
  1028. if not no_dialog and self.hasUserSettings and Preferences.getInstance().getValue("cura/active_mode") == 1:
  1029. self._application.discardOrKeepProfileChanges()
  1030. @pyqtProperty(QObject, fset = setQualityChangesGroup, notify = activeQualityChangesGroupChanged)
  1031. def activeQualityChangesGroup(self):
  1032. return self._current_quality_changes_group
  1033. @pyqtProperty(str, notify = activeQualityGroupChanged)
  1034. def activeQualityOrQualityChangesName(self):
  1035. name = self._empty_quality_container.getName()
  1036. if self._current_quality_changes_group:
  1037. name = self._current_quality_changes_group.name
  1038. elif self._current_quality_group:
  1039. name = self._current_quality_group.name
  1040. return name
  1041. def _updateUponMaterialMetadataChange(self):
  1042. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1043. self._updateMaterialWithVariant(None)
  1044. self._updateQualityWithMaterial()