MaterialManagementModel.py 14 KB

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