ContainerManager.py 51 KB

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