ContainerManager.py 42 KB

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