MachineManager.py 81 KB

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