ContainerManager.py 51 KB

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