MaterialManager.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from collections import defaultdict, OrderedDict
  4. import copy
  5. import uuid
  6. from typing import Optional, TYPE_CHECKING
  7. from PyQt5.Qt import QTimer, QObject, pyqtSignal, pyqtSlot
  8. from UM.Application import Application
  9. from UM.ConfigurationErrorMessage import ConfigurationErrorMessage
  10. from UM.Logger import Logger
  11. from UM.Settings.ContainerRegistry import ContainerRegistry
  12. from UM.Settings.SettingFunction import SettingFunction
  13. from UM.Util import parseBool
  14. from .MaterialNode import MaterialNode
  15. from .MaterialGroup import MaterialGroup
  16. if TYPE_CHECKING:
  17. from UM.Settings.DefinitionContainer import DefinitionContainer
  18. from UM.Settings.InstanceContainer import InstanceContainer
  19. from cura.Settings.GlobalStack import GlobalStack
  20. from cura.Settings.ExtruderStack import ExtruderStack
  21. #
  22. # MaterialManager maintains a number of maps and trees for material lookup.
  23. # The models GUI and QML use are now only dependent on the MaterialManager. That means as long as the data in
  24. # MaterialManager gets updated correctly, the GUI models should be updated correctly too, and the same goes for GUI.
  25. #
  26. # For now, updating the lookup maps and trees here is very simple: we discard the old data completely and recreate them
  27. # again. This means the update is exactly the same as initialization. There are performance concerns about this approach
  28. # but so far the creation of the tables and maps is very fast and there is no noticeable slowness, we keep it like this
  29. # because it's simple.
  30. #
  31. class MaterialManager(QObject):
  32. materialsUpdated = pyqtSignal() # Emitted whenever the material lookup tables are updated.
  33. def __init__(self, container_registry, parent = None):
  34. super().__init__(parent)
  35. self._application = Application.getInstance()
  36. self._container_registry = container_registry # type: ContainerRegistry
  37. self._fallback_materials_map = dict() # material_type -> generic material metadata
  38. self._material_group_map = dict() # root_material_id -> MaterialGroup
  39. self._diameter_machine_variant_material_map = dict() # approximate diameter str -> dict(machine_definition_id -> MaterialNode)
  40. # We're using these two maps to convert between the specific diameter material id and the generic material id
  41. # because the generic material ids are used in qualities and definitions, while the specific diameter material is meant
  42. # i.e. generic_pla -> generic_pla_175
  43. self._material_diameter_map = defaultdict(dict) # root_material_id -> approximate diameter str -> root_material_id for that diameter
  44. self._diameter_material_map = dict() # material id including diameter (generic_pla_175) -> material root id (generic_pla)
  45. # This is used in Legacy UM3 send material function and the material management page.
  46. self._guid_material_groups_map = defaultdict(list) # GUID -> a list of material_groups
  47. # The machine definition ID for the non-machine-specific materials.
  48. # This is used as the last fallback option if the given machine-specific material(s) cannot be found.
  49. self._default_machine_definition_id = "fdmprinter"
  50. self._default_approximate_diameter_for_quality_search = "3"
  51. # When a material gets added/imported, there can be more than one InstanceContainers. In those cases, we don't
  52. # want to react on every container/metadata changed signal. The timer here is to buffer it a bit so we don't
  53. # react too many time.
  54. self._update_timer = QTimer(self)
  55. self._update_timer.setInterval(300)
  56. self._update_timer.setSingleShot(True)
  57. self._update_timer.timeout.connect(self._updateMaps)
  58. self._container_registry.containerMetaDataChanged.connect(self._onContainerMetadataChanged)
  59. self._container_registry.containerAdded.connect(self._onContainerMetadataChanged)
  60. self._container_registry.containerRemoved.connect(self._onContainerMetadataChanged)
  61. def initialize(self):
  62. # Find all materials and put them in a matrix for quick search.
  63. material_metadatas = {metadata["id"]: metadata for metadata in
  64. self._container_registry.findContainersMetadata(type = "material") if
  65. metadata.get("GUID")}
  66. self._material_group_map = dict()
  67. # Map #1
  68. # root_material_id -> MaterialGroup
  69. for material_id, material_metadata in material_metadatas.items():
  70. # We don't store empty material in the lookup tables
  71. if material_id == "empty_material":
  72. continue
  73. root_material_id = material_metadata.get("base_file")
  74. if root_material_id not in self._material_group_map:
  75. self._material_group_map[root_material_id] = MaterialGroup(root_material_id, MaterialNode(material_metadatas[root_material_id]))
  76. self._material_group_map[root_material_id].is_read_only = self._container_registry.isReadOnly(root_material_id)
  77. group = self._material_group_map[root_material_id]
  78. # Store this material in the group of the appropriate root material.
  79. if material_id != root_material_id:
  80. new_node = MaterialNode(material_metadata)
  81. group.derived_material_node_list.append(new_node)
  82. # Order this map alphabetically so it's easier to navigate in a debugger
  83. self._material_group_map = OrderedDict(sorted(self._material_group_map.items(), key = lambda x: x[0]))
  84. # Map #1.5
  85. # GUID -> material group list
  86. self._guid_material_groups_map = defaultdict(list)
  87. for root_material_id, material_group in self._material_group_map.items():
  88. guid = material_group.root_material_node.metadata["GUID"]
  89. self._guid_material_groups_map[guid].append(material_group)
  90. # Map #2
  91. # Lookup table for material type -> fallback material metadata, only for read-only materials
  92. grouped_by_type_dict = dict()
  93. material_types_without_fallback = set()
  94. for root_material_id, material_node in self._material_group_map.items():
  95. material_type = material_node.root_material_node.metadata["material"]
  96. if material_type not in grouped_by_type_dict:
  97. grouped_by_type_dict[material_type] = {"generic": None,
  98. "others": []}
  99. material_types_without_fallback.add(material_type)
  100. brand = material_node.root_material_node.metadata["brand"]
  101. if brand.lower() == "generic":
  102. to_add = True
  103. if material_type in grouped_by_type_dict:
  104. diameter = material_node.root_material_node.metadata.get("approximate_diameter")
  105. if diameter != self._default_approximate_diameter_for_quality_search:
  106. to_add = False # don't add if it's not the default diameter
  107. if to_add:
  108. # Checking this first allow us to differentiate between not read only materials:
  109. # - if it's in the list, it means that is a new material without fallback
  110. # - if it is not, then it is a custom material with a fallback material (parent)
  111. if material_type in material_types_without_fallback:
  112. grouped_by_type_dict[material_type] = material_node.root_material_node.metadata
  113. material_types_without_fallback.remove(material_type)
  114. # Remove the materials that have no fallback materials
  115. for material_type in material_types_without_fallback:
  116. del grouped_by_type_dict[material_type]
  117. self._fallback_materials_map = grouped_by_type_dict
  118. # Map #3
  119. # There can be multiple material profiles for the same material with different diameters, such as "generic_pla"
  120. # and "generic_pla_175". This is inconvenient when we do material-specific quality lookup because a quality can
  121. # be for either "generic_pla" or "generic_pla_175", but not both. This map helps to get the correct material ID
  122. # for quality search.
  123. self._material_diameter_map = defaultdict(dict)
  124. self._diameter_material_map = dict()
  125. # Group the material IDs by the same name, material, brand, and color but with different diameters.
  126. material_group_dict = dict()
  127. keys_to_fetch = ("name", "material", "brand", "color")
  128. for root_material_id, machine_node in self._material_group_map.items():
  129. root_material_metadata = machine_node.root_material_node.metadata
  130. key_data = []
  131. for key in keys_to_fetch:
  132. key_data.append(root_material_metadata.get(key))
  133. key_data = tuple(key_data)
  134. # If the key_data doesn't exist, it doesn't matter if the material is read only...
  135. if key_data not in material_group_dict:
  136. material_group_dict[key_data] = dict()
  137. else:
  138. # ...but if key_data exists, we just overwrite it if the material is read only, otherwise we skip it
  139. if not machine_node.is_read_only:
  140. continue
  141. approximate_diameter = root_material_metadata.get("approximate_diameter")
  142. material_group_dict[key_data][approximate_diameter] = root_material_metadata["id"]
  143. # Map [root_material_id][diameter] -> root_material_id for this diameter
  144. for data_dict in material_group_dict.values():
  145. for root_material_id1 in data_dict.values():
  146. if root_material_id1 in self._material_diameter_map:
  147. continue
  148. diameter_map = data_dict
  149. for root_material_id2 in data_dict.values():
  150. self._material_diameter_map[root_material_id2] = diameter_map
  151. default_root_material_id = data_dict.get(self._default_approximate_diameter_for_quality_search)
  152. if default_root_material_id is None:
  153. default_root_material_id = list(data_dict.values())[0] # no default diameter present, just take "the" only one
  154. for root_material_id in data_dict.values():
  155. self._diameter_material_map[root_material_id] = default_root_material_id
  156. # Map #4
  157. # "machine" -> "variant_name" -> "root material ID" -> specific material InstanceContainer
  158. # Construct the "machine" -> "variant" -> "root material ID" -> specific material InstanceContainer
  159. self._diameter_machine_variant_material_map = dict()
  160. for material_metadata in material_metadatas.values():
  161. # We don't store empty material in the lookup tables
  162. if material_metadata["id"] == "empty_material":
  163. continue
  164. root_material_id = material_metadata["base_file"]
  165. definition = material_metadata["definition"]
  166. approximate_diameter = material_metadata["approximate_diameter"]
  167. if approximate_diameter not in self._diameter_machine_variant_material_map:
  168. self._diameter_machine_variant_material_map[approximate_diameter] = {}
  169. machine_variant_material_map = self._diameter_machine_variant_material_map[approximate_diameter]
  170. if definition not in machine_variant_material_map:
  171. machine_variant_material_map[definition] = MaterialNode()
  172. machine_node = machine_variant_material_map[definition]
  173. variant_name = material_metadata.get("variant_name")
  174. if not variant_name:
  175. # if there is no variant, this material is for the machine, so put its metadata in the machine node.
  176. machine_node.material_map[root_material_id] = MaterialNode(material_metadata)
  177. else:
  178. # this material is variant-specific, so we save it in a variant-specific node under the
  179. # machine-specific node
  180. # Check first if the variant exist in the manager
  181. existing_variant = self._application.getVariantManager().getVariantNode(definition, variant_name)
  182. if existing_variant is not None:
  183. if variant_name not in machine_node.children_map:
  184. machine_node.children_map[variant_name] = MaterialNode()
  185. variant_node = machine_node.children_map[variant_name]
  186. if root_material_id in variant_node.material_map: # We shouldn't have duplicated variant-specific materials for the same machine.
  187. ConfigurationErrorMessage.getInstance().addFaultyContainers(root_material_id)
  188. continue
  189. variant_node.material_map[root_material_id] = MaterialNode(material_metadata)
  190. else:
  191. # Add this container id to the wrong containers list in the registry
  192. Logger.log("w", "Not adding {id} to the material manager because the variant does not exist.".format(id = material_metadata["id"]))
  193. self._container_registry.addWrongContainerId(material_metadata["id"])
  194. self.materialsUpdated.emit()
  195. def _updateMaps(self):
  196. Logger.log("i", "Updating material lookup data ...")
  197. self.initialize()
  198. def _onContainerMetadataChanged(self, container):
  199. self._onContainerChanged(container)
  200. def _onContainerChanged(self, container):
  201. container_type = container.getMetaDataEntry("type")
  202. if container_type != "material":
  203. return
  204. # update the maps
  205. self._update_timer.start()
  206. def getMaterialGroup(self, root_material_id: str) -> Optional[MaterialGroup]:
  207. return self._material_group_map.get(root_material_id)
  208. def getRootMaterialIDForDiameter(self, root_material_id: str, approximate_diameter: str) -> str:
  209. return self._material_diameter_map.get(root_material_id, {}).get(approximate_diameter, root_material_id)
  210. def getRootMaterialIDWithoutDiameter(self, root_material_id: str) -> str:
  211. return self._diameter_material_map.get(root_material_id)
  212. def getMaterialGroupListByGUID(self, guid: str) -> Optional[list]:
  213. return self._guid_material_groups_map.get(guid)
  214. #
  215. # Return a dict with all root material IDs (k) and ContainerNodes (v) that's suitable for the given setup.
  216. #
  217. def getAvailableMaterials(self, machine_definition: "DefinitionContainer", extruder_variant_name: Optional[str],
  218. diameter: float) -> dict:
  219. # round the diameter to get the approximate diameter
  220. rounded_diameter = str(round(diameter))
  221. if rounded_diameter not in self._diameter_machine_variant_material_map:
  222. Logger.log("i", "Cannot find materials with diameter [%s] (rounded to [%s])", diameter, rounded_diameter)
  223. return dict()
  224. machine_definition_id = machine_definition.getId()
  225. # If there are variant materials, get the variant material
  226. machine_variant_material_map = self._diameter_machine_variant_material_map[rounded_diameter]
  227. machine_node = machine_variant_material_map.get(machine_definition_id)
  228. default_machine_node = machine_variant_material_map.get(self._default_machine_definition_id)
  229. variant_node = None
  230. if extruder_variant_name is not None and machine_node is not None:
  231. variant_node = machine_node.getChildNode(extruder_variant_name)
  232. nodes_to_check = [variant_node, machine_node, default_machine_node]
  233. # Fallback mechanism of finding materials:
  234. # 1. variant-specific material
  235. # 2. machine-specific material
  236. # 3. generic material (for fdmprinter)
  237. machine_exclude_materials = machine_definition.getMetaDataEntry("exclude_materials", [])
  238. material_id_metadata_dict = dict()
  239. for node in nodes_to_check:
  240. if node is not None:
  241. # Only exclude the materials that are explicitly specified in the "exclude_materials" field.
  242. # Do not exclude other materials that are of the same type.
  243. for material_id, node in node.material_map.items():
  244. if material_id in machine_exclude_materials:
  245. Logger.log("d", "Exclude material [%s] for machine [%s]",
  246. material_id, machine_definition.getId())
  247. continue
  248. if material_id not in material_id_metadata_dict:
  249. material_id_metadata_dict[material_id] = node
  250. return material_id_metadata_dict
  251. #
  252. # A convenience function to get available materials for the given machine with the extruder position.
  253. #
  254. def getAvailableMaterialsForMachineExtruder(self, machine: "GlobalStack",
  255. extruder_stack: "ExtruderStack") -> Optional[dict]:
  256. variant_name = None
  257. if extruder_stack.variant.getId() != "empty_variant":
  258. variant_name = extruder_stack.variant.getName()
  259. diameter = extruder_stack.approximateMaterialDiameter
  260. # Fetch the available materials (ContainerNode) for the current active machine and extruder setup.
  261. return self.getAvailableMaterials(machine.definition, variant_name, diameter)
  262. #
  263. # Gets MaterialNode for the given extruder and machine with the given material name.
  264. # Returns None if:
  265. # 1. the given machine doesn't have materials;
  266. # 2. cannot find any material InstanceContainers with the given settings.
  267. #
  268. def getMaterialNode(self, machine_definition_id: str, extruder_variant_name: Optional[str],
  269. diameter: float, root_material_id: str) -> Optional["InstanceContainer"]:
  270. # round the diameter to get the approximate diameter
  271. rounded_diameter = str(round(diameter))
  272. if rounded_diameter not in self._diameter_machine_variant_material_map:
  273. Logger.log("i", "Cannot find materials with diameter [%s] (rounded to [%s]) for root material id [%s]",
  274. diameter, rounded_diameter, root_material_id)
  275. return None
  276. # If there are variant materials, get the variant material
  277. machine_variant_material_map = self._diameter_machine_variant_material_map[rounded_diameter]
  278. machine_node = machine_variant_material_map.get(machine_definition_id)
  279. variant_node = None
  280. # Fallback for "fdmprinter" if the machine-specific materials cannot be found
  281. if machine_node is None:
  282. machine_node = machine_variant_material_map.get(self._default_machine_definition_id)
  283. if machine_node is not None and extruder_variant_name is not None:
  284. variant_node = machine_node.getChildNode(extruder_variant_name)
  285. # Fallback mechanism of finding materials:
  286. # 1. variant-specific material
  287. # 2. machine-specific material
  288. # 3. generic material (for fdmprinter)
  289. nodes_to_check = [variant_node, machine_node,
  290. machine_variant_material_map.get(self._default_machine_definition_id)]
  291. material_node = None
  292. for node in nodes_to_check:
  293. if node is not None:
  294. material_node = node.material_map.get(root_material_id)
  295. if material_node:
  296. break
  297. return material_node
  298. #
  299. # Gets MaterialNode for the given extruder and machine with the given material type.
  300. # Returns None if:
  301. # 1. the given machine doesn't have materials;
  302. # 2. cannot find any material InstanceContainers with the given settings.
  303. #
  304. def getMaterialNodeByType(self, global_stack: "GlobalStack", extruder_variant_name: str, material_guid: str) -> Optional["MaterialNode"]:
  305. node = None
  306. machine_definition = global_stack.definition
  307. if parseBool(machine_definition.getMetaDataEntry("has_materials", False)):
  308. material_diameter = machine_definition.getProperty("material_diameter", "value")
  309. if isinstance(material_diameter, SettingFunction):
  310. material_diameter = material_diameter(global_stack)
  311. # Look at the guid to material dictionary
  312. root_material_id = None
  313. for material_group in self._guid_material_groups_map[material_guid]:
  314. if material_group.is_read_only:
  315. root_material_id = material_group.root_material_node.metadata["id"]
  316. break
  317. if not root_material_id:
  318. Logger.log("i", "Cannot find materials with guid [%s] ", material_guid)
  319. return None
  320. node = self.getMaterialNode(machine_definition.getId(), extruder_variant_name,
  321. material_diameter, root_material_id)
  322. return node
  323. #
  324. # Used by QualityManager. Built-in quality profiles may be based on generic material IDs such as "generic_pla".
  325. # For materials such as ultimaker_pla_orange, no quality profiles may be found, so we should fall back to use
  326. # the generic material IDs to search for qualities.
  327. #
  328. # An example would be, suppose we have machine with preferred material set to "filo3d_pla" (1.75mm), but its
  329. # extruders only use 2.85mm materials, then we won't be able to find the preferred material for this machine.
  330. # A fallback would be to fetch a generic material of the same type "PLA" as "filo3d_pla", and in this case it will
  331. # be "generic_pla". This function is intended to get a generic fallback material for the given material type.
  332. #
  333. # This function returns the generic root material ID for the given material type, where material types are "PLA",
  334. # "ABS", etc.
  335. #
  336. def getFallbackMaterialIdByMaterialType(self, material_type: str) -> Optional[str]:
  337. # For safety
  338. if material_type not in self._fallback_materials_map:
  339. Logger.log("w", "The material type [%s] does not have a fallback material" % material_type)
  340. return None
  341. fallback_material = self._fallback_materials_map[material_type]
  342. if fallback_material:
  343. return self.getRootMaterialIDWithoutDiameter(fallback_material["id"])
  344. else:
  345. return None
  346. def getDefaultMaterial(self, global_stack: "GlobalStack", extruder_variant_name: Optional[str]) -> Optional["MaterialNode"]:
  347. node = None
  348. machine_definition = global_stack.definition
  349. if parseBool(global_stack.getMetaDataEntry("has_materials", False)):
  350. material_diameter = machine_definition.getProperty("material_diameter", "value")
  351. if isinstance(material_diameter, SettingFunction):
  352. material_diameter = material_diameter(global_stack)
  353. approximate_material_diameter = str(round(material_diameter))
  354. root_material_id = machine_definition.getMetaDataEntry("preferred_material")
  355. root_material_id = self.getRootMaterialIDForDiameter(root_material_id, approximate_material_diameter)
  356. node = self.getMaterialNode(machine_definition.getId(), extruder_variant_name,
  357. material_diameter, root_material_id)
  358. return node
  359. def removeMaterialByRootId(self, root_material_id: str):
  360. material_group = self.getMaterialGroup(root_material_id)
  361. if not material_group:
  362. Logger.log("i", "Unable to remove the material with id %s, because it doesn't exist.", root_material_id)
  363. return
  364. nodes_to_remove = [material_group.root_material_node] + material_group.derived_material_node_list
  365. for node in nodes_to_remove:
  366. self._container_registry.removeContainer(node.metadata["id"])
  367. #
  368. # Methods for GUI
  369. #
  370. #
  371. # Sets the new name for the given material.
  372. #
  373. @pyqtSlot("QVariant", str)
  374. def setMaterialName(self, material_node: "MaterialNode", name: str):
  375. root_material_id = material_node.metadata["base_file"]
  376. if self._container_registry.isReadOnly(root_material_id):
  377. Logger.log("w", "Cannot set name of read-only container %s.", root_material_id)
  378. return
  379. material_group = self.getMaterialGroup(root_material_id)
  380. if material_group:
  381. material_group.root_material_node.getContainer().setName(name)
  382. #
  383. # Removes the given material.
  384. #
  385. @pyqtSlot("QVariant")
  386. def removeMaterial(self, material_node: "MaterialNode"):
  387. root_material_id = material_node.metadata["base_file"]
  388. self.removeMaterialByRootId(root_material_id)
  389. #
  390. # Creates a duplicate of a material, which has the same GUID and base_file metadata.
  391. # Returns the root material ID of the duplicated material if successful.
  392. #
  393. @pyqtSlot("QVariant", result = str)
  394. def duplicateMaterial(self, material_node, new_base_id = None, new_metadata = None) -> Optional[str]:
  395. root_material_id = material_node.metadata["base_file"]
  396. material_group = self.getMaterialGroup(root_material_id)
  397. if not material_group:
  398. Logger.log("i", "Unable to duplicate the material with id %s, because it doesn't exist.", root_material_id)
  399. return None
  400. base_container = material_group.root_material_node.getContainer()
  401. if not base_container:
  402. return None
  403. # Ensure all settings are saved.
  404. self._application.saveSettings()
  405. # Create a new ID & container to hold the data.
  406. new_containers = []
  407. if new_base_id is None:
  408. new_base_id = self._container_registry.uniqueName(base_container.getId())
  409. new_base_container = copy.deepcopy(base_container)
  410. new_base_container.getMetaData()["id"] = new_base_id
  411. new_base_container.getMetaData()["base_file"] = new_base_id
  412. if new_metadata is not None:
  413. for key, value in new_metadata.items():
  414. new_base_container.getMetaData()[key] = value
  415. new_containers.append(new_base_container)
  416. # Clone all of them.
  417. for node in material_group.derived_material_node_list:
  418. container_to_copy = node.getContainer()
  419. if not container_to_copy:
  420. continue
  421. # Create unique IDs for every clone.
  422. new_id = new_base_id
  423. if container_to_copy.getMetaDataEntry("definition") != "fdmprinter":
  424. new_id += "_" + container_to_copy.getMetaDataEntry("definition")
  425. if container_to_copy.getMetaDataEntry("variant_name"):
  426. variant_name = container_to_copy.getMetaDataEntry("variant_name")
  427. new_id += "_" + variant_name.replace(" ", "_")
  428. new_container = copy.deepcopy(container_to_copy)
  429. new_container.getMetaData()["id"] = new_id
  430. new_container.getMetaData()["base_file"] = new_base_id
  431. if new_metadata is not None:
  432. for key, value in new_metadata.items():
  433. new_container.getMetaData()[key] = value
  434. new_containers.append(new_container)
  435. for container_to_add in new_containers:
  436. container_to_add.setDirty(True)
  437. self._container_registry.addContainer(container_to_add)
  438. return new_base_id
  439. #
  440. # Create a new material by cloning Generic PLA for the current material diameter and generate a new GUID.
  441. #
  442. @pyqtSlot(result = str)
  443. def createMaterial(self) -> str:
  444. from UM.i18n import i18nCatalog
  445. catalog = i18nCatalog("cura")
  446. # Ensure all settings are saved.
  447. self._application.saveSettings()
  448. machine_manager = self._application.getMachineManager()
  449. extruder_stack = machine_manager.activeStack
  450. approximate_diameter = str(extruder_stack.approximateMaterialDiameter)
  451. root_material_id = "generic_pla"
  452. root_material_id = self.getRootMaterialIDForDiameter(root_material_id, approximate_diameter)
  453. material_group = self.getMaterialGroup(root_material_id)
  454. # Create a new ID & container to hold the data.
  455. new_id = self._container_registry.uniqueName("custom_material")
  456. new_metadata = {"name": catalog.i18nc("@label", "Custom Material"),
  457. "brand": catalog.i18nc("@label", "Custom"),
  458. "GUID": str(uuid.uuid4()),
  459. }
  460. self.duplicateMaterial(material_group.root_material_node,
  461. new_base_id = new_id,
  462. new_metadata = new_metadata)
  463. return new_id