ContainerManager.py 37 KB

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