ContainerManager.py 20 KB

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