MachineManager.py 95 KB

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