ContainerManager.py 48 KB

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