ContainerManager.py 20 KB

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