ContainerManager.py 41 KB

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