MachineManager.py 89 KB

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