MaterialManagementModel.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 pyqtSignal, pyqtSlot, QObject, QUrl
  5. from PyQt5.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. self._checkIfNewMaterialsWereInstalled()
  29. def _checkIfNewMaterialsWereInstalled(self) -> None:
  30. """
  31. Checks whether new material packages were installed in the latest startup. If there were, then it shows
  32. a message prompting the user to sync the materials with their printers.
  33. """
  34. application = cura.CuraApplication.CuraApplication.getInstance()
  35. for package_id, package_data in application.getPackageManager().getPackagesInstalledOnStartup().items():
  36. if package_data["package_info"]["package_type"] == "material":
  37. # At least one new material was installed
  38. # TODO: This should be enabled again once CURA-8609 is merged
  39. #self._showSyncNewMaterialsMessage()
  40. break
  41. def _showSyncNewMaterialsMessage(self) -> None:
  42. sync_materials_message = Message(
  43. text = catalog.i18nc("@action:button",
  44. "Please sync the material profiles with your printers before starting to print."),
  45. title = catalog.i18nc("@action:button", "New materials installed"),
  46. message_type = Message.MessageType.WARNING,
  47. lifetime = 0
  48. )
  49. sync_materials_message.addAction(
  50. "sync",
  51. name = catalog.i18nc("@action:button", "Sync materials with printers"),
  52. icon = "",
  53. description = "Sync your newly installed materials with your printers.",
  54. button_align = Message.ActionButtonAlignment.ALIGN_RIGHT
  55. )
  56. sync_materials_message.addAction(
  57. "learn_more",
  58. name = catalog.i18nc("@action:button", "Learn more"),
  59. icon = "",
  60. description = "Learn more about syncing your newly installed materials with your printers.",
  61. button_align = Message.ActionButtonAlignment.ALIGN_LEFT,
  62. button_style = Message.ActionButtonStyle.LINK
  63. )
  64. sync_materials_message.actionTriggered.connect(self._onSyncMaterialsMessageActionTriggered)
  65. # Show the message only if there are printers that support material export
  66. container_registry = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry()
  67. global_stacks = container_registry.findContainerStacks(type = "machine")
  68. if any([stack.supportsMaterialExport for stack in global_stacks]):
  69. sync_materials_message.show()
  70. def _onSyncMaterialsMessageActionTriggered(self, sync_message: Message, sync_message_action: str):
  71. if sync_message_action == "sync":
  72. QDesktopServices.openUrl(QUrl("https://example.com/openSyncAllWindow"))
  73. # self.openSyncAllWindow()
  74. sync_message.hide()
  75. elif sync_message_action == "learn_more":
  76. QDesktopServices.openUrl(QUrl("https://support.ultimaker.com/hc/en-us/articles/360013137919?utm_source=cura&utm_medium=software&utm_campaign=sync-material-printer-message"))
  77. @pyqtSlot("QVariant", result = bool)
  78. def canMaterialBeRemoved(self, material_node: "MaterialNode") -> bool:
  79. """Can a certain material be deleted, or is it still in use in one of the container stacks anywhere?
  80. We forbid the user from deleting a material if it's in use in any stack. Deleting it while it's in use can
  81. lead to corrupted stacks. In the future we might enable this functionality again (deleting the material from
  82. those stacks) but for now it is easier to prevent the user from doing this.
  83. :param material_node: The ContainerTree node of the material to check.
  84. :return: Whether or not the material can be removed.
  85. """
  86. container_registry = CuraContainerRegistry.getInstance()
  87. ids_to_remove = {metadata.get("id", "") for metadata in container_registry.findInstanceContainersMetadata(base_file = material_node.base_file)}
  88. for extruder_stack in container_registry.findContainerStacks(type = "extruder_train"):
  89. if extruder_stack.material.getId() in ids_to_remove:
  90. return False
  91. return True
  92. @pyqtSlot("QVariant", str)
  93. def setMaterialName(self, material_node: "MaterialNode", name: str) -> None:
  94. """Change the user-visible name of a material.
  95. :param material_node: The ContainerTree node of the material to rename.
  96. :param name: The new name for the material.
  97. """
  98. container_registry = CuraContainerRegistry.getInstance()
  99. root_material_id = material_node.base_file
  100. if container_registry.isReadOnly(root_material_id):
  101. Logger.log("w", "Cannot set name of read-only container %s.", root_material_id)
  102. return
  103. return container_registry.findContainers(id = root_material_id)[0].setName(name)
  104. @pyqtSlot("QVariant")
  105. def removeMaterial(self, material_node: "MaterialNode") -> None:
  106. """Deletes a material from Cura.
  107. This function does not do any safety checking any more. Please call this function only if:
  108. - The material is not read-only.
  109. - The material is not used in any stacks.
  110. If the material was not lazy-loaded yet, this will fully load the container. When removing this material
  111. node, all other materials with the same base fill will also be removed.
  112. :param material_node: The material to remove.
  113. """
  114. Logger.info(f"Removing material {material_node.container_id}")
  115. container_registry = CuraContainerRegistry.getInstance()
  116. materials_this_base_file = container_registry.findContainersMetadata(base_file = material_node.base_file)
  117. # The material containers belonging to the same material file are supposed to work together. This postponeSignals()
  118. # does two things:
  119. # - optimizing the signal emitting.
  120. # - making sure that the signals will only be emitted after all the material containers have been removed.
  121. with postponeSignals(container_registry.containerRemoved, compress = CompressTechnique.CompressPerParameterValue):
  122. # CURA-6886: Some containers may not have been loaded. If remove one material container, its material file
  123. # will be removed. If later we remove a sub-material container which hasn't been loaded previously, it will
  124. # crash because removeContainer() requires to load the container first, but the material file was already
  125. # gone.
  126. for material_metadata in materials_this_base_file:
  127. container_registry.findInstanceContainers(id = material_metadata["id"])
  128. for material_metadata in materials_this_base_file:
  129. container_registry.removeContainer(material_metadata["id"])
  130. def duplicateMaterialByBaseFile(self, base_file: str, new_base_id: Optional[str] = None,
  131. new_metadata: Optional[Dict[str, Any]] = None) -> Optional[str]:
  132. """Creates a duplicate of a material with the same GUID and base_file metadata
  133. :param base_file: The base file of the material to duplicate.
  134. :param new_base_id: A new material ID for the base material. The IDs of the submaterials will be based off this
  135. one. If not provided, a material ID will be generated automatically.
  136. :param new_metadata: Metadata for the new material. If not provided, this will be duplicated from the original
  137. material.
  138. :return: The root material ID of the duplicate material.
  139. """
  140. container_registry = CuraContainerRegistry.getInstance()
  141. root_materials = container_registry.findContainers(id = base_file)
  142. if not root_materials:
  143. Logger.log("i", "Unable to duplicate the root material with ID {root_id}, because it doesn't exist.".format(root_id = base_file))
  144. return None
  145. root_material = root_materials[0]
  146. # Ensure that all settings are saved.
  147. application = cura.CuraApplication.CuraApplication.getInstance()
  148. application.saveSettings()
  149. # Create a new ID and container to hold the data.
  150. if new_base_id is None:
  151. new_base_id = container_registry.uniqueName(root_material.getId())
  152. new_root_material = copy.deepcopy(root_material)
  153. new_root_material.getMetaData()["id"] = new_base_id
  154. new_root_material.getMetaData()["base_file"] = new_base_id
  155. if new_metadata is not None:
  156. new_root_material.getMetaData().update(new_metadata)
  157. new_containers = [new_root_material]
  158. # Clone all submaterials.
  159. for container_to_copy in container_registry.findInstanceContainers(base_file = base_file):
  160. if container_to_copy.getId() == base_file:
  161. continue # We already have that one. Skip it.
  162. new_id = new_base_id
  163. definition = container_to_copy.getMetaDataEntry("definition")
  164. if definition != "fdmprinter":
  165. new_id += "_" + definition
  166. variant_name = container_to_copy.getMetaDataEntry("variant_name")
  167. if variant_name:
  168. new_id += "_" + variant_name.replace(" ", "_")
  169. new_container = copy.deepcopy(container_to_copy)
  170. new_container.getMetaData()["id"] = new_id
  171. new_container.getMetaData()["base_file"] = new_base_id
  172. if new_metadata is not None:
  173. new_container.getMetaData().update(new_metadata)
  174. new_containers.append(new_container)
  175. # CURA-6863: Nodes in ContainerTree will be updated upon ContainerAdded signals, one at a time. It will use the
  176. # best fit material container at the time it sees one. For example, if you duplicate and get generic_pva #2,
  177. # if the node update function sees the containers in the following order:
  178. #
  179. # - generic_pva #2
  180. # - generic_pva #2_um3_aa04
  181. #
  182. # It will first use "generic_pva #2" because that's the best fit it has ever seen, and later "generic_pva #2_um3_aa04"
  183. # once it sees that. Because things run in the Qt event loop, they don't happen at the same time. This means if
  184. # between those two events, the ContainerTree will have nodes that contain invalid data.
  185. #
  186. # This sort fixes the problem by emitting the most specific containers first.
  187. new_containers = sorted(new_containers, key = lambda x: x.getId(), reverse = True)
  188. # Optimization. Serving the same purpose as the postponeSignals() in removeMaterial()
  189. # postpone the signals emitted when duplicating materials. This is easier on the event loop; changes the
  190. # behavior to be like a transaction. Prevents concurrency issues.
  191. with postponeSignals(container_registry.containerAdded, compress=CompressTechnique.CompressPerParameterValue):
  192. for container_to_add in new_containers:
  193. container_to_add.setDirty(True)
  194. container_registry.addContainer(container_to_add)
  195. # If the duplicated material was favorite then the new material should also be added to the favorites.
  196. favorites_set = set(application.getPreferences().getValue("cura/favorite_materials").split(";"))
  197. if base_file in favorites_set:
  198. favorites_set.add(new_base_id)
  199. application.getPreferences().setValue("cura/favorite_materials", ";".join(favorites_set))
  200. return new_base_id
  201. @pyqtSlot("QVariant", result = str)
  202. def duplicateMaterial(self, material_node: "MaterialNode", new_base_id: Optional[str] = None,
  203. new_metadata: Optional[Dict[str, Any]] = None) -> Optional[str]:
  204. """Creates a duplicate of a material with the same GUID and base_file metadata
  205. :param material_node: The node representing the material to duplicate.
  206. :param new_base_id: A new material ID for the base material. The IDs of the submaterials will be based off this
  207. one. If not provided, a material ID will be generated automatically.
  208. :param new_metadata: Metadata for the new material. If not provided, this will be duplicated from the original
  209. material.
  210. :return: The root material ID of the duplicate material.
  211. """
  212. Logger.info(f"Duplicating material {material_node.base_file} to {new_base_id}")
  213. return self.duplicateMaterialByBaseFile(material_node.base_file, new_base_id, new_metadata)
  214. @pyqtSlot(result = str)
  215. def createMaterial(self) -> str:
  216. """Create a new material by cloning the preferred material for the current material diameter and generate a new
  217. GUID.
  218. The material type is explicitly left to be the one from the preferred material, since this allows the user to
  219. still have SOME profiles to work with.
  220. :return: The ID of the newly created material.
  221. """
  222. # Ensure all settings are saved.
  223. application = cura.CuraApplication.CuraApplication.getInstance()
  224. application.saveSettings()
  225. # Find the preferred material.
  226. extruder_stack = application.getMachineManager().activeStack
  227. active_variant_name = extruder_stack.variant.getName()
  228. approximate_diameter = int(extruder_stack.approximateMaterialDiameter)
  229. global_container_stack = application.getGlobalContainerStack()
  230. if not global_container_stack:
  231. return ""
  232. machine_node = ContainerTree.getInstance().machines[global_container_stack.definition.getId()]
  233. preferred_material_node = machine_node.variants[active_variant_name].preferredMaterial(approximate_diameter)
  234. # Create a new ID & new metadata for the new material.
  235. new_id = CuraContainerRegistry.getInstance().uniqueName("custom_material")
  236. new_metadata = {"name": catalog.i18nc("@label", "Custom Material"),
  237. "brand": catalog.i18nc("@label", "Custom"),
  238. "GUID": str(uuid.uuid4()),
  239. }
  240. self.duplicateMaterial(preferred_material_node, new_base_id = new_id, new_metadata = new_metadata)
  241. return new_id
  242. @pyqtSlot(str)
  243. def addFavorite(self, material_base_file: str) -> None:
  244. """Adds a certain material to the favorite materials.
  245. :param material_base_file: The base file of the material to add.
  246. """
  247. application = cura.CuraApplication.CuraApplication.getInstance()
  248. favorites = application.getPreferences().getValue("cura/favorite_materials").split(";")
  249. if material_base_file not in favorites:
  250. favorites.append(material_base_file)
  251. application.getPreferences().setValue("cura/favorite_materials", ";".join(favorites))
  252. application.saveSettings()
  253. self.favoritesChanged.emit(material_base_file)
  254. @pyqtSlot(str)
  255. def removeFavorite(self, material_base_file: str) -> None:
  256. """Removes a certain material from the favorite materials.
  257. If the material was not in the favorite materials, nothing happens.
  258. """
  259. application = cura.CuraApplication.CuraApplication.getInstance()
  260. favorites = application.getPreferences().getValue("cura/favorite_materials").split(";")
  261. try:
  262. favorites.remove(material_base_file)
  263. application.getPreferences().setValue("cura/favorite_materials", ";".join(favorites))
  264. application.saveSettings()
  265. self.favoritesChanged.emit(material_base_file)
  266. except ValueError: # Material was not in the favorites list.
  267. Logger.log("w", "Material {material_base_file} was already not a favorite material.".format(material_base_file = material_base_file))
  268. @pyqtSlot()
  269. def openSyncAllWindow(self) -> None:
  270. """
  271. Opens the window to sync all materials.
  272. """
  273. self._material_sync.openSyncAllWindow()