ContainerManager.py 23 KB

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