MaterialManager.py 31 KB

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