MachineManager.py 67 KB

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