ContainerManager.py 30 KB

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