BaseMaterialsModel.py 9.7 KB

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