MaterialManagementModel.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import copy # To duplicate materials.
  4. from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot # To allow the preference page proxy to be used from the actual preferences page.
  5. from typing import Any, Dict, Optional, TYPE_CHECKING
  6. import uuid # To generate new GUIDs for new materials.
  7. from UM.i18n import i18nCatalog
  8. from UM.Logger import Logger
  9. from UM.Signal import postponeSignals, CompressTechnique
  10. import cura.CuraApplication # Imported like this to prevent circular imports.
  11. from cura.Machines.ContainerTree import ContainerTree
  12. from cura.Settings.CuraContainerRegistry import CuraContainerRegistry # To find the sets of materials belonging to each other, and currently loaded extruder stacks.
  13. if TYPE_CHECKING:
  14. from cura.Machines.MaterialNode import MaterialNode
  15. catalog = i18nCatalog("cura")
  16. class MaterialManagementModel(QObject):
  17. """Proxy class to the materials page in the preferences.
  18. This class handles the actions in that page, such as creating new materials, renaming them, etc.
  19. """
  20. favoritesChanged = pyqtSignal(str)
  21. """Triggered when a favorite is added or removed.
  22. :param The base file of the material is provided as parameter when this emits
  23. """
  24. @pyqtSlot("QVariant", result = bool)
  25. def canMaterialBeRemoved(self, material_node: "MaterialNode") -> bool:
  26. """Can a certain material be deleted, or is it still in use in one of the container stacks anywhere?
  27. We forbid the user from deleting a material if it's in use in any stack. Deleting it while it's in use can
  28. lead to corrupted stacks. In the future we might enable this functionality again (deleting the material from
  29. those stacks) but for now it is easier to prevent the user from doing this.
  30. :param material_node: The ContainerTree node of the material to check.
  31. :return: Whether or not the material can be removed.
  32. """
  33. container_registry = CuraContainerRegistry.getInstance()
  34. ids_to_remove = {metadata.get("id", "") for metadata in container_registry.findInstanceContainersMetadata(base_file = material_node.base_file)}
  35. for extruder_stack in container_registry.findContainerStacks(type = "extruder_train"):
  36. if extruder_stack.material.getId() in ids_to_remove:
  37. return False
  38. return True
  39. @pyqtSlot("QVariant", str)
  40. def setMaterialName(self, material_node: "MaterialNode", name: str) -> None:
  41. """Change the user-visible name of a material.
  42. :param material_node: The ContainerTree node of the material to rename.
  43. :param name: The new name for the material.
  44. """
  45. container_registry = CuraContainerRegistry.getInstance()
  46. root_material_id = material_node.base_file
  47. if container_registry.isReadOnly(root_material_id):
  48. Logger.log("w", "Cannot set name of read-only container %s.", root_material_id)
  49. return
  50. return container_registry.findContainers(id = root_material_id)[0].setName(name)
  51. @pyqtSlot("QVariant")
  52. def removeMaterial(self, material_node: "MaterialNode") -> None:
  53. """Deletes a material from Cura.
  54. This function does not do any safety checking any more. Please call this function only if:
  55. - The material is not read-only.
  56. - The material is not used in any stacks.
  57. If the material was not lazy-loaded yet, this will fully load the container. When removing this material
  58. node, all other materials with the same base fill will also be removed.
  59. :param material_node: The material to remove.
  60. """
  61. container_registry = CuraContainerRegistry.getInstance()
  62. materials_this_base_file = container_registry.findContainersMetadata(base_file = material_node.base_file)
  63. # The material containers belonging to the same material file are supposed to work together. This postponeSignals()
  64. # does two things:
  65. # - optimizing the signal emitting.
  66. # - making sure that the signals will only be emitted after all the material containers have been removed.
  67. with postponeSignals(container_registry.containerRemoved, compress = CompressTechnique.CompressPerParameterValue):
  68. # CURA-6886: Some containers may not have been loaded. If remove one material container, its material file
  69. # will be removed. If later we remove a sub-material container which hasn't been loaded previously, it will
  70. # crash because removeContainer() requires to load the container first, but the material file was already
  71. # gone.
  72. for material_metadata in materials_this_base_file:
  73. container_registry.findInstanceContainers(id = material_metadata["id"])
  74. for material_metadata in materials_this_base_file:
  75. container_registry.removeContainer(material_metadata["id"])
  76. def duplicateMaterialByBaseFile(self, base_file: str, new_base_id: Optional[str] = None,
  77. new_metadata: Optional[Dict[str, Any]] = None) -> Optional[str]:
  78. """Creates a duplicate of a material with the same GUID and base_file metadata
  79. :param base_file: The base file of the material to duplicate.
  80. :param new_base_id: A new material ID for the base material. The IDs of the submaterials will be based off this
  81. one. If not provided, a material ID will be generated automatically.
  82. :param new_metadata: Metadata for the new material. If not provided, this will be duplicated from the original
  83. material.
  84. :return: The root material ID of the duplicate material.
  85. """
  86. container_registry = CuraContainerRegistry.getInstance()
  87. root_materials = container_registry.findContainers(id = base_file)
  88. if not root_materials:
  89. Logger.log("i", "Unable to duplicate the root material with ID {root_id}, because it doesn't exist.".format(root_id = base_file))
  90. return None
  91. root_material = root_materials[0]
  92. # Ensure that all settings are saved.
  93. application = cura.CuraApplication.CuraApplication.getInstance()
  94. application.saveSettings()
  95. # Create a new ID and container to hold the data.
  96. if new_base_id is None:
  97. new_base_id = container_registry.uniqueName(root_material.getId())
  98. new_root_material = copy.deepcopy(root_material)
  99. new_root_material.getMetaData()["id"] = new_base_id
  100. new_root_material.getMetaData()["base_file"] = new_base_id
  101. if new_metadata is not None:
  102. new_root_material.getMetaData().update(new_metadata)
  103. new_containers = [new_root_material]
  104. # Clone all submaterials.
  105. for container_to_copy in container_registry.findInstanceContainers(base_file = base_file):
  106. if container_to_copy.getId() == base_file:
  107. continue # We already have that one. Skip it.
  108. new_id = new_base_id
  109. definition = container_to_copy.getMetaDataEntry("definition")
  110. if definition != "fdmprinter":
  111. new_id += "_" + definition
  112. variant_name = container_to_copy.getMetaDataEntry("variant_name")
  113. if variant_name:
  114. new_id += "_" + variant_name.replace(" ", "_")
  115. new_container = copy.deepcopy(container_to_copy)
  116. new_container.getMetaData()["id"] = new_id
  117. new_container.getMetaData()["base_file"] = new_base_id
  118. if new_metadata is not None:
  119. new_container.getMetaData().update(new_metadata)
  120. new_containers.append(new_container)
  121. # CURA-6863: Nodes in ContainerTree will be updated upon ContainerAdded signals, one at a time. It will use the
  122. # best fit material container at the time it sees one. For example, if you duplicate and get generic_pva #2,
  123. # if the node update function sees the containers in the following order:
  124. #
  125. # - generic_pva #2
  126. # - generic_pva #2_um3_aa04
  127. #
  128. # It will first use "generic_pva #2" because that's the best fit it has ever seen, and later "generic_pva #2_um3_aa04"
  129. # once it sees that. Because things run in the Qt event loop, they don't happen at the same time. This means if
  130. # between those two events, the ContainerTree will have nodes that contain invalid data.
  131. #
  132. # This sort fixes the problem by emitting the most specific containers first.
  133. new_containers = sorted(new_containers, key = lambda x: x.getId(), reverse = True)
  134. # Optimization. Serving the same purpose as the postponeSignals() in removeMaterial()
  135. # postpone the signals emitted when duplicating materials. This is easier on the event loop; changes the
  136. # behavior to be like a transaction. Prevents concurrency issues.
  137. with postponeSignals(container_registry.containerAdded, compress=CompressTechnique.CompressPerParameterValue):
  138. for container_to_add in new_containers:
  139. container_to_add.setDirty(True)
  140. container_registry.addContainer(container_to_add)
  141. # If the duplicated material was favorite then the new material should also be added to the favorites.
  142. favorites_set = set(application.getPreferences().getValue("cura/favorite_materials").split(";"))
  143. if base_file in favorites_set:
  144. favorites_set.add(new_base_id)
  145. application.getPreferences().setValue("cura/favorite_materials", ";".join(favorites_set))
  146. return new_base_id
  147. @pyqtSlot("QVariant", result = str)
  148. def duplicateMaterial(self, material_node: "MaterialNode", new_base_id: Optional[str] = None,
  149. new_metadata: Optional[Dict[str, Any]] = None) -> Optional[str]:
  150. """Creates a duplicate of a material with the same GUID and base_file metadata
  151. :param material_node: The node representing the material to duplicate.
  152. :param new_base_id: A new material ID for the base material. The IDs of the submaterials will be based off this
  153. one. If not provided, a material ID will be generated automatically.
  154. :param new_metadata: Metadata for the new material. If not provided, this will be duplicated from the original
  155. material.
  156. :return: The root material ID of the duplicate material.
  157. """
  158. return self.duplicateMaterialByBaseFile(material_node.base_file, new_base_id, new_metadata)
  159. @pyqtSlot(result = str)
  160. def createMaterial(self) -> str:
  161. """Create a new material by cloning the preferred material for the current material diameter and generate a new
  162. GUID.
  163. The material type is explicitly left to be the one from the preferred material, since this allows the user to
  164. still have SOME profiles to work with.
  165. :return: The ID of the newly created material.
  166. """
  167. # Ensure all settings are saved.
  168. application = cura.CuraApplication.CuraApplication.getInstance()
  169. application.saveSettings()
  170. # Find the preferred material.
  171. extruder_stack = application.getMachineManager().activeStack
  172. active_variant_name = extruder_stack.variant.getName()
  173. approximate_diameter = int(extruder_stack.approximateMaterialDiameter)
  174. global_container_stack = application.getGlobalContainerStack()
  175. if not global_container_stack:
  176. return ""
  177. machine_node = ContainerTree.getInstance().machines[global_container_stack.definition.getId()]
  178. preferred_material_node = machine_node.variants[active_variant_name].preferredMaterial(approximate_diameter)
  179. # Create a new ID & new metadata for the new material.
  180. new_id = CuraContainerRegistry.getInstance().uniqueName("custom_material")
  181. new_metadata = {"name": catalog.i18nc("@label", "Custom Material"),
  182. "brand": catalog.i18nc("@label", "Custom"),
  183. "GUID": str(uuid.uuid4()),
  184. }
  185. self.duplicateMaterial(preferred_material_node, new_base_id = new_id, new_metadata = new_metadata)
  186. return new_id
  187. @pyqtSlot(str)
  188. def addFavorite(self, material_base_file: str) -> None:
  189. """Adds a certain material to the favorite materials.
  190. :param material_base_file: The base file of the material to add.
  191. """
  192. application = cura.CuraApplication.CuraApplication.getInstance()
  193. favorites = application.getPreferences().getValue("cura/favorite_materials").split(";")
  194. if material_base_file not in favorites:
  195. favorites.append(material_base_file)
  196. application.getPreferences().setValue("cura/favorite_materials", ";".join(favorites))
  197. application.saveSettings()
  198. self.favoritesChanged.emit(material_base_file)
  199. @pyqtSlot(str)
  200. def removeFavorite(self, material_base_file: str) -> None:
  201. """Removes a certain material from the favorite materials.
  202. If the material was not in the favorite materials, nothing happens.
  203. """
  204. application = cura.CuraApplication.CuraApplication.getInstance()
  205. favorites = application.getPreferences().getValue("cura/favorite_materials").split(";")
  206. try:
  207. favorites.remove(material_base_file)
  208. application.getPreferences().setValue("cura/favorite_materials", ";".join(favorites))
  209. application.saveSettings()
  210. self.favoritesChanged.emit(material_base_file)
  211. except ValueError: # Material was not in the favorites list.
  212. Logger.log("w", "Material {material_base_file} was already not a favorite material.".format(material_base_file = material_base_file))