ContainerManager.py 38 KB

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