MachineManager.py 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470
  1. # Copyright (c) 2017 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. #Type hinting.
  4. from typing import Union, List, Dict
  5. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  6. from UM.Signal import Signal
  7. from PyQt5.QtCore import QObject, pyqtProperty, pyqtSignal, QTimer
  8. from UM.FlameProfiler import pyqtSlot
  9. from PyQt5.QtWidgets import QMessageBox
  10. from UM import Util
  11. from UM.Application import Application
  12. from UM.Preferences import Preferences
  13. from UM.Logger import Logger
  14. from UM.Message import Message
  15. from UM.Decorators import deprecated
  16. from UM.Settings.ContainerRegistry import ContainerRegistry
  17. from UM.Settings.ContainerStack import ContainerStack
  18. from UM.Settings.InstanceContainer import InstanceContainer
  19. from UM.Settings.SettingFunction import SettingFunction
  20. from UM.Signal import postponeSignals, CompressTechnique
  21. import UM.FlameProfiler
  22. from cura.QualityManager import QualityManager
  23. from cura.PrinterOutputDevice import PrinterOutputDevice
  24. from cura.Settings.ExtruderManager import ExtruderManager
  25. from .CuraStackBuilder import CuraStackBuilder
  26. from UM.i18n import i18nCatalog
  27. catalog = i18nCatalog("cura")
  28. from cura.Settings.ProfilesModel import ProfilesModel
  29. from typing import TYPE_CHECKING, Optional
  30. if TYPE_CHECKING:
  31. from UM.Settings.DefinitionContainer import DefinitionContainer
  32. from cura.Settings.CuraContainerStack import CuraContainerStack
  33. from cura.Settings.GlobalStack import GlobalStack
  34. class MachineManager(QObject):
  35. def __init__(self, parent = None):
  36. super().__init__(parent)
  37. self._active_container_stack = None # type: CuraContainerStack
  38. self._global_container_stack = None # type: GlobalStack
  39. # Used to store the new containers until after confirming the dialog
  40. self._new_variant_container = None
  41. self._new_buildplate_container = None
  42. self._new_material_container = None
  43. self._new_quality_containers = []
  44. self._error_check_timer = QTimer()
  45. self._error_check_timer.setInterval(250)
  46. self._error_check_timer.setSingleShot(True)
  47. self._error_check_timer.timeout.connect(self._updateStacksHaveErrors)
  48. self._instance_container_timer = QTimer()
  49. self._instance_container_timer.setInterval(250)
  50. self._instance_container_timer.setSingleShot(True)
  51. self._instance_container_timer.timeout.connect(self.__emitChangedSignals)
  52. Application.getInstance().globalContainerStackChanged.connect(self._onGlobalContainerChanged)
  53. Application.getInstance().getContainerRegistry().containerLoadComplete.connect(self._onInstanceContainersChanged)
  54. self._connected_to_profiles_model = False
  55. ## When the global container is changed, active material probably needs to be updated.
  56. self.globalContainerChanged.connect(self.activeMaterialChanged)
  57. self.globalContainerChanged.connect(self.activeVariantChanged)
  58. self.globalContainerChanged.connect(self.activeQualityChanged)
  59. self._stacks_have_errors = None
  60. self._empty_definition_changes_container = ContainerRegistry.getInstance().findContainers(id = "empty_definition_changes")[0]
  61. self._empty_variant_container = ContainerRegistry.getInstance().findContainers(id = "empty_variant")[0]
  62. self._empty_material_container = ContainerRegistry.getInstance().findContainers(id = "empty_material")[0]
  63. self._empty_quality_container = ContainerRegistry.getInstance().findContainers(id = "empty_quality")[0]
  64. self._empty_quality_changes_container = ContainerRegistry.getInstance().findContainers(id = "empty_quality_changes")[0]
  65. self._onGlobalContainerChanged()
  66. ExtruderManager.getInstance().activeExtruderChanged.connect(self._onActiveExtruderStackChanged)
  67. self._onActiveExtruderStackChanged()
  68. ExtruderManager.getInstance().activeExtruderChanged.connect(self.activeMaterialChanged)
  69. ExtruderManager.getInstance().activeExtruderChanged.connect(self.activeVariantChanged)
  70. ExtruderManager.getInstance().activeExtruderChanged.connect(self.activeQualityChanged)
  71. self.globalContainerChanged.connect(self.activeStackChanged)
  72. self.globalValueChanged.connect(self.activeStackValueChanged)
  73. ExtruderManager.getInstance().activeExtruderChanged.connect(self.activeStackChanged)
  74. self.activeStackChanged.connect(self.activeStackValueChanged)
  75. # when a user closed dialog check if any delayed material or variant changes need to be applied
  76. Application.getInstance().onDiscardOrKeepProfileChangesClosed.connect(self._executeDelayedActiveContainerStackChanges)
  77. Preferences.getInstance().addPreference("cura/active_machine", "")
  78. self._global_event_keys = set()
  79. active_machine_id = Preferences.getInstance().getValue("cura/active_machine")
  80. self._printer_output_devices = []
  81. Application.getInstance().getOutputDeviceManager().outputDevicesChanged.connect(self._onOutputDevicesChanged)
  82. # There might already be some output devices by the time the signal is connected
  83. self._onOutputDevicesChanged()
  84. if active_machine_id != "" and ContainerRegistry.getInstance().findContainerStacksMetadata(id = active_machine_id):
  85. # An active machine was saved, so restore it.
  86. self.setActiveMachine(active_machine_id)
  87. # Make sure _active_container_stack is properly initiated
  88. ExtruderManager.getInstance().setActiveExtruderIndex(0)
  89. self._auto_materials_changed = {}
  90. self._auto_hotends_changed = {}
  91. self._material_incompatible_message = Message(catalog.i18nc("@info:status",
  92. "The selected material is incompatible with the selected machine or configuration."),
  93. title = catalog.i18nc("@info:title", "Incompatible Material"))
  94. containers = ContainerRegistry.getInstance().findInstanceContainers(id = self.activeMaterialId)
  95. if containers:
  96. containers[0].nameChanged.connect(self._onMaterialNameChanged)
  97. globalContainerChanged = pyqtSignal() # Emitted whenever the global stack is changed (ie: when changing between printers, changing a global profile, but not when changing a value)
  98. activeMaterialChanged = pyqtSignal()
  99. activeVariantChanged = pyqtSignal()
  100. activeQualityChanged = pyqtSignal()
  101. activeStackChanged = pyqtSignal() # Emitted whenever the active stack is changed (ie: when changing between extruders, changing a profile, but not when changing a value)
  102. globalValueChanged = pyqtSignal() # Emitted whenever a value inside global container is changed.
  103. activeStackValueChanged = pyqtSignal() # Emitted whenever a value inside the active stack is changed.
  104. activeStackValidationChanged = pyqtSignal() # Emitted whenever a validation inside active container is changed
  105. stacksValidationChanged = pyqtSignal() # Emitted whenever a validation is changed
  106. blurSettings = pyqtSignal() # Emitted to force fields in the advanced sidebar to un-focus, so they update properly
  107. outputDevicesChanged = pyqtSignal()
  108. def _onOutputDevicesChanged(self) -> None:
  109. for printer_output_device in self._printer_output_devices:
  110. printer_output_device.hotendIdChanged.disconnect(self._onHotendIdChanged)
  111. printer_output_device.materialIdChanged.disconnect(self._onMaterialIdChanged)
  112. self._printer_output_devices = []
  113. for printer_output_device in Application.getInstance().getOutputDeviceManager().getOutputDevices():
  114. if isinstance(printer_output_device, PrinterOutputDevice):
  115. self._printer_output_devices.append(printer_output_device)
  116. printer_output_device.hotendIdChanged.connect(self._onHotendIdChanged)
  117. printer_output_device.materialIdChanged.connect(self._onMaterialIdChanged)
  118. self.outputDevicesChanged.emit()
  119. @property
  120. def newVariant(self):
  121. return self._new_variant_container
  122. @property
  123. def newBuildplate(self):
  124. return self._new_buildplate_container
  125. @property
  126. def newMaterial(self):
  127. return self._new_material_container
  128. @pyqtProperty("QVariantList", notify = outputDevicesChanged)
  129. def printerOutputDevices(self):
  130. return self._printer_output_devices
  131. @pyqtProperty(int, constant=True)
  132. def totalNumberOfSettings(self) -> int:
  133. return len(ContainerRegistry.getInstance().findDefinitionContainers(id = "fdmprinter")[0].getAllKeys())
  134. def _onHotendIdChanged(self):
  135. if not self._global_container_stack or not self._printer_output_devices:
  136. return
  137. active_printer_model = self._printer_output_devices[0].activePrinter
  138. if not active_printer_model:
  139. return
  140. change_found = False
  141. machine_id = self.activeMachineId
  142. extruders = sorted(ExtruderManager.getInstance().getMachineExtruders(machine_id),
  143. key=lambda k: k.getMetaDataEntry("position"))
  144. for extruder_model, extruder in zip(active_printer_model.extruders, extruders):
  145. containers = ContainerRegistry.getInstance().findInstanceContainersMetadata(type="variant",
  146. definition=self._global_container_stack.definition.getId(),
  147. name=extruder_model.hotendID)
  148. if containers:
  149. # The hotend ID is known.
  150. machine_id = self.activeMachineId
  151. if extruder.variant.getName() != extruder_model.hotendID:
  152. change_found = True
  153. self._auto_hotends_changed[extruder.getMetaDataEntry("position")] = containers[0]["id"]
  154. if change_found:
  155. # A change was found, let the output device handle this.
  156. self._printer_output_devices[0].materialHotendChangedMessage(self._materialHotendChangedCallback)
  157. def _onMaterialIdChanged(self):
  158. if not self._global_container_stack or not self._printer_output_devices:
  159. return
  160. active_printer_model = self._printer_output_devices[0].activePrinter
  161. if not active_printer_model:
  162. return
  163. change_found = False
  164. machine_id = self.activeMachineId
  165. extruders = sorted(ExtruderManager.getInstance().getMachineExtruders(machine_id),
  166. key=lambda k: k.getMetaDataEntry("position"))
  167. for extruder_model, extruder in zip(active_printer_model.extruders, extruders):
  168. if extruder_model.activeMaterial is None:
  169. continue
  170. containers = ContainerRegistry.getInstance().findInstanceContainersMetadata(type="material",
  171. definition=self._global_container_stack.definition.getId(),
  172. GUID=extruder_model.activeMaterial.guid)
  173. if containers:
  174. # The material is known.
  175. if extruder.material.getMetaDataEntry("GUID") != extruder_model.activeMaterial.guid:
  176. change_found = True
  177. if self._global_container_stack.definition.getMetaDataEntry("has_variants") and extruder.variant:
  178. variant_id = self.getQualityVariantId(self._global_container_stack.definition,
  179. extruder.variant)
  180. for container in containers:
  181. if container.get("variant") == variant_id:
  182. self._auto_materials_changed[extruder.getMetaDataEntry("position")] = container["id"]
  183. break
  184. else:
  185. # Just use the first result we found.
  186. self._auto_materials_changed[extruder.getMetaDataEntry("position")] = containers[0]["id"]
  187. if change_found:
  188. # A change was found, let the output device handle this.
  189. self._printer_output_devices[0].materialHotendChangedMessage(self._materialHotendChangedCallback)
  190. def _materialHotendChangedCallback(self, button):
  191. if button == QMessageBox.No:
  192. self._auto_materials_changed = {}
  193. self._auto_hotends_changed = {}
  194. return
  195. self._autoUpdateMaterials()
  196. self._autoUpdateHotends()
  197. def _autoUpdateMaterials(self):
  198. extruder_manager = ExtruderManager.getInstance()
  199. for position in self._auto_materials_changed:
  200. material_id = self._auto_materials_changed[position]
  201. old_index = extruder_manager.activeExtruderIndex
  202. if old_index != int(position):
  203. extruder_manager.setActiveExtruderIndex(int(position))
  204. else:
  205. old_index = None
  206. Logger.log("d", "Setting material of hotend %s to %s" % (position, material_id))
  207. self.setActiveMaterial(material_id)
  208. if old_index is not None:
  209. extruder_manager.setActiveExtruderIndex(old_index)
  210. self._auto_materials_changed = {} #Processed all of them now.
  211. def _autoUpdateHotends(self):
  212. extruder_manager = ExtruderManager.getInstance()
  213. for position in self._auto_hotends_changed:
  214. hotend_id = self._auto_hotends_changed[position]
  215. old_index = extruder_manager.activeExtruderIndex
  216. if old_index != int(position):
  217. extruder_manager.setActiveExtruderIndex(int(position))
  218. else:
  219. old_index = None
  220. Logger.log("d", "Setting hotend variant of hotend %s to %s" % (position, hotend_id))
  221. self.setActiveVariant(hotend_id)
  222. if old_index is not None:
  223. extruder_manager.setActiveExtruderIndex(old_index)
  224. self._auto_hotends_changed = {} # Processed all of them now.
  225. def _onGlobalContainerChanged(self):
  226. if self._global_container_stack:
  227. try:
  228. self._global_container_stack.nameChanged.disconnect(self._onMachineNameChanged)
  229. except TypeError: # pyQtSignal gives a TypeError when disconnecting from something that was already disconnected.
  230. pass
  231. try:
  232. self._global_container_stack.containersChanged.disconnect(self._onInstanceContainersChanged)
  233. except TypeError:
  234. pass
  235. try:
  236. self._global_container_stack.propertyChanged.disconnect(self._onPropertyChanged)
  237. except TypeError:
  238. pass
  239. for extruder_stack in ExtruderManager.getInstance().getActiveExtruderStacks():
  240. extruder_stack.propertyChanged.disconnect(self._onPropertyChanged)
  241. extruder_stack.containersChanged.disconnect(self._onInstanceContainersChanged)
  242. # update the local global container stack reference
  243. self._global_container_stack = Application.getInstance().getGlobalContainerStack()
  244. self.globalContainerChanged.emit()
  245. # after switching the global stack we reconnect all the signals and set the variant and material references
  246. if self._global_container_stack:
  247. Preferences.getInstance().setValue("cura/active_machine", self._global_container_stack.getId())
  248. self._global_container_stack.nameChanged.connect(self._onMachineNameChanged)
  249. self._global_container_stack.containersChanged.connect(self._onInstanceContainersChanged)
  250. self._global_container_stack.propertyChanged.connect(self._onPropertyChanged)
  251. # Global stack can have only a variant if it is a buildplate
  252. global_variant = self._global_container_stack.variant
  253. if global_variant != self._empty_variant_container:
  254. if global_variant.getMetaDataEntry("hardware_type") != "buildplate":
  255. self._global_container_stack.setVariant(self._empty_variant_container)
  256. # set the global material to empty as we now use the extruder stack at all times - CURA-4482
  257. global_material = self._global_container_stack.material
  258. if global_material != self._empty_material_container:
  259. self._global_container_stack.setMaterial(self._empty_material_container)
  260. # Listen for changes on all extruder stacks
  261. for extruder_stack in ExtruderManager.getInstance().getActiveExtruderStacks():
  262. extruder_stack.propertyChanged.connect(self._onPropertyChanged)
  263. extruder_stack.containersChanged.connect(self._onInstanceContainersChanged)
  264. self._error_check_timer.start()
  265. ## Update self._stacks_valid according to _checkStacksForErrors and emit if change.
  266. def _updateStacksHaveErrors(self):
  267. old_stacks_have_errors = self._stacks_have_errors
  268. self._stacks_have_errors = self._checkStacksHaveErrors()
  269. if old_stacks_have_errors != self._stacks_have_errors:
  270. self.stacksValidationChanged.emit()
  271. Application.getInstance().stacksValidationFinished.emit()
  272. def _onActiveExtruderStackChanged(self):
  273. self.blurSettings.emit() # Ensure no-one has focus.
  274. old_active_container_stack = self._active_container_stack
  275. self._active_container_stack = ExtruderManager.getInstance().getActiveExtruderStack()
  276. self._error_check_timer.start()
  277. if old_active_container_stack != self._active_container_stack:
  278. # Many methods and properties related to the active quality actually depend
  279. # on _active_container_stack. If it changes, then the properties change.
  280. self.activeQualityChanged.emit()
  281. def __emitChangedSignals(self):
  282. self.activeQualityChanged.emit()
  283. self.activeVariantChanged.emit()
  284. self.activeMaterialChanged.emit()
  285. self._updateStacksHaveErrors() # Prevents unwanted re-slices after changing machine
  286. self._error_check_timer.start()
  287. def _onProfilesModelChanged(self, *args):
  288. self.__emitChangedSignals()
  289. def _onInstanceContainersChanged(self, container):
  290. # This should not trigger the ProfilesModel to be created, or there will be an infinite recursion
  291. if not self._connected_to_profiles_model and ProfilesModel.hasInstance():
  292. # This triggers updating the qualityModel in SidebarSimple whenever ProfilesModel is updated
  293. Logger.log("d", "Connecting profiles model...")
  294. ProfilesModel.getInstance().itemsChanged.connect(self._onProfilesModelChanged)
  295. self._connected_to_profiles_model = True
  296. self._instance_container_timer.start()
  297. def _onPropertyChanged(self, key: str, property_name: str):
  298. if property_name == "value":
  299. # Notify UI items, such as the "changed" star in profile pull down menu.
  300. self.activeStackValueChanged.emit()
  301. elif property_name == "validationState":
  302. self._error_check_timer.start()
  303. @pyqtSlot(str)
  304. def setActiveMachine(self, stack_id: str) -> None:
  305. self.blurSettings.emit() # Ensure no-one has focus.
  306. self._cancelDelayedActiveContainerStackChanges()
  307. container_registry = ContainerRegistry.getInstance()
  308. containers = container_registry.findContainerStacks(id = stack_id)
  309. if containers:
  310. Application.getInstance().setGlobalContainerStack(containers[0])
  311. self.__emitChangedSignals()
  312. @pyqtSlot(str, str)
  313. def addMachine(self, name: str, definition_id: str) -> None:
  314. new_stack = CuraStackBuilder.createMachine(name, definition_id)
  315. if new_stack:
  316. # Instead of setting the global container stack here, we set the active machine and so the signals are emitted
  317. self.setActiveMachine(new_stack.getId())
  318. else:
  319. Logger.log("w", "Failed creating a new machine!")
  320. def _checkStacksHaveErrors(self) -> bool:
  321. if self._global_container_stack is None: #No active machine.
  322. return False
  323. if self._global_container_stack.hasErrors():
  324. return True
  325. for stack in ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()):
  326. if stack.hasErrors():
  327. return True
  328. return False
  329. ## Remove all instances from the top instanceContainer (effectively removing all user-changed settings)
  330. @pyqtSlot()
  331. def clearUserSettings(self):
  332. if not self._active_container_stack:
  333. return
  334. self.blurSettings.emit()
  335. user_settings = self._active_container_stack.getTop()
  336. user_settings.clear()
  337. ## Check if the global_container has instances in the user container
  338. @pyqtProperty(bool, notify = activeStackValueChanged)
  339. def hasUserSettings(self) -> bool:
  340. if not self._global_container_stack:
  341. return False
  342. if self._global_container_stack.getTop().findInstances():
  343. return True
  344. stacks = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
  345. for stack in stacks:
  346. if stack.getTop().findInstances():
  347. return True
  348. return False
  349. @pyqtProperty(int, notify = activeStackValueChanged)
  350. def numUserSettings(self) -> int:
  351. if not self._global_container_stack:
  352. return 0
  353. num_user_settings = 0
  354. num_user_settings += len(self._global_container_stack.getTop().findInstances())
  355. stacks = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
  356. for stack in stacks:
  357. num_user_settings += len(stack.getTop().findInstances())
  358. return num_user_settings
  359. ## Delete a user setting from the global stack and all extruder stacks.
  360. # \param key \type{str} the name of the key to delete
  361. @pyqtSlot(str)
  362. def clearUserSettingAllCurrentStacks(self, key: str):
  363. if not self._global_container_stack:
  364. return
  365. send_emits_containers = []
  366. top_container = self._global_container_stack.getTop()
  367. top_container.removeInstance(key, postpone_emit=True)
  368. send_emits_containers.append(top_container)
  369. linked = not self._global_container_stack.getProperty(key, "settable_per_extruder") or \
  370. self._global_container_stack.getProperty(key, "limit_to_extruder") != "-1"
  371. if not linked:
  372. stack = ExtruderManager.getInstance().getActiveExtruderStack()
  373. stacks = [stack]
  374. else:
  375. stacks = ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId())
  376. for stack in stacks:
  377. if stack is not None:
  378. container = stack.getTop()
  379. container.removeInstance(key, postpone_emit=True)
  380. send_emits_containers.append(container)
  381. for container in send_emits_containers:
  382. container.sendPostponedEmits()
  383. ## Check if none of the stacks contain error states
  384. # Note that the _stacks_have_errors is cached due to performance issues
  385. # Calling _checkStack(s)ForErrors on every change is simply too expensive
  386. @pyqtProperty(bool, notify = stacksValidationChanged)
  387. def stacksHaveErrors(self) -> bool:
  388. return bool(self._stacks_have_errors)
  389. @pyqtProperty(str, notify = activeStackChanged)
  390. def activeUserProfileId(self) -> str:
  391. if self._active_container_stack:
  392. return self._active_container_stack.getTop().getId()
  393. return ""
  394. @pyqtProperty(str, notify = globalContainerChanged)
  395. def activeMachineName(self) -> str:
  396. if self._global_container_stack:
  397. return self._global_container_stack.getName()
  398. return ""
  399. @pyqtProperty(str, notify = globalContainerChanged)
  400. def activeMachineId(self) -> str:
  401. if self._global_container_stack:
  402. return self._global_container_stack.getId()
  403. return ""
  404. @pyqtProperty(QObject, notify = globalContainerChanged)
  405. def activeMachine(self) -> Optional["GlobalStack"]:
  406. return self._global_container_stack
  407. @pyqtProperty(str, notify = activeStackChanged)
  408. def activeStackId(self) -> str:
  409. if self._active_container_stack:
  410. return self._active_container_stack.getId()
  411. return ""
  412. @pyqtProperty(str, notify = activeMaterialChanged)
  413. def activeMaterialName(self) -> str:
  414. if self._active_container_stack:
  415. material = self._active_container_stack.material
  416. if material:
  417. return material.getName()
  418. return ""
  419. @pyqtProperty("QVariantList", notify=activeVariantChanged)
  420. def activeVariantNames(self) -> List[str]:
  421. result = []
  422. active_stacks = ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks()
  423. if active_stacks is not None:
  424. for stack in active_stacks:
  425. variant_container = stack.variant
  426. if variant_container and variant_container != self._empty_variant_container:
  427. result.append(variant_container.getName())
  428. return result
  429. @pyqtProperty("QVariantList", notify = activeMaterialChanged)
  430. def activeMaterialNames(self) -> List[str]:
  431. result = []
  432. active_stacks = ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks()
  433. if active_stacks is not None:
  434. for stack in active_stacks:
  435. material_container = stack.material
  436. if material_container and material_container != self._empty_material_container:
  437. result.append(material_container.getName())
  438. return result
  439. @pyqtProperty(str, notify=activeMaterialChanged)
  440. def activeMaterialId(self) -> str:
  441. if self._active_container_stack:
  442. material = self._active_container_stack.material
  443. if material:
  444. return material.getId()
  445. return ""
  446. @pyqtProperty("QVariantMap", notify = activeVariantChanged)
  447. def allActiveVariantIds(self) -> Dict[str, str]:
  448. result = {}
  449. active_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  450. if active_stacks is not None: #If we have a global stack.
  451. for stack in active_stacks:
  452. variant_container = stack.variant
  453. if not variant_container:
  454. continue
  455. result[stack.getId()] = variant_container.getId()
  456. return result
  457. ## Gets a dict with the active materials ids set in all extruder stacks and the global stack
  458. # (when there is one extruder, the material is set in the global stack)
  459. #
  460. # \return The material ids in all stacks
  461. @pyqtProperty("QVariantMap", notify = activeMaterialChanged)
  462. def allActiveMaterialIds(self) -> Dict[str, str]:
  463. result = {}
  464. active_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  465. if active_stacks is not None: # If we have extruder stacks
  466. for stack in active_stacks:
  467. material_container = stack.material
  468. if not material_container:
  469. continue
  470. result[stack.getId()] = material_container.getId()
  471. return result
  472. ## Gets the layer height of the currently active quality profile.
  473. #
  474. # This is indicated together with the name of the active quality profile.
  475. #
  476. # \return The layer height of the currently active quality profile. If
  477. # there is no quality profile, this returns 0.
  478. @pyqtProperty(float, notify=activeQualityChanged)
  479. def activeQualityLayerHeight(self) -> float:
  480. if not self._global_container_stack:
  481. return 0
  482. quality_changes = self._global_container_stack.qualityChanges
  483. if quality_changes:
  484. value = self._global_container_stack.getRawProperty("layer_height", "value", skip_until_container = quality_changes.getId())
  485. if isinstance(value, SettingFunction):
  486. value = value(self._global_container_stack)
  487. return value
  488. quality = self._global_container_stack.quality
  489. if quality:
  490. value = self._global_container_stack.getRawProperty("layer_height", "value", skip_until_container = quality.getId())
  491. if isinstance(value, SettingFunction):
  492. value = value(self._global_container_stack)
  493. return value
  494. return 0 # No quality profile.
  495. ## Get the Material ID associated with the currently active material
  496. # \returns MaterialID (string) if found, empty string otherwise
  497. @pyqtProperty(str, notify=activeQualityChanged)
  498. def activeQualityMaterialId(self) -> str:
  499. if self._active_container_stack:
  500. quality = self._active_container_stack.quality
  501. if quality:
  502. material_id = quality.getMetaDataEntry("material")
  503. if material_id:
  504. # if the currently active machine inherits its qualities from a different machine
  505. # definition, make sure to return a material that is relevant to that machine definition
  506. definition_id = self.activeDefinitionId
  507. quality_definition_id = self.activeQualityDefinitionId
  508. if definition_id != quality_definition_id:
  509. material_id = material_id.replace(definition_id, quality_definition_id, 1)
  510. return material_id
  511. return ""
  512. @pyqtProperty(str, notify=activeQualityChanged)
  513. def activeQualityName(self) -> str:
  514. if self._active_container_stack and self._global_container_stack:
  515. quality = self._global_container_stack.qualityChanges
  516. if quality and not isinstance(quality, type(self._empty_quality_changes_container)):
  517. return quality.getName()
  518. quality = self._active_container_stack.quality
  519. if quality:
  520. return quality.getName()
  521. return ""
  522. @pyqtProperty(str, notify=activeQualityChanged)
  523. def activeQualityId(self) -> str:
  524. if self._active_container_stack:
  525. quality = self._active_container_stack.quality
  526. if isinstance(quality, type(self._empty_quality_container)):
  527. return ""
  528. quality_changes = self._active_container_stack.qualityChanges
  529. if quality and quality_changes:
  530. if isinstance(quality_changes, type(self._empty_quality_changes_container)):
  531. # It's a built-in profile
  532. return quality.getId()
  533. else:
  534. # Custom profile
  535. return quality_changes.getId()
  536. return ""
  537. @pyqtProperty(str, notify=activeQualityChanged)
  538. def globalQualityId(self) -> str:
  539. if self._global_container_stack:
  540. quality = self._global_container_stack.qualityChanges
  541. if quality and not isinstance(quality, type(self._empty_quality_changes_container)):
  542. return quality.getId()
  543. quality = self._global_container_stack.quality
  544. if quality:
  545. return quality.getId()
  546. return ""
  547. @pyqtProperty(str, notify=activeVariantChanged)
  548. def globalVariantId(self) -> str:
  549. if self._global_container_stack:
  550. variant = self._global_container_stack.variant
  551. if variant and not isinstance(variant, type(self._empty_variant_container)):
  552. return variant.getId()
  553. return ""
  554. @pyqtProperty(str, notify = activeQualityChanged)
  555. def activeQualityType(self) -> str:
  556. if self._active_container_stack:
  557. quality = self._active_container_stack.quality
  558. if quality:
  559. return quality.getMetaDataEntry("quality_type")
  560. return ""
  561. @pyqtProperty(bool, notify = activeQualityChanged)
  562. def isActiveQualitySupported(self) -> bool:
  563. if self._active_container_stack:
  564. quality = self._active_container_stack.quality
  565. if quality:
  566. return Util.parseBool(quality.getMetaDataEntry("supported", True))
  567. return False
  568. ## Returns whether there is anything unsupported in the current set-up.
  569. #
  570. # The current set-up signifies the global stack and all extruder stacks,
  571. # so this indicates whether there is any container in any of the container
  572. # stacks that is not marked as supported.
  573. @pyqtProperty(bool, notify = activeQualityChanged)
  574. def isCurrentSetupSupported(self) -> bool:
  575. if not self._global_container_stack:
  576. return False
  577. for stack in [self._global_container_stack] + list(self._global_container_stack.extruders.values()):
  578. for container in stack.getContainers():
  579. if not container:
  580. return False
  581. if not Util.parseBool(container.getMetaDataEntry("supported", True)):
  582. return False
  583. return True
  584. ## Get the Quality ID associated with the currently active extruder
  585. # Note that this only returns the "quality", not the "quality_changes"
  586. # \returns QualityID (string) if found, empty string otherwise
  587. # \sa activeQualityId()
  588. # \todo Ideally, this method would be named activeQualityId(), and the other one
  589. # would be named something like activeQualityOrQualityChanges() for consistency
  590. @pyqtProperty(str, notify = activeQualityChanged)
  591. def activeQualityContainerId(self) -> str:
  592. # We're using the active stack instead of the global stack in case the list of qualities differs per extruder
  593. if self._global_container_stack:
  594. quality = self._active_container_stack.quality
  595. if quality:
  596. return quality.getId()
  597. return ""
  598. @pyqtProperty(str, notify = activeQualityChanged)
  599. def activeQualityChangesId(self) -> str:
  600. if self._active_container_stack:
  601. quality_changes = self._active_container_stack.qualityChanges
  602. if quality_changes and not isinstance(quality_changes, type(self._empty_quality_changes_container)):
  603. return quality_changes.getId()
  604. return ""
  605. ## Check if a container is read_only
  606. @pyqtSlot(str, result = bool)
  607. def isReadOnly(self, container_id: str) -> bool:
  608. return ContainerRegistry.getInstance().isReadOnly(container_id)
  609. ## Copy the value of the setting of the current extruder to all other extruders as well as the global container.
  610. @pyqtSlot(str)
  611. def copyValueToExtruders(self, key: str):
  612. new_value = self._active_container_stack.getProperty(key, "value")
  613. extruder_stacks = [stack for stack in ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId())]
  614. # check in which stack the value has to be replaced
  615. for extruder_stack in extruder_stacks:
  616. if extruder_stack != self._active_container_stack and extruder_stack.getProperty(key, "value") != new_value:
  617. extruder_stack.userChanges.setProperty(key, "value", new_value) # TODO: nested property access, should be improved
  618. ## Set the active material by switching out a container
  619. # Depending on from/to material+current variant, a quality profile is chosen and set.
  620. @pyqtSlot(str)
  621. def setActiveMaterial(self, material_id: str, always_discard_changes = False):
  622. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  623. containers = ContainerRegistry.getInstance().findInstanceContainers(id = material_id)
  624. if not containers or not self._active_container_stack:
  625. return
  626. material_container = containers[0]
  627. Logger.log("d", "Attempting to change the active material to %s", material_id)
  628. old_material = self._active_container_stack.material
  629. old_quality = self._active_container_stack.quality
  630. old_quality_type = None
  631. if old_quality and old_quality.getId() != self._empty_quality_container.getId():
  632. old_quality_type = old_quality.getMetaDataEntry("quality_type")
  633. old_quality_changes = self._active_container_stack.qualityChanges
  634. if not old_material:
  635. Logger.log("w", "While trying to set the active material, no material was found to replace it.")
  636. return
  637. if old_quality_changes and isinstance(old_quality_changes, type(self._empty_quality_changes_container)):
  638. old_quality_changes = None
  639. self.blurSettings.emit()
  640. old_material.nameChanged.disconnect(self._onMaterialNameChanged)
  641. self._new_material_container = material_container # self._active_container_stack will be updated with a delay
  642. Logger.log("d", "Active material changed")
  643. material_container.nameChanged.connect(self._onMaterialNameChanged)
  644. if material_container.getMetaDataEntry("compatible") == False:
  645. self._material_incompatible_message.show()
  646. else:
  647. self._material_incompatible_message.hide()
  648. quality_type = None
  649. new_quality_id = None
  650. if old_quality:
  651. new_quality_id = old_quality.getId()
  652. quality_type = old_quality.getMetaDataEntry("quality_type")
  653. if old_quality_changes:
  654. quality_type = old_quality_changes.getMetaDataEntry("quality_type")
  655. new_quality_id = old_quality_changes.getId()
  656. global_stack = Application.getInstance().getGlobalContainerStack()
  657. if global_stack:
  658. quality_manager = QualityManager.getInstance()
  659. candidate_quality = None
  660. if quality_type:
  661. candidate_quality = quality_manager.findQualityByQualityType(quality_type,
  662. quality_manager.getWholeMachineDefinition(global_stack.definition),
  663. [material_container.getMetaData()])
  664. if not candidate_quality or candidate_quality.getId() == self._empty_quality_changes_container:
  665. Logger.log("d", "Attempting to find fallback quality")
  666. # Fall back to a quality (which must be compatible with all other extruders)
  667. new_qualities = quality_manager.findAllUsableQualitiesForMachineAndExtruders(
  668. self._global_container_stack, ExtruderManager.getInstance().getExtruderStacks())
  669. quality_types = sorted([q.getMetaDataEntry("quality_type") for q in new_qualities], reverse = True)
  670. quality_type_to_use = None
  671. if quality_types:
  672. # try to use the same quality as before, otherwise the first one in the quality_types
  673. quality_type_to_use = quality_types[0]
  674. if old_quality_type is not None and old_quality_type in quality_type_to_use:
  675. quality_type_to_use = old_quality_type
  676. new_quality = None
  677. for q in new_qualities:
  678. if quality_type_to_use is not None and q.getMetaDataEntry("quality_type") == quality_type_to_use:
  679. new_quality = q
  680. break
  681. if new_quality is not None:
  682. new_quality_id = new_quality.getId() # Just pick the first available one
  683. else:
  684. Logger.log("w", "No quality profile found that matches the current machine and extruders.")
  685. else:
  686. if not old_quality_changes:
  687. new_quality_id = candidate_quality.getId()
  688. self.setActiveQuality(new_quality_id, always_discard_changes = always_discard_changes)
  689. @pyqtSlot(str)
  690. def setActiveVariant(self, variant_id: str, always_discard_changes = False):
  691. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  692. containers = ContainerRegistry.getInstance().findInstanceContainers(id = variant_id)
  693. if not containers or not self._active_container_stack:
  694. return
  695. Logger.log("d", "Attempting to change the active variant to %s", variant_id)
  696. old_variant = self._active_container_stack.variant
  697. old_material = self._active_container_stack.material
  698. if old_variant:
  699. self.blurSettings.emit()
  700. self._new_variant_container = containers[0] # self._active_container_stack will be updated with a delay
  701. Logger.log("d", "Active variant changed to {active_variant_id}".format(active_variant_id = containers[0].getId()))
  702. preferred_material_name = None
  703. if old_material:
  704. preferred_material_name = old_material.getName()
  705. preferred_material_id = self._updateMaterialContainer(self._global_container_stack.definition, self._global_container_stack, containers[0], preferred_material_name).id
  706. self.setActiveMaterial(preferred_material_id, always_discard_changes = always_discard_changes)
  707. else:
  708. Logger.log("w", "While trying to set the active variant, no variant was found to replace.")
  709. @pyqtSlot(str)
  710. def setActiveVariantBuildplate(self, variant_buildplate_id: str):
  711. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  712. containers = ContainerRegistry.getInstance().findInstanceContainers(id = variant_buildplate_id)
  713. if not containers or not self._global_container_stack:
  714. return
  715. Logger.log("d", "Attempting to change the active buildplate to %s", variant_buildplate_id)
  716. old_buildplate = self._global_container_stack.variant
  717. if old_buildplate:
  718. self.blurSettings.emit()
  719. self._new_buildplate_container = containers[0] # self._active_container_stack will be updated with a delay
  720. Logger.log("d", "Active buildplate changed to {active_variant_buildplate_id}".format(active_variant_buildplate_id = containers[0].getId()))
  721. # Force set the active quality as it is so the values are updated
  722. self.setActiveMaterial(self._active_container_stack.material.getId())
  723. else:
  724. Logger.log("w", "While trying to set the active buildplate, no buildplate was found to replace.")
  725. ## set the active quality
  726. # \param quality_id The quality_id of either a quality or a quality_changes
  727. @pyqtSlot(str)
  728. def setActiveQuality(self, quality_id: str, always_discard_changes = False):
  729. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  730. self.blurSettings.emit()
  731. Logger.log("d", "Attempting to change the active quality to %s", quality_id)
  732. containers = ContainerRegistry.getInstance().findInstanceContainersMetadata(id = quality_id)
  733. if not containers or not self._global_container_stack:
  734. return
  735. # Quality profile come in two flavours: type=quality and type=quality_changes
  736. # If we found a quality_changes profile then look up its parent quality profile.
  737. container_type = containers[0].get("type")
  738. quality_name = containers[0]["name"]
  739. quality_type = containers[0].get("quality_type")
  740. # Get quality container and optionally the quality_changes container.
  741. if container_type == "quality":
  742. new_quality_settings_list = self.determineQualityAndQualityChangesForQualityType(quality_type)
  743. elif container_type == "quality_changes":
  744. new_quality_settings_list = self._determineQualityAndQualityChangesForQualityChanges(quality_name)
  745. else:
  746. Logger.log("e", "Tried to set quality to a container that is not of the right type: {container_id}".format(container_id = containers[0]["id"]))
  747. return
  748. # Check if it was at all possible to find new settings
  749. if new_quality_settings_list is None:
  750. return
  751. # check if any of the stacks have a not supported profile
  752. # if that is the case, all stacks should have a not supported state (otherwise it will show quality_type normal)
  753. has_not_supported_quality = False
  754. # check all stacks for not supported
  755. for setting_info in new_quality_settings_list:
  756. if setting_info["quality"].getMetaDataEntry("quality_type") == "not_supported":
  757. has_not_supported_quality = True
  758. break
  759. # set all stacks to not supported if that's the case
  760. if has_not_supported_quality:
  761. for setting_info in new_quality_settings_list:
  762. setting_info["quality"] = self._empty_quality_container
  763. self._new_quality_containers.clear()
  764. # store the upcoming quality profile changes per stack for later execution
  765. # this prevents re-slicing before the user has made a choice in the discard or keep dialog
  766. # (see _executeDelayedActiveContainerStackChanges)
  767. for setting_info in new_quality_settings_list:
  768. stack = setting_info["stack"]
  769. stack_quality = setting_info["quality"]
  770. stack_quality_changes = setting_info["quality_changes"]
  771. self._new_quality_containers.append({
  772. "stack": stack,
  773. "quality": stack_quality,
  774. "quality_changes": stack_quality_changes
  775. })
  776. Logger.log("d", "Active quality changed")
  777. # show the keep/discard dialog after the containers have been switched. Otherwise, the default values on
  778. # the dialog will be the those before the switching.
  779. self._executeDelayedActiveContainerStackChanges()
  780. if self.hasUserSettings and Preferences.getInstance().getValue("cura/active_mode") == 1 and not always_discard_changes:
  781. Application.getInstance().discardOrKeepProfileChanges()
  782. ## Used to update material and variant in the active container stack with a delay.
  783. # This delay prevents the stack from triggering a lot of signals (eventually resulting in slicing)
  784. # before the user decided to keep or discard any of their changes using the dialog.
  785. # The Application.onDiscardOrKeepProfileChangesClosed signal triggers this method.
  786. def _executeDelayedActiveContainerStackChanges(self):
  787. Logger.log("d", "Applying configuration changes...")
  788. if self._new_variant_container is not None:
  789. self._active_container_stack.variant = self._new_variant_container
  790. self._new_variant_container = None
  791. if self._new_buildplate_container is not None:
  792. self._global_container_stack.variant = self._new_buildplate_container
  793. self._new_buildplate_container = None
  794. if self._new_material_container is not None:
  795. self._active_container_stack.material = self._new_material_container
  796. self._new_material_container = None
  797. # apply the new quality to all stacks
  798. if self._new_quality_containers:
  799. for new_quality in self._new_quality_containers:
  800. self._replaceQualityOrQualityChangesInStack(new_quality["stack"], new_quality["quality"], postpone_emit = True)
  801. self._replaceQualityOrQualityChangesInStack(new_quality["stack"], new_quality["quality_changes"], postpone_emit = True)
  802. for new_quality in self._new_quality_containers:
  803. new_quality["stack"].nameChanged.connect(self._onQualityNameChanged)
  804. new_quality["stack"].sendPostponedEmits() # Send the signals that were postponed in _replaceQualityOrQualityChangesInStack
  805. self._new_quality_containers.clear()
  806. Logger.log("d", "New configuration applied")
  807. ## Cancel set changes for material and variant in the active container stack.
  808. # Used for ignoring any changes when switching between printers (setActiveMachine)
  809. def _cancelDelayedActiveContainerStackChanges(self):
  810. self._new_material_container = None
  811. self._new_buildplate_container = None
  812. self._new_variant_container = None
  813. ## Determine the quality and quality changes settings for the current machine for a quality name.
  814. #
  815. # \param quality_name \type{str} the name of the quality.
  816. # \return \type{List[Dict]} with keys "stack", "quality" and "quality_changes".
  817. @UM.FlameProfiler.profile
  818. def determineQualityAndQualityChangesForQualityType(self, quality_type: str) -> List[Dict[str, Union["CuraContainerStack", InstanceContainer]]]:
  819. quality_manager = QualityManager.getInstance()
  820. result = []
  821. empty_quality_changes = self._empty_quality_changes_container
  822. global_container_stack = self._global_container_stack
  823. if not global_container_stack:
  824. return []
  825. global_machine_definition = quality_manager.getParentMachineDefinition(global_container_stack.definition)
  826. extruder_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  827. # find qualities for extruders
  828. for extruder_stack in extruder_stacks:
  829. material_metadata = extruder_stack.material.getMetaData()
  830. # TODO: fix this
  831. if self._new_material_container and extruder_stack.getId() == self._active_container_stack.getId():
  832. material_metadata = self._new_material_container.getMetaData()
  833. quality = quality_manager.findQualityByQualityType(quality_type, global_machine_definition, [material_metadata])
  834. if not quality:
  835. # No quality profile is found for this quality type.
  836. quality = self._empty_quality_container
  837. result.append({
  838. "stack": extruder_stack,
  839. "quality": quality,
  840. "quality_changes": empty_quality_changes
  841. })
  842. # also find a global quality for the machine
  843. global_quality = quality_manager.findQualityByQualityType(quality_type, global_machine_definition, [], global_quality = "True")
  844. # if there is not global quality but we're using a single extrusion machine, copy the quality of the first extruder - CURA-4482
  845. if not global_quality and len(extruder_stacks) == 1:
  846. global_quality = result[0]["quality"]
  847. # if there is still no global quality, set it to empty (not supported)
  848. if not global_quality:
  849. global_quality = self._empty_quality_container
  850. result.append({
  851. "stack": global_container_stack,
  852. "quality": global_quality,
  853. "quality_changes": empty_quality_changes
  854. })
  855. return result
  856. ## Determine the quality and quality changes settings for the current machine for a quality changes name.
  857. #
  858. # \param quality_changes_name \type{str} the name of the quality changes.
  859. # \return \type{List[Dict]} with keys "stack", "quality" and "quality_changes".
  860. def _determineQualityAndQualityChangesForQualityChanges(self, quality_changes_name: str) -> Optional[List[Dict[str, Union["CuraContainerStack", InstanceContainer]]]]:
  861. result = []
  862. quality_manager = QualityManager.getInstance()
  863. global_container_stack = self._global_container_stack
  864. global_machine_definition = quality_manager.getParentMachineDefinition(global_container_stack.definition)
  865. quality_changes_profiles = quality_manager.findQualityChangesByName(quality_changes_name, global_machine_definition)
  866. global_quality_changes = [qcp for qcp in quality_changes_profiles if qcp.getMetaDataEntry("extruder") is None]
  867. if global_quality_changes:
  868. global_quality_changes = global_quality_changes[0]
  869. else:
  870. Logger.log("e", "Could not find the global quality changes container with name %s", quality_changes_name)
  871. return None
  872. # For the global stack, find a quality which matches the quality_type in
  873. # the quality changes profile and also satisfies any material constraints.
  874. quality_type = global_quality_changes.getMetaDataEntry("quality_type")
  875. extruder_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  876. # append the extruder quality changes
  877. for extruder_stack in extruder_stacks:
  878. extruder_definition = quality_manager.getParentMachineDefinition(extruder_stack.definition)
  879. quality_changes_list = [qcp for qcp in quality_changes_profiles if qcp.getMetaDataEntry("extruder") == extruder_definition.getId()]
  880. if quality_changes_list:
  881. quality_changes = quality_changes_list[0]
  882. else:
  883. quality_changes = global_quality_changes
  884. if not quality_changes:
  885. quality_changes = self._empty_quality_changes_container
  886. material_metadata = extruder_stack.material.getMetaData()
  887. if self._new_material_container and self._active_container_stack.getId() == extruder_stack.getId():
  888. material_metadata = self._new_material_container.getMetaData()
  889. quality = quality_manager.findQualityByQualityType(quality_type, global_machine_definition, [material_metadata])
  890. if not quality:
  891. # No quality profile found for this quality type.
  892. quality = self._empty_quality_container
  893. result.append({
  894. "stack": extruder_stack,
  895. "quality": quality,
  896. "quality_changes": quality_changes
  897. })
  898. # append the global quality changes
  899. global_quality = quality_manager.findQualityByQualityType(quality_type, global_machine_definition, global_quality = "True")
  900. # if there is not global quality but we're using a single extrusion machine, copy the quality of the first extruder - CURA-4482
  901. if not global_quality and len(extruder_stacks) == 1:
  902. global_quality = result[0]["quality"]
  903. # if still no global quality changes are found we set it to empty (not supported)
  904. if not global_quality:
  905. global_quality = self._empty_quality_container
  906. result.append({
  907. "stack": global_container_stack,
  908. "quality": global_quality,
  909. "quality_changes": global_quality_changes
  910. })
  911. return result
  912. def _replaceQualityOrQualityChangesInStack(self, stack: "CuraContainerStack", container: "InstanceContainer", postpone_emit = False):
  913. # Disconnect the signal handling from the old container.
  914. container_type = container.getMetaDataEntry("type")
  915. if container_type == "quality":
  916. stack.quality.nameChanged.disconnect(self._onQualityNameChanged)
  917. stack.setQuality(container, postpone_emit = postpone_emit)
  918. stack.quality.nameChanged.connect(self._onQualityNameChanged)
  919. elif container_type == "quality_changes" or container_type is None:
  920. # If the container is an empty container, we need to change the quality_changes.
  921. # Quality can never be set to empty.
  922. stack.qualityChanges.nameChanged.disconnect(self._onQualityNameChanged)
  923. stack.setQualityChanges(container, postpone_emit = postpone_emit)
  924. stack.qualityChanges.nameChanged.connect(self._onQualityNameChanged)
  925. self._onQualityNameChanged()
  926. @pyqtProperty(str, notify = activeVariantChanged)
  927. def activeVariantName(self) -> str:
  928. if self._active_container_stack:
  929. variant = self._active_container_stack.variant
  930. if variant:
  931. return variant.getName()
  932. return ""
  933. @pyqtProperty(str, notify = activeVariantChanged)
  934. def activeVariantId(self) -> str:
  935. if self._active_container_stack:
  936. variant = self._active_container_stack.variant
  937. if variant:
  938. return variant.getId()
  939. return ""
  940. @pyqtProperty(str, notify = activeVariantChanged)
  941. def activeVariantBuildplateName(self) -> str:
  942. if self._global_container_stack:
  943. variant = self._global_container_stack.variant
  944. if variant:
  945. return variant.getName()
  946. return ""
  947. @pyqtProperty(str, notify = globalContainerChanged)
  948. def activeDefinitionId(self) -> str:
  949. if self._global_container_stack:
  950. return self._global_container_stack.definition.id
  951. return ""
  952. @pyqtProperty(str, notify=globalContainerChanged)
  953. def activeDefinitionName(self) -> str:
  954. if self._global_container_stack:
  955. return self._global_container_stack.definition.getName()
  956. return ""
  957. ## Get the Definition ID to use to select quality profiles for the currently active machine
  958. # \returns DefinitionID (string) if found, empty string otherwise
  959. # \sa getQualityDefinitionId
  960. @pyqtProperty(str, notify = globalContainerChanged)
  961. def activeQualityDefinitionId(self) -> str:
  962. if self._global_container_stack:
  963. return self.getQualityDefinitionId(self._global_container_stack.definition)
  964. return ""
  965. ## Get the Definition ID to use to select quality profiles for machines of the specified definition
  966. # This is normally the id of the definition itself, but machines can specify a different definition to inherit qualities from
  967. # \param definition (DefinitionContainer) machine definition
  968. # \returns DefinitionID (string) if found, empty string otherwise
  969. def getQualityDefinitionId(self, definition: "DefinitionContainer") -> str:
  970. return QualityManager.getInstance().getParentMachineDefinition(definition).getId()
  971. ## Get the Variant ID to use to select quality profiles for the currently active variant
  972. # \returns VariantID (string) if found, empty string otherwise
  973. # \sa getQualityVariantId
  974. @pyqtProperty(str, notify = activeVariantChanged)
  975. def activeQualityVariantId(self) -> str:
  976. if self._active_container_stack:
  977. variant = self._active_container_stack.variant
  978. if variant:
  979. return self.getQualityVariantId(self._global_container_stack.definition, variant)
  980. return ""
  981. ## Get the Variant ID to use to select quality profiles for variants of the specified definitions
  982. # This is normally the id of the variant itself, but machines can specify a different definition
  983. # to inherit qualities from, which has consequences for the variant to use as well
  984. # \param definition (DefinitionContainer) machine definition
  985. # \param variant (InstanceContainer) variant definition
  986. # \returns VariantID (string) if found, empty string otherwise
  987. def getQualityVariantId(self, definition: "DefinitionContainer", variant: "InstanceContainer") -> str:
  988. variant_id = variant.getId()
  989. definition_id = definition.getId()
  990. quality_definition_id = self.getQualityDefinitionId(definition)
  991. if definition_id != quality_definition_id:
  992. variant_id = variant_id.replace(definition_id, quality_definition_id, 1)
  993. return variant_id
  994. ## Gets how the active definition calls variants
  995. # Caveat: per-definition-variant-title is currently not translated (though the fallback is)
  996. @pyqtProperty(str, notify = globalContainerChanged)
  997. def activeDefinitionVariantsName(self) -> str:
  998. fallback_title = catalog.i18nc("@label", "Nozzle")
  999. if self._global_container_stack:
  1000. return self._global_container_stack.definition.getMetaDataEntry("variants_name", fallback_title)
  1001. return fallback_title
  1002. @pyqtSlot(str, str)
  1003. def renameMachine(self, machine_id: str, new_name: str):
  1004. container_registry = ContainerRegistry.getInstance()
  1005. machine_stack = container_registry.findContainerStacks(id = machine_id)
  1006. if machine_stack:
  1007. new_name = container_registry.createUniqueName("machine", machine_stack[0].getName(), new_name, machine_stack[0].definition.getName())
  1008. machine_stack[0].setName(new_name)
  1009. self.globalContainerChanged.emit()
  1010. @pyqtSlot(str)
  1011. def removeMachine(self, machine_id: str):
  1012. # If the machine that is being removed is the currently active machine, set another machine as the active machine.
  1013. activate_new_machine = (self._global_container_stack and self._global_container_stack.getId() == machine_id)
  1014. # activate a new machine before removing a machine because this is safer
  1015. if activate_new_machine:
  1016. machine_stacks = ContainerRegistry.getInstance().findContainerStacksMetadata(type = "machine")
  1017. other_machine_stacks = [s for s in machine_stacks if s["id"] != machine_id]
  1018. if other_machine_stacks:
  1019. self.setActiveMachine(other_machine_stacks[0]["id"])
  1020. ExtruderManager.getInstance().removeMachineExtruders(machine_id)
  1021. containers = ContainerRegistry.getInstance().findInstanceContainersMetadata(type = "user", machine = machine_id)
  1022. for container in containers:
  1023. ContainerRegistry.getInstance().removeContainer(container["id"])
  1024. ContainerRegistry.getInstance().removeContainer(machine_id)
  1025. @pyqtProperty(bool, notify = globalContainerChanged)
  1026. def hasMaterials(self) -> bool:
  1027. if self._global_container_stack:
  1028. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_materials", False))
  1029. return False
  1030. @pyqtProperty(bool, notify = globalContainerChanged)
  1031. def hasVariants(self) -> bool:
  1032. if self._global_container_stack:
  1033. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_variants", False))
  1034. return False
  1035. @pyqtProperty(bool, notify = globalContainerChanged)
  1036. def hasVariantBuildplates(self) -> bool:
  1037. if self._global_container_stack:
  1038. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_variant_buildplates", False))
  1039. return False
  1040. ## The selected buildplate is compatible if it is compatible with all the materials in all the extruders
  1041. @pyqtProperty(bool, notify = activeMaterialChanged)
  1042. def variantBuildplateCompatible(self) -> bool:
  1043. if not self._global_container_stack:
  1044. return True
  1045. buildplate_compatible = True # It is compatible by default
  1046. extruder_stacks = self._global_container_stack.extruders.values()
  1047. for stack in extruder_stacks:
  1048. material_container = stack.material
  1049. if material_container == self._empty_material_container:
  1050. continue
  1051. if material_container.getMetaDataEntry("buildplate_compatible"):
  1052. buildplate_compatible = buildplate_compatible and material_container.getMetaDataEntry("buildplate_compatible")[self.activeVariantBuildplateName]
  1053. return buildplate_compatible
  1054. ## The selected buildplate is usable if it is usable for all materials OR it is compatible for one but not compatible
  1055. # for the other material but the buildplate is still usable
  1056. @pyqtProperty(bool, notify = activeMaterialChanged)
  1057. def variantBuildplateUsable(self) -> bool:
  1058. if not self._global_container_stack:
  1059. return True
  1060. # Here the next formula is being calculated:
  1061. # result = (not (material_left_compatible and material_right_compatible)) and
  1062. # (material_left_compatible or material_left_usable) and
  1063. # (material_right_compatible or material_right_usable)
  1064. result = not self.variantBuildplateCompatible
  1065. extruder_stacks = self._global_container_stack.extruders.values()
  1066. for stack in extruder_stacks:
  1067. material_container = stack.material
  1068. if material_container == self._empty_material_container:
  1069. continue
  1070. buildplate_compatible = material_container.getMetaDataEntry("buildplate_compatible")[self.activeVariantBuildplateName] if material_container.getMetaDataEntry("buildplate_compatible") else True
  1071. buildplate_usable = material_container.getMetaDataEntry("buildplate_recommended")[self.activeVariantBuildplateName] if material_container.getMetaDataEntry("buildplate_recommended") else True
  1072. result = result and (buildplate_compatible or buildplate_usable)
  1073. return result
  1074. ## Property to indicate if a machine has "specialized" material profiles.
  1075. # Some machines have their own material profiles that "override" the default catch all profiles.
  1076. @pyqtProperty(bool, notify = globalContainerChanged)
  1077. def filterMaterialsByMachine(self) -> bool:
  1078. if self._global_container_stack:
  1079. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_machine_materials", False))
  1080. return False
  1081. ## Property to indicate if a machine has "specialized" quality profiles.
  1082. # Some machines have their own quality profiles that "override" the default catch all profiles.
  1083. @pyqtProperty(bool, notify = globalContainerChanged)
  1084. def filterQualityByMachine(self) -> bool:
  1085. if self._global_container_stack:
  1086. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_machine_quality", False))
  1087. return False
  1088. ## Get the Definition ID of a machine (specified by ID)
  1089. # \param machine_id string machine id to get the definition ID of
  1090. # \returns DefinitionID (string) if found, None otherwise
  1091. @pyqtSlot(str, result = str)
  1092. def getDefinitionByMachineId(self, machine_id: str) -> str:
  1093. containers = ContainerRegistry.getInstance().findContainerStacks(id = machine_id)
  1094. if containers:
  1095. return containers[0].definition.getId()
  1096. ## Set the amount of extruders on the active machine (global stack)
  1097. # \param extruder_count int the number of extruders to set
  1098. def setActiveMachineExtruderCount(self, extruder_count):
  1099. extruder_manager = Application.getInstance().getExtruderManager()
  1100. definition_changes_container = self._global_container_stack.definitionChanges
  1101. if not self._global_container_stack or definition_changes_container == self._empty_definition_changes_container:
  1102. return
  1103. previous_extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  1104. if extruder_count == previous_extruder_count:
  1105. return
  1106. # reset all extruder number settings whose value is no longer valid
  1107. for setting_instance in self._global_container_stack.userChanges.findInstances():
  1108. setting_key = setting_instance.definition.key
  1109. if not self._global_container_stack.getProperty(setting_key, "type") in ("extruder", "optional_extruder"):
  1110. continue
  1111. old_value = int(self._global_container_stack.userChanges.getProperty(setting_key, "value"))
  1112. if old_value >= extruder_count:
  1113. self._global_container_stack.userChanges.removeInstance(setting_key)
  1114. Logger.log("d", "Reset [%s] because its old value [%s] is no longer valid ", setting_key, old_value)
  1115. # Check to see if any objects are set to print with an extruder that will no longer exist
  1116. root_node = Application.getInstance().getController().getScene().getRoot()
  1117. for node in DepthFirstIterator(root_node):
  1118. if node.getMeshData():
  1119. extruder_nr = node.callDecoration("getActiveExtruderPosition")
  1120. if extruder_nr is not None and int(extruder_nr) > extruder_count - 1:
  1121. node.callDecoration("setActiveExtruder", extruder_manager.getExtruderStack(extruder_count - 1).getId())
  1122. definition_changes_container.setProperty("machine_extruder_count", "value", extruder_count)
  1123. # Make sure one of the extruder stacks is active
  1124. extruder_manager.setActiveExtruderIndex(0)
  1125. # Move settable_per_extruder values out of the global container
  1126. # After CURA-4482 this should not be the case anymore, but we still want to support older project files.
  1127. global_user_container = self._global_container_stack.getTop()
  1128. # Make sure extruder_stacks exists
  1129. extruder_stacks = []
  1130. if previous_extruder_count == 1:
  1131. extruder_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  1132. global_user_container = self._global_container_stack.getTop()
  1133. for setting_instance in global_user_container.findInstances():
  1134. setting_key = setting_instance.definition.key
  1135. settable_per_extruder = self._global_container_stack.getProperty(setting_key, "settable_per_extruder")
  1136. if settable_per_extruder:
  1137. limit_to_extruder = int(self._global_container_stack.getProperty(setting_key, "limit_to_extruder"))
  1138. extruder_stack = extruder_stacks[max(0, limit_to_extruder)]
  1139. extruder_stack.getTop().setProperty(setting_key, "value", global_user_container.getProperty(setting_key, "value"))
  1140. global_user_container.removeInstance(setting_key)
  1141. # Signal that the global stack has changed
  1142. Application.getInstance().globalContainerStackChanged.emit()
  1143. @staticmethod
  1144. def createMachineManager():
  1145. return MachineManager()
  1146. @deprecated("Use ExtruderStack.material = ... and it won't be necessary", "2.7")
  1147. def _updateMaterialContainer(self, definition: "DefinitionContainer", stack: "ContainerStack", variant_container: Optional["InstanceContainer"] = None, preferred_material_name: Optional[str] = None) -> InstanceContainer:
  1148. if not definition.getMetaDataEntry("has_materials"):
  1149. return self._empty_material_container
  1150. approximate_material_diameter = str(round(stack.getProperty("material_diameter", "value")))
  1151. search_criteria = { "type": "material", "approximate_diameter": approximate_material_diameter }
  1152. if definition.getMetaDataEntry("has_machine_materials"):
  1153. search_criteria["definition"] = self.getQualityDefinitionId(definition)
  1154. if definition.getMetaDataEntry("has_variants") and variant_container:
  1155. search_criteria["variant"] = self.getQualityVariantId(definition, variant_container)
  1156. else:
  1157. search_criteria["definition"] = "fdmprinter"
  1158. if preferred_material_name:
  1159. search_criteria["name"] = preferred_material_name
  1160. else:
  1161. preferred_material = definition.getMetaDataEntry("preferred_material")
  1162. if preferred_material:
  1163. search_criteria["id"] = preferred_material
  1164. containers = ContainerRegistry.getInstance().findInstanceContainers(**search_criteria)
  1165. if containers:
  1166. return containers[0]
  1167. if "variant" in search_criteria or "id" in search_criteria:
  1168. # If a material by this name can not be found, try a wider set of search criteria
  1169. search_criteria.pop("variant", None)
  1170. search_criteria.pop("id", None)
  1171. containers = ContainerRegistry.getInstance().findInstanceContainers(**search_criteria)
  1172. if containers:
  1173. return containers[0]
  1174. Logger.log("w", "Unable to find a material container with provided criteria, returning an empty one instead.")
  1175. return self._empty_material_container
  1176. def _onMachineNameChanged(self):
  1177. self.globalContainerChanged.emit()
  1178. def _onMaterialNameChanged(self):
  1179. self.activeMaterialChanged.emit()
  1180. def _onQualityNameChanged(self):
  1181. self.activeQualityChanged.emit()
  1182. def _getContainerChangedSignals(self) -> List[Signal]:
  1183. stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  1184. stacks.append(self._global_container_stack)
  1185. return [ s.containersChanged for s in stacks ]