ContainerManager.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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
  7. from PyQt5.QtCore import QObject, QUrl, QVariant
  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. catalog = i18nCatalog("cura")
  20. ## Manager class that contains common actions to deal with containers in Cura.
  21. #
  22. # This is primarily intended as a class to be able to perform certain actions
  23. # from within QML. We want to be able to trigger things like removing a container
  24. # when a certain action happens. This can be done through this class.
  25. class ContainerManager(QObject):
  26. def __init__(self, application):
  27. if ContainerManager.__instance is not None:
  28. raise RuntimeError("Try to create singleton '%s' more than once" % self.__class__.__name__)
  29. ContainerManager.__instance = self
  30. super().__init__(parent = application)
  31. self._application = application
  32. self._plugin_registry = self._application.getPluginRegistry()
  33. self._container_registry = self._application.getContainerRegistry()
  34. self._machine_manager = self._application.getMachineManager()
  35. self._material_manager = self._application.getMaterialManager()
  36. self._container_name_filters = {}
  37. @pyqtSlot(str, str, result=str)
  38. def getContainerMetaDataEntry(self, container_id, entry_name):
  39. metadatas = self._container_registry.findContainersMetadata(id = container_id)
  40. if not metadatas:
  41. Logger.log("w", "Could not get metadata of container %s because it was not found.", container_id)
  42. return ""
  43. return str(metadatas[0].get(entry_name, ""))
  44. ## Set a metadata entry of the specified container.
  45. #
  46. # This will set the specified entry of the container's metadata to the specified
  47. # value. Note that entries containing dictionaries can have their entries changed
  48. # by using "/" as a separator. For example, to change an entry "foo" in a
  49. # dictionary entry "bar", you can specify "bar/foo" as entry name.
  50. #
  51. # \param container_id \type{str} The ID of the container to change.
  52. # \param entry_name \type{str} The name of the metadata entry to change.
  53. # \param entry_value The new value of the entry.
  54. #
  55. # \return True if successful, False if not.
  56. # TODO: This is ONLY used by MaterialView for material containers. Maybe refactor this.
  57. @pyqtSlot("QVariant", str, str)
  58. def setContainerMetaDataEntry(self, container_node, entry_name, entry_value):
  59. root_material_id = container_node.metadata["base_file"]
  60. if self._container_registry.isReadOnly(root_material_id):
  61. Logger.log("w", "Cannot set metadata of read-only container %s.", root_material_id)
  62. return False
  63. material_group = self._material_manager.getMaterialGroup(root_material_id)
  64. entries = entry_name.split("/")
  65. entry_name = entries.pop()
  66. sub_item_changed = False
  67. if entries:
  68. root_name = entries.pop(0)
  69. root = material_group.root_material_node.metadata.get(root_name)
  70. item = root
  71. for _ in range(len(entries)):
  72. item = item.get(entries.pop(0), { })
  73. if item[entry_name] != entry_value:
  74. sub_item_changed = True
  75. item[entry_name] = entry_value
  76. entry_name = root_name
  77. entry_value = root
  78. container = material_group.root_material_node.getContainer()
  79. if container is not None:
  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 self._container_registry.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 ContainerFormatError:
  240. return {"status": "error", "Message": "The material file appears to be corrupt."}
  241. except Exception as ex:
  242. return {"status": "error", "message": str(ex)}
  243. container.setDirty(True)
  244. self._container_registry.addContainer(container)
  245. return {"status": "success", "message": "Successfully imported container {0}".format(container.getName())}
  246. ## Update the current active quality changes container with the settings from the user container.
  247. #
  248. # This will go through the active global stack and all active extruder stacks and merge the changes from the user
  249. # container into the quality_changes container. After that, the user container is cleared.
  250. #
  251. # \return \type{bool} True if successful, False if not.
  252. @pyqtSlot(result = bool)
  253. def updateQualityChanges(self):
  254. global_stack = self._machine_manager.activeMachine
  255. if not global_stack:
  256. return False
  257. self._machine_manager.blurSettings.emit()
  258. global_stack = self._machine_manager.activeMachine
  259. extruder_stacks = list(global_stack.extruders.values())
  260. for stack in [global_stack] + extruder_stacks:
  261. # Find the quality_changes container for this stack and merge the contents of the top container into it.
  262. quality_changes = stack.qualityChanges
  263. if not quality_changes or self._container_registry.isReadOnly(quality_changes.getId()):
  264. Logger.log("e", "Could not update quality of a nonexistant or read only quality profile in stack %s", stack.getId())
  265. continue
  266. self._performMerge(quality_changes, stack.getTop())
  267. self._machine_manager.activeQualityChangesGroupChanged.emit()
  268. return True
  269. ## Clear the top-most (user) containers of the active stacks.
  270. @pyqtSlot()
  271. def clearUserContainers(self) -> None:
  272. self._machine_manager.blurSettings.emit()
  273. send_emits_containers = []
  274. # Go through global and extruder stacks and clear their topmost container (the user settings).
  275. global_stack = self._machine_manager.activeMachine
  276. extruder_stacks = list(global_stack.extruders.values())
  277. for stack in [global_stack] + extruder_stacks:
  278. container = stack.userChanges
  279. container.clear()
  280. send_emits_containers.append(container)
  281. # user changes are possibly added to make the current setup match the current enabled extruders
  282. self._machine_manager.correctExtruderSettings()
  283. for container in send_emits_containers:
  284. container.sendPostponedEmits()
  285. ## Get a list of materials that have the same GUID as the reference material
  286. #
  287. # \param material_id \type{str} the id of the material for which to get the linked materials.
  288. # \return \type{list} a list of names of materials with the same GUID
  289. @pyqtSlot("QVariant", bool, result = "QStringList")
  290. def getLinkedMaterials(self, material_node, exclude_self = False):
  291. guid = material_node.metadata["GUID"]
  292. self_root_material_id = material_node.metadata["base_file"]
  293. material_group_list = self._material_manager.getMaterialGroupListByGUID(guid)
  294. linked_material_names = []
  295. if material_group_list:
  296. for material_group in material_group_list:
  297. if exclude_self and material_group.name == self_root_material_id:
  298. continue
  299. linked_material_names.append(material_group.root_material_node.metadata["name"])
  300. return linked_material_names
  301. ## Unlink a material from all other materials by creating a new GUID
  302. # \param material_id \type{str} the id of the material to create a new GUID for.
  303. @pyqtSlot("QVariant")
  304. def unlinkMaterial(self, material_node):
  305. # Get the material group
  306. material_group = self._material_manager.getMaterialGroup(material_node.metadata["base_file"])
  307. # Generate a new GUID
  308. new_guid = str(uuid.uuid4())
  309. # Update the GUID
  310. # NOTE: We only need to set the root material container because XmlMaterialProfile.setMetaDataEntry() will
  311. # take care of the derived containers too
  312. container = material_group.root_material_node.getContainer()
  313. if container is not None:
  314. container.setMetaDataEntry("GUID", new_guid)
  315. def _performMerge(self, merge_into, merge, clear_settings = True):
  316. if merge == merge_into:
  317. return
  318. for key in merge.getAllKeys():
  319. merge_into.setProperty(key, "value", merge.getProperty(key, "value"))
  320. if clear_settings:
  321. merge.clear()
  322. def _updateContainerNameFilters(self) -> None:
  323. self._container_name_filters = {}
  324. for plugin_id, container_type in self._container_registry.getContainerTypes():
  325. # Ignore default container types since those are not plugins
  326. if container_type in (InstanceContainer, ContainerStack, DefinitionContainer):
  327. continue
  328. serialize_type = ""
  329. try:
  330. plugin_metadata = self._plugin_registry.getMetaData(plugin_id)
  331. if plugin_metadata:
  332. serialize_type = plugin_metadata["settings_container"]["type"]
  333. else:
  334. continue
  335. except KeyError as e:
  336. continue
  337. mime_type = self._container_registry.getMimeTypeForContainer(container_type)
  338. entry = {
  339. "type": serialize_type,
  340. "mime": mime_type,
  341. "container": container_type
  342. }
  343. suffix = mime_type.preferredSuffix
  344. if Platform.isOSX() and "." in suffix:
  345. # OSX's File dialog is stupid and does not allow selecting files with a . in its name
  346. suffix = suffix[suffix.index(".") + 1:]
  347. suffix_list = "*." + suffix
  348. for suffix in mime_type.suffixes:
  349. if suffix == mime_type.preferredSuffix:
  350. continue
  351. if Platform.isOSX() and "." in suffix:
  352. # OSX's File dialog is stupid and does not allow selecting files with a . in its name
  353. suffix = suffix[suffix.index("."):]
  354. suffix_list += ", *." + suffix
  355. name_filter = "{0} ({1})".format(mime_type.comment, suffix_list)
  356. self._container_name_filters[name_filter] = entry
  357. ## Import single profile, file_url does not have to end with curaprofile
  358. @pyqtSlot(QUrl, result="QVariantMap")
  359. def importProfile(self, file_url):
  360. if not file_url.isValid():
  361. return
  362. path = file_url.toLocalFile()
  363. if not path:
  364. return
  365. return self._container_registry.importProfile(path)
  366. @pyqtSlot(QObject, QUrl, str)
  367. def exportQualityChangesGroup(self, quality_changes_group, file_url: QUrl, file_type: str):
  368. if not file_url.isValid():
  369. return
  370. path = file_url.toLocalFile()
  371. if not path:
  372. return
  373. container_list = [n.getContainer() for n in quality_changes_group.getAllNodes() if n.getContainer() is not None]
  374. self._container_registry.exportQualityProfile(container_list, path, file_type)
  375. __instance = None
  376. @classmethod
  377. def getInstance(cls, *args, **kwargs) -> "ContainerManager":
  378. return cls.__instance