ContainerManager.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  1. # Copyright (c) 2016 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. import os.path
  4. import urllib
  5. from PyQt5.QtCore import QObject, pyqtSlot, pyqtProperty, pyqtSignal, QUrl
  6. from PyQt5.QtWidgets import QMessageBox
  7. import UM.PluginRegistry
  8. import UM.Settings
  9. import UM.SaveFile
  10. import UM.Platform
  11. import UM.MimeTypeDatabase
  12. import UM.Logger
  13. import cura.Settings
  14. from cura.QualityManager import QualityManager
  15. from UM.MimeTypeDatabase import MimeTypeNotFoundError
  16. from UM.i18n import i18nCatalog
  17. catalog = i18nCatalog("cura")
  18. ## Manager class that contains common actions to deal with containers in Cura.
  19. #
  20. # This is primarily intended as a class to be able to perform certain actions
  21. # from within QML. We want to be able to trigger things like removing a container
  22. # when a certain action happens. This can be done through this class.
  23. class ContainerManager(QObject):
  24. def __init__(self, parent = None):
  25. super().__init__(parent)
  26. self._container_registry = UM.Settings.ContainerRegistry.getInstance()
  27. self._machine_manager = UM.Application.getInstance().getMachineManager()
  28. self._container_name_filters = {}
  29. ## Create a duplicate of the specified container
  30. #
  31. # This will create and add a duplicate of the container corresponding
  32. # to the container ID.
  33. #
  34. # \param container_id \type{str} The ID of the container to duplicate.
  35. #
  36. # \return The ID of the new container, or an empty string if duplication failed.
  37. @pyqtSlot(str, result = str)
  38. def duplicateContainer(self, container_id):
  39. containers = self._container_registry.findContainers(None, id = container_id)
  40. if not containers:
  41. UM.Logger.log("w", "Could duplicate container %s because it was not found.", container_id)
  42. return ""
  43. container = containers[0]
  44. new_container = None
  45. new_name = self._container_registry.uniqueName(container.getName())
  46. # Only InstanceContainer has a duplicate method at the moment.
  47. # So fall back to serialize/deserialize when no duplicate method exists.
  48. if hasattr(container, "duplicate"):
  49. new_container = container.duplicate(new_name)
  50. else:
  51. new_container = container.__class__(new_name)
  52. new_container.deserialize(container.serialize())
  53. new_container.setName(new_name)
  54. if new_container:
  55. self._container_registry.addContainer(new_container)
  56. return new_container.getId()
  57. ## Change the name of a specified container to a new name.
  58. #
  59. # \param container_id \type{str} The ID of the container to change the name of.
  60. # \param new_id \type{str} The new ID of the container.
  61. # \param new_name \type{str} The new name of the specified container.
  62. #
  63. # \return True if successful, False if not.
  64. @pyqtSlot(str, str, str, result = bool)
  65. def renameContainer(self, container_id, new_id, new_name):
  66. containers = self._container_registry.findContainers(None, id = container_id)
  67. if not containers:
  68. UM.Logger.log("w", "Could rename container %s because it was not found.", container_id)
  69. return False
  70. container = containers[0]
  71. # First, remove the container from the registry. This will clean up any files related to the container.
  72. self._container_registry.removeContainer(container)
  73. # Ensure we have a unique name for the container
  74. new_name = self._container_registry.uniqueName(new_name)
  75. # Then, update the name and ID of the container
  76. container.setName(new_name)
  77. container._id = new_id # TODO: Find a nicer way to set a new, unique ID
  78. # Finally, re-add the container so it will be properly serialized again.
  79. self._container_registry.addContainer(container)
  80. return True
  81. ## Remove the specified container.
  82. #
  83. # \param container_id \type{str} The ID of the container to remove.
  84. #
  85. # \return True if the container was successfully removed, False if not.
  86. @pyqtSlot(str, result = bool)
  87. def removeContainer(self, container_id):
  88. containers = self._container_registry.findContainers(None, id = container_id)
  89. if not containers:
  90. UM.Logger.log("w", "Could remove container %s because it was not found.", container_id)
  91. return False
  92. self._container_registry.removeContainer(containers[0].getId())
  93. return True
  94. ## Merge a container with another.
  95. #
  96. # This will try to merge one container into the other, by going through the container
  97. # and setting the right properties on the other container.
  98. #
  99. # \param merge_into_id \type{str} The ID of the container to merge into.
  100. # \param merge_id \type{str} The ID of the container to merge.
  101. #
  102. # \return True if successfully merged, False if not.
  103. @pyqtSlot(str, result = bool)
  104. def mergeContainers(self, merge_into_id, merge_id):
  105. containers = self._container_registry.findContainers(None, id = merge_into_id)
  106. if not containers:
  107. UM.Logger.log("w", "Could merge into container %s because it was not found.", merge_into_id)
  108. return False
  109. merge_into = containers[0]
  110. containers = self._container_registry.findContainers(None, id = merge_id)
  111. if not containers:
  112. UM.Logger.log("w", "Could not merge container %s because it was not found", merge_id)
  113. return False
  114. merge = containers[0]
  115. if not isinstance(merge, type(merge_into)):
  116. UM.Logger.log("w", "Cannot merge two containers of different types")
  117. return False
  118. self._performMerge(merge_into, merge)
  119. return True
  120. ## Clear the contents of a container.
  121. #
  122. # \param container_id \type{str} The ID of the container to clear.
  123. #
  124. # \return True if successful, False if not.
  125. @pyqtSlot(str, result = bool)
  126. def clearContainer(self, container_id):
  127. containers = self._container_registry.findContainers(None, id = container_id)
  128. if not containers:
  129. UM.Logger.log("w", "Could clear container %s because it was not found.", container_id)
  130. return False
  131. if containers[0].isReadOnly():
  132. UM.Logger.log("w", "Cannot clear read-only container %s", container_id)
  133. return False
  134. containers[0].clear()
  135. return True
  136. @pyqtSlot(str, str, result=str)
  137. def getContainerMetaDataEntry(self, container_id, entry_name):
  138. containers = self._container_registry.findContainers(None, id=container_id)
  139. if not containers:
  140. UM.Logger.log("w", "Could not get metadata of container %s because it was not found.", container_id)
  141. return ""
  142. result = containers[0].getMetaDataEntry(entry_name)
  143. if result is not None:
  144. return str(result)
  145. else:
  146. return ""
  147. ## Set a metadata entry of the specified container.
  148. #
  149. # This will set the specified entry of the container's metadata to the specified
  150. # value. Note that entries containing dictionaries can have their entries changed
  151. # by using "/" as a separator. For example, to change an entry "foo" in a
  152. # dictionary entry "bar", you can specify "bar/foo" as entry name.
  153. #
  154. # \param container_id \type{str} The ID of the container to change.
  155. # \param entry_name \type{str} The name of the metadata entry to change.
  156. # \param entry_value The new value of the entry.
  157. #
  158. # \return True if successful, False if not.
  159. @pyqtSlot(str, str, str, result = bool)
  160. def setContainerMetaDataEntry(self, container_id, entry_name, entry_value):
  161. containers = self._container_registry.findContainers(None, id = container_id)
  162. if not containers:
  163. UM.Logger.log("w", "Could not set metadata of container %s because it was not found.", container_id)
  164. return False
  165. container = containers[0]
  166. if container.isReadOnly():
  167. UM.Logger.log("w", "Cannot set metadata of read-only container %s.", container_id)
  168. return False
  169. entries = entry_name.split("/")
  170. entry_name = entries.pop()
  171. if entries:
  172. root_name = entries.pop(0)
  173. root = container.getMetaDataEntry(root_name)
  174. item = root
  175. for entry in entries:
  176. item = item.get(entries.pop(0), { })
  177. item[entry_name] = entry_value
  178. entry_name = root_name
  179. entry_value = root
  180. container.setMetaDataEntry(entry_name, entry_value)
  181. return True
  182. ## Set the name of the specified container.
  183. @pyqtSlot(str, str, result = bool)
  184. def setContainerName(self, container_id, new_name):
  185. containers = self._container_registry.findContainers(None, id = container_id)
  186. if not containers:
  187. UM.Logger.log("w", "Could not set name of container %s because it was not found.", container_id)
  188. return False
  189. container = containers[0]
  190. if container.isReadOnly():
  191. UM.Logger.log("w", "Cannot set name of read-only container %s.", container_id)
  192. return False
  193. container.setName(new_name)
  194. return True
  195. ## Find instance containers matching certain criteria.
  196. #
  197. # This effectively forwards to ContainerRegistry::findInstanceContainers.
  198. #
  199. # \param criteria A dict of key - value pairs to search for.
  200. #
  201. # \return A list of container IDs that match the given criteria.
  202. @pyqtSlot("QVariantMap", result = "QVariantList")
  203. def findInstanceContainers(self, criteria):
  204. result = []
  205. for entry in self._container_registry.findInstanceContainers(**criteria):
  206. result.append(entry.getId())
  207. return result
  208. @pyqtSlot(str, result = bool)
  209. def isContainerUsed(self, container_id):
  210. UM.Logger.log("d", "Checking if container %s is currently used in the active stacks", container_id)
  211. for stack in cura.Settings.ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks():
  212. if container_id in [child.getId() for child in stack.getContainers()]:
  213. UM.Logger.log("d", "The container is in use by %s", stack.getId())
  214. return True
  215. return False
  216. @pyqtSlot(str, result = str)
  217. def makeUniqueName(self, original_name):
  218. return self._container_registry.uniqueName(original_name)
  219. ## Get a list of string that can be used as name filters for a Qt File Dialog
  220. #
  221. # This will go through the list of available container types and generate a list of strings
  222. # out of that. The strings are formatted as "description (*.extension)" and can be directly
  223. # passed to a nameFilters property of a Qt File Dialog.
  224. #
  225. # \param type_name Which types of containers to list. These types correspond to the "type"
  226. # key of the plugin metadata.
  227. #
  228. # \return A string list with name filters.
  229. @pyqtSlot(str, result = "QStringList")
  230. def getContainerNameFilters(self, type_name):
  231. if not self._container_name_filters:
  232. self._updateContainerNameFilters()
  233. filters = []
  234. for filter_string, entry in self._container_name_filters.items():
  235. if not type_name or entry["type"] == type_name:
  236. filters.append(filter_string)
  237. filters.append("All Files (*)")
  238. return filters
  239. ## Export a container to a file
  240. #
  241. # \param container_id The ID of the container to export
  242. # \param file_type The type of file to save as. Should be in the form of "description (*.extension, *.ext)"
  243. # \param file_url The URL where to save the file.
  244. #
  245. # \return A dictionary containing a key "status" with a status code and a key "message" with a message
  246. # explaining the status.
  247. # The status code can be one of "error", "cancelled", "success"
  248. @pyqtSlot(str, str, QUrl, result = "QVariantMap")
  249. def exportContainer(self, container_id, file_type, file_url):
  250. if not container_id or not file_type or not file_url:
  251. return { "status": "error", "message": "Invalid arguments"}
  252. if isinstance(file_url, QUrl):
  253. file_url = file_url.toLocalFile()
  254. if not file_url:
  255. return { "status": "error", "message": "Invalid path"}
  256. mime_type = None
  257. if not file_type in self._container_name_filters:
  258. try:
  259. mime_type = UM.MimeTypeDatabase.getMimeTypeForFile(file_url)
  260. except MimeTypeNotFoundError:
  261. return { "status": "error", "message": "Unknown File Type" }
  262. else:
  263. mime_type = self._container_name_filters[file_type]["mime"]
  264. containers = self._container_registry.findContainers(None, id = container_id)
  265. if not containers:
  266. return { "status": "error", "message": "Container not found"}
  267. container = containers[0]
  268. if UM.Platform.isOSX() and "." in file_url:
  269. file_url = file_url[:file_url.rfind(".")]
  270. for suffix in mime_type.suffixes:
  271. if file_url.endswith(suffix):
  272. break
  273. else:
  274. file_url += "." + mime_type.preferredSuffix
  275. if not UM.Platform.isWindows():
  276. if os.path.exists(file_url):
  277. result = QMessageBox.question(None, catalog.i18nc("@title:window", "File Already Exists"),
  278. catalog.i18nc("@label", "The file <filename>{0}</filename> already exists. Are you sure you want to overwrite it?").format(file_url))
  279. if result == QMessageBox.No:
  280. return { "status": "cancelled", "message": "User cancelled"}
  281. try:
  282. contents = container.serialize()
  283. except NotImplementedError:
  284. return { "status": "error", "message": "Unable to serialize container"}
  285. if contents is None:
  286. return {"status": "error", "message": "Serialization returned None. Unable to write to file"}
  287. with UM.SaveFile(file_url, "w") as f:
  288. f.write(contents)
  289. return { "status": "success", "message": "Succesfully exported container", "path": file_url}
  290. ## Imports a profile from a file
  291. #
  292. # \param file_url A URL that points to the file to import.
  293. #
  294. # \return \type{Dict} dict with a 'status' key containing the string 'success' or 'error', and a 'message' key
  295. # containing a message for the user
  296. @pyqtSlot(QUrl, result = "QVariantMap")
  297. def importContainer(self, file_url):
  298. if not file_url:
  299. return { "status": "error", "message": "Invalid path"}
  300. if isinstance(file_url, QUrl):
  301. file_url = file_url.toLocalFile()
  302. if not file_url or not os.path.exists(file_url):
  303. return { "status": "error", "message": "Invalid path" }
  304. try:
  305. mime_type = UM.MimeTypeDatabase.getMimeTypeForFile(file_url)
  306. except MimeTypeNotFoundError:
  307. return { "status": "error", "message": "Could not determine mime type of file" }
  308. container_type = UM.Settings.ContainerRegistry.getContainerForMimeType(mime_type)
  309. if not container_type:
  310. return { "status": "error", "message": "Could not find a container to handle the specified file."}
  311. container_id = urllib.parse.unquote_plus(mime_type.stripExtension(os.path.basename(file_url)))
  312. container_id = self._container_registry.uniqueName(container_id)
  313. container = container_type(container_id)
  314. try:
  315. with open(file_url, "rt") as f:
  316. container.deserialize(f.read())
  317. except PermissionError:
  318. return { "status": "error", "message": "Permission denied when trying to read the file"}
  319. container.setName(container_id)
  320. self._container_registry.addContainer(container)
  321. return { "status": "success", "message": "Successfully imported container {0}".format(container.getName()) }
  322. ## Update the current active quality changes container with the settings from the user container.
  323. #
  324. # This will go through the active global stack and all active extruder stacks and merge the changes from the user
  325. # container into the quality_changes container. After that, the user container is cleared.
  326. #
  327. # \return \type{bool} True if successful, False if not.
  328. @pyqtSlot(result = bool)
  329. def updateQualityChanges(self):
  330. global_stack = UM.Application.getInstance().getGlobalContainerStack()
  331. if not global_stack:
  332. return False
  333. self._machine_manager.blurSettings.emit()
  334. for stack in cura.Settings.ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks():
  335. # Find the quality_changes container for this stack and merge the contents of the top container into it.
  336. quality_changes = stack.findContainer(type = "quality_changes")
  337. if not quality_changes or quality_changes.isReadOnly():
  338. UM.Logger.log("e", "Could not update quality of a nonexistant or read only quality profile in stack %s", stack.getId())
  339. continue
  340. self._performMerge(quality_changes, stack.getTop())
  341. self._machine_manager.activeQualityChanged.emit()
  342. return True
  343. ## Clear the top-most (user) containers of the active stacks.
  344. @pyqtSlot()
  345. def clearUserContainers(self):
  346. self._machine_manager.blurSettings.emit()
  347. send_emits_containers = []
  348. # Go through global and extruder stacks and clear their topmost container (the user settings).
  349. for stack in cura.Settings.ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks():
  350. container = stack.getTop()
  351. container.clear()
  352. send_emits_containers.append(container)
  353. for container in send_emits_containers:
  354. container.sendPostponedEmits()
  355. ## Create quality changes containers from the user containers in the active stacks.
  356. #
  357. # This will go through the global and extruder stacks and create quality_changes containers from
  358. # the user containers in each stack. These then replace the quality_changes containers in the
  359. # stack and clear the user settings.
  360. #
  361. # \return \type{bool} True if the operation was successfully, False if not.
  362. @pyqtSlot(str, result = bool)
  363. def createQualityChanges(self, base_name):
  364. global_stack = UM.Application.getInstance().getGlobalContainerStack()
  365. if not global_stack:
  366. return False
  367. active_quality_name = self._machine_manager.activeQualityName
  368. if active_quality_name == "":
  369. UM.Logger.log("w", "No quality container found in stack %s, cannot create profile", global_stack.getId())
  370. return False
  371. self._machine_manager.blurSettings.emit()
  372. if base_name is None or base_name == "":
  373. base_name = active_quality_name
  374. unique_name = self._container_registry.uniqueName(base_name)
  375. global_changes = None
  376. # Go through the active stacks and create quality_changes containers from the user containers.
  377. for stack in cura.Settings.ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks():
  378. user_container = stack.getTop()
  379. quality_container = stack.findContainer(type = "quality")
  380. quality_changes_container = stack.findContainer(type = "quality_changes")
  381. if not quality_container or not quality_changes_container:
  382. UM.Logger.log("w", "No quality or quality changes container found in stack %s, ignoring it", stack.getId())
  383. continue
  384. extruder_id = None if stack is global_stack else QualityManager.getInstance().getParentMachineDefinition(stack.getBottom()).getId()
  385. new_changes = self._createQualityChanges(quality_container, unique_name,
  386. UM.Application.getInstance().getGlobalContainerStack().getBottom(),
  387. extruder_id)
  388. self._performMerge(new_changes, user_container)
  389. if stack is global_stack:
  390. global_changes = new_changes
  391. else:
  392. new_changes.setMetaDataEntry("global_profile", global_changes.getId())
  393. self._container_registry.addContainer(new_changes)
  394. stack.replaceContainer(stack.getContainerIndex(quality_changes_container), new_changes)
  395. self._machine_manager.activeQualityChanged.emit()
  396. return True
  397. ## Remove all quality changes containers matching a specified name.
  398. #
  399. # This will search for quality_changes containers matching the supplied name and remove them.
  400. # Note that if the machine specifies that qualities should be filtered by machine and/or material
  401. # only the containers related to the active machine/material are removed.
  402. #
  403. # \param quality_name The name of the quality changes to remove.
  404. #
  405. # \return \type{bool} True if successful, False if not.
  406. @pyqtSlot(str, result = bool)
  407. def removeQualityChanges(self, quality_name):
  408. UM.Logger.log("d", "Attempting to remove the quality change containers with name %s", quality_name)
  409. containers_found = False
  410. if not quality_name:
  411. return containers_found # Without a name we will never find a container to remove.
  412. # If the container that is being removed is the currently active quality, set another quality as the active quality
  413. activate_quality = quality_name == self._machine_manager.activeQualityName
  414. activate_quality_type = None
  415. global_stack = UM.Application.getInstance().getGlobalContainerStack()
  416. if not global_stack or not quality_name:
  417. return ""
  418. machine_definition = global_stack.getBottom()
  419. for container in QualityManager.getInstance().findQualityChangesByName(quality_name, machine_definition):
  420. containers_found = True
  421. if activate_quality and not activate_quality_type:
  422. activate_quality_type = container.getMetaDataEntry("quality")
  423. self._container_registry.removeContainer(container.getId())
  424. if not containers_found:
  425. UM.Logger.log("d", "Unable to remove quality containers, as we did not find any by the name of %s", quality_name)
  426. elif activate_quality:
  427. definition_id = "fdmprinter" if not self._machine_manager.filterQualityByMachine else self._machine_manager.activeDefinitionId
  428. containers = self._container_registry.findInstanceContainers(type = "quality", definition = definition_id, quality_type = activate_quality_type)
  429. if containers:
  430. self._machine_manager.setActiveQuality(containers[0].getId())
  431. self._machine_manager.activeQualityChanged.emit()
  432. return containers_found
  433. ## Rename a set of quality changes containers.
  434. #
  435. # This will search for quality_changes containers matching the supplied name and rename them.
  436. # Note that if the machine specifies that qualities should be filtered by machine and/or material
  437. # only the containers related to the active machine/material are renamed.
  438. #
  439. # \param quality_name The name of the quality changes containers to rename.
  440. # \param new_name The new name of the quality changes.
  441. #
  442. # \return True if successful, False if not.
  443. @pyqtSlot(str, str, result = bool)
  444. def renameQualityChanges(self, quality_name, new_name):
  445. UM.Logger.log("d", "User requested QualityChanges container rename of %s to %s", quality_name, new_name)
  446. if not quality_name or not new_name:
  447. return False
  448. if quality_name == new_name:
  449. UM.Logger.log("w", "Unable to rename %s to %s, because they are the same.", quality_name, new_name)
  450. return True
  451. global_stack = UM.Application.getInstance().getGlobalContainerStack()
  452. if not global_stack:
  453. return False
  454. self._machine_manager.blurSettings.emit()
  455. new_name = self._container_registry.uniqueName(new_name)
  456. container_registry = self._container_registry
  457. containers_to_rename = self._container_registry.findInstanceContainers(type = "quality_changes", name = quality_name)
  458. containers_to_rename.extend(self._container_registry.findInstanceContainers(type = "quality_changes", global_profile = quality_name))
  459. global_changes_id = ""
  460. for container in containers_to_rename:
  461. stack_id = container.getMetaDataEntry("extruder", global_stack.getId())
  462. container_registry.renameContainer(container.getId(), new_name, self._createUniqueId(stack_id, new_name))
  463. if "global_profile" not in container.getMetaData():
  464. global_changes_id = container.getId()
  465. else:
  466. container.setMetaDataEntry("global_profile", global_changes_id)
  467. if not containers_to_rename:
  468. UM.Logger.log("e", "Unable to rename %s, because we could not find the profile", quality_name)
  469. self._machine_manager.activeQualityChanged.emit()
  470. return True
  471. ## Duplicate a specified set of quality or quality_changes containers.
  472. #
  473. # This will search for containers matching the specified name. If the container is a "quality" type container, a new
  474. # quality_changes container will be created with the specified quality as base. If the container is a "quality_changes"
  475. # container, it is simply duplicated and renamed.
  476. #
  477. # \param quality_name The name of the quality to duplicate.
  478. #
  479. # \return A string containing the name of the duplicated containers, or an empty string if it failed.
  480. @pyqtSlot(str, str, result = str)
  481. def duplicateQualityOrQualityChanges(self, quality_name, base_name):
  482. global_stack = UM.Application.getInstance().getGlobalContainerStack()
  483. if not global_stack or not quality_name:
  484. return ""
  485. machine_definition = global_stack.getBottom()
  486. active_stacks = cura.Settings.ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks()
  487. material_containers = [stack.findContainer(type="material") for stack in active_stacks]
  488. result = self._duplicateQualityOrQualityChangesForMachineType(quality_name, base_name,
  489. QualityManager.getInstance().getParentMachineDefinition(machine_definition),
  490. material_containers)
  491. return result[0].getName() if result else ""
  492. ## Duplicate a quality or quality changes profile specific to a machine type
  493. #
  494. # \param quality_name \type{str} the name of the quality or quality changes container to duplicate.
  495. # \param base_name \type{str} the desired name for the new container.
  496. # \param machine_definition \type{DefinitionContainer}
  497. # \param material_instances \type{List[InstanceContainer]}
  498. # \return \type{str} the name of the newly created container.
  499. def _duplicateQualityOrQualityChangesForMachineType(self, quality_name, base_name, machine_definition, material_instances):
  500. UM.Logger.log("d", "Attempting to duplicate the quality %s", quality_name)
  501. if base_name is None:
  502. base_name = quality_name
  503. # Try to find a Quality with the name.
  504. containers = QualityManager.getInstance().findQualityByName(quality_name, machine_definition, material_instances)
  505. if containers:
  506. container = containers[0]
  507. return self._duplicateQualityForMachineType(container, base_name, machine_definition)
  508. # Assume it is a quality changes.
  509. return self._duplicateQualityChangesForMachineType(quality_name, base_name, machine_definition)
  510. # Duplicate a quality profile
  511. def _duplicateQualityForMachineType(self, quality_container, base_name, machine_definition):
  512. if base_name is None:
  513. base_name = quality_container.getName()
  514. new_name = self._container_registry.uniqueName(base_name)
  515. new_change_instances = []
  516. # Handle the global stack first.
  517. global_changes = self._createQualityChanges(quality_container, new_name, machine_definition, None)
  518. new_changes.addMetaDataEntry("global_profile", global_changes.getId())
  519. new_change_instances.append(global_changes)
  520. self._container_registry.addContainer(new_changes)
  521. # Handle the extruders if present.
  522. extruders = machine_definition.getMetaDataEntry("machine_extruder_trains")
  523. if extruders:
  524. for key in extruders:
  525. value = extruders[key]
  526. new_changes = self._createQualityChanges(quality_container, new_name, machine_definition, value)
  527. new_changes.addMetaDataEntry("global_profile", global_changes.getId())
  528. new_change_instances.append(new_changes)
  529. self._container_registry.addContainer(new_changes)
  530. return new_change_instances
  531. # Duplicate a quality changes container
  532. def _duplicateQualityChangesForMachineType(self, quality_changes_name, base_name, machine_definition):
  533. new_change_instances = []
  534. profile_index = -1
  535. global_changes_id = ""
  536. for container in QualityManager.getInstance().findQualityChangesByName(quality_changes_name,
  537. machine_definition):
  538. new_unique_id = self._createUniqueId(container.getId(), base_name)
  539. new_container = container.duplicate(new_unique_id, base_name)
  540. if profile_index >= 0:
  541. new_changes.setMetaDataEntry("global_profile", global_changes_id)
  542. else:
  543. global_changes_id = new_unique_id
  544. new_change_instances.append(new_container)
  545. self._container_registry.addContainer(new_container)
  546. return new_change_instances
  547. @pyqtSlot(str, result = str)
  548. def duplicateMaterial(self, material_id):
  549. containers = self._container_registry.findInstanceContainers(id=material_id)
  550. if not containers:
  551. UM.Logger.log("d", "Unable to duplicate the material with id %s, because it doesn't exist.", material_id)
  552. return ""
  553. # Ensure all settings are saved.
  554. UM.Application.getInstance().saveSettings()
  555. # Create a new ID & container to hold the data.
  556. new_id = self._container_registry.uniqueName(material_id)
  557. container_type = type(containers[0]) # Could be either a XMLMaterialProfile or a InstanceContainer
  558. duplicated_container = container_type(new_id)
  559. # Instead of duplicating we load the data from the basefile again.
  560. # This ensures that the inheritance goes well and all "cut up" subclasses of the xmlMaterial profile
  561. # are also correctly created.
  562. with open(containers[0].getPath(), encoding="utf-8") as f:
  563. duplicated_container.deserialize(f.read())
  564. duplicated_container.setDirty(True)
  565. self._container_registry.addContainer(duplicated_container)
  566. ## Get the singleton instance for this class.
  567. @classmethod
  568. def getInstance(cls):
  569. # Note: Explicit use of class name to prevent issues with inheritance.
  570. if ContainerManager.__instance is None:
  571. ContainerManager.__instance = cls()
  572. return ContainerManager.__instance
  573. __instance = None
  574. # Factory function, used by QML
  575. @staticmethod
  576. def createContainerManager(engine, js_engine):
  577. return ContainerManager()
  578. def _performMerge(self, merge_into, merge):
  579. assert isinstance(merge, type(merge_into))
  580. if merge == merge_into:
  581. return
  582. for key in merge.getAllKeys():
  583. merge_into.setProperty(key, "value", merge.getProperty(key, "value"))
  584. merge.clear()
  585. def _updateContainerNameFilters(self):
  586. self._container_name_filters = {}
  587. for plugin_id, container_type in UM.Settings.ContainerRegistry.getContainerTypes():
  588. # Ignore default container types since those are not plugins
  589. if container_type in (UM.Settings.InstanceContainer, UM.Settings.ContainerStack, UM.Settings.DefinitionContainer):
  590. continue
  591. serialize_type = ""
  592. try:
  593. plugin_metadata = UM.PluginRegistry.getInstance().getMetaData(plugin_id)
  594. if plugin_metadata:
  595. serialize_type = plugin_metadata["settings_container"]["type"]
  596. else:
  597. continue
  598. except KeyError as e:
  599. continue
  600. mime_type = UM.Settings.ContainerRegistry.getMimeTypeForContainer(container_type)
  601. entry = {
  602. "type": serialize_type,
  603. "mime": mime_type,
  604. "container": container_type
  605. }
  606. suffix = mime_type.preferredSuffix
  607. if UM.Platform.isOSX() and "." in suffix:
  608. # OSX's File dialog is stupid and does not allow selecting files with a . in its name
  609. suffix = suffix[suffix.index(".") + 1:]
  610. suffix_list = "*." + suffix
  611. for suffix in mime_type.suffixes:
  612. if suffix == mime_type.preferredSuffix:
  613. continue
  614. if UM.Platform.isOSX() and "." in suffix:
  615. # OSX's File dialog is stupid and does not allow selecting files with a . in its name
  616. suffix = suffix[suffix.index("."):]
  617. suffix_list += ", *." + suffix
  618. name_filter = "{0} ({1})".format(mime_type.comment, suffix_list)
  619. self._container_name_filters[name_filter] = entry
  620. ## Get containers filtered by machine type and material if required.
  621. #
  622. # \param kwargs Initial search criteria that the containers need to match.
  623. #
  624. # \return A list of containers matching the search criteria.
  625. def _getFilteredContainers(self, **kwargs):
  626. return QualityManager.getInstance()._getFilteredContainers(**kwargs)
  627. ## Creates a unique ID for a container by prefixing the name with the stack ID.
  628. #
  629. # This method creates a unique ID for a container by prefixing it with a specified stack ID.
  630. # This is done to ensure we have an easily identified ID for quality changes, which have the
  631. # same name across several stacks.
  632. #
  633. # \param stack_id The ID of the stack to prepend.
  634. # \param container_name The name of the container that we are creating a unique ID for.
  635. #
  636. # \return Container name prefixed with stack ID, in lower case with spaces replaced by underscores.
  637. def _createUniqueId(self, stack_id, container_name):
  638. result = stack_id + "_" + container_name
  639. result = result.lower()
  640. result.replace(" ", "_")
  641. return result
  642. ## Create a quality changes container for a specified quality container.
  643. #
  644. # \param quality_container The quality container to create a changes container for.
  645. # \param new_name The name of the new quality_changes container.
  646. # \param machine_definition The machine definition this quality changes container is specific to.
  647. # \param extruder_id
  648. #
  649. # \return A new quality_changes container with the specified container as base.
  650. def _createQualityChanges(self, quality_container, new_name, machine_definition, extruder_id):
  651. base_id = machine_definition.getId() if extruder_id is None else extruder_id
  652. # Create a new quality_changes container for the quality.
  653. quality_changes = UM.Settings.InstanceContainer(self._createUniqueId(base_id, new_name))
  654. quality_changes.setName(new_name)
  655. quality_changes.addMetaDataEntry("type", "quality_changes")
  656. quality_changes.addMetaDataEntry("quality_type", quality_container.getMetaDataEntry("quality_type"))
  657. # If we are creating a container for an extruder, ensure we add that to the container
  658. if extruder_id is not None:
  659. quality_changes.addMetaDataEntry("extruder", extruder_id)
  660. # If the machine specifies qualities should be filtered, ensure we match the current criteria.
  661. if not machine_definition.getMetaDataEntry("has_machine_quality"):
  662. quality_changes.setDefinition(self._container_registry.findContainers(id = "fdmprinter")[0])
  663. else:
  664. quality_changes.setDefinition(QualityManager.getInstance().getParentMachineDefinition(machine_definition))
  665. return quality_changes