ContainerManager.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  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. if entries:
  180. root_name = entries.pop(0)
  181. root = container.getMetaDataEntry(root_name)
  182. item = root
  183. for entry in entries:
  184. item = item.get(entries.pop(0), { })
  185. item[entry_name] = entry_value
  186. entry_name = root_name
  187. entry_value = root
  188. container.setMetaDataEntry(entry_name, entry_value)
  189. return True
  190. ## Set the name of the specified container.
  191. @pyqtSlot(str, str, result = bool)
  192. def setContainerName(self, container_id, new_name):
  193. containers = self._container_registry.findContainers(None, id = container_id)
  194. if not containers:
  195. Logger.log("w", "Could not set name of container %s because it was not found.", container_id)
  196. return False
  197. container = containers[0]
  198. if container.isReadOnly():
  199. Logger.log("w", "Cannot set name of read-only container %s.", container_id)
  200. return False
  201. container.setName(new_name)
  202. return True
  203. ## Find instance containers matching certain criteria.
  204. #
  205. # This effectively forwards to ContainerRegistry::findInstanceContainers.
  206. #
  207. # \param criteria A dict of key - value pairs to search for.
  208. #
  209. # \return A list of container IDs that match the given criteria.
  210. @pyqtSlot("QVariantMap", result = "QVariantList")
  211. def findInstanceContainers(self, criteria):
  212. result = []
  213. for entry in self._container_registry.findInstanceContainers(**criteria):
  214. result.append(entry.getId())
  215. return result
  216. @pyqtSlot(str, result = bool)
  217. def isContainerUsed(self, container_id):
  218. Logger.log("d", "Checking if container %s is currently used", container_id)
  219. containers = self._container_registry.findContainerStacks()
  220. for stack in containers:
  221. if container_id in [child.getId() for child in stack.getContainers()]:
  222. Logger.log("d", "The container is in use by %s", stack.getId())
  223. return True
  224. return False
  225. @pyqtSlot(str, result = str)
  226. def makeUniqueName(self, original_name):
  227. return self._container_registry.uniqueName(original_name)
  228. ## Get a list of string that can be used as name filters for a Qt File Dialog
  229. #
  230. # This will go through the list of available container types and generate a list of strings
  231. # out of that. The strings are formatted as "description (*.extension)" and can be directly
  232. # passed to a nameFilters property of a Qt File Dialog.
  233. #
  234. # \param type_name Which types of containers to list. These types correspond to the "type"
  235. # key of the plugin metadata.
  236. #
  237. # \return A string list with name filters.
  238. @pyqtSlot(str, result = "QStringList")
  239. def getContainerNameFilters(self, type_name):
  240. if not self._container_name_filters:
  241. self._updateContainerNameFilters()
  242. filters = []
  243. for filter_string, entry in self._container_name_filters.items():
  244. if not type_name or entry["type"] == type_name:
  245. filters.append(filter_string)
  246. filters.append("All Files (*)")
  247. return filters
  248. ## Export a container to a file
  249. #
  250. # \param container_id The ID of the container to export
  251. # \param file_type The type of file to save as. Should be in the form of "description (*.extension, *.ext)"
  252. # \param file_url_or_string The URL where to save the file.
  253. #
  254. # \return A dictionary containing a key "status" with a status code and a key "message" with a message
  255. # explaining the status.
  256. # The status code can be one of "error", "cancelled", "success"
  257. @pyqtSlot(str, str, QUrl, result = "QVariantMap")
  258. def exportContainer(self, container_id: str, file_type: str, file_url_or_string: Union[QUrl, str]) -> Dict[str, str]:
  259. if not container_id or not file_type or not file_url_or_string:
  260. return { "status": "error", "message": "Invalid arguments"}
  261. if isinstance(file_url_or_string, QUrl):
  262. file_url = file_url_or_string.toLocalFile()
  263. else:
  264. file_url = file_url_or_string
  265. if not file_url:
  266. return { "status": "error", "message": "Invalid path"}
  267. mime_type = None
  268. if not file_type in self._container_name_filters:
  269. try:
  270. mime_type = MimeTypeDatabase.getMimeTypeForFile(file_url)
  271. except MimeTypeNotFoundError:
  272. return { "status": "error", "message": "Unknown File Type" }
  273. else:
  274. mime_type = self._container_name_filters[file_type]["mime"]
  275. containers = self._container_registry.findContainers(None, id = container_id)
  276. if not containers:
  277. return { "status": "error", "message": "Container not found"}
  278. container = containers[0]
  279. if Platform.isOSX() and "." in file_url:
  280. file_url = file_url[:file_url.rfind(".")]
  281. for suffix in mime_type.suffixes:
  282. if file_url.endswith(suffix):
  283. break
  284. else:
  285. file_url += "." + mime_type.preferredSuffix
  286. if not Platform.isWindows():
  287. if os.path.exists(file_url):
  288. result = QMessageBox.question(None, catalog.i18nc("@title:window", "File Already Exists"),
  289. catalog.i18nc("@label", "The file <filename>{0}</filename> already exists. Are you sure you want to overwrite it?").format(file_url))
  290. if result == QMessageBox.No:
  291. return { "status": "cancelled", "message": "User cancelled"}
  292. try:
  293. contents = container.serialize()
  294. except NotImplementedError:
  295. return { "status": "error", "message": "Unable to serialize container"}
  296. if contents is None:
  297. return {"status": "error", "message": "Serialization returned None. Unable to write to file"}
  298. with SaveFile(file_url, "w") as f:
  299. f.write(contents)
  300. return { "status": "success", "message": "Succesfully exported container", "path": file_url}
  301. ## Imports a profile from a file
  302. #
  303. # \param file_url A URL that points to the file to import.
  304. #
  305. # \return \type{Dict} dict with a 'status' key containing the string 'success' or 'error', and a 'message' key
  306. # containing a message for the user
  307. @pyqtSlot(QUrl, result = "QVariantMap")
  308. def importContainer(self, file_url_or_string: Union[QUrl, str]) -> Dict[str, str]:
  309. if not file_url_or_string:
  310. return { "status": "error", "message": "Invalid path"}
  311. if isinstance(file_url_or_string, QUrl):
  312. file_url = file_url_or_string.toLocalFile()
  313. else:
  314. file_url = file_url_or_string
  315. if not file_url or not os.path.exists(file_url):
  316. return { "status": "error", "message": "Invalid path" }
  317. try:
  318. mime_type = MimeTypeDatabase.getMimeTypeForFile(file_url)
  319. except MimeTypeNotFoundError:
  320. return { "status": "error", "message": "Could not determine mime type of file" }
  321. container_type = self._container_registry.getContainerForMimeType(mime_type)
  322. if not container_type:
  323. return { "status": "error", "message": "Could not find a container to handle the specified file."}
  324. container_id = urllib.parse.unquote_plus(mime_type.stripExtension(os.path.basename(file_url)))
  325. container_id = self._container_registry.uniqueName(container_id)
  326. container = container_type(container_id)
  327. try:
  328. with open(file_url, "rt") as f:
  329. container.deserialize(f.read())
  330. except PermissionError:
  331. return { "status": "error", "message": "Permission denied when trying to read the file"}
  332. container.setName(container_id)
  333. self._container_registry.addContainer(container)
  334. return { "status": "success", "message": "Successfully imported container {0}".format(container.getName()) }
  335. ## Update the current active quality changes container with the settings from the user container.
  336. #
  337. # This will go through the active global stack and all active extruder stacks and merge the changes from the user
  338. # container into the quality_changes container. After that, the user container is cleared.
  339. #
  340. # \return \type{bool} True if successful, False if not.
  341. @pyqtSlot(result = bool)
  342. def updateQualityChanges(self):
  343. global_stack = Application.getInstance().getGlobalContainerStack()
  344. if not global_stack:
  345. return False
  346. self._machine_manager.blurSettings.emit()
  347. for stack in ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks():
  348. # Find the quality_changes container for this stack and merge the contents of the top container into it.
  349. quality_changes = stack.qualityChanges
  350. if not quality_changes or quality_changes.isReadOnly():
  351. Logger.log("e", "Could not update quality of a nonexistant or read only quality profile in stack %s", stack.getId())
  352. continue
  353. self._performMerge(quality_changes, stack.getTop())
  354. self._machine_manager.activeQualityChanged.emit()
  355. return True
  356. ## Clear the top-most (user) containers of the active stacks.
  357. @pyqtSlot()
  358. def clearUserContainers(self) -> None:
  359. self._machine_manager.blurSettings.emit()
  360. send_emits_containers = []
  361. # Go through global and extruder stacks and clear their topmost container (the user settings).
  362. for stack in ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks():
  363. container = stack.getTop()
  364. container.clear()
  365. send_emits_containers.append(container)
  366. for container in send_emits_containers:
  367. container.sendPostponedEmits()
  368. ## Create quality changes containers from the user containers in the active stacks.
  369. #
  370. # This will go through the global and extruder stacks and create quality_changes containers from
  371. # the user containers in each stack. These then replace the quality_changes containers in the
  372. # stack and clear the user settings.
  373. #
  374. # \return \type{bool} True if the operation was successfully, False if not.
  375. @pyqtSlot(str, result = bool)
  376. def createQualityChanges(self, base_name):
  377. global_stack = Application.getInstance().getGlobalContainerStack()
  378. if not global_stack:
  379. return False
  380. active_quality_name = self._machine_manager.activeQualityName
  381. if active_quality_name == "":
  382. Logger.log("w", "No quality container found in stack %s, cannot create profile", global_stack.getId())
  383. return False
  384. self._machine_manager.blurSettings.emit()
  385. if base_name is None or base_name == "":
  386. base_name = active_quality_name
  387. unique_name = self._container_registry.uniqueName(base_name)
  388. # Go through the active stacks and create quality_changes containers from the user containers.
  389. for stack in ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks():
  390. user_container = stack.getTop()
  391. quality_container = stack.quality
  392. quality_changes_container = stack.qualityChanges
  393. if not quality_container or not quality_changes_container:
  394. Logger.log("w", "No quality or quality changes container found in stack %s, ignoring it", stack.getId())
  395. continue
  396. extruder_id = None if stack is global_stack else QualityManager.getInstance().getParentMachineDefinition(stack.getBottom()).getId()
  397. new_changes = self._createQualityChanges(quality_container, unique_name,
  398. Application.getInstance().getGlobalContainerStack().getBottom(),
  399. extruder_id)
  400. self._performMerge(new_changes, quality_changes_container, clear_settings = False)
  401. self._performMerge(new_changes, user_container)
  402. self._container_registry.addContainer(new_changes)
  403. stack.replaceContainer(stack.getContainerIndex(quality_changes_container), new_changes)
  404. self._machine_manager.activeQualityChanged.emit()
  405. return True
  406. ## Remove all quality changes containers matching a specified name.
  407. #
  408. # This will search for quality_changes containers matching the supplied name and remove them.
  409. # Note that if the machine specifies that qualities should be filtered by machine and/or material
  410. # only the containers related to the active machine/material are removed.
  411. #
  412. # \param quality_name The name of the quality changes to remove.
  413. #
  414. # \return \type{bool} True if successful, False if not.
  415. @pyqtSlot(str, result = bool)
  416. def removeQualityChanges(self, quality_name):
  417. Logger.log("d", "Attempting to remove the quality change containers with name %s", quality_name)
  418. containers_found = False
  419. if not quality_name:
  420. return containers_found # Without a name we will never find a container to remove.
  421. # If the container that is being removed is the currently active quality, set another quality as the active quality
  422. activate_quality = quality_name == self._machine_manager.activeQualityName
  423. activate_quality_type = None
  424. global_stack = Application.getInstance().getGlobalContainerStack()
  425. if not global_stack or not quality_name:
  426. return ""
  427. machine_definition = global_stack.getBottom()
  428. for container in QualityManager.getInstance().findQualityChangesByName(quality_name, machine_definition):
  429. containers_found = True
  430. if activate_quality and not activate_quality_type:
  431. activate_quality_type = container.getMetaDataEntry("quality")
  432. self._container_registry.removeContainer(container.getId())
  433. if not containers_found:
  434. Logger.log("d", "Unable to remove quality containers, as we did not find any by the name of %s", quality_name)
  435. elif activate_quality:
  436. definition_id = "fdmprinter" if not self._machine_manager.filterQualityByMachine else self._machine_manager.activeDefinitionId
  437. containers = self._container_registry.findInstanceContainers(type = "quality", definition = definition_id, quality_type = activate_quality_type)
  438. if containers:
  439. self._machine_manager.setActiveQuality(containers[0].getId())
  440. self._machine_manager.activeQualityChanged.emit()
  441. return containers_found
  442. ## Rename a set of quality changes containers.
  443. #
  444. # This will search for quality_changes containers matching the supplied name and rename them.
  445. # Note that if the machine specifies that qualities should be filtered by machine and/or material
  446. # only the containers related to the active machine/material are renamed.
  447. #
  448. # \param quality_name The name of the quality changes containers to rename.
  449. # \param new_name The new name of the quality changes.
  450. #
  451. # \return True if successful, False if not.
  452. @pyqtSlot(str, str, result = bool)
  453. def renameQualityChanges(self, quality_name, new_name):
  454. Logger.log("d", "User requested QualityChanges container rename of %s to %s", quality_name, new_name)
  455. if not quality_name or not new_name:
  456. return False
  457. if quality_name == new_name:
  458. Logger.log("w", "Unable to rename %s to %s, because they are the same.", quality_name, new_name)
  459. return True
  460. global_stack = Application.getInstance().getGlobalContainerStack()
  461. if not global_stack:
  462. return False
  463. self._machine_manager.blurSettings.emit()
  464. new_name = self._container_registry.uniqueName(new_name)
  465. container_registry = self._container_registry
  466. containers_to_rename = self._container_registry.findInstanceContainers(type = "quality_changes", name = quality_name)
  467. for container in containers_to_rename:
  468. stack_id = container.getMetaDataEntry("extruder", global_stack.getId())
  469. container_registry.renameContainer(container.getId(), new_name, self._createUniqueId(stack_id, new_name))
  470. if not containers_to_rename:
  471. Logger.log("e", "Unable to rename %s, because we could not find the profile", quality_name)
  472. self._machine_manager.activeQualityChanged.emit()
  473. return True
  474. ## Duplicate a specified set of quality or quality_changes containers.
  475. #
  476. # This will search for containers matching the specified name. If the container is a "quality" type container, a new
  477. # quality_changes container will be created with the specified quality as base. If the container is a "quality_changes"
  478. # container, it is simply duplicated and renamed.
  479. #
  480. # \param quality_name The name of the quality to duplicate.
  481. #
  482. # \return A string containing the name of the duplicated containers, or an empty string if it failed.
  483. @pyqtSlot(str, str, result = str)
  484. def duplicateQualityOrQualityChanges(self, quality_name, base_name):
  485. global_stack = Application.getInstance().getGlobalContainerStack()
  486. if not global_stack or not quality_name:
  487. return ""
  488. machine_definition = global_stack.getBottom()
  489. active_stacks = ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks()
  490. material_containers = [stack.material for stack in active_stacks]
  491. result = self._duplicateQualityOrQualityChangesForMachineType(quality_name, base_name,
  492. QualityManager.getInstance().getParentMachineDefinition(machine_definition),
  493. material_containers)
  494. return result[0].getName() if result else ""
  495. ## Duplicate a quality or quality changes profile specific to a machine type
  496. #
  497. # \param quality_name \type{str} the name of the quality or quality changes container to duplicate.
  498. # \param base_name \type{str} the desired name for the new container.
  499. # \param machine_definition \type{DefinitionContainer}
  500. # \param material_instances \type{List[InstanceContainer]}
  501. # \return \type{str} the name of the newly created container.
  502. def _duplicateQualityOrQualityChangesForMachineType(self, quality_name, base_name, machine_definition, material_instances):
  503. Logger.log("d", "Attempting to duplicate the quality %s", quality_name)
  504. if base_name is None:
  505. base_name = quality_name
  506. # Try to find a Quality with the name.
  507. container = QualityManager.getInstance().findQualityByName(quality_name, machine_definition, material_instances)
  508. if container:
  509. Logger.log("d", "We found a quality to duplicate.")
  510. return self._duplicateQualityForMachineType(container, base_name, machine_definition)
  511. Logger.log("d", "We found a quality_changes to duplicate.")
  512. # Assume it is a quality changes.
  513. return self._duplicateQualityChangesForMachineType(quality_name, base_name, machine_definition)
  514. # Duplicate a quality profile
  515. def _duplicateQualityForMachineType(self, quality_container, base_name, machine_definition):
  516. if base_name is None:
  517. base_name = quality_container.getName()
  518. new_name = self._container_registry.uniqueName(base_name)
  519. new_change_instances = []
  520. # Handle the global stack first.
  521. global_changes = self._createQualityChanges(quality_container, new_name, machine_definition, None)
  522. new_change_instances.append(global_changes)
  523. self._container_registry.addContainer(global_changes)
  524. # Handle the extruders if present.
  525. extruders = machine_definition.getMetaDataEntry("machine_extruder_trains")
  526. if extruders:
  527. for extruder_id in extruders:
  528. extruder = extruders[extruder_id]
  529. new_changes = self._createQualityChanges(quality_container, new_name, machine_definition, extruder)
  530. new_change_instances.append(new_changes)
  531. self._container_registry.addContainer(new_changes)
  532. return new_change_instances
  533. # Duplicate a quality changes container
  534. def _duplicateQualityChangesForMachineType(self, quality_changes_name, base_name, machine_definition):
  535. new_change_instances = []
  536. for container in QualityManager.getInstance().findQualityChangesByName(quality_changes_name,
  537. machine_definition):
  538. base_id = container.getMetaDataEntry("extruder")
  539. if not base_id:
  540. base_id = container.getDefinition().getId()
  541. new_unique_id = self._createUniqueId(base_id, base_name)
  542. new_container = container.duplicate(new_unique_id, base_name)
  543. new_change_instances.append(new_container)
  544. self._container_registry.addContainer(new_container)
  545. return new_change_instances
  546. ## Create a duplicate of a material, which has the same GUID and base_file metadata
  547. #
  548. # \return \type{str} the id of the newly created container.
  549. @pyqtSlot(str, result = str)
  550. def duplicateMaterial(self, material_id: str) -> str:
  551. containers = self._container_registry.findInstanceContainers(id=material_id)
  552. if not containers:
  553. Logger.log("d", "Unable to duplicate the material with id %s, because it doesn't exist.", material_id)
  554. return ""
  555. # Ensure all settings are saved.
  556. Application.getInstance().saveSettings()
  557. # Create a new ID & container to hold the data.
  558. new_id = self._container_registry.uniqueName(material_id)
  559. container_type = type(containers[0]) # Could be either a XMLMaterialProfile or a InstanceContainer
  560. duplicated_container = container_type(new_id)
  561. # Instead of duplicating we load the data from the basefile again.
  562. # This ensures that the inheritance goes well and all "cut up" subclasses of the xmlMaterial profile
  563. # are also correctly created.
  564. with open(containers[0].getPath(), encoding="utf-8") as f:
  565. duplicated_container.deserialize(f.read())
  566. duplicated_container.setDirty(True)
  567. self._container_registry.addContainer(duplicated_container)
  568. return self._getMaterialContainerIdForActiveMachine(new_id)
  569. ## Create a new material by cloning Generic PLA and setting the GUID to something unqiue
  570. #
  571. # \return \type{str} the id of the newly created container.
  572. @pyqtSlot(result = str)
  573. def createMaterial(self) -> str:
  574. # Ensure all settings are saved.
  575. Application.getInstance().saveSettings()
  576. global_stack = Application.getInstance().getGlobalContainerStack()
  577. if not global_stack:
  578. return ""
  579. containers = self._container_registry.findInstanceContainers(id="generic_pla")
  580. if not containers:
  581. Logger.log("d", "Unable to create a new material by cloning generic_pla, because it doesn't exist.")
  582. return ""
  583. # Create a new ID & container to hold the data.
  584. new_id = self._container_registry.uniqueName("custom_material")
  585. container_type = type(containers[0]) # Could be either a XMLMaterialProfile or a InstanceContainer
  586. duplicated_container = container_type(new_id)
  587. # Instead of duplicating we load the data from the basefile again.
  588. # This ensures that the inheritance goes well and all "cut up" subclasses of the xmlMaterial profile
  589. # are also correctly created.
  590. with open(containers[0].getPath(), encoding="utf-8") as f:
  591. duplicated_container.deserialize(f.read())
  592. duplicated_container.setMetaDataEntry("GUID", str(uuid.uuid4()))
  593. duplicated_container.setMetaDataEntry("brand", catalog.i18nc("@label", "Custom"))
  594. duplicated_container.setMetaDataEntry("material", catalog.i18nc("@label", "Custom"))
  595. duplicated_container.setName(catalog.i18nc("@label", "Custom Material"))
  596. # Set new material diameter to match the current machine, or it will not be listed
  597. material_diameter = global_stack.getProperty("material_diameter", "value")
  598. properties = duplicated_container.getMetaDataEntry("properties", {})
  599. properties["diameter"] = str(material_diameter)
  600. duplicated_container.setMetaDataEntry("properties", properties)
  601. duplicated_container.setMetaDataEntry("approximate_diameter", round(material_diameter))
  602. self._container_registry.addContainer(duplicated_container)
  603. return self._getMaterialContainerIdForActiveMachine(new_id)
  604. ## Find the id of a material container based on the new material
  605. # Utilty function that is shared between duplicateMaterial and createMaterial
  606. #
  607. # \param base_file \type{str} the id of the created container.
  608. def _getMaterialContainerIdForActiveMachine(self, base_file):
  609. global_stack = Application.getInstance().getGlobalContainerStack()
  610. if not global_stack:
  611. return base_file
  612. has_machine_materials = parseBool(global_stack.getMetaDataEntry("has_machine_materials", default = False))
  613. has_variant_materials = parseBool(global_stack.getMetaDataEntry("has_variant_materials", default = False))
  614. has_variants = parseBool(global_stack.getMetaDataEntry("has_variants", default = False))
  615. if has_machine_materials or has_variant_materials:
  616. if has_variants:
  617. materials = self._container_registry.findInstanceContainers(type = "material", base_file = base_file, definition = global_stack.getBottom().getId(), variant = self._machine_manager.activeVariantId)
  618. else:
  619. materials = self._container_registry.findInstanceContainers(type = "material", base_file = base_file, definition = global_stack.getBottom().getId())
  620. if materials:
  621. return materials[0].getId()
  622. Logger.log("w", "Unable to find a suitable container based on %s for the current machine .", base_file)
  623. return "" # do not activate a new material if a container can not be found
  624. return base_file
  625. ## Get a list of materials that have the same GUID as the reference material
  626. #
  627. # \param material_id \type{str} the id of the material for which to get the linked materials.
  628. # \return \type{list} a list of names of materials with the same GUID
  629. @pyqtSlot(str, result = "QStringList")
  630. def getLinkedMaterials(self, material_id: str):
  631. containers = self._container_registry.findInstanceContainers(id=material_id)
  632. if not containers:
  633. Logger.log("d", "Unable to find materials linked to material with id %s, because it doesn't exist.", material_id)
  634. return []
  635. material_container = containers[0]
  636. material_base_file = material_container.getMetaDataEntry("base_file", "")
  637. material_guid = material_container.getMetaDataEntry("GUID", "")
  638. if not material_guid:
  639. Logger.log("d", "Unable to find materials linked to material with id %s, because it doesn't have a GUID.", material_id)
  640. return []
  641. containers = self._container_registry.findInstanceContainers(type = "material", GUID = material_guid)
  642. linked_material_names = []
  643. for container in containers:
  644. if container.getId() in [material_id, material_base_file] or container.getMetaDataEntry("base_file") != container.getId():
  645. continue
  646. linked_material_names.append(container.getName())
  647. return linked_material_names
  648. ## Unlink a material from all other materials by creating a new GUID
  649. # \param material_id \type{str} the id of the material to create a new GUID for.
  650. @pyqtSlot(str)
  651. def unlinkMaterial(self, material_id: str):
  652. containers = self._container_registry.findInstanceContainers(id=material_id)
  653. if not containers:
  654. Logger.log("d", "Unable to make the material with id %s unique, because it doesn't exist.", material_id)
  655. return ""
  656. containers[0].setMetaDataEntry("GUID", str(uuid.uuid4()))
  657. ## Get the singleton instance for this class.
  658. @classmethod
  659. def getInstance(cls) -> "ContainerManager":
  660. # Note: Explicit use of class name to prevent issues with inheritance.
  661. if ContainerManager.__instance is None:
  662. ContainerManager.__instance = cls()
  663. return ContainerManager.__instance
  664. __instance = None # type: "ContainerManager"
  665. # Factory function, used by QML
  666. @staticmethod
  667. def createContainerManager(engine, js_engine):
  668. return ContainerManager.getInstance()
  669. def _performMerge(self, merge_into, merge, clear_settings = True):
  670. assert isinstance(merge, type(merge_into))
  671. if merge == merge_into:
  672. return
  673. for key in merge.getAllKeys():
  674. merge_into.setProperty(key, "value", merge.getProperty(key, "value"))
  675. if clear_settings:
  676. merge.clear()
  677. def _updateContainerNameFilters(self) -> None:
  678. self._container_name_filters = {}
  679. for plugin_id, container_type in self._container_registry.getContainerTypes():
  680. # Ignore default container types since those are not plugins
  681. if container_type in (InstanceContainer, ContainerStack, DefinitionContainer):
  682. continue
  683. serialize_type = ""
  684. try:
  685. plugin_metadata = PluginRegistry.getInstance().getMetaData(plugin_id)
  686. if plugin_metadata:
  687. serialize_type = plugin_metadata["settings_container"]["type"]
  688. else:
  689. continue
  690. except KeyError as e:
  691. continue
  692. mime_type = self._container_registry.getMimeTypeForContainer(container_type)
  693. entry = {
  694. "type": serialize_type,
  695. "mime": mime_type,
  696. "container": container_type
  697. }
  698. suffix = mime_type.preferredSuffix
  699. if Platform.isOSX() and "." in suffix:
  700. # OSX's File dialog is stupid and does not allow selecting files with a . in its name
  701. suffix = suffix[suffix.index(".") + 1:]
  702. suffix_list = "*." + suffix
  703. for suffix in mime_type.suffixes:
  704. if suffix == mime_type.preferredSuffix:
  705. continue
  706. if Platform.isOSX() and "." in suffix:
  707. # OSX's File dialog is stupid and does not allow selecting files with a . in its name
  708. suffix = suffix[suffix.index("."):]
  709. suffix_list += ", *." + suffix
  710. name_filter = "{0} ({1})".format(mime_type.comment, suffix_list)
  711. self._container_name_filters[name_filter] = entry
  712. ## Get containers filtered by machine type and material if required.
  713. #
  714. # \param kwargs Initial search criteria that the containers need to match.
  715. #
  716. # \return A list of containers matching the search criteria.
  717. def _getFilteredContainers(self, **kwargs):
  718. return QualityManager.getInstance()._getFilteredContainers(**kwargs)
  719. ## Creates a unique ID for a container by prefixing the name with the stack ID.
  720. #
  721. # This method creates a unique ID for a container by prefixing it with a specified stack ID.
  722. # This is done to ensure we have an easily identified ID for quality changes, which have the
  723. # same name across several stacks.
  724. #
  725. # \param stack_id The ID of the stack to prepend.
  726. # \param container_name The name of the container that we are creating a unique ID for.
  727. #
  728. # \return Container name prefixed with stack ID, in lower case with spaces replaced by underscores.
  729. def _createUniqueId(self, stack_id, container_name):
  730. result = stack_id + "_" + container_name
  731. result = result.lower()
  732. result.replace(" ", "_")
  733. return result
  734. ## Create a quality changes container for a specified quality container.
  735. #
  736. # \param quality_container The quality container to create a changes container for.
  737. # \param new_name The name of the new quality_changes container.
  738. # \param machine_definition The machine definition this quality changes container is specific to.
  739. # \param extruder_id
  740. #
  741. # \return A new quality_changes container with the specified container as base.
  742. def _createQualityChanges(self, quality_container, new_name, machine_definition, extruder_id):
  743. base_id = machine_definition.getId() if extruder_id is None else extruder_id
  744. # Create a new quality_changes container for the quality.
  745. quality_changes = InstanceContainer(self._createUniqueId(base_id, new_name))
  746. quality_changes.setName(new_name)
  747. quality_changes.addMetaDataEntry("type", "quality_changes")
  748. quality_changes.addMetaDataEntry("quality_type", quality_container.getMetaDataEntry("quality_type"))
  749. # If we are creating a container for an extruder, ensure we add that to the container
  750. if extruder_id is not None:
  751. quality_changes.addMetaDataEntry("extruder", extruder_id)
  752. # If the machine specifies qualities should be filtered, ensure we match the current criteria.
  753. if not machine_definition.getMetaDataEntry("has_machine_quality"):
  754. quality_changes.setDefinition(self._container_registry.findContainers(id = "fdmprinter")[0])
  755. else:
  756. quality_changes.setDefinition(QualityManager.getInstance().getParentMachineDefinition(machine_definition))
  757. from cura.CuraApplication import CuraApplication
  758. quality_changes.addMetaDataEntry("setting_version", CuraApplication.SettingVersion)
  759. return quality_changes
  760. ## Import profiles from a list of file_urls.
  761. # Each QUrl item must end with .curaprofile, or it will not be imported.
  762. #
  763. # \param QVariant<QUrl>, essentially a list with QUrl objects.
  764. # \return Dict with keys status, text
  765. @pyqtSlot("QVariantList", result="QVariantMap")
  766. def importProfiles(self, file_urls):
  767. status = "ok"
  768. results = {"ok": [], "error": []}
  769. for file_url in file_urls:
  770. if not file_url.isValid():
  771. continue
  772. path = file_url.toLocalFile()
  773. if not path:
  774. continue
  775. if not path.endswith(".curaprofile"):
  776. continue
  777. single_result = self._container_registry.importProfile(path)
  778. if single_result["status"] == "error":
  779. status = "error"
  780. results[single_result["status"]].append(single_result["message"])
  781. return {
  782. "status": status,
  783. "message": "\n".join(results["ok"] + results["error"])}
  784. ## Import single profile, file_url does not have to end with curaprofile
  785. @pyqtSlot(QUrl, result="QVariantMap")
  786. def importProfile(self, file_url):
  787. if not file_url.isValid():
  788. return
  789. path = file_url.toLocalFile()
  790. if not path:
  791. return
  792. return self._container_registry.importProfile(path)
  793. @pyqtSlot("QVariantList", QUrl, str)
  794. def exportProfile(self, instance_id: str, file_url: QUrl, file_type: str) -> None:
  795. if not file_url.isValid():
  796. return
  797. path = file_url.toLocalFile()
  798. if not path:
  799. return
  800. self._container_registry.exportProfile(instance_id, path, file_type)