ContainerManager.py 48 KB

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