ContainerManager.py 37 KB

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