MachineManager.py 80 KB

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