MachineManager.py 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563
  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. @pyqtProperty(bool, notify = activeQualityGroupChanged)
  506. def isActiveQualityExperimental(self) -> bool:
  507. is_experimental = False
  508. if self._global_container_stack:
  509. if self._current_quality_group:
  510. is_experimental = self._current_quality_group.is_experimental
  511. return is_experimental
  512. ## Returns whether there is anything unsupported in the current set-up.
  513. #
  514. # The current set-up signifies the global stack and all extruder stacks,
  515. # so this indicates whether there is any container in any of the container
  516. # stacks that is not marked as supported.
  517. @pyqtProperty(bool, notify = activeQualityChanged)
  518. def isCurrentSetupSupported(self) -> bool:
  519. if not self._global_container_stack:
  520. return False
  521. for stack in [self._global_container_stack] + list(self._global_container_stack.extruders.values()):
  522. for container in stack.getContainers():
  523. if not container:
  524. return False
  525. if not Util.parseBool(container.getMetaDataEntry("supported", True)):
  526. return False
  527. return True
  528. ## Check if a container is read_only
  529. @pyqtSlot(str, result = bool)
  530. def isReadOnly(self, container_id: str) -> bool:
  531. return CuraContainerRegistry.getInstance().isReadOnly(container_id)
  532. ## Copy the value of the setting of the current extruder to all other extruders as well as the global container.
  533. @pyqtSlot(str)
  534. def copyValueToExtruders(self, key: str) -> None:
  535. if self._active_container_stack is None or self._global_container_stack is None:
  536. return
  537. new_value = self._active_container_stack.getProperty(key, "value")
  538. extruder_stacks = [stack for stack in ExtruderManager.getInstance().getActiveExtruderStacks()]
  539. # Check in which stack the value has to be replaced
  540. for extruder_stack in extruder_stacks:
  541. if extruder_stack != self._active_container_stack and extruder_stack.getProperty(key, "value") != new_value:
  542. extruder_stack.userChanges.setProperty(key, "value", new_value) # TODO: nested property access, should be improved
  543. ## Copy the value of all manually changed settings of the current extruder to all other extruders.
  544. @pyqtSlot()
  545. def copyAllValuesToExtruders(self) -> None:
  546. if self._active_container_stack is None or self._global_container_stack is None:
  547. return
  548. extruder_stacks = list(self._global_container_stack.extruders.values())
  549. for extruder_stack in extruder_stacks:
  550. if extruder_stack != self._active_container_stack:
  551. for key in self._active_container_stack.userChanges.getAllKeys():
  552. new_value = self._active_container_stack.getProperty(key, "value")
  553. # Check if the value has to be replaced
  554. extruder_stack.userChanges.setProperty(key, "value", new_value)
  555. @pyqtProperty(str, notify = activeVariantChanged)
  556. def activeVariantName(self) -> str:
  557. if self._active_container_stack:
  558. variant = self._active_container_stack.variant
  559. if variant:
  560. return variant.getName()
  561. return ""
  562. @pyqtProperty(str, notify = activeVariantChanged)
  563. def activeVariantId(self) -> str:
  564. if self._active_container_stack:
  565. variant = self._active_container_stack.variant
  566. if variant:
  567. return variant.getId()
  568. return ""
  569. @pyqtProperty(str, notify = activeVariantChanged)
  570. def activeVariantBuildplateName(self) -> str:
  571. if self._global_container_stack:
  572. variant = self._global_container_stack.variant
  573. if variant:
  574. return variant.getName()
  575. return ""
  576. @pyqtProperty(str, notify = globalContainerChanged)
  577. def activeDefinitionId(self) -> str:
  578. if self._global_container_stack:
  579. return self._global_container_stack.definition.id
  580. return ""
  581. ## Get the Definition ID to use to select quality profiles for the currently active machine
  582. # \returns DefinitionID (string) if found, empty string otherwise
  583. @pyqtProperty(str, notify = globalContainerChanged)
  584. def activeQualityDefinitionId(self) -> str:
  585. if self._global_container_stack:
  586. return getMachineDefinitionIDForQualitySearch(self._global_container_stack.definition)
  587. return ""
  588. ## Gets how the active definition calls variants
  589. # Caveat: per-definition-variant-title is currently not translated (though the fallback is)
  590. @pyqtProperty(str, notify = globalContainerChanged)
  591. def activeDefinitionVariantsName(self) -> str:
  592. fallback_title = catalog.i18nc("@label", "Nozzle")
  593. if self._global_container_stack:
  594. return self._global_container_stack.definition.getMetaDataEntry("variants_name", fallback_title)
  595. return fallback_title
  596. @pyqtSlot(str, str)
  597. def renameMachine(self, machine_id: str, new_name: str) -> None:
  598. container_registry = CuraContainerRegistry.getInstance()
  599. machine_stack = container_registry.findContainerStacks(id = machine_id)
  600. if machine_stack:
  601. new_name = container_registry.createUniqueName("machine", machine_stack[0].getName(), new_name, machine_stack[0].definition.getName())
  602. machine_stack[0].setName(new_name)
  603. self.globalContainerChanged.emit()
  604. @pyqtSlot(str)
  605. def removeMachine(self, machine_id: str) -> None:
  606. # If the machine that is being removed is the currently active machine, set another machine as the active machine.
  607. activate_new_machine = (self._global_container_stack and self._global_container_stack.getId() == machine_id)
  608. # Activate a new machine before removing a machine because this is safer
  609. if activate_new_machine:
  610. machine_stacks = CuraContainerRegistry.getInstance().findContainerStacksMetadata(type = "machine")
  611. other_machine_stacks = [s for s in machine_stacks if s["id"] != machine_id]
  612. if other_machine_stacks:
  613. self.setActiveMachine(other_machine_stacks[0]["id"])
  614. metadata = CuraContainerRegistry.getInstance().findContainerStacksMetadata(id = machine_id)[0]
  615. network_key = metadata["um_network_key"] if "um_network_key" in metadata else None
  616. ExtruderManager.getInstance().removeMachineExtruders(machine_id)
  617. containers = CuraContainerRegistry.getInstance().findInstanceContainersMetadata(type = "user", machine = machine_id)
  618. for container in containers:
  619. CuraContainerRegistry.getInstance().removeContainer(container["id"])
  620. CuraContainerRegistry.getInstance().removeContainer(machine_id)
  621. # If the printer that is being removed is a network printer, the hidden printers have to be also removed
  622. if network_key:
  623. metadata_filter = {"um_network_key": network_key}
  624. hidden_containers = CuraContainerRegistry.getInstance().findContainerStacks(type = "machine", **metadata_filter)
  625. if hidden_containers:
  626. # This reuses the method and remove all printers recursively
  627. self.removeMachine(hidden_containers[0].getId())
  628. @pyqtProperty(bool, notify = globalContainerChanged)
  629. def hasMaterials(self) -> bool:
  630. if self._global_container_stack:
  631. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_materials", False))
  632. return False
  633. @pyqtProperty(bool, notify = globalContainerChanged)
  634. def hasVariants(self) -> bool:
  635. if self._global_container_stack:
  636. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_variants", False))
  637. return False
  638. @pyqtProperty(bool, notify = globalContainerChanged)
  639. def hasVariantBuildplates(self) -> bool:
  640. if self._global_container_stack:
  641. return Util.parseBool(self._global_container_stack.getMetaDataEntry("has_variant_buildplates", False))
  642. return False
  643. ## The selected buildplate is compatible if it is compatible with all the materials in all the extruders
  644. @pyqtProperty(bool, notify = activeMaterialChanged)
  645. def variantBuildplateCompatible(self) -> bool:
  646. if not self._global_container_stack:
  647. return True
  648. buildplate_compatible = True # It is compatible by default
  649. extruder_stacks = self._global_container_stack.extruders.values()
  650. for stack in extruder_stacks:
  651. if not stack.isEnabled:
  652. continue
  653. material_container = stack.material
  654. if material_container == empty_material_container:
  655. continue
  656. if material_container.getMetaDataEntry("buildplate_compatible"):
  657. buildplate_compatible = buildplate_compatible and material_container.getMetaDataEntry("buildplate_compatible")[self.activeVariantBuildplateName]
  658. return buildplate_compatible
  659. ## The selected buildplate is usable if it is usable for all materials OR it is compatible for one but not compatible
  660. # for the other material but the buildplate is still usable
  661. @pyqtProperty(bool, notify = activeMaterialChanged)
  662. def variantBuildplateUsable(self) -> bool:
  663. if not self._global_container_stack:
  664. return True
  665. # Here the next formula is being calculated:
  666. # result = (not (material_left_compatible and material_right_compatible)) and
  667. # (material_left_compatible or material_left_usable) and
  668. # (material_right_compatible or material_right_usable)
  669. result = not self.variantBuildplateCompatible
  670. extruder_stacks = self._global_container_stack.extruders.values()
  671. for stack in extruder_stacks:
  672. material_container = stack.material
  673. if material_container == empty_material_container:
  674. continue
  675. buildplate_compatible = material_container.getMetaDataEntry("buildplate_compatible")[self.activeVariantBuildplateName] if material_container.getMetaDataEntry("buildplate_compatible") else True
  676. buildplate_usable = material_container.getMetaDataEntry("buildplate_recommended")[self.activeVariantBuildplateName] if material_container.getMetaDataEntry("buildplate_recommended") else True
  677. result = result and (buildplate_compatible or buildplate_usable)
  678. return result
  679. ## Get the Definition ID of a machine (specified by ID)
  680. # \param machine_id string machine id to get the definition ID of
  681. # \returns DefinitionID if found, None otherwise
  682. @pyqtSlot(str, result = str)
  683. def getDefinitionByMachineId(self, machine_id: str) -> Optional[str]:
  684. containers = CuraContainerRegistry.getInstance().findContainerStacks(id = machine_id)
  685. if containers:
  686. return containers[0].definition.getId()
  687. return None
  688. def getIncompatibleSettingsOnEnabledExtruders(self, container: InstanceContainer) -> List[str]:
  689. if self._global_container_stack is None:
  690. return []
  691. extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  692. result = [] # type: List[str]
  693. for setting_instance in container.findInstances():
  694. setting_key = setting_instance.definition.key
  695. setting_enabled = self._global_container_stack.getProperty(setting_key, "enabled")
  696. if not setting_enabled:
  697. # A setting is not visible anymore
  698. result.append(setting_key)
  699. Logger.log("d", "Reset setting [%s] from [%s] because the setting is no longer enabled", setting_key, container)
  700. continue
  701. if not self._global_container_stack.getProperty(setting_key, "type") in ("extruder", "optional_extruder"):
  702. continue
  703. old_value = container.getProperty(setting_key, "value")
  704. if int(old_value) < 0:
  705. continue
  706. if int(old_value) >= extruder_count or not self._global_container_stack.extruders[str(old_value)].isEnabled:
  707. result.append(setting_key)
  708. Logger.log("d", "Reset setting [%s] in [%s] because its old value [%s] is no longer valid", setting_key, container, old_value)
  709. return result
  710. ## Update extruder number to a valid value when the number of extruders are changed, or when an extruder is changed
  711. def correctExtruderSettings(self) -> None:
  712. if self._global_container_stack is None:
  713. return
  714. for setting_key in self.getIncompatibleSettingsOnEnabledExtruders(self._global_container_stack.userChanges):
  715. self._global_container_stack.userChanges.removeInstance(setting_key)
  716. add_user_changes = self.getIncompatibleSettingsOnEnabledExtruders(self._global_container_stack.qualityChanges)
  717. for setting_key in add_user_changes:
  718. # Apply quality changes that are incompatible to user changes, so we do not change the quality changes itself.
  719. self._global_container_stack.userChanges.setProperty(setting_key, "value", self._default_extruder_position)
  720. if add_user_changes:
  721. caution_message = Message(catalog.i18nc(
  722. "@info:generic",
  723. "Settings have been changed to match the current availability of extruders: [%s]" % ", ".join(add_user_changes)),
  724. lifetime = 0,
  725. title = catalog.i18nc("@info:title", "Settings updated"))
  726. caution_message.show()
  727. ## Set the amount of extruders on the active machine (global stack)
  728. # \param extruder_count int the number of extruders to set
  729. def setActiveMachineExtruderCount(self, extruder_count: int) -> None:
  730. if self._global_container_stack is None:
  731. return
  732. extruder_manager = self._application.getExtruderManager()
  733. definition_changes_container = self._global_container_stack.definitionChanges
  734. if not self._global_container_stack or definition_changes_container == empty_definition_changes_container:
  735. return
  736. previous_extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  737. if extruder_count == previous_extruder_count:
  738. return
  739. definition_changes_container.setProperty("machine_extruder_count", "value", extruder_count)
  740. self.updateDefaultExtruder()
  741. self.updateNumberExtrudersEnabled()
  742. self.correctExtruderSettings()
  743. # Check to see if any objects are set to print with an extruder that will no longer exist
  744. root_node = self._application.getController().getScene().getRoot()
  745. for node in DepthFirstIterator(root_node): #type: ignore #Ignore type error because iter() should get called automatically by Python syntax.
  746. if node.getMeshData():
  747. extruder_nr = node.callDecoration("getActiveExtruderPosition")
  748. if extruder_nr is not None and int(extruder_nr) > extruder_count - 1:
  749. extruder = extruder_manager.getExtruderStack(extruder_count - 1)
  750. if extruder is not None:
  751. node.callDecoration("setActiveExtruder", extruder.getId())
  752. else:
  753. Logger.log("w", "Could not find extruder to set active.")
  754. # Make sure one of the extruder stacks is active
  755. extruder_manager.setActiveExtruderIndex(0)
  756. # Move settable_per_extruder values out of the global container
  757. # After CURA-4482 this should not be the case anymore, but we still want to support older project files.
  758. global_user_container = self._global_container_stack.userChanges
  759. for setting_instance in global_user_container.findInstances():
  760. setting_key = setting_instance.definition.key
  761. settable_per_extruder = self._global_container_stack.getProperty(setting_key, "settable_per_extruder")
  762. if settable_per_extruder:
  763. limit_to_extruder = int(self._global_container_stack.getProperty(setting_key, "limit_to_extruder"))
  764. extruder_position = max(0, limit_to_extruder)
  765. extruder_stack = self.getExtruder(extruder_position)
  766. if extruder_stack:
  767. extruder_stack.userChanges.setProperty(setting_key, "value", global_user_container.getProperty(setting_key, "value"))
  768. else:
  769. Logger.log("e", "Unable to find extruder on position %s", extruder_position)
  770. global_user_container.removeInstance(setting_key)
  771. # Signal that the global stack has changed
  772. self._application.globalContainerStackChanged.emit()
  773. self.forceUpdateAllSettings()
  774. @pyqtSlot(int, result = QObject)
  775. def getExtruder(self, position: int) -> Optional[ExtruderStack]:
  776. if self._global_container_stack:
  777. return self._global_container_stack.extruders.get(str(position))
  778. return None
  779. def updateDefaultExtruder(self) -> None:
  780. if self._global_container_stack is None:
  781. return
  782. extruder_items = sorted(self._global_container_stack.extruders.items())
  783. old_position = self._default_extruder_position
  784. new_default_position = "0"
  785. for position, extruder in extruder_items:
  786. if extruder.isEnabled:
  787. new_default_position = position
  788. break
  789. if new_default_position != old_position:
  790. self._default_extruder_position = new_default_position
  791. self.extruderChanged.emit()
  792. def updateNumberExtrudersEnabled(self) -> None:
  793. if self._global_container_stack is None:
  794. return
  795. definition_changes_container = self._global_container_stack.definitionChanges
  796. machine_extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  797. extruder_count = 0
  798. for position, extruder in self._global_container_stack.extruders.items():
  799. if extruder.isEnabled and int(position) < machine_extruder_count:
  800. extruder_count += 1
  801. if self.numberExtrudersEnabled != extruder_count:
  802. definition_changes_container.setProperty("extruders_enabled_count", "value", extruder_count)
  803. self.numberExtrudersEnabledChanged.emit()
  804. @pyqtProperty(int, notify = numberExtrudersEnabledChanged)
  805. def numberExtrudersEnabled(self) -> int:
  806. if self._global_container_stack is None:
  807. return 1
  808. return self._global_container_stack.definitionChanges.getProperty("extruders_enabled_count", "value")
  809. @pyqtProperty(str, notify = extruderChanged)
  810. def defaultExtruderPosition(self) -> str:
  811. return self._default_extruder_position
  812. ## This will fire the propertiesChanged for all settings so they will be updated in the front-end
  813. @pyqtSlot()
  814. def forceUpdateAllSettings(self) -> None:
  815. if self._global_container_stack is None:
  816. return
  817. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  818. property_names = ["value", "resolve", "validationState"]
  819. for container in [self._global_container_stack] + list(self._global_container_stack.extruders.values()):
  820. for setting_key in container.getAllKeys():
  821. container.propertiesChanged.emit(setting_key, property_names)
  822. @pyqtSlot(int, bool)
  823. def setExtruderEnabled(self, position: int, enabled: bool) -> None:
  824. extruder = self.getExtruder(position)
  825. if not extruder or self._global_container_stack is None:
  826. Logger.log("w", "Could not find extruder on position %s", position)
  827. return
  828. extruder.setEnabled(enabled)
  829. self.updateDefaultExtruder()
  830. self.updateNumberExtrudersEnabled()
  831. self.correctExtruderSettings()
  832. # In case this extruder is being disabled and it's the currently selected one, switch to the default extruder
  833. if not enabled and position == ExtruderManager.getInstance().activeExtruderIndex:
  834. ExtruderManager.getInstance().setActiveExtruderIndex(int(self._default_extruder_position))
  835. # Ensure that the quality profile is compatible with current combination, or choose a compatible one if available
  836. self._updateQualityWithMaterial()
  837. self.extruderChanged.emit()
  838. # Update material compatibility color
  839. self.activeQualityGroupChanged.emit()
  840. # Update items in SettingExtruder
  841. ExtruderManager.getInstance().extrudersChanged.emit(self._global_container_stack.getId())
  842. # Make sure the front end reflects changes
  843. self.forceUpdateAllSettings()
  844. # Also trigger the build plate compatibility to update
  845. self.activeMaterialChanged.emit()
  846. def _onMachineNameChanged(self) -> None:
  847. self.globalContainerChanged.emit()
  848. def _onMaterialNameChanged(self) -> None:
  849. self.activeMaterialChanged.emit()
  850. def _onQualityNameChanged(self) -> None:
  851. self.activeQualityChanged.emit()
  852. def _getContainerChangedSignals(self) -> List[Signal]:
  853. if self._global_container_stack is None:
  854. return []
  855. stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  856. stacks.append(self._global_container_stack)
  857. return [ s.containersChanged for s in stacks ]
  858. @pyqtSlot(str, str, str)
  859. def setSettingForAllExtruders(self, setting_name: str, property_name: str, property_value: 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.setProperty(setting_name, property_name, property_value)
  865. ## Reset all setting properties of a setting for all extruders.
  866. # \param setting_name The ID of the setting to reset.
  867. @pyqtSlot(str)
  868. def resetSettingForAllExtruders(self, setting_name: str) -> None:
  869. if self._global_container_stack is None:
  870. return
  871. for key, extruder in self._global_container_stack.extruders.items():
  872. container = extruder.userChanges
  873. container.removeInstance(setting_name)
  874. @pyqtProperty("QVariantList", notify = globalContainerChanged)
  875. def currentExtruderPositions(self) -> List[str]:
  876. if self._global_container_stack is None:
  877. return []
  878. return sorted(list(self._global_container_stack.extruders.keys()))
  879. ## Update _current_root_material_id when the current root material was changed.
  880. def _onRootMaterialChanged(self) -> None:
  881. self._current_root_material_id = {}
  882. if self._global_container_stack:
  883. for position in self._global_container_stack.extruders:
  884. self._current_root_material_id[position] = self._global_container_stack.extruders[position].material.getMetaDataEntry("base_file")
  885. @pyqtProperty("QVariant", notify = rootMaterialChanged)
  886. def currentRootMaterialId(self) -> Dict[str, str]:
  887. return self._current_root_material_id
  888. ## Return the variant names in the extruder stack(s).
  889. ## For the variant in the global stack, use activeVariantBuildplateName
  890. @pyqtProperty("QVariant", notify = activeVariantChanged)
  891. def activeVariantNames(self) -> Dict[str, str]:
  892. result = {}
  893. active_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
  894. for stack in active_stacks:
  895. variant_container = stack.variant
  896. position = stack.getMetaDataEntry("position")
  897. if variant_container and variant_container != empty_variant_container:
  898. result[position] = variant_container.getName()
  899. return result
  900. # Sets all quality and quality_changes containers to empty_quality and empty_quality_changes containers
  901. # for all stacks in the currently active machine.
  902. #
  903. def _setEmptyQuality(self) -> None:
  904. if self._global_container_stack is None:
  905. return
  906. self._current_quality_group = None
  907. self._current_quality_changes_group = None
  908. self._global_container_stack.quality = empty_quality_container
  909. self._global_container_stack.qualityChanges = empty_quality_changes_container
  910. for extruder in self._global_container_stack.extruders.values():
  911. extruder.quality = empty_quality_container
  912. extruder.qualityChanges = empty_quality_changes_container
  913. self.activeQualityGroupChanged.emit()
  914. self.activeQualityChangesGroupChanged.emit()
  915. def _setQualityGroup(self, quality_group: Optional["QualityGroup"], empty_quality_changes: bool = True) -> None:
  916. if self._global_container_stack is None:
  917. return
  918. if quality_group is None:
  919. self._setEmptyQuality()
  920. return
  921. if quality_group.node_for_global is None or quality_group.node_for_global.getContainer() is None:
  922. return
  923. for node in quality_group.nodes_for_extruders.values():
  924. if node.getContainer() is None:
  925. return
  926. self._current_quality_group = quality_group
  927. if empty_quality_changes:
  928. self._current_quality_changes_group = None
  929. # Set quality and quality_changes for the GlobalStack
  930. self._global_container_stack.quality = quality_group.node_for_global.getContainer()
  931. if empty_quality_changes:
  932. self._global_container_stack.qualityChanges = empty_quality_changes_container
  933. # Set quality and quality_changes for each ExtruderStack
  934. for position, node in quality_group.nodes_for_extruders.items():
  935. self._global_container_stack.extruders[str(position)].quality = node.getContainer()
  936. if empty_quality_changes:
  937. self._global_container_stack.extruders[str(position)].qualityChanges = empty_quality_changes_container
  938. self.activeQualityGroupChanged.emit()
  939. self.activeQualityChangesGroupChanged.emit()
  940. def _fixQualityChangesGroupToNotSupported(self, quality_changes_group: "QualityChangesGroup") -> None:
  941. nodes = [quality_changes_group.node_for_global] + list(quality_changes_group.nodes_for_extruders.values())
  942. containers = [n.getContainer() for n in nodes if n is not None]
  943. for container in containers:
  944. if container:
  945. container.setMetaDataEntry("quality_type", "not_supported")
  946. quality_changes_group.quality_type = "not_supported"
  947. def _setQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup") -> None:
  948. if self._global_container_stack is None:
  949. return # Can't change that.
  950. quality_type = quality_changes_group.quality_type
  951. # A custom quality can be created based on "not supported".
  952. # In that case, do not set quality containers to empty.
  953. quality_group = None
  954. if quality_type != "not_supported":
  955. quality_group_dict = self._quality_manager.getQualityGroups(self._global_container_stack)
  956. quality_group = quality_group_dict.get(quality_type)
  957. if quality_group is None:
  958. self._fixQualityChangesGroupToNotSupported(quality_changes_group)
  959. quality_changes_container = empty_quality_changes_container
  960. quality_container = empty_quality_container # type: Optional[InstanceContainer]
  961. if quality_changes_group.node_for_global and quality_changes_group.node_for_global.getContainer():
  962. quality_changes_container = cast(InstanceContainer, quality_changes_group.node_for_global.getContainer())
  963. if quality_group is not None and quality_group.node_for_global and quality_group.node_for_global.getContainer():
  964. quality_container = quality_group.node_for_global.getContainer()
  965. self._global_container_stack.quality = quality_container
  966. self._global_container_stack.qualityChanges = quality_changes_container
  967. for position, extruder in self._global_container_stack.extruders.items():
  968. quality_changes_node = quality_changes_group.nodes_for_extruders.get(position)
  969. quality_node = None
  970. if quality_group is not None:
  971. quality_node = quality_group.nodes_for_extruders.get(position)
  972. quality_changes_container = empty_quality_changes_container
  973. quality_container = empty_quality_container
  974. if quality_changes_node and quality_changes_node.getContainer():
  975. quality_changes_container = cast(InstanceContainer, quality_changes_node.getContainer())
  976. if quality_node and quality_node.getContainer():
  977. quality_container = quality_node.getContainer()
  978. extruder.quality = quality_container
  979. extruder.qualityChanges = quality_changes_container
  980. self._current_quality_group = quality_group
  981. self._current_quality_changes_group = quality_changes_group
  982. self.activeQualityGroupChanged.emit()
  983. self.activeQualityChangesGroupChanged.emit()
  984. def _setVariantNode(self, position: str, container_node: "ContainerNode") -> None:
  985. if container_node.getContainer() is None or self._global_container_stack is None:
  986. return
  987. self._global_container_stack.extruders[position].variant = container_node.getContainer()
  988. self.activeVariantChanged.emit()
  989. def _setGlobalVariant(self, container_node: "ContainerNode") -> None:
  990. if self._global_container_stack is None:
  991. return
  992. self._global_container_stack.variant = container_node.getContainer()
  993. if not self._global_container_stack.variant:
  994. self._global_container_stack.variant = self._application.empty_variant_container
  995. def _setMaterial(self, position: str, container_node: Optional["ContainerNode"] = None) -> None:
  996. if self._global_container_stack is None:
  997. return
  998. if container_node and container_node.getContainer():
  999. self._global_container_stack.extruders[position].material = container_node.getContainer()
  1000. root_material_id = container_node.getMetaDataEntry("base_file", None)
  1001. else:
  1002. self._global_container_stack.extruders[position].material = empty_material_container
  1003. root_material_id = None
  1004. # The _current_root_material_id is used in the MaterialMenu to see which material is selected
  1005. if root_material_id != self._current_root_material_id[position]:
  1006. self._current_root_material_id[position] = root_material_id
  1007. self.rootMaterialChanged.emit()
  1008. def activeMaterialsCompatible(self) -> bool:
  1009. # Check material - variant compatibility
  1010. if self._global_container_stack is not None:
  1011. if Util.parseBool(self._global_container_stack.getMetaDataEntry("has_materials", False)):
  1012. for position, extruder in self._global_container_stack.extruders.items():
  1013. if extruder.isEnabled and not extruder.material.getMetaDataEntry("compatible"):
  1014. return False
  1015. if not extruder.material.getMetaDataEntry("compatible"):
  1016. return False
  1017. return True
  1018. ## Update current quality type and machine after setting material
  1019. def _updateQualityWithMaterial(self, *args: Any) -> None:
  1020. if self._global_container_stack is None:
  1021. return
  1022. Logger.log("i", "Updating quality/quality_changes due to material change")
  1023. current_quality_type = None
  1024. if self._current_quality_group:
  1025. current_quality_type = self._current_quality_group.quality_type
  1026. candidate_quality_groups = self._quality_manager.getQualityGroups(self._global_container_stack)
  1027. available_quality_types = {qt for qt, g in candidate_quality_groups.items() if g.is_available}
  1028. Logger.log("d", "Current quality type = [%s]", current_quality_type)
  1029. if not self.activeMaterialsCompatible():
  1030. if current_quality_type is not None:
  1031. Logger.log("i", "Active materials are not compatible, setting all qualities to empty (Not Supported).")
  1032. self._setEmptyQuality()
  1033. return
  1034. if not available_quality_types:
  1035. if self._current_quality_changes_group is None:
  1036. Logger.log("i", "No available quality types found, setting all qualities to empty (Not Supported).")
  1037. self._setEmptyQuality()
  1038. return
  1039. if current_quality_type in available_quality_types:
  1040. Logger.log("i", "Current available quality type [%s] is available, applying changes.", current_quality_type)
  1041. self._setQualityGroup(candidate_quality_groups[current_quality_type], empty_quality_changes = False)
  1042. return
  1043. # The current quality type is not available so we use the preferred quality type if it's available,
  1044. # otherwise use one of the available quality types.
  1045. quality_type = sorted(list(available_quality_types))[0]
  1046. preferred_quality_type = self._global_container_stack.getMetaDataEntry("preferred_quality_type")
  1047. if preferred_quality_type in available_quality_types:
  1048. quality_type = preferred_quality_type
  1049. Logger.log("i", "The current quality type [%s] is not available, switching to [%s] instead",
  1050. current_quality_type, quality_type)
  1051. self._setQualityGroup(candidate_quality_groups[quality_type], empty_quality_changes = True)
  1052. def updateMaterialWithVariant(self, position: Optional[str]) -> None:
  1053. if self._global_container_stack is None:
  1054. return
  1055. if position is None:
  1056. position_list = list(self._global_container_stack.extruders.keys())
  1057. else:
  1058. position_list = [position]
  1059. buildplate_name = None
  1060. if self._global_container_stack.variant.getId() != "empty_variant":
  1061. buildplate_name = self._global_container_stack.variant.getName()
  1062. for position_item in position_list:
  1063. extruder = self._global_container_stack.extruders[position_item]
  1064. current_material_base_name = extruder.material.getMetaDataEntry("base_file")
  1065. current_nozzle_name = None
  1066. if extruder.variant.getId() != empty_variant_container.getId():
  1067. current_nozzle_name = extruder.variant.getMetaDataEntry("name")
  1068. material_diameter = extruder.getCompatibleMaterialDiameter()
  1069. candidate_materials = self._material_manager.getAvailableMaterials(
  1070. self._global_container_stack.definition,
  1071. current_nozzle_name,
  1072. buildplate_name,
  1073. material_diameter)
  1074. if not candidate_materials:
  1075. self._setMaterial(position_item, container_node = None)
  1076. continue
  1077. if current_material_base_name in candidate_materials:
  1078. new_material = candidate_materials[current_material_base_name]
  1079. self._setMaterial(position_item, new_material)
  1080. continue
  1081. # The current material is not available, find the preferred one
  1082. material_node = self._material_manager.getDefaultMaterial(self._global_container_stack, position_item, current_nozzle_name)
  1083. if material_node is not None:
  1084. self._setMaterial(position_item, material_node)
  1085. ## Given a printer definition name, select the right machine instance. In case it doesn't exist, create a new
  1086. # instance with the same network key.
  1087. @pyqtSlot(str)
  1088. def switchPrinterType(self, machine_name: str) -> None:
  1089. # Don't switch if the user tries to change to the same type of printer
  1090. if self._global_container_stack is None or self.activeMachineDefinitionName == machine_name:
  1091. return
  1092. # Get the definition id corresponding to this machine name
  1093. machine_definition_id = CuraContainerRegistry.getInstance().findDefinitionContainers(name = machine_name)[0].getId()
  1094. # Try to find a machine with the same network key
  1095. new_machine = self.getMachine(machine_definition_id, metadata_filter = {"um_network_key": self.activeMachineNetworkKey})
  1096. # If there is no machine, then create a new one and set it to the non-hidden instance
  1097. if not new_machine:
  1098. new_machine = CuraStackBuilder.createMachine(machine_definition_id + "_sync", machine_definition_id)
  1099. if not new_machine:
  1100. return
  1101. new_machine.setMetaDataEntry("um_network_key", self.activeMachineNetworkKey)
  1102. new_machine.setMetaDataEntry("connect_group_name", self.activeMachineNetworkGroupName)
  1103. new_machine.setMetaDataEntry("hidden", False)
  1104. else:
  1105. Logger.log("i", "Found a %s with the key %s. Let's use it!", machine_name, self.activeMachineNetworkKey)
  1106. new_machine.setMetaDataEntry("hidden", False)
  1107. # Set the current printer instance to hidden (the metadata entry must exist)
  1108. self._global_container_stack.setMetaDataEntry("hidden", True)
  1109. self.setActiveMachine(new_machine.getId())
  1110. @pyqtSlot(QObject)
  1111. def applyRemoteConfiguration(self, configuration: ConfigurationModel) -> None:
  1112. if self._global_container_stack is None:
  1113. return
  1114. self.blurSettings.emit()
  1115. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1116. self.switchPrinterType(configuration.printerType)
  1117. for extruder_configuration in configuration.extruderConfigurations:
  1118. position = str(extruder_configuration.position)
  1119. variant_container_node = self._variant_manager.getVariantNode(self._global_container_stack.definition.getId(), extruder_configuration.hotendID)
  1120. material_container_node = self._material_manager.getMaterialNodeByType(self._global_container_stack,
  1121. position,
  1122. extruder_configuration.hotendID,
  1123. configuration.buildplateConfiguration,
  1124. extruder_configuration.material.guid)
  1125. if variant_container_node:
  1126. self._setVariantNode(position, variant_container_node)
  1127. else:
  1128. self._global_container_stack.extruders[position].variant = empty_variant_container
  1129. if material_container_node:
  1130. self._setMaterial(position, material_container_node)
  1131. else:
  1132. self._global_container_stack.extruders[position].material = empty_material_container
  1133. self.updateMaterialWithVariant(position)
  1134. if configuration.buildplateConfiguration is not None:
  1135. global_variant_container_node = self._variant_manager.getBuildplateVariantNode(self._global_container_stack.definition.getId(), configuration.buildplateConfiguration)
  1136. if global_variant_container_node:
  1137. self._setGlobalVariant(global_variant_container_node)
  1138. else:
  1139. self._global_container_stack.variant = empty_variant_container
  1140. else:
  1141. self._global_container_stack.variant = empty_variant_container
  1142. self._updateQualityWithMaterial()
  1143. # See if we need to show the Discard or Keep changes screen
  1144. if self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1145. self._application.discardOrKeepProfileChanges()
  1146. ## Find all container stacks that has the pair 'key = value' in its metadata and replaces the value with 'new_value'
  1147. def replaceContainersMetadata(self, key: str, value: str, new_value: str) -> None:
  1148. machines = CuraContainerRegistry.getInstance().findContainerStacks(type = "machine")
  1149. for machine in machines:
  1150. if machine.getMetaDataEntry(key) == value:
  1151. machine.setMetaDataEntry(key, new_value)
  1152. ## This method checks if the name of the group stored in the definition container is correct.
  1153. # 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
  1154. # then all the container stacks are updated, both the current and the hidden ones.
  1155. def checkCorrectGroupName(self, device_id: str, group_name: str) -> None:
  1156. if self._global_container_stack and device_id == self.activeMachineNetworkKey:
  1157. # Check if the connect_group_name is correct. If not, update all the containers connected to the same printer
  1158. if self.activeMachineNetworkGroupName != group_name:
  1159. metadata_filter = {"um_network_key": self.activeMachineNetworkKey}
  1160. containers = CuraContainerRegistry.getInstance().findContainerStacks(type = "machine", **metadata_filter)
  1161. for container in containers:
  1162. container.setMetaDataEntry("connect_group_name", group_name)
  1163. ## This method checks if there is an instance connected to the given network_key
  1164. def existNetworkInstances(self, network_key: str) -> bool:
  1165. metadata_filter = {"um_network_key": network_key}
  1166. containers = CuraContainerRegistry.getInstance().findContainerStacks(type = "machine", **metadata_filter)
  1167. return bool(containers)
  1168. @pyqtSlot("QVariant")
  1169. def setGlobalVariant(self, container_node: "ContainerNode") -> None:
  1170. self.blurSettings.emit()
  1171. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1172. self._setGlobalVariant(container_node)
  1173. self.updateMaterialWithVariant(None) # Update all materials
  1174. self._updateQualityWithMaterial()
  1175. @pyqtSlot(str, str)
  1176. def setMaterialById(self, position: str, root_material_id: str) -> None:
  1177. if self._global_container_stack is None:
  1178. return
  1179. buildplate_name = None
  1180. if self._global_container_stack.variant.getId() != "empty_variant":
  1181. buildplate_name = self._global_container_stack.variant.getName()
  1182. machine_definition_id = self._global_container_stack.definition.id
  1183. position = str(position)
  1184. extruder_stack = self._global_container_stack.extruders[position]
  1185. nozzle_name = extruder_stack.variant.getName()
  1186. material_diameter = extruder_stack.getApproximateMaterialDiameter()
  1187. material_node = self._material_manager.getMaterialNode(machine_definition_id, nozzle_name, buildplate_name,
  1188. material_diameter, root_material_id)
  1189. self.setMaterial(position, material_node)
  1190. ## Global_stack: if you want to provide your own global_stack instead of the current active one
  1191. # if you update an active machine, special measures have to be taken.
  1192. @pyqtSlot(str, "QVariant")
  1193. def setMaterial(self, position: str, container_node, global_stack: Optional["GlobalStack"] = None) -> None:
  1194. if global_stack is not None and global_stack != self._global_container_stack:
  1195. global_stack.extruders[position].material = container_node.getContainer()
  1196. return
  1197. position = str(position)
  1198. self.blurSettings.emit()
  1199. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1200. self._setMaterial(position, container_node)
  1201. self._updateQualityWithMaterial()
  1202. # See if we need to show the Discard or Keep changes screen
  1203. if self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1204. self._application.discardOrKeepProfileChanges()
  1205. @pyqtSlot(str, str)
  1206. def setVariantByName(self, position: str, variant_name: str) -> None:
  1207. if self._global_container_stack is None:
  1208. return
  1209. machine_definition_id = self._global_container_stack.definition.id
  1210. variant_node = self._variant_manager.getVariantNode(machine_definition_id, variant_name)
  1211. self.setVariant(position, variant_node)
  1212. @pyqtSlot(str, "QVariant")
  1213. def setVariant(self, position: str, container_node: "ContainerNode") -> None:
  1214. position = str(position)
  1215. self.blurSettings.emit()
  1216. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1217. self._setVariantNode(position, container_node)
  1218. self.updateMaterialWithVariant(position)
  1219. self._updateQualityWithMaterial()
  1220. # See if we need to show the Discard or Keep changes screen
  1221. if self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1222. self._application.discardOrKeepProfileChanges()
  1223. @pyqtSlot(str)
  1224. def setQualityGroupByQualityType(self, quality_type: str) -> None:
  1225. if self._global_container_stack is None:
  1226. return
  1227. # Get all the quality groups for this global stack and filter out by quality_type
  1228. quality_group_dict = self._quality_manager.getQualityGroups(self._global_container_stack)
  1229. quality_group = quality_group_dict[quality_type]
  1230. self.setQualityGroup(quality_group)
  1231. ## Optionally provide global_stack if you want to use your own
  1232. # The active global_stack is treated differently.
  1233. @pyqtSlot(QObject)
  1234. def setQualityGroup(self, quality_group: "QualityGroup", no_dialog: bool = False, global_stack: Optional["GlobalStack"] = None) -> None:
  1235. if global_stack is not None and global_stack != self._global_container_stack:
  1236. if quality_group is None:
  1237. Logger.log("e", "Could not set quality group because quality group is None")
  1238. return
  1239. if quality_group.node_for_global is None:
  1240. Logger.log("e", "Could not set quality group [%s] because it has no node_for_global", str(quality_group))
  1241. return
  1242. # This is not changing the quality for the active machine !!!!!!!!
  1243. global_stack.quality = quality_group.node_for_global.getContainer()
  1244. for extruder_nr, extruder_stack in global_stack.extruders.items():
  1245. quality_container = empty_quality_container
  1246. if extruder_nr in quality_group.nodes_for_extruders:
  1247. container = quality_group.nodes_for_extruders[extruder_nr].getContainer()
  1248. quality_container = container if container is not None else quality_container
  1249. extruder_stack.quality = quality_container
  1250. return
  1251. self.blurSettings.emit()
  1252. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1253. self._setQualityGroup(quality_group)
  1254. # See if we need to show the Discard or Keep changes screen
  1255. if not no_dialog and self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1256. self._application.discardOrKeepProfileChanges()
  1257. @pyqtProperty(QObject, fset = setQualityGroup, notify = activeQualityGroupChanged)
  1258. def activeQualityGroup(self) -> Optional["QualityGroup"]:
  1259. return self._current_quality_group
  1260. @pyqtSlot(QObject)
  1261. def setQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup", no_dialog: bool = False) -> None:
  1262. self.blurSettings.emit()
  1263. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1264. self._setQualityChangesGroup(quality_changes_group)
  1265. # See if we need to show the Discard or Keep changes screen
  1266. if not no_dialog and self.hasUserSettings and self._application.getPreferences().getValue("cura/active_mode") == 1:
  1267. self._application.discardOrKeepProfileChanges()
  1268. @pyqtSlot()
  1269. def resetToUseDefaultQuality(self) -> None:
  1270. if self._global_container_stack is None:
  1271. return
  1272. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1273. self._setQualityGroup(self._current_quality_group)
  1274. for stack in [self._global_container_stack] + list(self._global_container_stack.extruders.values()):
  1275. stack.userChanges.clear()
  1276. @pyqtProperty(QObject, fset = setQualityChangesGroup, notify = activeQualityChangesGroupChanged)
  1277. def activeQualityChangesGroup(self) -> Optional["QualityChangesGroup"]:
  1278. return self._current_quality_changes_group
  1279. @pyqtProperty(str, notify = activeQualityGroupChanged)
  1280. def activeQualityOrQualityChangesName(self) -> str:
  1281. name = empty_quality_container.getName()
  1282. if self._current_quality_changes_group:
  1283. name = self._current_quality_changes_group.name
  1284. elif self._current_quality_group:
  1285. name = self._current_quality_group.name
  1286. return name
  1287. def _updateUponMaterialMetadataChange(self) -> None:
  1288. if self._global_container_stack is None:
  1289. return
  1290. with postponeSignals(*self._getContainerChangedSignals(), compress = CompressTechnique.CompressPerParameterValue):
  1291. self.updateMaterialWithVariant(None)
  1292. self._updateQualityWithMaterial()
  1293. ## This function will translate any printer type name to an abbreviated printer type name
  1294. @pyqtSlot(str, result = str)
  1295. def getAbbreviatedMachineName(self, machine_type_name: str) -> str:
  1296. abbr_machine = ""
  1297. for word in re.findall(r"[\w']+", machine_type_name):
  1298. if word.lower() == "ultimaker":
  1299. abbr_machine += "UM"
  1300. elif word.isdigit():
  1301. abbr_machine += word
  1302. else:
  1303. stripped_word = "".join(char for char in unicodedata.normalize("NFD", word.upper()) if unicodedata.category(char) != "Mn")
  1304. # - use only the first character if the word is too long (> 3 characters)
  1305. # - use the whole word if it's not too long (<= 3 characters)
  1306. if len(stripped_word) > 3:
  1307. stripped_word = stripped_word[0]
  1308. abbr_machine += stripped_word
  1309. return abbr_machine