ExtruderManager.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. # Copyright (c) 2016 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. from PyQt5.QtCore import pyqtSignal, pyqtProperty, pyqtSlot, QObject, QVariant #For communicating data and events to Qt.
  4. import UM.Application #To get the global container stack to find the current machine.
  5. import UM.Logger
  6. import UM.Settings.ContainerRegistry #Finding containers by ID.
  7. import UM.Settings.SettingFunction
  8. ## Manages all existing extruder stacks.
  9. #
  10. # This keeps a list of extruder stacks for each machine.
  11. class ExtruderManager(QObject):
  12. ## Signal to notify other components when the list of extruders for a machine definition changes.
  13. extrudersChanged = pyqtSignal(QVariant)
  14. ## Signal to notify other components when the global container stack is switched to a definition
  15. # that has different extruders than the previous global container stack
  16. globalContainerStackDefinitionChanged = pyqtSignal()
  17. ## Notify when the user switches the currently active extruder.
  18. activeExtruderChanged = pyqtSignal()
  19. ## Registers listeners and such to listen to changes to the extruders.
  20. def __init__(self, parent = None):
  21. super().__init__(parent)
  22. self._extruder_trains = { } #Per machine, a dictionary of extruder container stack IDs.
  23. self._active_extruder_index = 0
  24. UM.Application.getInstance().globalContainerStackChanged.connect(self.__globalContainerStackChanged)
  25. self._global_container_stack_definition_id = None
  26. self._addCurrentMachineExtruders()
  27. ## Gets the unique identifier of the currently active extruder stack.
  28. #
  29. # The currently active extruder stack is the stack that is currently being
  30. # edited.
  31. #
  32. # \return The unique ID of the currently active extruder stack.
  33. @pyqtProperty(str, notify = activeExtruderChanged)
  34. def activeExtruderStackId(self):
  35. if not UM.Application.getInstance().getGlobalContainerStack():
  36. return None # No active machine, so no active extruder.
  37. try:
  38. return self._extruder_trains[UM.Application.getInstance().getGlobalContainerStack().getId()][str(self._active_extruder_index)].getId()
  39. except KeyError: # Extruder index could be -1 if the global tab is selected, or the entry doesn't exist if the machine definition is wrong.
  40. return None
  41. @pyqtProperty(int, notify = extrudersChanged)
  42. def extruderCount(self):
  43. if not UM.Application.getInstance().getGlobalContainerStack():
  44. return 0 # No active machine, so no extruders.
  45. return len(self._extruder_trains[UM.Application.getInstance().getGlobalContainerStack().getId()])
  46. @pyqtProperty("QVariantMap", notify=extrudersChanged)
  47. def extruderIds(self):
  48. map = {}
  49. for position in self._extruder_trains[UM.Application.getInstance().getGlobalContainerStack().getId()]:
  50. map[position] = self._extruder_trains[UM.Application.getInstance().getGlobalContainerStack().getId()][position].getId()
  51. return map
  52. @pyqtSlot(str, result = str)
  53. def getQualityChangesIdByExtruderStackId(self, id):
  54. for position in self._extruder_trains[UM.Application.getInstance().getGlobalContainerStack().getId()]:
  55. extruder = self._extruder_trains[UM.Application.getInstance().getGlobalContainerStack().getId()][position]
  56. if extruder.getId() == id:
  57. return extruder.findContainer(type = "quality_changes").getId()
  58. ## The instance of the singleton pattern.
  59. #
  60. # It's None if the extruder manager hasn't been created yet.
  61. __instance = None
  62. ## Gets an instance of the extruder manager, or creates one if no instance
  63. # exists yet.
  64. #
  65. # This is an implementation of singleton. If an extruder manager already
  66. # exists, it is re-used.
  67. #
  68. # \return The extruder manager.
  69. @classmethod
  70. def getInstance(cls):
  71. if not cls.__instance:
  72. cls.__instance = ExtruderManager()
  73. return cls.__instance
  74. ## Changes the active extruder by index.
  75. #
  76. # \param index The index of the new active extruder.
  77. @pyqtSlot(int)
  78. def setActiveExtruderIndex(self, index):
  79. self._active_extruder_index = index
  80. self.activeExtruderChanged.emit()
  81. @pyqtProperty(int, notify = activeExtruderChanged)
  82. def activeExtruderIndex(self):
  83. return self._active_extruder_index
  84. def getActiveExtruderStack(self):
  85. global_container_stack = UM.Application.getInstance().getGlobalContainerStack()
  86. if global_container_stack:
  87. if global_container_stack.getId() in self._extruder_trains:
  88. if str(self._active_extruder_index) in self._extruder_trains[global_container_stack.getId()]:
  89. return self._extruder_trains[global_container_stack.getId()][str(self._active_extruder_index)]
  90. return None
  91. ## Get an extruder stack by index
  92. def getExtruderStack(self, index):
  93. global_container_stack = UM.Application.getInstance().getGlobalContainerStack()
  94. if global_container_stack:
  95. if global_container_stack.getId() in self._extruder_trains:
  96. if str(index) in self._extruder_trains[global_container_stack.getId()]:
  97. return self._extruder_trains[global_container_stack.getId()][str(index)]
  98. return None
  99. ## Adds all extruders of a specific machine definition to the extruder
  100. # manager.
  101. #
  102. # \param machine_definition The machine definition to add the extruders for.
  103. # \param machine_id The machine_id to add the extruders for.
  104. def addMachineExtruders(self, machine_definition, machine_id):
  105. changed = False
  106. machine_definition_id = machine_definition.getId()
  107. if machine_id not in self._extruder_trains:
  108. self._extruder_trains[machine_id] = { }
  109. changed = True
  110. container_registry = UM.Settings.ContainerRegistry.getInstance()
  111. if container_registry:
  112. # Add the extruder trains that don't exist yet.
  113. for extruder_definition in container_registry.findDefinitionContainers(machine = machine_definition_id):
  114. position = extruder_definition.getMetaDataEntry("position", None)
  115. if not position:
  116. UM.Logger.log("w", "Extruder definition %s specifies no position metadata entry.", extruder_definition.getId())
  117. if not container_registry.findContainerStacks(machine = machine_id, position = position): # Doesn't exist yet.
  118. self.createExtruderTrain(extruder_definition, machine_definition, position, machine_id)
  119. changed = True
  120. # Gets the extruder trains that we just created as well as any that still existed.
  121. extruder_trains = container_registry.findContainerStacks(type = "extruder_train", machine = machine_id)
  122. for extruder_train in extruder_trains:
  123. self._extruder_trains[machine_id][extruder_train.getMetaDataEntry("position")] = extruder_train
  124. # regardless of what the next stack is, we have to set it again, because of signal routing.
  125. extruder_train.setNextStack(UM.Application.getInstance().getGlobalContainerStack())
  126. changed = True
  127. if changed:
  128. self.extrudersChanged.emit(machine_id)
  129. ## Creates a container stack for an extruder train.
  130. #
  131. # The container stack has an extruder definition at the bottom, which is
  132. # linked to a machine definition. Then it has a variant profile, a material
  133. # profile, a quality profile and a user profile, in that order.
  134. #
  135. # The resulting container stack is added to the registry.
  136. #
  137. # \param extruder_definition The extruder to create the extruder train for.
  138. # \param machine_definition The machine that the extruder train belongs to.
  139. # \param position The position of this extruder train in the extruder slots of the machine.
  140. # \param machine_id The id of the "global" stack this extruder is linked to.
  141. def createExtruderTrain(self, extruder_definition, machine_definition, position, machine_id):
  142. # Cache some things.
  143. container_registry = UM.Settings.ContainerRegistry.getInstance()
  144. machine_definition_id = UM.Application.getInstance().getMachineManager().getQualityDefinitionId(machine_definition)
  145. # Create a container stack for this extruder.
  146. extruder_stack_id = container_registry.uniqueName(extruder_definition.getId())
  147. container_stack = UM.Settings.ContainerStack(extruder_stack_id)
  148. container_stack.setName(extruder_definition.getName()) # Take over the display name to display the stack with.
  149. container_stack.addMetaDataEntry("type", "extruder_train")
  150. container_stack.addMetaDataEntry("machine", machine_id)
  151. container_stack.addMetaDataEntry("position", position)
  152. container_stack.addContainer(extruder_definition)
  153. # Find the variant to use for this extruder.
  154. variant = container_registry.findInstanceContainers(id = "empty_variant")[0]
  155. if machine_definition.getMetaDataEntry("has_variants"):
  156. # First add any variant. Later, overwrite with preference if the preference is valid.
  157. variants = container_registry.findInstanceContainers(definition = machine_definition_id, type = "variant")
  158. if len(variants) >= 1:
  159. variant = variants[0]
  160. preferred_variant_id = machine_definition.getMetaDataEntry("preferred_variant")
  161. if preferred_variant_id:
  162. preferred_variants = container_registry.findInstanceContainers(id = preferred_variant_id, definition = machine_definition_id, type = "variant")
  163. if len(preferred_variants) >= 1:
  164. variant = preferred_variants[0]
  165. else:
  166. UM.Logger.log("w", "The preferred variant \"%s\" of machine %s doesn't exist or is not a variant profile.", preferred_variant_id, machine_id)
  167. # And leave it at the default variant.
  168. container_stack.addContainer(variant)
  169. # Find a material to use for this variant.
  170. material = container_registry.findInstanceContainers(id = "empty_material")[0]
  171. if machine_definition.getMetaDataEntry("has_materials"):
  172. # First add any material. Later, overwrite with preference if the preference is valid.
  173. machine_has_variant_materials = machine_definition.getMetaDataEntry("has_variant_materials", default = False)
  174. if machine_has_variant_materials or machine_has_variant_materials == "True":
  175. materials = container_registry.findInstanceContainers(type = "material", definition = machine_definition_id, variant = variant.getId())
  176. else:
  177. materials = container_registry.findInstanceContainers(type = "material", definition = machine_definition_id)
  178. if len(materials) >= 1:
  179. material = materials[0]
  180. preferred_material_id = machine_definition.getMetaDataEntry("preferred_material")
  181. if preferred_material_id:
  182. search_criteria = { "type": "material", "id": preferred_material_id}
  183. if machine_definition.getMetaDataEntry("has_machine_materials"):
  184. search_criteria["definition"] = machine_definition.id
  185. if machine_definition.getMetaDataEntry("has_variants") and variant:
  186. search_criteria["variant"] = variant.id
  187. else:
  188. search_criteria["definition"] = "fdmprinter"
  189. preferred_materials = container_registry.findInstanceContainers(**search_criteria)
  190. if len(preferred_materials) >= 1:
  191. material = preferred_materials[0]
  192. else:
  193. UM.Logger.log("w", "The preferred material \"%s\" of machine %s doesn't exist or is not a material profile.", preferred_material_id, machine_id)
  194. # And leave it at the default material.
  195. container_stack.addContainer(material)
  196. # Find a quality to use for this extruder.
  197. quality = container_registry.getEmptyInstanceContainer()
  198. search_criteria = { "type": "quality" }
  199. if machine_definition.getMetaDataEntry("has_machine_quality"):
  200. search_criteria["definition"] = machine_definition_id
  201. if machine_definition.getMetaDataEntry("has_materials") and material:
  202. search_criteria["material"] = material.id
  203. else:
  204. search_criteria["definition"] = "fdmprinter"
  205. preferred_quality = machine_definition.getMetaDataEntry("preferred_quality")
  206. if preferred_quality:
  207. search_criteria["id"] = preferred_quality
  208. containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(**search_criteria)
  209. if not containers and preferred_quality:
  210. UM.Logger.log("w", "The preferred quality \"%s\" of machine %s doesn't exist or is not a quality profile.", preferred_quality, machine_id)
  211. search_criteria.pop("id", None)
  212. containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(**search_criteria)
  213. if containers:
  214. quality = containers[0]
  215. container_stack.addContainer(quality)
  216. empty_quality_changes = container_registry.findInstanceContainers(id = "empty_quality_changes")[0]
  217. container_stack.addContainer(empty_quality_changes)
  218. user_profile = container_registry.findInstanceContainers(type = "user", extruder = extruder_stack_id)
  219. if user_profile: # There was already a user profile, loaded from settings.
  220. user_profile = user_profile[0]
  221. else:
  222. user_profile = UM.Settings.InstanceContainer(extruder_stack_id + "_current_settings") # Add an empty user profile.
  223. user_profile.addMetaDataEntry("type", "user")
  224. user_profile.addMetaDataEntry("extruder", extruder_stack_id)
  225. user_profile.setDefinition(machine_definition)
  226. container_registry.addContainer(user_profile)
  227. container_stack.addContainer(user_profile)
  228. # regardless of what the next stack is, we have to set it again, because of signal routing.
  229. container_stack.setNextStack(UM.Application.getInstance().getGlobalContainerStack())
  230. container_registry.addContainer(container_stack)
  231. def getAllExtruderValues(self, setting_key):
  232. global_container_stack = UM.Application.getInstance().getGlobalContainerStack()
  233. multi_extrusion = global_container_stack.getProperty("machine_extruder_count", "value") > 1
  234. if not multi_extrusion:
  235. return [global_container_stack.getProperty(setting_key, "value")]
  236. result = []
  237. for index in self.extruderIds:
  238. extruder_stack_id = self.extruderIds[str(index)]
  239. stack = UM.Settings.ContainerRegistry.getInstance().findContainerStacks(id=extruder_stack_id)[0]
  240. result.append(stack.getProperty(setting_key, "value"))
  241. return result
  242. ## Removes the container stack and user profile for the extruders for a specific machine.
  243. #
  244. # \param machine_id The machine to remove the extruders for.
  245. def removeMachineExtruders(self, machine_id):
  246. for extruder in self.getMachineExtruders(machine_id):
  247. containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(type = "user", extruder = extruder.getId())
  248. for container in containers:
  249. UM.Settings.ContainerRegistry.getInstance().removeContainer(container.getId())
  250. UM.Settings.ContainerRegistry.getInstance().removeContainer(extruder.getId())
  251. ## Returns extruders for a specific machine.
  252. #
  253. # \param machine_id The machine to get the extruders of.
  254. def getMachineExtruders(self, machine_id):
  255. if machine_id not in self._extruder_trains:
  256. UM.Logger.log("w", "Tried to get the extruder trains for machine %s, which doesn't exist.", machine_id)
  257. return
  258. for name in self._extruder_trains[machine_id]:
  259. yield self._extruder_trains[machine_id][name]
  260. ## Returns a list containing the global stack and active extruder stacks.
  261. #
  262. # The first element is the global container stack, followed by any extruder stacks.
  263. # \return \type{List[ContainerStack]}
  264. def getActiveGlobalAndExtruderStacks(self):
  265. global_stack = UM.Application.getInstance().getGlobalContainerStack()
  266. if not global_stack:
  267. return None
  268. result = [global_stack]
  269. result.extend(self.getActiveExtruderStacks())
  270. return result
  271. ## Returns the list of active extruder stacks.
  272. #
  273. # \return \type{List[ContainerStack]} a list of
  274. def getActiveExtruderStacks(self):
  275. global_stack = UM.Application.getInstance().getGlobalContainerStack()
  276. return list(self._extruder_trains[global_stack.getId()].values()) if global_stack else []
  277. def __globalContainerStackChanged(self):
  278. self._addCurrentMachineExtruders()
  279. global_container_stack = UM.Application.getInstance().getGlobalContainerStack()
  280. if global_container_stack and global_container_stack.getBottom() and global_container_stack.getBottom().getId() != self._global_container_stack_definition_id:
  281. self._global_container_stack_definition_id = global_container_stack.getBottom().getId()
  282. self.globalContainerStackDefinitionChanged.emit()
  283. self.activeExtruderChanged.emit()
  284. ## Adds the extruders of the currently active machine.
  285. def _addCurrentMachineExtruders(self):
  286. global_stack = UM.Application.getInstance().getGlobalContainerStack()
  287. if global_stack and global_stack.getBottom():
  288. self.addMachineExtruders(global_stack.getBottom(), global_stack.getId())
  289. ## Get all extruder values for a certain setting.
  290. #
  291. # This is exposed to SettingFunction so it can be used in value functions.
  292. #
  293. # \param key The key of the setting to retieve values for.
  294. #
  295. # \return A list of values for all extruders. If an extruder does not have a value, it will not be in the list.
  296. # If no extruder has the value, the list will contain the global value.
  297. @staticmethod
  298. def getExtruderValues(key):
  299. global_stack = UM.Application.getInstance().getGlobalContainerStack()
  300. result = []
  301. for extruder in ExtruderManager.getInstance().getMachineExtruders(global_stack.getId()):
  302. value = extruder.getRawProperty(key, "value")
  303. if value is None:
  304. continue
  305. if isinstance(value, UM.Settings.SettingFunction):
  306. value = value(extruder)
  307. result.append(value)
  308. if not result:
  309. result.append(global_stack.getProperty(key, "value"))
  310. return result
  311. ## Get all extruder values for a certain setting.
  312. #
  313. # This is exposed to qml for display purposes
  314. #
  315. # \param key The key of the setting to retieve values for.
  316. #
  317. # \return String representing the extruder values
  318. @pyqtSlot(str, result="QVariant")
  319. def getInstanceExtruderValues(self, key):
  320. return ExtruderManager.getExtruderValues(key)
  321. ## Get the value for a setting from a specific extruder.
  322. #
  323. # This is exposed to SettingFunction to use in value functions.
  324. #
  325. # \param extruder_index The index of the extruder to get the value from.
  326. # \param key The key of the setting to get the value of.
  327. #
  328. # \return The value of the setting for the specified extruder or for the
  329. # global stack if not found.
  330. @staticmethod
  331. def getExtruderValue(extruder_index, key):
  332. extruder = ExtruderManager.getInstance().getExtruderStack(extruder_index)
  333. if extruder:
  334. value = extruder.getRawProperty(key, "value")
  335. if isinstance(value, UM.Settings.SettingFunction):
  336. value = value(extruder)
  337. else: #Just a value from global.
  338. value = UM.Application.getInstance().getGlobalContainerStack().getProperty(key, "value")
  339. return value
  340. ## Get the resolve value or value for a given key
  341. #
  342. # This is the effective value for a given key, it is used for values in the global stack.
  343. # This is exposed to SettingFunction to use in value functions.
  344. # \param key The key of the setting to get the value of.
  345. #
  346. # \return The effective value
  347. @staticmethod
  348. def getResolveOrValue(key):
  349. global_stack = UM.Application.getInstance().getGlobalContainerStack()
  350. resolved_value = global_stack.getProperty(key, "resolve")
  351. if resolved_value is not None:
  352. user_container = global_stack.findContainer({"type": "user"})
  353. quality_changes_container = global_stack.findContainer({"type": "quality_changes"})
  354. if user_container.hasProperty(key, "value") or quality_changes_container.hasProperty(key, "value"):
  355. # Normal case
  356. value = global_stack.getProperty(key, "value")
  357. else:
  358. # We have a resolved value and we're using it because of no user and quality_changes value
  359. value = resolved_value
  360. else:
  361. value = global_stack.getRawProperty(key, "value")
  362. return value