BaseMaterialsModel.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from typing import Dict, Set, Optional
  4. from PyQt5.QtCore import Qt, QTimer, pyqtSignal, pyqtProperty
  5. from UM.Qt.ListModel import ListModel
  6. from UM.Logger import Logger
  7. import cura.CuraApplication # Imported like this to prevent a circular reference.
  8. from cura.Machines.ContainerTree import ContainerTree
  9. from cura.Machines.MaterialNode import MaterialNode
  10. from cura.Settings.CuraContainerRegistry import CuraContainerRegistry
  11. class BaseMaterialsModel(ListModel):
  12. """This is the base model class for GenericMaterialsModel and MaterialBrandsModel.
  13. Those 2 models are used by the material drop down menu to show generic materials and branded materials
  14. separately. The extruder position defined here is being used to bound a menu to the correct extruder. This is
  15. used in the top bar menu "Settings" -> "Extruder nr" -> "Material" -> this menu
  16. """
  17. extruderPositionChanged = pyqtSignal()
  18. enabledChanged = pyqtSignal()
  19. def __init__(self, parent: Optional["QObject"] = None) -> None:
  20. super(BaseMaterialsModel, self).__init__(parent = parent)
  21. from cura.CuraApplication import CuraApplication
  22. self._application = CuraApplication.getInstance()
  23. self._available_materials = {} # type: Dict[str, MaterialNode]
  24. self._favorite_ids = set() # type: Set[str]
  25. # Make these managers available to all material models
  26. self._container_registry = self._application.getInstance().getContainerRegistry()
  27. self._machine_manager = self._application.getMachineManager()
  28. self._extruder_position = 0
  29. self._extruder_stack = None
  30. self._enabled = True
  31. # CURA-6904
  32. # Updating the material model requires information from material nodes and containers. We use a timer here to
  33. # make sure that an update function call will not be directly invoked by an event. Because the triggered event
  34. # can be caused in the middle of a XMLMaterial loading, and the material container we try to find may not be
  35. # in the system yet. This will cause an infinite recursion of (1) trying to load a material, (2) trying to
  36. # update the material model, (3) cannot find the material container, load it, (4) repeat #1.
  37. self._update_timer = QTimer(self)
  38. self._update_timer.setInterval(100)
  39. self._update_timer.setSingleShot(True)
  40. self._update_timer.timeout.connect(self._update)
  41. # Update the stack and the model data when the machine changes
  42. self._machine_manager.globalContainerChanged.connect(self._updateExtruderStack)
  43. self._updateExtruderStack()
  44. # Update this model when switching machines or tabs, when adding materials or changing their metadata.
  45. self._machine_manager.activeStackChanged.connect(self._onChanged)
  46. ContainerTree.getInstance().materialsChanged.connect(self._materialsListChanged)
  47. self._application.getMaterialManagementModel().favoritesChanged.connect(self._onChanged)
  48. self.addRoleName(Qt.UserRole + 1, "root_material_id")
  49. self.addRoleName(Qt.UserRole + 2, "id")
  50. self.addRoleName(Qt.UserRole + 3, "GUID")
  51. self.addRoleName(Qt.UserRole + 4, "name")
  52. self.addRoleName(Qt.UserRole + 5, "brand")
  53. self.addRoleName(Qt.UserRole + 6, "description")
  54. self.addRoleName(Qt.UserRole + 7, "material")
  55. self.addRoleName(Qt.UserRole + 8, "color_name")
  56. self.addRoleName(Qt.UserRole + 9, "color_code")
  57. self.addRoleName(Qt.UserRole + 10, "density")
  58. self.addRoleName(Qt.UserRole + 11, "diameter")
  59. self.addRoleName(Qt.UserRole + 12, "approximate_diameter")
  60. self.addRoleName(Qt.UserRole + 13, "adhesion_info")
  61. self.addRoleName(Qt.UserRole + 14, "is_read_only")
  62. self.addRoleName(Qt.UserRole + 15, "container_node")
  63. self.addRoleName(Qt.UserRole + 16, "is_favorite")
  64. def _onChanged(self) -> None:
  65. self._update_timer.start()
  66. def _updateExtruderStack(self):
  67. global_stack = self._machine_manager.activeMachine
  68. if global_stack is None:
  69. return
  70. if self._extruder_stack is not None:
  71. self._extruder_stack.pyqtContainersChanged.disconnect(self._onChanged)
  72. self._extruder_stack.approximateMaterialDiameterChanged.disconnect(self._onChanged)
  73. try:
  74. self._extruder_stack = global_stack.extruderList[self._extruder_position]
  75. except IndexError:
  76. self._extruder_stack = None
  77. if self._extruder_stack is not None:
  78. self._extruder_stack.pyqtContainersChanged.connect(self._onChanged)
  79. self._extruder_stack.approximateMaterialDiameterChanged.connect(self._onChanged)
  80. # Force update the model when the extruder stack changes
  81. self._onChanged()
  82. def setExtruderPosition(self, position: int):
  83. if self._extruder_stack is None or self._extruder_position != position:
  84. self._extruder_position = position
  85. self._updateExtruderStack()
  86. self.extruderPositionChanged.emit()
  87. @pyqtProperty(int, fset = setExtruderPosition, notify = extruderPositionChanged)
  88. def extruderPosition(self) -> int:
  89. return self._extruder_position
  90. def setEnabled(self, enabled):
  91. if self._enabled != enabled:
  92. self._enabled = enabled
  93. if self._enabled:
  94. # ensure the data is there again.
  95. self._onChanged()
  96. self.enabledChanged.emit()
  97. @pyqtProperty(bool, fset = setEnabled, notify = enabledChanged)
  98. def enabled(self):
  99. return self._enabled
  100. def _materialsListChanged(self, material: MaterialNode) -> None:
  101. """Triggered when a list of materials changed somewhere in the container
  102. tree. This change may trigger an _update() call when the materials changed for the configuration that this
  103. model is looking for.
  104. """
  105. if self._extruder_stack is None:
  106. return
  107. if material.variant.container_id != self._extruder_stack.variant.getId():
  108. return
  109. global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  110. if not global_stack:
  111. return
  112. if material.variant.machine.container_id != global_stack.definition.getId():
  113. return
  114. self._onChanged()
  115. def _favoritesChanged(self, material_base_file: str) -> None:
  116. """Triggered when the list of favorite materials is changed."""
  117. if material_base_file in self._available_materials:
  118. self._onChanged()
  119. def _update(self):
  120. """This is an abstract method that needs to be implemented by the specific models themselves. """
  121. self._favorite_ids = set(cura.CuraApplication.CuraApplication.getInstance().getPreferences().getValue("cura/favorite_materials").split(";"))
  122. # Update the available materials (ContainerNode) for the current active machine and extruder setup.
  123. global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
  124. if not global_stack or not global_stack.hasMaterials:
  125. return # There are no materials for this machine, so nothing to do.
  126. extruder_list = global_stack.extruderList
  127. if self._extruder_position > len(extruder_list):
  128. return
  129. extruder_stack = extruder_list[self._extruder_position]
  130. nozzle_name = extruder_stack.variant.getName()
  131. machine_node = ContainerTree.getInstance().machines[global_stack.definition.getId()]
  132. if nozzle_name not in machine_node.variants:
  133. Logger.log("w", "Unable to find variant %s in container tree", nozzle_name)
  134. self._available_materials = {}
  135. return
  136. materials = machine_node.variants[nozzle_name].materials
  137. approximate_material_diameter = extruder_stack.getApproximateMaterialDiameter()
  138. self._available_materials = {key: material for key, material in materials.items() if float(material.getMetaDataEntry("approximate_diameter", -1)) == approximate_material_diameter}
  139. def _canUpdate(self):
  140. """This method is used by all material models in the beginning of the _update() method in order to prevent
  141. errors. It's the same in all models so it's placed here for easy access. """
  142. global_stack = self._machine_manager.activeMachine
  143. if global_stack is None or not self._enabled:
  144. return False
  145. if self._extruder_position >= len(global_stack.extruderList):
  146. return False
  147. return True
  148. def _createMaterialItem(self, root_material_id, container_node):
  149. """This is another convenience function which is shared by all material models so it's put here to avoid having
  150. so much duplicated code. """
  151. metadata_list = CuraContainerRegistry.getInstance().findContainersMetadata(id = container_node.container_id)
  152. if not metadata_list:
  153. return None
  154. metadata = metadata_list[0]
  155. item = {
  156. "root_material_id": root_material_id,
  157. "id": metadata["id"],
  158. "container_id": metadata["id"], # TODO: Remove duplicate in material manager qml
  159. "GUID": metadata["GUID"],
  160. "name": metadata["name"],
  161. "brand": metadata["brand"],
  162. "description": metadata["description"],
  163. "material": metadata["material"],
  164. "color_name": metadata["color_name"],
  165. "color_code": metadata.get("color_code", ""),
  166. "density": metadata.get("properties", {}).get("density", ""),
  167. "diameter": metadata.get("properties", {}).get("diameter", ""),
  168. "approximate_diameter": metadata["approximate_diameter"],
  169. "adhesion_info": metadata["adhesion_info"],
  170. "is_read_only": self._container_registry.isReadOnly(metadata["id"]),
  171. "container_node": container_node,
  172. "is_favorite": root_material_id in self._favorite_ids
  173. }
  174. return item