ContainerManager.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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._quality_manager = self._application.getQualityManager()
  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. if container is not None:
  81. container.setMetaDataEntry(entry_name, entry_value)
  82. 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.
  83. container.metaDataChanged.emit(container)
  84. ## Set a setting property of the specified container.
  85. #
  86. # This will set the specified property of the specified setting of the container
  87. # and all containers that share the same base_file (if any). The latter only
  88. # happens for material containers.
  89. #
  90. # \param container_id \type{str} The ID of the container to change.
  91. # \param setting_key \type{str} The key of the setting.
  92. # \param property_name \type{str} The name of the property, eg "value".
  93. # \param property_value \type{str} The new value of the property.
  94. #
  95. # \return True if successful, False if not.
  96. @pyqtSlot(str, str, str, str, result = bool)
  97. def setContainerProperty(self, container_id, setting_key, property_name, property_value):
  98. if self._container_registry.isReadOnly(container_id):
  99. Logger.log("w", "Cannot set properties of read-only container %s.", container_id)
  100. return False
  101. containers = self._container_registry.findContainers(id = container_id)
  102. if not containers:
  103. Logger.log("w", "Could not set properties of container %s because it was not found.", container_id)
  104. return False
  105. container = containers[0]
  106. container.setProperty(setting_key, property_name, property_value)
  107. basefile = container.getMetaDataEntry("base_file", container_id)
  108. for sibbling_container in self._container_registry.findInstanceContainers(base_file = basefile):
  109. if sibbling_container != container:
  110. sibbling_container.setProperty(setting_key, property_name, property_value)
  111. return True
  112. ## Get a setting property of the specified container.
  113. #
  114. # This will get the specified property of the specified setting of the
  115. # specified container.
  116. #
  117. # \param container_id The ID of the container to get the setting property
  118. # of.
  119. # \param setting_key The key of the setting to get the property of.
  120. # \param property_name The property to obtain.
  121. # \return The value of the specified property. The type of this property
  122. # value depends on the type of the property. For instance, the "value"
  123. # property of an integer setting will be a Python int, but the "value"
  124. # property of an enum setting will be a Python str.
  125. @pyqtSlot(str, str, str, result = QVariant)
  126. def getContainerProperty(self, container_id: str, setting_key: str, property_name: str):
  127. containers = self._container_registry.findContainers(id = container_id)
  128. if not containers:
  129. Logger.log("w", "Could not get properties of container %s because it was not found.", container_id)
  130. return ""
  131. container = containers[0]
  132. return container.getProperty(setting_key, property_name)
  133. @pyqtSlot(str, result = str)
  134. def makeUniqueName(self, original_name):
  135. return self._container_registry.uniqueName(original_name)
  136. ## Get a list of string that can be used as name filters for a Qt File Dialog
  137. #
  138. # This will go through the list of available container types and generate a list of strings
  139. # out of that. The strings are formatted as "description (*.extension)" and can be directly
  140. # passed to a nameFilters property of a Qt File Dialog.
  141. #
  142. # \param type_name Which types of containers to list. These types correspond to the "type"
  143. # key of the plugin metadata.
  144. #
  145. # \return A string list with name filters.
  146. @pyqtSlot(str, result = "QStringList")
  147. def getContainerNameFilters(self, type_name):
  148. if not self._container_name_filters:
  149. self._updateContainerNameFilters()
  150. filters = []
  151. for filter_string, entry in self._container_name_filters.items():
  152. if not type_name or entry["type"] == type_name:
  153. filters.append(filter_string)
  154. filters.append("All Files (*)")
  155. return filters
  156. ## Export a container to a file
  157. #
  158. # \param container_id The ID of the container to export
  159. # \param file_type The type of file to save as. Should be in the form of "description (*.extension, *.ext)"
  160. # \param file_url_or_string The URL where to save the file.
  161. #
  162. # \return A dictionary containing a key "status" with a status code and a key "message" with a message
  163. # explaining the status.
  164. # The status code can be one of "error", "cancelled", "success"
  165. @pyqtSlot(str, str, QUrl, result = "QVariantMap")
  166. def exportContainer(self, container_id: str, file_type: str, file_url_or_string: Union[QUrl, str]) -> Dict[str, str]:
  167. if not container_id or not file_type or not file_url_or_string:
  168. return {"status": "error", "message": "Invalid arguments"}
  169. if isinstance(file_url_or_string, QUrl):
  170. file_url = file_url_or_string.toLocalFile()
  171. else:
  172. file_url = file_url_or_string
  173. if not file_url:
  174. return {"status": "error", "message": "Invalid path"}
  175. mime_type = None
  176. if file_type not in self._container_name_filters:
  177. try:
  178. mime_type = MimeTypeDatabase.getMimeTypeForFile(file_url)
  179. except MimeTypeNotFoundError:
  180. return {"status": "error", "message": "Unknown File Type"}
  181. else:
  182. mime_type = self._container_name_filters[file_type]["mime"]
  183. containers = self._container_registry.findContainers(id = container_id)
  184. if not containers:
  185. return {"status": "error", "message": "Container not found"}
  186. container = containers[0]
  187. if Platform.isOSX() and "." in file_url:
  188. file_url = file_url[:file_url.rfind(".")]
  189. for suffix in mime_type.suffixes:
  190. if file_url.endswith(suffix):
  191. break
  192. else:
  193. file_url += "." + mime_type.preferredSuffix
  194. if not Platform.isWindows():
  195. if os.path.exists(file_url):
  196. result = QMessageBox.question(None, catalog.i18nc("@title:window", "File Already Exists"),
  197. 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))
  198. if result == QMessageBox.No:
  199. return {"status": "cancelled", "message": "User cancelled"}
  200. try:
  201. contents = container.serialize()
  202. except NotImplementedError:
  203. return {"status": "error", "message": "Unable to serialize container"}
  204. if contents is None:
  205. return {"status": "error", "message": "Serialization returned None. Unable to write to file"}
  206. with SaveFile(file_url, "w") as f:
  207. f.write(contents)
  208. return {"status": "success", "message": "Successfully exported container", "path": file_url}
  209. ## Imports a profile from a file
  210. #
  211. # \param file_url A URL that points to the file to import.
  212. #
  213. # \return \type{Dict} dict with a 'status' key containing the string 'success' or 'error', and a 'message' key
  214. # containing a message for the user
  215. @pyqtSlot(QUrl, result = "QVariantMap")
  216. def importMaterialContainer(self, file_url_or_string: Union[QUrl, str]) -> Dict[str, str]:
  217. if not file_url_or_string:
  218. return {"status": "error", "message": "Invalid path"}
  219. if isinstance(file_url_or_string, QUrl):
  220. file_url = file_url_or_string.toLocalFile()
  221. else:
  222. file_url = file_url_or_string
  223. if not file_url or not os.path.exists(file_url):
  224. return {"status": "error", "message": "Invalid path"}
  225. try:
  226. mime_type = MimeTypeDatabase.getMimeTypeForFile(file_url)
  227. except MimeTypeNotFoundError:
  228. return {"status": "error", "message": "Could not determine mime type of file"}
  229. container_type = self._container_registry.getContainerForMimeType(mime_type)
  230. if not container_type:
  231. return {"status": "error", "message": "Could not find a container to handle the specified file."}
  232. container_id = urllib.parse.unquote_plus(mime_type.stripExtension(os.path.basename(file_url)))
  233. container_id = self._container_registry.uniqueName(container_id)
  234. container = container_type(container_id)
  235. try:
  236. with open(file_url, "rt", encoding = "utf-8") as f:
  237. container.deserialize(f.read())
  238. except PermissionError:
  239. return {"status": "error", "message": "Permission denied when trying to read the file."}
  240. except ContainerFormatError:
  241. return {"status": "error", "Message": "The material file appears to be corrupt."}
  242. except Exception as ex:
  243. return {"status": "error", "message": str(ex)}
  244. container.setDirty(True)
  245. self._container_registry.addContainer(container)
  246. return {"status": "success", "message": "Successfully imported container {0}".format(container.getName())}
  247. ## Update the current active quality changes container with the settings from the user container.
  248. #
  249. # This will go through the active global stack and all active extruder stacks and merge the changes from the user
  250. # container into the quality_changes container. After that, the user container is cleared.
  251. #
  252. # \return \type{bool} True if successful, False if not.
  253. @pyqtSlot(result = bool)
  254. def updateQualityChanges(self):
  255. global_stack = self._machine_manager.activeMachine
  256. if not global_stack:
  257. return False
  258. self._machine_manager.blurSettings.emit()
  259. current_quality_changes_name = global_stack.qualityChanges.getName()
  260. current_quality_type = global_stack.quality.getMetaDataEntry("quality_type")
  261. extruder_stacks = list(global_stack.extruders.values())
  262. for stack in [global_stack] + extruder_stacks:
  263. # Find the quality_changes container for this stack and merge the contents of the top container into it.
  264. quality_changes = stack.qualityChanges
  265. if quality_changes.getId() == "empty_quality_changes":
  266. quality_changes = self._quality_manager._createQualityChanges(current_quality_type, current_quality_changes_name,
  267. global_stack, stack)
  268. self._container_registry.addContainer(quality_changes)
  269. stack.qualityChanges = quality_changes
  270. if not quality_changes or self._container_registry.isReadOnly(quality_changes.getId()):
  271. Logger.log("e", "Could not update quality of a nonexistant or read only quality profile in stack %s", stack.getId())
  272. continue
  273. self._performMerge(quality_changes, stack.getTop())
  274. self._machine_manager.activeQualityChangesGroupChanged.emit()
  275. return True
  276. ## Clear the top-most (user) containers of the active stacks.
  277. @pyqtSlot()
  278. def clearUserContainers(self) -> None:
  279. self._machine_manager.blurSettings.emit()
  280. send_emits_containers = []
  281. # Go through global and extruder stacks and clear their topmost container (the user settings).
  282. global_stack = self._machine_manager.activeMachine
  283. extruder_stacks = list(global_stack.extruders.values())
  284. for stack in [global_stack] + extruder_stacks:
  285. container = stack.userChanges
  286. container.clear()
  287. send_emits_containers.append(container)
  288. # user changes are possibly added to make the current setup match the current enabled extruders
  289. self._machine_manager.correctExtruderSettings()
  290. for container in send_emits_containers:
  291. container.sendPostponedEmits()
  292. ## Get a list of materials that have the same GUID as the reference material
  293. #
  294. # \param material_id \type{str} the id of the material for which to get the linked materials.
  295. # \return \type{list} a list of names of materials with the same GUID
  296. @pyqtSlot("QVariant", bool, result = "QStringList")
  297. def getLinkedMaterials(self, material_node, exclude_self = False):
  298. guid = material_node.metadata["GUID"]
  299. self_root_material_id = material_node.metadata["base_file"]
  300. material_group_list = self._material_manager.getMaterialGroupListByGUID(guid)
  301. linked_material_names = []
  302. if material_group_list:
  303. for material_group in material_group_list:
  304. if exclude_self and material_group.name == self_root_material_id:
  305. continue
  306. linked_material_names.append(material_group.root_material_node.metadata["name"])
  307. return linked_material_names
  308. ## Unlink a material from all other materials by creating a new GUID
  309. # \param material_id \type{str} the id of the material to create a new GUID for.
  310. @pyqtSlot("QVariant")
  311. def unlinkMaterial(self, material_node):
  312. # Get the material group
  313. material_group = self._material_manager.getMaterialGroup(material_node.metadata["base_file"])
  314. # Generate a new GUID
  315. new_guid = str(uuid.uuid4())
  316. # Update the GUID
  317. # NOTE: We only need to set the root material container because XmlMaterialProfile.setMetaDataEntry() will
  318. # take care of the derived containers too
  319. container = material_group.root_material_node.getContainer()
  320. if container is not None:
  321. container.setMetaDataEntry("GUID", new_guid)
  322. def _performMerge(self, merge_into, merge, clear_settings = True):
  323. if merge == merge_into:
  324. return
  325. for key in merge.getAllKeys():
  326. merge_into.setProperty(key, "value", merge.getProperty(key, "value"))
  327. if clear_settings:
  328. merge.clear()
  329. def _updateContainerNameFilters(self) -> None:
  330. self._container_name_filters = {}
  331. for plugin_id, container_type in self._container_registry.getContainerTypes():
  332. # Ignore default container types since those are not plugins
  333. if container_type in (InstanceContainer, ContainerStack, DefinitionContainer):
  334. continue
  335. serialize_type = ""
  336. try:
  337. plugin_metadata = self._plugin_registry.getMetaData(plugin_id)
  338. if plugin_metadata:
  339. serialize_type = plugin_metadata["settings_container"]["type"]
  340. else:
  341. continue
  342. except KeyError as e:
  343. continue
  344. mime_type = self._container_registry.getMimeTypeForContainer(container_type)
  345. entry = {
  346. "type": serialize_type,
  347. "mime": mime_type,
  348. "container": container_type
  349. }
  350. suffix = mime_type.preferredSuffix
  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(".") + 1:]
  354. suffix_list = "*." + suffix
  355. for suffix in mime_type.suffixes:
  356. if suffix == mime_type.preferredSuffix:
  357. continue
  358. if Platform.isOSX() and "." in suffix:
  359. # OSX's File dialog is stupid and does not allow selecting files with a . in its name
  360. suffix = suffix[suffix.index("."):]
  361. suffix_list += ", *." + suffix
  362. name_filter = "{0} ({1})".format(mime_type.comment, suffix_list)
  363. self._container_name_filters[name_filter] = entry
  364. ## Import single profile, file_url does not have to end with curaprofile
  365. @pyqtSlot(QUrl, result="QVariantMap")
  366. def importProfile(self, file_url):
  367. if not file_url.isValid():
  368. return
  369. path = file_url.toLocalFile()
  370. if not path:
  371. return
  372. return self._container_registry.importProfile(path)
  373. @pyqtSlot(QObject, QUrl, str)
  374. def exportQualityChangesGroup(self, quality_changes_group, file_url: QUrl, file_type: str):
  375. if not file_url.isValid():
  376. return
  377. path = file_url.toLocalFile()
  378. if not path:
  379. return
  380. container_list = [n.getContainer() for n in quality_changes_group.getAllNodes() if n.getContainer() is not None]
  381. self._container_registry.exportQualityProfile(container_list, path, file_type)
  382. __instance = None
  383. @classmethod
  384. def getInstance(cls, *args, **kwargs) -> "ContainerManager":
  385. return cls.__instance