MachineManager.py 87 KB

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