ContainerManager.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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. super().__init__(parent = application)
  41. self._application = application # type: CuraApplication
  42. self._plugin_registry = self._application.getPluginRegistry() # type: PluginRegistry
  43. self._container_registry = self._application.getContainerRegistry() # type: CuraContainerRegistry
  44. self._machine_manager = self._application.getMachineManager() # type: MachineManager
  45. self._material_manager = self._application.getMaterialManager() # type: MaterialManager
  46. self._quality_manager = self._application.getQualityManager() # type: QualityManager
  47. self._container_name_filters = {} # type: Dict[str, Dict[str, Any]]
  48. @pyqtSlot(str, str, result=str)
  49. def getContainerMetaDataEntry(self, container_id: str, entry_names: str) -> str:
  50. metadatas = self._container_registry.findContainersMetadata(id = container_id)
  51. if not metadatas:
  52. Logger.log("w", "Could not get metadata of container %s because it was not found.", container_id)
  53. return ""
  54. entries = entry_names.split("/")
  55. result = metadatas[0]
  56. while entries:
  57. entry = entries.pop(0)
  58. result = result.get(entry, {})
  59. if not result:
  60. return ""
  61. return str(result)
  62. ## Set a metadata entry of the specified container.
  63. #
  64. # This will set the specified entry of the container's metadata to the specified
  65. # value. Note that entries containing dictionaries can have their entries changed
  66. # by using "/" as a separator. For example, to change an entry "foo" in a
  67. # dictionary entry "bar", you can specify "bar/foo" as entry name.
  68. #
  69. # \param container_node \type{ContainerNode}
  70. # \param entry_name \type{str} The name of the metadata entry to change.
  71. # \param entry_value The new value of the entry.
  72. #
  73. # TODO: This is ONLY used by MaterialView for material containers. Maybe refactor this.
  74. # Update: In order for QML to use objects and sub objects, those (sub) objects must all be QObject. Is that what we want?
  75. @pyqtSlot("QVariant", str, str)
  76. def setContainerMetaDataEntry(self, container_node: "ContainerNode", entry_name: str, entry_value: str) -> bool:
  77. root_material_id = container_node.getMetaDataEntry("base_file", "")
  78. if self._container_registry.isReadOnly(root_material_id):
  79. Logger.log("w", "Cannot set metadata of read-only container %s.", root_material_id)
  80. return False
  81. material_group = self._material_manager.getMaterialGroup(root_material_id)
  82. if material_group is None:
  83. Logger.log("w", "Unable to find material group for: %s.", root_material_id)
  84. return False
  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 = material_group.root_material_node.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. container = material_group.root_material_node.getContainer()
  100. if container is not None:
  101. container.setMetaDataEntry(entry_name, entry_value)
  102. 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.
  103. container.metaDataChanged.emit(container)
  104. return True
  105. @pyqtSlot(str, result = str)
  106. def makeUniqueName(self, original_name: str) -> str:
  107. return self._container_registry.uniqueName(original_name)
  108. ## Get a list of string that can be used as name filters for a Qt File Dialog
  109. #
  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. #
  114. # \param type_name Which types of containers to list. These types correspond to the "type"
  115. # key of the plugin metadata.
  116. #
  117. # \return A string list with name filters.
  118. @pyqtSlot(str, result = "QStringList")
  119. def getContainerNameFilters(self, type_name: str) -> List[str]:
  120. if not self._container_name_filters:
  121. self._updateContainerNameFilters()
  122. filters = []
  123. for filter_string, entry in self._container_name_filters.items():
  124. if not type_name or entry["type"] == type_name:
  125. filters.append(filter_string)
  126. filters.append("All Files (*)")
  127. return filters
  128. ## Export a container to a file
  129. #
  130. # \param container_id The ID of the container to export
  131. # \param file_type The type of file to save as. Should be in the form of "description (*.extension, *.ext)"
  132. # \param file_url_or_string The URL where to save the file.
  133. #
  134. # \return A dictionary containing a key "status" with a status code and a key "message" with a message
  135. # explaining the status.
  136. # The status code can be one of "error", "cancelled", "success"
  137. @pyqtSlot(str, str, QUrl, result = "QVariantMap")
  138. def exportContainer(self, container_id: str, file_type: str, file_url_or_string: Union[QUrl, str]) -> Dict[str, str]:
  139. if not container_id or not file_type or not file_url_or_string:
  140. return {"status": "error", "message": "Invalid arguments"}
  141. if isinstance(file_url_or_string, QUrl):
  142. file_url = file_url_or_string.toLocalFile()
  143. else:
  144. file_url = file_url_or_string
  145. if not file_url:
  146. return {"status": "error", "message": "Invalid path"}
  147. if file_type not in self._container_name_filters:
  148. try:
  149. mime_type = MimeTypeDatabase.getMimeTypeForFile(file_url)
  150. except MimeTypeNotFoundError:
  151. return {"status": "error", "message": "Unknown File Type"}
  152. else:
  153. mime_type = self._container_name_filters[file_type]["mime"]
  154. containers = self._container_registry.findContainers(id = container_id)
  155. if not containers:
  156. return {"status": "error", "message": "Container not found"}
  157. container = containers[0]
  158. if Platform.isOSX() and "." in file_url:
  159. file_url = file_url[:file_url.rfind(".")]
  160. for suffix in mime_type.suffixes:
  161. if file_url.endswith(suffix):
  162. break
  163. else:
  164. file_url += "." + mime_type.preferredSuffix
  165. if not Platform.isWindows():
  166. if os.path.exists(file_url):
  167. result = QMessageBox.question(None, catalog.i18nc("@title:window", "File Already Exists"),
  168. 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))
  169. if result == QMessageBox.No:
  170. return {"status": "cancelled", "message": "User cancelled"}
  171. try:
  172. contents = container.serialize()
  173. except NotImplementedError:
  174. return {"status": "error", "message": "Unable to serialize container"}
  175. if contents is None:
  176. return {"status": "error", "message": "Serialization returned None. Unable to write to file"}
  177. with SaveFile(file_url, "w") as f:
  178. f.write(contents)
  179. return {"status": "success", "message": "Successfully exported container", "path": file_url}
  180. ## Imports a profile from a file
  181. #
  182. # \param file_url A URL that points to the file to import.
  183. #
  184. # \return \type{Dict} dict with a 'status' key containing the string 'success' or 'error', and a 'message' key
  185. # containing a message for the user
  186. @pyqtSlot(QUrl, result = "QVariantMap")
  187. def importMaterialContainer(self, file_url_or_string: Union[QUrl, str]) -> Dict[str, str]:
  188. if not file_url_or_string:
  189. return {"status": "error", "message": "Invalid path"}
  190. if isinstance(file_url_or_string, QUrl):
  191. file_url = file_url_or_string.toLocalFile()
  192. else:
  193. file_url = file_url_or_string
  194. if not file_url or not os.path.exists(file_url):
  195. return {"status": "error", "message": "Invalid path"}
  196. try:
  197. mime_type = MimeTypeDatabase.getMimeTypeForFile(file_url)
  198. except MimeTypeNotFoundError:
  199. return {"status": "error", "message": "Could not determine mime type of file"}
  200. container_type = self._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. container_id = urllib.parse.unquote_plus(mime_type.stripExtension(os.path.basename(file_url)))
  204. container_id = self._container_registry.uniqueName(container_id)
  205. container = container_type(container_id)
  206. try:
  207. with open(file_url, "rt", encoding = "utf-8") as f:
  208. container.deserialize(f.read())
  209. except PermissionError:
  210. return {"status": "error", "message": "Permission denied when trying to read the file."}
  211. except ContainerFormatError:
  212. return {"status": "error", "Message": "The material file appears to be corrupt."}
  213. except Exception as ex:
  214. return {"status": "error", "message": str(ex)}
  215. container.setDirty(True)
  216. self._container_registry.addContainer(container)
  217. return {"status": "success", "message": "Successfully imported container {0}".format(container.getName())}
  218. ## Update the current active quality changes container with the settings from the user container.
  219. #
  220. # This will go through the active global stack and all active extruder stacks and merge the changes from the user
  221. # container into the quality_changes container. After that, the user container is cleared.
  222. #
  223. # \return \type{bool} True if successful, False if not.
  224. @pyqtSlot(result = bool)
  225. def updateQualityChanges(self) -> bool:
  226. global_stack = self._machine_manager.activeMachine
  227. if not global_stack:
  228. return False
  229. self._machine_manager.blurSettings.emit()
  230. current_quality_changes_name = global_stack.qualityChanges.getName()
  231. current_quality_type = global_stack.quality.getMetaDataEntry("quality_type")
  232. extruder_stacks = list(global_stack.extruders.values())
  233. for stack in [global_stack] + extruder_stacks:
  234. # Find the quality_changes container for this stack and merge the contents of the top container into it.
  235. quality_changes = stack.qualityChanges
  236. if quality_changes.getId() == "empty_quality_changes":
  237. quality_changes = self._quality_manager._createQualityChanges(current_quality_type, current_quality_changes_name,
  238. global_stack, stack)
  239. self._container_registry.addContainer(quality_changes)
  240. stack.qualityChanges = quality_changes
  241. if not quality_changes or self._container_registry.isReadOnly(quality_changes.getId()):
  242. Logger.log("e", "Could not update quality of a nonexistant or read only quality profile in stack %s", stack.getId())
  243. continue
  244. self._performMerge(quality_changes, stack.getTop())
  245. self._machine_manager.activeQualityChangesGroupChanged.emit()
  246. return True
  247. ## Clear the top-most (user) containers of the active stacks.
  248. @pyqtSlot()
  249. def clearUserContainers(self) -> None:
  250. self._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 = self._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. self._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_id \type{str} the id of the material for which to get the linked materials.
  266. # \return \type{list} a list of names of materials with the same GUID
  267. @pyqtSlot("QVariant", bool, result = "QStringList")
  268. def getLinkedMaterials(self, material_node: "MaterialNode", exclude_self: bool = False):
  269. guid = material_node.getMetaDataEntry("GUID", "")
  270. self_root_material_id = material_node.getMetaDataEntry("base_file")
  271. material_group_list = self._material_manager.getMaterialGroupListByGUID(guid)
  272. linked_material_names = []
  273. if material_group_list:
  274. for material_group in material_group_list:
  275. if exclude_self and material_group.name == self_root_material_id:
  276. continue
  277. linked_material_names.append(material_group.root_material_node.getMetaDataEntry("name", ""))
  278. return linked_material_names
  279. ## Unlink a material from all other materials by creating a new GUID
  280. # \param material_id \type{str} the id of the material to create a new GUID for.
  281. @pyqtSlot("QVariant")
  282. def unlinkMaterial(self, material_node: "MaterialNode") -> None:
  283. # Get the material group
  284. material_group = self._material_manager.getMaterialGroup(material_node.getMetaDataEntry("base_file", ""))
  285. if material_group is None:
  286. Logger.log("w", "Unable to find material group for %s", material_node)
  287. return
  288. # Generate a new GUID
  289. new_guid = str(uuid.uuid4())
  290. # Update the GUID
  291. # NOTE: We only need to set the root material container because XmlMaterialProfile.setMetaDataEntry() will
  292. # take care of the derived containers too
  293. container = material_group.root_material_node.getContainer()
  294. if container is not None:
  295. container.setMetaDataEntry("GUID", new_guid)
  296. def _performMerge(self, merge_into: InstanceContainer, merge: InstanceContainer, clear_settings: bool = True) -> None:
  297. if merge == merge_into:
  298. return
  299. for key in merge.getAllKeys():
  300. merge_into.setProperty(key, "value", merge.getProperty(key, "value"))
  301. if clear_settings:
  302. merge.clear()
  303. def _updateContainerNameFilters(self) -> None:
  304. self._container_name_filters = {}
  305. for plugin_id, container_type in self._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 = self._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 = self._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 self._container_registry.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.getContainer() for n in quality_changes_group.getAllNodes() if n.getContainer() is not None]
  357. self._container_registry.exportQualityProfile(container_list, path, file_type)
  358. __instance = None # type: ContainerManager
  359. @classmethod
  360. def getInstance(cls, *args, **kwargs) -> "ContainerManager":
  361. return cls.__instance