MachineManager.py 85 KB

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