ContainerManager.py 18 KB

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