ContainerManager.py 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  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
  6. import uuid
  7. from typing import Any, Dict, List, Union
  8. from PyQt5.QtCore import QObject, QUrl, QVariant
  9. from UM.FlameProfiler import pyqtSlot
  10. from PyQt5.QtWidgets import QMessageBox
  11. from UM.Util import parseBool
  12. from UM.PluginRegistry import PluginRegistry
  13. from UM.SaveFile import SaveFile
  14. from UM.Platform import Platform
  15. from UM.MimeTypeDatabase import MimeTypeDatabase
  16. from UM.Logger import Logger
  17. from UM.Application import Application
  18. from UM.Settings.ContainerStack import ContainerStack
  19. from UM.Settings.DefinitionContainer import DefinitionContainer
  20. from UM.Settings.InstanceContainer import InstanceContainer
  21. from cura.QualityManager import QualityManager
  22. from UM.MimeTypeDatabase import MimeTypeNotFoundError
  23. from UM.Settings.ContainerRegistry import ContainerRegistry
  24. from UM.i18n import i18nCatalog
  25. from cura.Settings.ExtruderManager import ExtruderManager
  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._container_registry = ContainerRegistry.getInstance()
  36. self._machine_manager = Application.getInstance().getMachineManager()
  37. self._container_name_filters = {}
  38. ## Create a duplicate of the specified container
  39. #
  40. # This will create and add a duplicate of the container corresponding
  41. # to the container ID.
  42. #
  43. # \param container_id \type{str} The ID of the container to duplicate.
  44. #
  45. # \return The ID of the new container, or an empty string if duplication failed.
  46. @pyqtSlot(str, result = str)
  47. def duplicateContainer(self, container_id):
  48. #TODO: It should be able to duplicate a container of which only the metadata is known.
  49. containers = self._container_registry.findContainers(id = container_id)
  50. if not containers:
  51. Logger.log("w", "Could duplicate container %s because it was not found.", container_id)
  52. return ""
  53. container = containers[0]
  54. new_name = self._container_registry.uniqueName(container.getName())
  55. # Only InstanceContainer has a duplicate method at the moment.
  56. # So fall back to serialize/deserialize when no duplicate method exists.
  57. if hasattr(container, "duplicate"):
  58. new_container = container.duplicate(new_name)
  59. else:
  60. new_container = container.__class__(new_name)
  61. new_container.deserialize(container.serialize())
  62. new_container.setName(new_name)
  63. if new_container:
  64. self._container_registry.addContainer(new_container)
  65. return new_container.getId()
  66. ## Change the name of a specified container to a new name.
  67. #
  68. # \param container_id \type{str} The ID of the container to change the name of.
  69. # \param new_id \type{str} The new ID of the container.
  70. # \param new_name \type{str} The new name of the specified container.
  71. #
  72. # \return True if successful, False if not.
  73. @pyqtSlot(str, str, str, result = bool)
  74. def renameContainer(self, container_id, new_id, new_name):
  75. containers = self._container_registry.findContainers(id = container_id)
  76. if not containers:
  77. Logger.log("w", "Could rename container %s because it was not found.", container_id)
  78. return False
  79. container = containers[0]
  80. # First, remove the container from the registry. This will clean up any files related to the container.
  81. self._container_registry.removeContainer(container_id)
  82. # Ensure we have a unique name for the container
  83. new_name = self._container_registry.uniqueName(new_name)
  84. # Then, update the name and ID of the container
  85. container.setName(new_name)
  86. container._id = new_id # TODO: Find a nicer way to set a new, unique ID
  87. # Finally, re-add the container so it will be properly serialized again.
  88. self._container_registry.addContainer(container)
  89. return True
  90. ## Remove the specified container.
  91. #
  92. # \param container_id \type{str} The ID of the container to remove.
  93. #
  94. # \return True if the container was successfully removed, False if not.
  95. @pyqtSlot(str, result = bool)
  96. def removeContainer(self, container_id):
  97. containers = self._container_registry.findContainers(id = container_id)
  98. if not containers:
  99. Logger.log("w", "Could remove container %s because it was not found.", container_id)
  100. return False
  101. self._container_registry.removeContainer(containers[0].getId())
  102. return True
  103. ## Merge a container with another.
  104. #
  105. # This will try to merge one container into the other, by going through the container
  106. # and setting the right properties on the other container.
  107. #
  108. # \param merge_into_id \type{str} The ID of the container to merge into.
  109. # \param merge_id \type{str} The ID of the container to merge.
  110. #
  111. # \return True if successfully merged, False if not.
  112. @pyqtSlot(str, result = bool)
  113. def mergeContainers(self, merge_into_id, merge_id):
  114. containers = self._container_registry.findContainers(id = merge_into_id)
  115. if not containers:
  116. Logger.log("w", "Could merge into container %s because it was not found.", merge_into_id)
  117. return False
  118. merge_into = containers[0]
  119. containers = self._container_registry.findContainers(id = merge_id)
  120. if not containers:
  121. Logger.log("w", "Could not merge container %s because it was not found", merge_id)
  122. return False
  123. merge = containers[0]
  124. if not isinstance(merge, type(merge_into)):
  125. Logger.log("w", "Cannot merge two containers of different types")
  126. return False
  127. self._performMerge(merge_into, merge)
  128. return True
  129. ## Clear the contents of a container.
  130. #
  131. # \param container_id \type{str} The ID of the container to clear.
  132. #
  133. # \return True if successful, False if not.
  134. @pyqtSlot(str, result = bool)
  135. def clearContainer(self, container_id):
  136. if self._container_registry.isReadOnly(container_id):
  137. Logger.log("w", "Cannot clear read-only container %s", container_id)
  138. return False
  139. containers = self._container_registry.findContainers(id = container_id)
  140. if not containers:
  141. Logger.log("w", "Could clear container %s because it was not found.", container_id)
  142. return False
  143. containers[0].clear()
  144. return True
  145. @pyqtSlot(str, str, result=str)
  146. def getContainerMetaDataEntry(self, container_id, entry_name):
  147. metadatas = self._container_registry.findContainersMetadata(id = container_id)
  148. if not metadatas:
  149. Logger.log("w", "Could not get metadata of container %s because it was not found.", container_id)
  150. return ""
  151. return str(metadatas[0].get(entry_name, ""))
  152. ## Set a metadata entry of the specified container.
  153. #
  154. # This will set the specified entry of the container's metadata to the specified
  155. # value. Note that entries containing dictionaries can have their entries changed
  156. # by using "/" as a separator. For example, to change an entry "foo" in a
  157. # dictionary entry "bar", you can specify "bar/foo" as entry name.
  158. #
  159. # \param container_id \type{str} The ID of the container to change.
  160. # \param entry_name \type{str} The name of the metadata entry to change.
  161. # \param entry_value The new value of the entry.
  162. #
  163. # \return True if successful, False if not.
  164. @pyqtSlot(str, str, str, result = bool)
  165. def setContainerMetaDataEntry(self, container_id, entry_name, entry_value):
  166. if self._container_registry.isReadOnly(container_id):
  167. Logger.log("w", "Cannot set metadata of read-only container %s.", container_id)
  168. return False
  169. containers = self._container_registry.findContainers(id = container_id) #We need the complete container, since we need to know whether the container is read-only or not.
  170. if not containers:
  171. Logger.log("w", "Could not set metadata of container %s because it was not found.", container_id)
  172. return False
  173. container = containers[0]
  174. entries = entry_name.split("/")
  175. entry_name = entries.pop()
  176. sub_item_changed = False
  177. if entries:
  178. root_name = entries.pop(0)
  179. root = container.getMetaDataEntry(root_name)
  180. item = root
  181. for _ in range(len(entries)):
  182. item = item.get(entries.pop(0), { })
  183. if item[entry_name] != entry_value:
  184. sub_item_changed = True
  185. item[entry_name] = entry_value
  186. entry_name = root_name
  187. entry_value = root
  188. container.setMetaDataEntry(entry_name, entry_value)
  189. 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.
  190. container.metaDataChanged.emit(container)
  191. return True
  192. ## Set a setting property of the specified container.
  193. #
  194. # This will set the specified property of the specified setting of the container
  195. # and all containers that share the same base_file (if any). The latter only
  196. # happens for material containers.
  197. #
  198. # \param container_id \type{str} The ID of the container to change.
  199. # \param setting_key \type{str} The key of the setting.
  200. # \param property_name \type{str} The name of the property, eg "value".
  201. # \param property_value \type{str} The new value of the property.
  202. #
  203. # \return True if successful, False if not.
  204. @pyqtSlot(str, str, str, str, result = bool)
  205. def setContainerProperty(self, container_id, setting_key, property_name, property_value):
  206. if self._container_registry.isReadOnly(container_id):
  207. Logger.log("w", "Cannot set properties of read-only container %s.", container_id)
  208. return False
  209. containers = self._container_registry.findContainers(id = container_id)
  210. if not containers:
  211. Logger.log("w", "Could not set properties of container %s because it was not found.", container_id)
  212. return False
  213. container = containers[0]
  214. container.setProperty(setting_key, property_name, property_value)
  215. basefile = container.getMetaDataEntry("base_file", container_id)
  216. for sibbling_container in ContainerRegistry.getInstance().findInstanceContainers(base_file = basefile):
  217. if sibbling_container != container:
  218. sibbling_container.setProperty(setting_key, property_name, property_value)
  219. return True
  220. ## Get a setting property of the specified container.
  221. #
  222. # This will get the specified property of the specified setting of the
  223. # specified container.
  224. #
  225. # \param container_id The ID of the container to get the setting property
  226. # of.
  227. # \param setting_key The key of the setting to get the property of.
  228. # \param property_name The property to obtain.
  229. # \return The value of the specified property. The type of this property
  230. # value depends on the type of the property. For instance, the "value"
  231. # property of an integer setting will be a Python int, but the "value"
  232. # property of an enum setting will be a Python str.
  233. @pyqtSlot(str, str, str, result = QVariant)
  234. def getContainerProperty(self, container_id: str, setting_key: str, property_name: str):
  235. containers = self._container_registry.findContainers(id = container_id)
  236. if not containers:
  237. Logger.log("w", "Could not get properties of container %s because it was not found.", container_id)
  238. return ""
  239. container = containers[0]
  240. return container.getProperty(setting_key, property_name)
  241. ## Set the name of the specified container.
  242. @pyqtSlot(str, str, result = bool)
  243. def setContainerName(self, container_id, new_name):
  244. if self._container_registry.isReadOnly(container_id):
  245. Logger.log("w", "Cannot set name of read-only container %s.", container_id)
  246. return False
  247. containers = self._container_registry.findContainers(id = container_id) #We need to get the full container, not just metadata, since we need to know whether it's read-only.
  248. if not containers:
  249. Logger.log("w", "Could not set name of container %s because it was not found.", container_id)
  250. return False
  251. containers[0].setName(new_name)
  252. return True
  253. ## Find instance containers matching certain criteria.
  254. #
  255. # This effectively forwards to
  256. # ContainerRegistry::findInstanceContainersMetadata.
  257. #
  258. # \param criteria A dict of key - value pairs to search for.
  259. #
  260. # \return A list of container IDs that match the given criteria.
  261. @pyqtSlot("QVariantMap", result = "QVariantList")
  262. def findInstanceContainers(self, criteria):
  263. return [entry["id"] for entry in self._container_registry.findInstanceContainersMetadata(**criteria)]
  264. @pyqtSlot(str, result = bool)
  265. def isContainerUsed(self, container_id):
  266. Logger.log("d", "Checking if container %s is currently used", container_id)
  267. # check if this is a material container. If so, check if any material with the same base is being used by any
  268. # stacks.
  269. container_ids_to_check = [container_id]
  270. container_results = self._container_registry.findInstanceContainersMetadata(id = container_id, type = "material")
  271. if container_results:
  272. this_container = container_results[0]
  273. material_base_file = this_container["id"]
  274. if "base_file" in this_container:
  275. material_base_file = this_container["base_file"]
  276. # check all material container IDs with the same base
  277. material_containers = self._container_registry.findInstanceContainersMetadata(base_file = material_base_file,
  278. type = "material")
  279. if material_containers:
  280. container_ids_to_check = [container["id"] for container in material_containers]
  281. all_stacks = self._container_registry.findContainerStacks()
  282. for stack in all_stacks:
  283. for used_container_id in container_ids_to_check:
  284. if used_container_id in [child.getId() for child in stack.getContainers()]:
  285. Logger.log("d", "The container is in use by %s", stack.getId())
  286. return True
  287. return False
  288. @pyqtSlot(str, result = str)
  289. def makeUniqueName(self, original_name):
  290. return self._container_registry.uniqueName(original_name)
  291. ## Get a list of string that can be used as name filters for a Qt File Dialog
  292. #
  293. # This will go through the list of available container types and generate a list of strings
  294. # out of that. The strings are formatted as "description (*.extension)" and can be directly
  295. # passed to a nameFilters property of a Qt File Dialog.
  296. #
  297. # \param type_name Which types of containers to list. These types correspond to the "type"
  298. # key of the plugin metadata.
  299. #
  300. # \return A string list with name filters.
  301. @pyqtSlot(str, result = "QStringList")
  302. def getContainerNameFilters(self, type_name):
  303. if not self._container_name_filters:
  304. self._updateContainerNameFilters()
  305. filters = []
  306. for filter_string, entry in self._container_name_filters.items():
  307. if not type_name or entry["type"] == type_name:
  308. filters.append(filter_string)
  309. filters.append("All Files (*)")
  310. return filters
  311. ## Export a container to a file
  312. #
  313. # \param container_id The ID of the container to export
  314. # \param file_type The type of file to save as. Should be in the form of "description (*.extension, *.ext)"
  315. # \param file_url_or_string The URL where to save the file.
  316. #
  317. # \return A dictionary containing a key "status" with a status code and a key "message" with a message
  318. # explaining the status.
  319. # The status code can be one of "error", "cancelled", "success"
  320. @pyqtSlot(str, str, QUrl, result = "QVariantMap")
  321. def exportContainer(self, container_id: str, file_type: str, file_url_or_string: Union[QUrl, str]) -> Dict[str, str]:
  322. if not container_id or not file_type or not file_url_or_string:
  323. return { "status": "error", "message": "Invalid arguments"}
  324. if isinstance(file_url_or_string, QUrl):
  325. file_url = file_url_or_string.toLocalFile()
  326. else:
  327. file_url = file_url_or_string
  328. if not file_url:
  329. return { "status": "error", "message": "Invalid path"}
  330. mime_type = None
  331. if not file_type in self._container_name_filters:
  332. try:
  333. mime_type = MimeTypeDatabase.getMimeTypeForFile(file_url)
  334. except MimeTypeNotFoundError:
  335. return { "status": "error", "message": "Unknown File Type" }
  336. else:
  337. mime_type = self._container_name_filters[file_type]["mime"]
  338. containers = self._container_registry.findContainers(id = container_id)
  339. if not containers:
  340. return { "status": "error", "message": "Container not found"}
  341. container = containers[0]
  342. if Platform.isOSX() and "." in file_url:
  343. file_url = file_url[:file_url.rfind(".")]
  344. for suffix in mime_type.suffixes:
  345. if file_url.endswith(suffix):
  346. break
  347. else:
  348. file_url += "." + mime_type.preferredSuffix
  349. if not Platform.isWindows():
  350. if os.path.exists(file_url):
  351. result = QMessageBox.question(None, catalog.i18nc("@title:window", "File Already Exists"),
  352. 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))
  353. if result == QMessageBox.No:
  354. return { "status": "cancelled", "message": "User cancelled"}
  355. try:
  356. contents = container.serialize()
  357. except NotImplementedError:
  358. return { "status": "error", "message": "Unable to serialize container"}
  359. if contents is None:
  360. return {"status": "error", "message": "Serialization returned None. Unable to write to file"}
  361. with SaveFile(file_url, "w") as f:
  362. f.write(contents)
  363. return { "status": "success", "message": "Succesfully exported container", "path": file_url}
  364. ## Imports a profile from a file
  365. #
  366. # \param file_url A URL that points to the file to import.
  367. #
  368. # \return \type{Dict} dict with a 'status' key containing the string 'success' or 'error', and a 'message' key
  369. # containing a message for the user
  370. @pyqtSlot(QUrl, result = "QVariantMap")
  371. def importContainer(self, file_url_or_string: Union[QUrl, str]) -> Dict[str, str]:
  372. if not file_url_or_string:
  373. return { "status": "error", "message": "Invalid path"}
  374. if isinstance(file_url_or_string, QUrl):
  375. file_url = file_url_or_string.toLocalFile()
  376. else:
  377. file_url = file_url_or_string
  378. if not file_url or not os.path.exists(file_url):
  379. return { "status": "error", "message": "Invalid path" }
  380. try:
  381. mime_type = MimeTypeDatabase.getMimeTypeForFile(file_url)
  382. except MimeTypeNotFoundError:
  383. return { "status": "error", "message": "Could not determine mime type of file" }
  384. container_type = self._container_registry.getContainerForMimeType(mime_type)
  385. if not container_type:
  386. return { "status": "error", "message": "Could not find a container to handle the specified file."}
  387. container_id = urllib.parse.unquote_plus(mime_type.stripExtension(os.path.basename(file_url)))
  388. container_id = self._container_registry.uniqueName(container_id)
  389. container = container_type(container_id)
  390. try:
  391. with open(file_url, "rt") as f:
  392. container.deserialize(f.read())
  393. except PermissionError:
  394. return { "status": "error", "message": "Permission denied when trying to read the file"}
  395. container.setName(container_id)
  396. self._container_registry.addContainer(container)
  397. return { "status": "success", "message": "Successfully imported container {0}".format(container.getName()) }
  398. ## Update the current active quality changes container with the settings from the user container.
  399. #
  400. # This will go through the active global stack and all active extruder stacks and merge the changes from the user
  401. # container into the quality_changes container. After that, the user container is cleared.
  402. #
  403. # \return \type{bool} True if successful, False if not.
  404. @pyqtSlot(result = bool)
  405. def updateQualityChanges(self):
  406. global_stack = Application.getInstance().getGlobalContainerStack()
  407. if not global_stack:
  408. return False
  409. self._machine_manager.blurSettings.emit()
  410. for stack in ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks():
  411. # Find the quality_changes container for this stack and merge the contents of the top container into it.
  412. quality_changes = stack.qualityChanges
  413. if not quality_changes or quality_changes.isReadOnly():
  414. Logger.log("e", "Could not update quality of a nonexistant or read only quality profile in stack %s", stack.getId())
  415. continue
  416. self._performMerge(quality_changes, stack.getTop())
  417. self._machine_manager.activeQualityChanged.emit()
  418. return True
  419. ## Clear the top-most (user) containers of the active stacks.
  420. @pyqtSlot()
  421. def clearUserContainers(self) -> None:
  422. self._machine_manager.blurSettings.emit()
  423. send_emits_containers = []
  424. # Go through global and extruder stacks and clear their topmost container (the user settings).
  425. for stack in ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks():
  426. container = stack.getTop()
  427. container.clear()
  428. send_emits_containers.append(container)
  429. for container in send_emits_containers:
  430. container.sendPostponedEmits()
  431. ## Create quality changes containers from the user containers in the active stacks.
  432. #
  433. # This will go through the global and extruder stacks and create quality_changes containers from
  434. # the user containers in each stack. These then replace the quality_changes containers in the
  435. # stack and clear the user settings.
  436. #
  437. # \return \type{bool} True if the operation was successfully, False if not.
  438. @pyqtSlot(str, result = bool)
  439. def createQualityChanges(self, base_name):
  440. global_stack = Application.getInstance().getGlobalContainerStack()
  441. if not global_stack:
  442. return False
  443. active_quality_name = self._machine_manager.activeQualityName
  444. if active_quality_name == "":
  445. Logger.log("w", "No quality container found in stack %s, cannot create profile", global_stack.getId())
  446. return False
  447. self._machine_manager.blurSettings.emit()
  448. if base_name is None or base_name == "":
  449. base_name = active_quality_name
  450. unique_name = self._container_registry.uniqueName(base_name)
  451. # Go through the active stacks and create quality_changes containers from the user containers.
  452. for stack in ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks():
  453. user_container = stack.getTop()
  454. quality_container = stack.quality
  455. quality_changes_container = stack.qualityChanges
  456. if not quality_container or not quality_changes_container:
  457. Logger.log("w", "No quality or quality changes container found in stack %s, ignoring it", stack.getId())
  458. continue
  459. extruder_id = None if stack is global_stack else QualityManager.getInstance().getParentMachineDefinition(stack.getBottom()).getId()
  460. new_changes = self._createQualityChanges(quality_container, unique_name,
  461. Application.getInstance().getGlobalContainerStack().getBottom(),
  462. extruder_id)
  463. self._performMerge(new_changes, quality_changes_container, clear_settings = False)
  464. self._performMerge(new_changes, user_container)
  465. self._container_registry.addContainer(new_changes)
  466. stack.replaceContainer(stack.getContainerIndex(quality_changes_container), new_changes)
  467. self._machine_manager.activeQualityChanged.emit()
  468. return True
  469. ## Remove all quality changes containers matching a specified name.
  470. #
  471. # This will search for quality_changes containers matching the supplied name and remove them.
  472. # Note that if the machine specifies that qualities should be filtered by machine and/or material
  473. # only the containers related to the active machine/material are removed.
  474. #
  475. # \param quality_name The name of the quality changes to remove.
  476. #
  477. # \return \type{bool} True if successful, False if not.
  478. @pyqtSlot(str, result = bool)
  479. def removeQualityChanges(self, quality_name):
  480. Logger.log("d", "Attempting to remove the quality change containers with name %s", quality_name)
  481. containers_found = False
  482. if not quality_name:
  483. return containers_found # Without a name we will never find a container to remove.
  484. # If the container that is being removed is the currently active quality, set another quality as the active quality
  485. activate_quality = quality_name == self._machine_manager.activeQualityName
  486. activate_quality_type = None
  487. global_stack = Application.getInstance().getGlobalContainerStack()
  488. if not global_stack or not quality_name:
  489. return ""
  490. machine_definition = QualityManager.getInstance().getParentMachineDefinition(global_stack.getBottom())
  491. for container in QualityManager.getInstance().findQualityChangesByName(quality_name, machine_definition):
  492. containers_found = True
  493. if activate_quality and not activate_quality_type:
  494. activate_quality_type = container.getMetaDataEntry("quality")
  495. self._container_registry.removeContainer(container.getId())
  496. if not containers_found:
  497. Logger.log("d", "Unable to remove quality containers, as we did not find any by the name of %s", quality_name)
  498. elif activate_quality:
  499. definition_id = "fdmprinter" if not self._machine_manager.filterQualityByMachine else self._machine_manager.activeDefinitionId
  500. containers = self._container_registry.findInstanceContainersMetadata(type = "quality", definition = definition_id, quality_type = activate_quality_type)
  501. if containers:
  502. self._machine_manager.setActiveQuality(containers[0]["id"])
  503. self._machine_manager.activeQualityChanged.emit()
  504. return containers_found
  505. ## Rename a set of quality changes containers.
  506. #
  507. # This will search for quality_changes containers matching the supplied name and rename them.
  508. # Note that if the machine specifies that qualities should be filtered by machine and/or material
  509. # only the containers related to the active machine/material are renamed.
  510. #
  511. # \param quality_name The name of the quality changes containers to rename.
  512. # \param new_name The new name of the quality changes.
  513. #
  514. # \return True if successful, False if not.
  515. @pyqtSlot(str, str, result = bool)
  516. def renameQualityChanges(self, quality_name, new_name):
  517. Logger.log("d", "User requested QualityChanges container rename of %s to %s", quality_name, new_name)
  518. if not quality_name or not new_name:
  519. return False
  520. if quality_name == new_name:
  521. Logger.log("w", "Unable to rename %s to %s, because they are the same.", quality_name, new_name)
  522. return True
  523. global_stack = Application.getInstance().getGlobalContainerStack()
  524. if not global_stack:
  525. return False
  526. self._machine_manager.blurSettings.emit()
  527. new_name = self._container_registry.uniqueName(new_name)
  528. container_registry = self._container_registry
  529. containers_to_rename = self._container_registry.findInstanceContainersMetadata(type = "quality_changes", name = quality_name)
  530. for container in containers_to_rename:
  531. stack_id = global_stack.getId()
  532. if "extruder" in container:
  533. stack_id = container["extruder"]
  534. container_registry.renameContainer(container["id"], new_name, self._createUniqueId(stack_id, new_name))
  535. if not containers_to_rename:
  536. Logger.log("e", "Unable to rename %s, because we could not find the profile", quality_name)
  537. self._machine_manager.activeQualityChanged.emit()
  538. return True
  539. ## Duplicate a specified set of quality or quality_changes containers.
  540. #
  541. # This will search for containers matching the specified name. If the container is a "quality" type container, a new
  542. # quality_changes container will be created with the specified quality as base. If the container is a "quality_changes"
  543. # container, it is simply duplicated and renamed.
  544. #
  545. # \param quality_name The name of the quality to duplicate.
  546. #
  547. # \return A string containing the name of the duplicated containers, or an empty string if it failed.
  548. @pyqtSlot(str, str, result = str)
  549. def duplicateQualityOrQualityChanges(self, quality_name, base_name):
  550. global_stack = Application.getInstance().getGlobalContainerStack()
  551. if not global_stack or not quality_name:
  552. return ""
  553. machine_definition = global_stack.getBottom()
  554. active_stacks = ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks()
  555. if active_stacks is None:
  556. return ""
  557. material_metadatas = [stack.material.getMetaData() for stack in active_stacks]
  558. result = self._duplicateQualityOrQualityChangesForMachineType(quality_name, base_name,
  559. QualityManager.getInstance().getParentMachineDefinition(machine_definition),
  560. material_metadatas)
  561. return result[0].getName() if result else ""
  562. ## Duplicate a quality or quality changes profile specific to a machine type
  563. #
  564. # \param quality_name The name of the quality or quality changes container to duplicate.
  565. # \param base_name The desired name for the new container.
  566. # \param machine_definition The machine with the specific machine type.
  567. # \param material_metadatas Metadata of materials
  568. # \return List of duplicated quality profiles.
  569. def _duplicateQualityOrQualityChangesForMachineType(self, quality_name: str, base_name: str, machine_definition: DefinitionContainer, material_metadatas: List[Dict[str, Any]]) -> List[InstanceContainer]:
  570. Logger.log("d", "Attempting to duplicate the quality %s", quality_name)
  571. if base_name is None:
  572. base_name = quality_name
  573. # Try to find a Quality with the name.
  574. container = QualityManager.getInstance().findQualityByName(quality_name, machine_definition, material_metadatas)
  575. if container:
  576. Logger.log("d", "We found a quality to duplicate.")
  577. return self._duplicateQualityForMachineType(container, base_name, machine_definition)
  578. Logger.log("d", "We found a quality_changes to duplicate.")
  579. # Assume it is a quality changes.
  580. return self._duplicateQualityChangesForMachineType(quality_name, base_name, machine_definition)
  581. # Duplicate a quality profile
  582. def _duplicateQualityForMachineType(self, quality_container, base_name, machine_definition) -> List[InstanceContainer]:
  583. if base_name is None:
  584. base_name = quality_container.getName()
  585. new_name = self._container_registry.uniqueName(base_name)
  586. new_change_instances = []
  587. # Handle the global stack first.
  588. global_changes = self._createQualityChanges(quality_container, new_name, machine_definition, None)
  589. new_change_instances.append(global_changes)
  590. self._container_registry.addContainer(global_changes)
  591. # Handle the extruders if present.
  592. extruders = machine_definition.getMetaDataEntry("machine_extruder_trains")
  593. if extruders:
  594. for extruder_id in extruders:
  595. extruder = extruders[extruder_id]
  596. new_changes = self._createQualityChanges(quality_container, new_name, machine_definition, extruder)
  597. new_change_instances.append(new_changes)
  598. self._container_registry.addContainer(new_changes)
  599. return new_change_instances
  600. # Duplicate a quality changes container
  601. def _duplicateQualityChangesForMachineType(self, quality_changes_name, base_name, machine_definition) -> List[InstanceContainer]:
  602. new_change_instances = []
  603. for container in QualityManager.getInstance().findQualityChangesByName(quality_changes_name,
  604. machine_definition):
  605. base_id = container.getMetaDataEntry("extruder")
  606. if not base_id:
  607. base_id = container.getDefinition().getId()
  608. new_unique_id = self._createUniqueId(base_id, base_name)
  609. new_container = container.duplicate(new_unique_id, base_name)
  610. new_change_instances.append(new_container)
  611. self._container_registry.addContainer(new_container)
  612. return new_change_instances
  613. ## Create a duplicate of a material, which has the same GUID and base_file metadata
  614. #
  615. # \return \type{str} the id of the newly created container.
  616. @pyqtSlot(str, result = str)
  617. def duplicateMaterial(self, material_id: str) -> str:
  618. original = self._container_registry.findContainersMetadata(id = material_id)
  619. if not original:
  620. Logger.log("d", "Unable to duplicate the material with id %s, because it doesn't exist.", material_id)
  621. return ""
  622. original = original[0]
  623. base_container_id = original.get("base_file")
  624. base_container = self._container_registry.findContainers(id = base_container_id)
  625. if not base_container:
  626. Logger.log("d", "Unable to duplicate the material with id {material_id}, because base_file {base_container_id} doesn't exist.".format(material_id = material_id, base_container_id = base_container_id))
  627. return ""
  628. base_container = base_container[0]
  629. #We'll copy all containers with the same base.
  630. #This way the correct variant and machine still gets assigned when loading the copy of the material.
  631. containers_to_copy = self._container_registry.findInstanceContainers(base_file = base_container_id)
  632. # Ensure all settings are saved.
  633. Application.getInstance().saveSettings()
  634. # Create a new ID & container to hold the data.
  635. new_containers = []
  636. new_base_id = self._container_registry.uniqueName(base_container.getId())
  637. new_base_container = copy.deepcopy(base_container)
  638. new_base_container.getMetaData()["id"] = new_base_id
  639. new_base_container.getMetaData()["base_file"] = new_base_id
  640. new_containers.append(new_base_container)
  641. #Clone all of them.
  642. clone_of_original = None #Keeping track of which one is the clone of the original material, since we need to return that.
  643. for container_to_copy in containers_to_copy:
  644. #Create unique IDs for every clone.
  645. current_id = container_to_copy.getId()
  646. new_id = self._container_registry.uniqueName(current_id)
  647. if current_id == material_id:
  648. clone_of_original = new_id
  649. new_container = copy.deepcopy(container_to_copy)
  650. new_container.getMetaData()["id"] = new_id
  651. new_container.getMetaData()["base_file"] = new_base_id
  652. new_containers.append(new_container)
  653. for container_to_add in new_containers:
  654. container_to_add.setDirty(True)
  655. ContainerRegistry.getInstance().addContainer(container_to_add)
  656. return self._getMaterialContainerIdForActiveMachine(clone_of_original)
  657. ## Create a new material by cloning Generic PLA for the current material diameter and setting the GUID to something unqiue
  658. #
  659. # \return \type{str} the id of the newly created container.
  660. @pyqtSlot(result = str)
  661. def createMaterial(self) -> str:
  662. # Ensure all settings are saved.
  663. Application.getInstance().saveSettings()
  664. global_stack = Application.getInstance().getGlobalContainerStack()
  665. if not global_stack:
  666. return ""
  667. approximate_diameter = str(round(global_stack.getProperty("material_diameter", "value")))
  668. containers = self._container_registry.findInstanceContainersMetadata(id = "generic_pla*", approximate_diameter = approximate_diameter)
  669. if not containers:
  670. Logger.log("d", "Unable to create a new material by cloning Generic PLA, because it cannot be found for the material diameter for this machine.")
  671. return ""
  672. base_file = containers[0].get("base_file")
  673. containers = self._container_registry.findInstanceContainers(id = base_file)
  674. if not containers:
  675. Logger.log("d", "Unable to create a new material by cloning Generic PLA, because the base file for Generic PLA for this machine can not be found.")
  676. return ""
  677. # Create a new ID & container to hold the data.
  678. new_id = self._container_registry.uniqueName("custom_material")
  679. container_type = type(containers[0]) # Always XMLMaterialProfile, since we specifically clone the base_file
  680. duplicated_container = container_type(new_id)
  681. # Instead of duplicating we load the data from the basefile again.
  682. # This ensures that the inheritance goes well and all "cut up" subclasses of the xmlMaterial profile
  683. # are also correctly created.
  684. with open(containers[0].getPath(), encoding="utf-8") as f:
  685. duplicated_container.deserialize(f.read())
  686. duplicated_container.setMetaDataEntry("GUID", str(uuid.uuid4()))
  687. duplicated_container.setMetaDataEntry("brand", catalog.i18nc("@label", "Custom"))
  688. # We're defaulting to PLA, as machines with material profiles don't like material types they don't know.
  689. # TODO: This is a hack, the only reason this is in now is to bandaid the problem as we're close to a release!
  690. duplicated_container.setMetaDataEntry("material", "PLA")
  691. duplicated_container.setName(catalog.i18nc("@label", "Custom Material"))
  692. self._container_registry.addContainer(duplicated_container)
  693. return self._getMaterialContainerIdForActiveMachine(new_id)
  694. ## Find the id of a material container based on the new material
  695. # Utilty function that is shared between duplicateMaterial and createMaterial
  696. #
  697. # \param base_file \type{str} the id of the created container.
  698. def _getMaterialContainerIdForActiveMachine(self, base_file):
  699. global_stack = Application.getInstance().getGlobalContainerStack()
  700. if not global_stack:
  701. return base_file
  702. has_machine_materials = parseBool(global_stack.getMetaDataEntry("has_machine_materials", default = False))
  703. has_variant_materials = parseBool(global_stack.getMetaDataEntry("has_variant_materials", default = False))
  704. has_variants = parseBool(global_stack.getMetaDataEntry("has_variants", default = False))
  705. if has_machine_materials or has_variant_materials:
  706. if has_variants:
  707. materials = self._container_registry.findInstanceContainersMetadata(type = "material", base_file = base_file, definition = global_stack.getBottom().getId(), variant = self._machine_manager.activeVariantId)
  708. else:
  709. materials = self._container_registry.findInstanceContainersMetadata(type = "material", base_file = base_file, definition = global_stack.getBottom().getId())
  710. if materials:
  711. return materials[0]["id"]
  712. Logger.log("w", "Unable to find a suitable container based on %s for the current machine.", base_file)
  713. return "" # do not activate a new material if a container can not be found
  714. return base_file
  715. ## Get a list of materials that have the same GUID as the reference material
  716. #
  717. # \param material_id \type{str} the id of the material for which to get the linked materials.
  718. # \return \type{list} a list of names of materials with the same GUID
  719. @pyqtSlot(str, result = "QStringList")
  720. def getLinkedMaterials(self, material_id: str):
  721. containers = self._container_registry.findInstanceContainersMetadata(id = material_id)
  722. if not containers:
  723. Logger.log("d", "Unable to find materials linked to material with id %s, because it doesn't exist.", material_id)
  724. return []
  725. material_container = containers[0]
  726. material_base_file = material_container.get("base_file", "")
  727. material_guid = material_container.get("GUID", "")
  728. if not material_guid:
  729. Logger.log("d", "Unable to find materials linked to material with id %s, because it doesn't have a GUID.", material_id)
  730. return []
  731. containers = self._container_registry.findInstanceContainersMetadata(type = "material", GUID = material_guid)
  732. linked_material_names = []
  733. for container in containers:
  734. if container["id"] in [material_id, material_base_file] or container.get("base_file") != container["id"]:
  735. continue
  736. linked_material_names.append(container["name"])
  737. return linked_material_names
  738. ## Unlink a material from all other materials by creating a new GUID
  739. # \param material_id \type{str} the id of the material to create a new GUID for.
  740. @pyqtSlot(str)
  741. def unlinkMaterial(self, material_id: str):
  742. containers = self._container_registry.findInstanceContainers(id=material_id)
  743. if not containers:
  744. Logger.log("d", "Unable to make the material with id %s unique, because it doesn't exist.", material_id)
  745. return ""
  746. containers[0].setMetaDataEntry("GUID", str(uuid.uuid4()))
  747. ## Get the singleton instance for this class.
  748. @classmethod
  749. def getInstance(cls) -> "ContainerManager":
  750. # Note: Explicit use of class name to prevent issues with inheritance.
  751. if ContainerManager.__instance is None:
  752. ContainerManager.__instance = cls()
  753. return ContainerManager.__instance
  754. __instance = None # type: "ContainerManager"
  755. # Factory function, used by QML
  756. @staticmethod
  757. def createContainerManager(engine, js_engine):
  758. return ContainerManager.getInstance()
  759. def _performMerge(self, merge_into, merge, clear_settings = True):
  760. assert isinstance(merge, type(merge_into))
  761. if merge == merge_into:
  762. return
  763. for key in merge.getAllKeys():
  764. merge_into.setProperty(key, "value", merge.getProperty(key, "value"))
  765. if clear_settings:
  766. merge.clear()
  767. def _updateContainerNameFilters(self) -> None:
  768. self._container_name_filters = {}
  769. for plugin_id, container_type in self._container_registry.getContainerTypes():
  770. # Ignore default container types since those are not plugins
  771. if container_type in (InstanceContainer, ContainerStack, DefinitionContainer):
  772. continue
  773. serialize_type = ""
  774. try:
  775. plugin_metadata = PluginRegistry.getInstance().getMetaData(plugin_id)
  776. if plugin_metadata:
  777. serialize_type = plugin_metadata["settings_container"]["type"]
  778. else:
  779. continue
  780. except KeyError as e:
  781. continue
  782. mime_type = self._container_registry.getMimeTypeForContainer(container_type)
  783. entry = {
  784. "type": serialize_type,
  785. "mime": mime_type,
  786. "container": container_type
  787. }
  788. suffix = mime_type.preferredSuffix
  789. if Platform.isOSX() and "." in suffix:
  790. # OSX's File dialog is stupid and does not allow selecting files with a . in its name
  791. suffix = suffix[suffix.index(".") + 1:]
  792. suffix_list = "*." + suffix
  793. for suffix in mime_type.suffixes:
  794. if suffix == mime_type.preferredSuffix:
  795. continue
  796. if Platform.isOSX() and "." in suffix:
  797. # OSX's File dialog is stupid and does not allow selecting files with a . in its name
  798. suffix = suffix[suffix.index("."):]
  799. suffix_list += ", *." + suffix
  800. name_filter = "{0} ({1})".format(mime_type.comment, suffix_list)
  801. self._container_name_filters[name_filter] = entry
  802. ## Creates a unique ID for a container by prefixing the name with the stack ID.
  803. #
  804. # This method creates a unique ID for a container by prefixing it with a specified stack ID.
  805. # This is done to ensure we have an easily identified ID for quality changes, which have the
  806. # same name across several stacks.
  807. #
  808. # \param stack_id The ID of the stack to prepend.
  809. # \param container_name The name of the container that we are creating a unique ID for.
  810. #
  811. # \return Container name prefixed with stack ID, in lower case with spaces replaced by underscores.
  812. def _createUniqueId(self, stack_id, container_name):
  813. result = stack_id + "_" + container_name
  814. result = result.lower()
  815. result.replace(" ", "_")
  816. return result
  817. ## Create a quality changes container for a specified quality container.
  818. #
  819. # \param quality_container The quality container to create a changes container for.
  820. # \param new_name The name of the new quality_changes container.
  821. # \param machine_definition The machine definition this quality changes container is specific to.
  822. # \param extruder_id
  823. #
  824. # \return A new quality_changes container with the specified container as base.
  825. def _createQualityChanges(self, quality_container, new_name, machine_definition, extruder_id):
  826. base_id = machine_definition.getId() if extruder_id is None else extruder_id
  827. # Create a new quality_changes container for the quality.
  828. quality_changes = InstanceContainer(self._createUniqueId(base_id, new_name))
  829. quality_changes.setName(new_name)
  830. quality_changes.addMetaDataEntry("type", "quality_changes")
  831. quality_changes.addMetaDataEntry("quality_type", quality_container.getMetaDataEntry("quality_type"))
  832. # If we are creating a container for an extruder, ensure we add that to the container
  833. if extruder_id is not None:
  834. quality_changes.addMetaDataEntry("extruder", extruder_id)
  835. # If the machine specifies qualities should be filtered, ensure we match the current criteria.
  836. if not machine_definition.getMetaDataEntry("has_machine_quality"):
  837. quality_changes.setDefinition("fdmprinter")
  838. else:
  839. quality_changes.setDefinition(QualityManager.getInstance().getParentMachineDefinition(machine_definition).getId())
  840. from cura.CuraApplication import CuraApplication
  841. quality_changes.addMetaDataEntry("setting_version", CuraApplication.SettingVersion)
  842. return quality_changes
  843. ## Import profiles from a list of file_urls.
  844. # Each QUrl item must end with .curaprofile, or it will not be imported.
  845. #
  846. # \param QVariant<QUrl>, essentially a list with QUrl objects.
  847. # \return Dict with keys status, text
  848. @pyqtSlot("QVariantList", result="QVariantMap")
  849. def importProfiles(self, file_urls):
  850. status = "ok"
  851. results = {"ok": [], "error": []}
  852. for file_url in file_urls:
  853. if not file_url.isValid():
  854. continue
  855. path = file_url.toLocalFile()
  856. if not path:
  857. continue
  858. if not path.endswith(".curaprofile"):
  859. continue
  860. single_result = self._container_registry.importProfile(path)
  861. if single_result["status"] == "error":
  862. status = "error"
  863. results[single_result["status"]].append(single_result["message"])
  864. return {
  865. "status": status,
  866. "message": "\n".join(results["ok"] + results["error"])}
  867. ## Import single profile, file_url does not have to end with curaprofile
  868. @pyqtSlot(QUrl, result="QVariantMap")
  869. def importProfile(self, file_url):
  870. if not file_url.isValid():
  871. return
  872. path = file_url.toLocalFile()
  873. if not path:
  874. return
  875. return self._container_registry.importProfile(path)
  876. @pyqtSlot("QVariantList", QUrl, str)
  877. def exportProfile(self, instance_id: str, file_url: QUrl, file_type: str) -> None:
  878. if not file_url.isValid():
  879. return
  880. path = file_url.toLocalFile()
  881. if not path:
  882. return
  883. self._container_registry.exportProfile(instance_id, path, file_type)