MaterialManagementModel.py 16 KB

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