MaterialManager.py 34 KB

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