MachineManager.py 82 KB

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