MachineManager.py 74 KB

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