ContainerManager.py 20 KB

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