ContainerManager.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import os
  4. import urllib.parse
  5. import uuid
  6. from typing import Any, cast, Dict, List, TYPE_CHECKING, Union
  7. from PyQt5.QtCore import QObject, QUrl
  8. from PyQt5.QtWidgets import QMessageBox
  9. from UM.i18n import i18nCatalog
  10. from UM.FlameProfiler import pyqtSlot
  11. from UM.Logger import Logger
  12. from UM.MimeTypeDatabase import MimeTypeDatabase, MimeTypeNotFoundError
  13. from UM.Platform import Platform
  14. from UM.SaveFile import SaveFile
  15. from UM.Settings.ContainerFormatError import ContainerFormatError
  16. from UM.Settings.ContainerRegistry import ContainerRegistry
  17. from UM.Settings.ContainerStack import ContainerStack
  18. from UM.Settings.DefinitionContainer import DefinitionContainer
  19. from UM.Settings.InstanceContainer import InstanceContainer
  20. import cura.CuraApplication
  21. from cura.Machines.ContainerTree import ContainerTree
  22. from cura.Settings.ExtruderStack import ExtruderStack
  23. from cura.Settings.GlobalStack import GlobalStack
  24. if TYPE_CHECKING:
  25. from cura.CuraApplication import CuraApplication
  26. from cura.Machines.ContainerNode import ContainerNode
  27. from cura.Machines.MaterialNode import MaterialNode
  28. from cura.Machines.QualityChangesGroup import QualityChangesGroup
  29. catalog = i18nCatalog("cura")
  30. class ContainerManager(QObject):
  31. """Manager class that contains common actions to deal with containers in Cura.
  32. This is primarily intended as a class to be able to perform certain actions
  33. from within QML. We want to be able to trigger things like removing a container
  34. when a certain action happens. This can be done through this class.
  35. """
  36. def __init__(self, application: "CuraApplication") -> None:
  37. if ContainerManager.__instance is not None:
  38. raise RuntimeError("Try to create singleton '%s' more than once" % self.__class__.__name__)
  39. ContainerManager.__instance = self
  40. try:
  41. super().__init__(parent = application)
  42. except TypeError:
  43. super().__init__()
  44. self._container_name_filters = {} # type: Dict[str, Dict[str, Any]]
  45. @pyqtSlot(str, str, result=str)
  46. def getContainerMetaDataEntry(self, container_id: str, entry_names: str) -> str:
  47. metadatas = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry().findContainersMetadata(id = container_id)
  48. if not metadatas:
  49. Logger.log("w", "Could not get metadata of container %s because it was not found.", container_id)
  50. return ""
  51. entries = entry_names.split("/")
  52. result = metadatas[0]
  53. while entries:
  54. entry = entries.pop(0)
  55. result = result.get(entry, {})
  56. if not result:
  57. return ""
  58. return str(result)
  59. @pyqtSlot("QVariant", str, str)
  60. def setContainerMetaDataEntry(self, container_node: "ContainerNode", entry_name: str, entry_value: str) -> bool:
  61. """Set a metadata entry of the specified container.
  62. This will set the specified entry of the container's metadata to the specified
  63. value. Note that entries containing dictionaries can have their entries changed
  64. by using "/" as a separator. For example, to change an entry "foo" in a
  65. dictionary entry "bar", you can specify "bar/foo" as entry name.
  66. :param container_node: :type{ContainerNode}
  67. :param entry_name: :type{str} The name of the metadata entry to change.
  68. :param entry_value: The new value of the entry.
  69. TODO: This is ONLY used by MaterialView for material containers. Maybe refactor this.
  70. Update: In order for QML to use objects and sub objects, those (sub) objects must all be QObject. Is that what we want?
  71. """
  72. if container_node.container is None:
  73. Logger.log("w", "Container node {0} doesn't have a container.".format(container_node.container_id))
  74. return False
  75. root_material_id = container_node.getMetaDataEntry("base_file", "")
  76. container_registry = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry()
  77. if container_registry.isReadOnly(root_material_id):
  78. Logger.log("w", "Cannot set metadata of read-only container %s.", root_material_id)
  79. return False
  80. root_material_query = container_registry.findContainers(id = root_material_id)
  81. if not root_material_query:
  82. Logger.log("w", "Unable to find root material: {root_material}.".format(root_material = root_material_id))
  83. return False
  84. root_material = root_material_query[0]
  85. entries = entry_name.split("/")
  86. entry_name = entries.pop()
  87. sub_item_changed = False
  88. if entries:
  89. root_name = entries.pop(0)
  90. root = root_material.getMetaDataEntry(root_name)
  91. item = root
  92. for _ in range(len(entries)):
  93. item = item.get(entries.pop(0), {})
  94. if item[entry_name] != entry_value:
  95. sub_item_changed = True
  96. item[entry_name] = entry_value
  97. entry_name = root_name
  98. entry_value = root
  99. root_material.setMetaDataEntry(entry_name, entry_value)
  100. if sub_item_changed: #If it was only a sub-item that has changed then the setMetaDataEntry won't correctly notice that something changed, and we must manually signal that the metadata changed.
  101. root_material.metaDataChanged.emit(root_material)
  102. cura.CuraApplication.CuraApplication.getInstance().getMachineManager().updateUponMaterialMetadataChange()
  103. return True
  104. @pyqtSlot(str, result = str)
  105. def makeUniqueName(self, original_name: str) -> str:
  106. return cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry().uniqueName(original_name)
  107. @pyqtSlot(str, result = "QStringList")
  108. def getContainerNameFilters(self, type_name: str) -> List[str]:
  109. """Get a list of string that can be used as name filters for a Qt File Dialog
  110. This will go through the list of available container types and generate a list of strings
  111. out of that. The strings are formatted as "description (*.extension)" and can be directly
  112. passed to a nameFilters property of a Qt File Dialog.
  113. :param type_name: Which types of containers to list. These types correspond to the "type"
  114. key of the plugin metadata.
  115. :return: A string list with name filters.
  116. """
  117. if not self._container_name_filters:
  118. self._updateContainerNameFilters()
  119. filters = []
  120. for filter_string, entry in self._container_name_filters.items():
  121. if not type_name or entry["type"] == type_name:
  122. filters.append(filter_string)
  123. filters.append("All Files (*)")
  124. return filters
  125. @pyqtSlot(str, str, QUrl, result = "QVariantMap")
  126. def exportContainer(self, container_id: str, file_type: str, file_url_or_string: Union[QUrl, str]) -> Dict[str, str]:
  127. """Export a container to a file
  128. :param container_id: The ID of the container to export
  129. :param file_type: The type of file to save as. Should be in the form of "description (*.extension, *.ext)"
  130. :param file_url_or_string: The URL where to save the file.
  131. :return: A dictionary containing a key "status" with a status code and a key "message" with a message
  132. explaining the status. The status code can be one of "error", "cancelled", "success"
  133. """
  134. if not container_id or not file_type or not file_url_or_string:
  135. return {"status": "error", "message": "Invalid arguments"}
  136. if isinstance(file_url_or_string, QUrl):
  137. file_url = file_url_or_string.toLocalFile()
  138. else:
  139. file_url = file_url_or_string
  140. if not file_url:
  141. return {"status": "error", "message": "Invalid path"}
  142. if file_type not in self._container_name_filters:
  143. try:
  144. mime_type = MimeTypeDatabase.getMimeTypeForFile(file_url)
  145. except MimeTypeNotFoundError:
  146. return {"status": "error", "message": "Unknown File Type"}
  147. else:
  148. mime_type = self._container_name_filters[file_type]["mime"]
  149. containers = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry().findContainers(id = container_id)
  150. if not containers:
  151. return {"status": "error", "message": "Container not found"}
  152. container = containers[0]
  153. if Platform.isOSX() and "." in file_url:
  154. file_url = file_url[:file_url.rfind(".")]
  155. for suffix in mime_type.suffixes:
  156. if file_url.endswith(suffix):
  157. break
  158. else:
  159. file_url += "." + mime_type.preferredSuffix
  160. if not Platform.isWindows():
  161. if os.path.exists(file_url):
  162. result = QMessageBox.question(None, catalog.i18nc("@title:window", "File Already Exists"),
  163. catalog.i18nc("@label Don't translate the XML tag <filename>!", "The file <filename>{0}</filename> already exists. Are you sure you want to overwrite it?").format(file_url))
  164. if result == QMessageBox.No:
  165. return {"status": "cancelled", "message": "User cancelled"}
  166. try:
  167. contents = container.serialize()
  168. except NotImplementedError:
  169. return {"status": "error", "message": "Unable to serialize container"}
  170. if contents is None:
  171. return {"status": "error", "message": "Serialization returned None. Unable to write to file"}
  172. try:
  173. with SaveFile(file_url, "w") as f:
  174. f.write(contents)
  175. except OSError:
  176. return {"status": "error", "message": "Unable to write to this location.", "path": file_url}
  177. Logger.info("Successfully exported container to {path}".format(path = file_url))
  178. return {"status": "success", "message": "Successfully exported container", "path": file_url}
  179. @pyqtSlot(QUrl, result = "QVariantMap")
  180. def importMaterialContainer(self, file_url_or_string: Union[QUrl, str]) -> Dict[str, str]:
  181. """Imports a profile from a file
  182. :param file_url: A URL that points to the file to import.
  183. :return: :type{Dict} dict with a 'status' key containing the string 'success' or 'error', and a 'message' key
  184. containing a message for the user
  185. """
  186. if not file_url_or_string:
  187. return {"status": "error", "message": "Invalid path"}
  188. if isinstance(file_url_or_string, QUrl):
  189. file_url = file_url_or_string.toLocalFile()
  190. else:
  191. file_url = file_url_or_string
  192. Logger.info(f"Importing material from {file_url}")
  193. if not file_url or not os.path.exists(file_url):
  194. return {"status": "error", "message": "Invalid path"}
  195. try:
  196. mime_type = MimeTypeDatabase.getMimeTypeForFile(file_url)
  197. except MimeTypeNotFoundError:
  198. return {"status": "error", "message": "Could not determine mime type of file"}
  199. container_registry = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry()
  200. container_type = container_registry.getContainerForMimeType(mime_type)
  201. if not container_type:
  202. return {"status": "error", "message": "Could not find a container to handle the specified file."}
  203. if not issubclass(container_type, InstanceContainer):
  204. return {"status": "error", "message": "This is not a material container, but another type of file."}
  205. container_id = urllib.parse.unquote_plus(mime_type.stripExtension(os.path.basename(file_url)))
  206. container_id = container_registry.uniqueName(container_id)
  207. container = container_type(container_id)
  208. try:
  209. with open(file_url, "rt", encoding = "utf-8") as f:
  210. container.deserialize(f.read(), file_url)
  211. except PermissionError:
  212. return {"status": "error", "message": "Permission denied when trying to read the file."}
  213. except ContainerFormatError:
  214. return {"status": "error", "Message": "The material file appears to be corrupt."}
  215. except Exception as ex:
  216. return {"status": "error", "message": str(ex)}
  217. container.setDirty(True)
  218. container_registry.addContainer(container)
  219. return {"status": "success", "message": "Successfully imported container {0}".format(container.getName())}
  220. @pyqtSlot(result = bool)
  221. def updateQualityChanges(self) -> bool:
  222. """Update the current active quality changes container with the settings from the user container.
  223. This will go through the active global stack and all active extruder stacks and merge the changes from the user
  224. container into the quality_changes container. After that, the user container is cleared.
  225. :return: :type{bool} True if successful, False if not.
  226. """
  227. application = cura.CuraApplication.CuraApplication.getInstance()
  228. global_stack = application.getMachineManager().activeMachine
  229. if not global_stack:
  230. return False
  231. application.getMachineManager().blurSettings.emit()
  232. current_quality_changes_name = global_stack.qualityChanges.getName()
  233. current_quality_type = global_stack.quality.getMetaDataEntry("quality_type")
  234. extruder_stacks = global_stack.extruderList
  235. container_registry = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry()
  236. machine_definition_id = ContainerTree.getInstance().machines[global_stack.definition.getId()].quality_definition
  237. for stack in [global_stack] + extruder_stacks:
  238. # Find the quality_changes container for this stack and merge the contents of the top container into it.
  239. quality_changes = stack.qualityChanges
  240. if quality_changes.getId() == "empty_quality_changes":
  241. quality_changes = InstanceContainer(container_registry.uniqueName((stack.getId() + "_" + current_quality_changes_name).lower().replace(" ", "_")))
  242. quality_changes.setName(current_quality_changes_name)
  243. quality_changes.setMetaDataEntry("type", "quality_changes")
  244. quality_changes.setMetaDataEntry("quality_type", current_quality_type)
  245. if stack.getMetaDataEntry("position") is not None: # Extruder stacks.
  246. quality_changes.setMetaDataEntry("position", stack.getMetaDataEntry("position"))
  247. quality_changes.setMetaDataEntry("intent_category", stack.quality.getMetaDataEntry("intent_category", "default"))
  248. quality_changes.setMetaDataEntry("setting_version", application.SettingVersion)
  249. quality_changes.setDefinition(machine_definition_id)
  250. container_registry.addContainer(quality_changes)
  251. stack.qualityChanges = quality_changes
  252. if not quality_changes or container_registry.isReadOnly(quality_changes.getId()):
  253. Logger.log("e", "Could not update quality of a nonexistent or read only quality profile in stack %s", stack.getId())
  254. continue
  255. self._performMerge(quality_changes, stack.getTop())
  256. cura.CuraApplication.CuraApplication.getInstance().getMachineManager().activeQualityChangesGroupChanged.emit()
  257. return True
  258. @pyqtSlot()
  259. def clearUserContainers(self) -> None:
  260. """Clear the top-most (user) containers of the active stacks."""
  261. machine_manager = cura.CuraApplication.CuraApplication.getInstance().getMachineManager()
  262. machine_manager.blurSettings.emit()
  263. send_emits_containers = []
  264. # Go through global and extruder stacks and clear their topmost container (the user settings).
  265. global_stack = machine_manager.activeMachine
  266. for stack in [global_stack] + global_stack.extruderList:
  267. container = stack.userChanges
  268. container.clear()
  269. send_emits_containers.append(container)
  270. # user changes are possibly added to make the current setup match the current enabled extruders
  271. machine_manager.correctExtruderSettings()
  272. # The Print Sequence should be changed to match the current setup
  273. machine_manager.correctPrintSequence()
  274. for container in send_emits_containers:
  275. container.sendPostponedEmits()
  276. @pyqtSlot("QVariant", bool, result = "QStringList")
  277. def getLinkedMaterials(self, material_node: "MaterialNode", exclude_self: bool = False) -> List[str]:
  278. """Get a list of materials that have the same GUID as the reference material
  279. :param material_node: The node representing the material for which to get
  280. the same GUID.
  281. :param exclude_self: Whether to include the name of the material you provided.
  282. :return: A list of names of materials with the same GUID.
  283. """
  284. same_guid = ContainerRegistry.getInstance().findInstanceContainersMetadata(GUID = material_node.guid)
  285. if exclude_self:
  286. return list({meta["name"] for meta in same_guid if meta["base_file"] != material_node.base_file})
  287. else:
  288. return list({meta["name"] for meta in same_guid})
  289. @pyqtSlot("QVariant")
  290. def unlinkMaterial(self, material_node: "MaterialNode") -> None:
  291. """Unlink a material from all other materials by creating a new GUID
  292. :param material_id: :type{str} the id of the material to create a new GUID for.
  293. """
  294. # Get the material group
  295. if material_node.container is None: # Failed to lazy-load this container.
  296. return
  297. root_material_query = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry().findInstanceContainers(id = material_node.getMetaDataEntry("base_file", ""))
  298. if not root_material_query:
  299. Logger.log("w", "Unable to find material group for %s", material_node)
  300. return
  301. root_material = root_material_query[0]
  302. # Generate a new GUID
  303. new_guid = str(uuid.uuid4())
  304. # Update the GUID
  305. # NOTE: We only need to set the root material container because XmlMaterialProfile.setMetaDataEntry() will
  306. # take care of the derived containers too
  307. root_material.setMetaDataEntry("GUID", new_guid)
  308. def _performMerge(self, merge_into: InstanceContainer, merge: InstanceContainer, clear_settings: bool = True) -> None:
  309. if merge == merge_into:
  310. return
  311. for key in merge.getAllKeys():
  312. merge_into.setProperty(key, "value", merge.getProperty(key, "value"))
  313. if clear_settings:
  314. merge.clear()
  315. def _updateContainerNameFilters(self) -> None:
  316. self._container_name_filters = {}
  317. plugin_registry = cura.CuraApplication.CuraApplication.getInstance().getPluginRegistry()
  318. container_registry = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry()
  319. for plugin_id, container_type in container_registry.getContainerTypes():
  320. # Ignore default container types since those are not plugins
  321. if container_type in (InstanceContainer, ContainerStack, DefinitionContainer, GlobalStack, ExtruderStack):
  322. continue
  323. serialize_type = ""
  324. try:
  325. plugin_metadata = plugin_registry.getMetaData(plugin_id)
  326. if plugin_metadata:
  327. serialize_type = plugin_metadata["settings_container"]["type"]
  328. else:
  329. continue
  330. except KeyError as e:
  331. continue
  332. mime_type = container_registry.getMimeTypeForContainer(container_type)
  333. if mime_type is None:
  334. continue
  335. entry = {
  336. "type": serialize_type,
  337. "mime": mime_type,
  338. "container": container_type
  339. }
  340. suffix = mime_type.preferredSuffix
  341. if Platform.isOSX() and "." in suffix:
  342. # OSX's File dialog is stupid and does not allow selecting files with a . in its name
  343. suffix = suffix[suffix.index(".") + 1:]
  344. suffix_list = "*." + suffix
  345. for suffix in mime_type.suffixes:
  346. if suffix == mime_type.preferredSuffix:
  347. continue
  348. if Platform.isOSX() and "." in suffix:
  349. # OSX's File dialog is stupid and does not allow selecting files with a . in its name
  350. suffix = suffix[suffix.index("."):]
  351. suffix_list += ", *." + suffix
  352. name_filter = "{0} ({1})".format(mime_type.comment, suffix_list)
  353. self._container_name_filters[name_filter] = entry
  354. @pyqtSlot(QUrl, result = "QVariantMap")
  355. def importProfile(self, file_url: QUrl) -> Dict[str, str]:
  356. """Import single profile, file_url does not have to end with curaprofile"""
  357. if not file_url.isValid():
  358. return {"status": "error", "message": catalog.i18nc("@info:status", "Invalid file URL:") + " " + str(file_url)}
  359. path = file_url.toLocalFile()
  360. if not path:
  361. return {"status": "error", "message": catalog.i18nc("@info:status", "Invalid file URL:") + " " + str(file_url)}
  362. return cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry().importProfile(path)
  363. @pyqtSlot(QObject, QUrl, str)
  364. def exportQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup", file_url: QUrl, file_type: str) -> None:
  365. if not file_url.isValid():
  366. return
  367. path = file_url.toLocalFile()
  368. if not path:
  369. return
  370. container_registry = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry()
  371. container_list = [cast(InstanceContainer, container_registry.findContainers(id = quality_changes_group.metadata_for_global["id"])[0])] # type: List[InstanceContainer]
  372. for metadata in quality_changes_group.metadata_per_extruder.values():
  373. container_list.append(cast(InstanceContainer, container_registry.findContainers(id = metadata["id"])[0]))
  374. cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry().exportQualityProfile(container_list, path, file_type)
  375. __instance = None # type: ContainerManager
  376. @classmethod
  377. def getInstance(cls, *args, **kwargs) -> "ContainerManager":
  378. return cls.__instance