From 9b836d95d9db1c2a08ed43a53af2487c140294ed Mon Sep 17 00:00:00 2001 From: Ghostkeeper Date: Wed, 16 Oct 2019 13:00:38 +0200 Subject: [PATCH] Remove quality, variant and material manager We don't use them any more and they are deprecated. Removing them removes a lot of maintenance. Contributes to issue CURA-6801. --- cura/CuraApplication.py | 17 -- cura/Machines/MaterialManager.py | 349 ------------------------------- cura/Machines/QualityManager.py | 215 ------------------- cura/Machines/VariantManager.py | 98 --------- tests/TestMaterialManager.py | 187 ----------------- tests/TestQualityManager.py | 129 ------------ 6 files changed, 995 deletions(-) delete mode 100644 cura/Machines/MaterialManager.py delete mode 100644 cura/Machines/QualityManager.py delete mode 100644 cura/Machines/VariantManager.py delete mode 100644 tests/TestMaterialManager.py delete mode 100644 tests/TestQualityManager.py diff --git a/cura/CuraApplication.py b/cura/CuraApplication.py index 579be0d953..8caccc786e 100755 --- a/cura/CuraApplication.py +++ b/cura/CuraApplication.py @@ -73,9 +73,6 @@ from cura.Scene import ZOffsetDecorator from cura.Machines.ContainerTree import ContainerTree from cura.Machines.MachineErrorChecker import MachineErrorChecker -import cura.Machines.MaterialManager #Imported like this to prevent circular imports. -import cura.Machines.QualityManager #Imported like this to prevent circular imports. -from cura.Machines.VariantManager import VariantManager from cura.Machines.Models.BuildPlateModel import BuildPlateModel from cura.Machines.Models.CustomQualityProfilesDropDownMenuModel import CustomQualityProfilesDropDownMenuModel @@ -924,20 +921,6 @@ class CuraApplication(QtApplication): self._extruder_manager = ExtruderManager() return self._extruder_manager - @deprecated("Use the ContainerTree structure instead.", since = "4.3") - def getVariantManager(self, *args) -> VariantManager: - return VariantManager.getInstance() - - # Can't deprecate this function since the deprecation marker collides with pyqtSlot! - @pyqtSlot(result = QObject) - def getMaterialManager(self, *args) -> cura.Machines.MaterialManager.MaterialManager: - return cura.Machines.MaterialManager.MaterialManager.getInstance() - - # Can't deprecate this function since the deprecation marker collides with pyqtSlot! - @pyqtSlot(result = QObject) - def getQualityManager(self, *args) -> cura.Machines.QualityManager.QualityManager: - return cura.Machines.QualityManager.QualityManager.getInstance() - def getIntentManager(self, *args) -> IntentManager: return IntentManager.getInstance() diff --git a/cura/Machines/MaterialManager.py b/cura/Machines/MaterialManager.py deleted file mode 100644 index 83be6941ea..0000000000 --- a/cura/Machines/MaterialManager.py +++ /dev/null @@ -1,349 +0,0 @@ -# Copyright (c) 2019 Ultimaker B.V. -# Cura is released under the terms of the LGPLv3 or higher. - -from collections import defaultdict -import copy -import uuid -from typing import Dict, Optional, TYPE_CHECKING, Any, List, cast - -from PyQt5.Qt import QTimer, QObject, pyqtSignal, pyqtSlot - -from UM.Decorators import deprecated -from UM.Logger import Logger -from UM.Settings.ContainerRegistry import ContainerRegistry -from UM.Util import parseBool -import cura.CuraApplication # Imported like this to prevent circular imports. -from cura.Machines.ContainerTree import ContainerTree -from cura.Settings.CuraContainerRegistry import CuraContainerRegistry - -from .MaterialNode import MaterialNode -from .MaterialGroup import MaterialGroup - -if TYPE_CHECKING: - from UM.Settings.DefinitionContainer import DefinitionContainer - from UM.Settings.InstanceContainer import InstanceContainer - from cura.Settings.GlobalStack import GlobalStack - from cura.Settings.ExtruderStack import ExtruderStack - - -# -# MaterialManager maintains a number of maps and trees for material lookup. -# The models GUI and QML use are now only dependent on the MaterialManager. That means as long as the data in -# MaterialManager gets updated correctly, the GUI models should be updated correctly too, and the same goes for GUI. -# -# For now, updating the lookup maps and trees here is very simple: we discard the old data completely and recreate them -# again. This means the update is exactly the same as initialization. There are performance concerns about this approach -# but so far the creation of the tables and maps is very fast and there is no noticeable slowness, we keep it like this -# because it's simple. -# -class MaterialManager(QObject): - __instance = None - - @classmethod - @deprecated("Use the ContainerTree structure instead.", since = "4.3") - def getInstance(cls) -> "MaterialManager": - if cls.__instance is None: - cls.__instance = MaterialManager() - return cls.__instance - - materialsUpdated = pyqtSignal() # Emitted whenever the material lookup tables are updated. - favoritesUpdated = pyqtSignal() # Emitted whenever the favorites are changed - - def __init__(self, parent = None): - super().__init__(parent) - # Material_type -> generic material metadata - self._fallback_materials_map = dict() # type: Dict[str, Dict[str, Any]] - - # Root_material_id -> MaterialGroup - self._material_group_map = dict() # type: Dict[str, MaterialGroup] - - # Material id including diameter (generic_pla_175) -> material root id (generic_pla) - self._diameter_material_map = dict() # type: Dict[str, str] - - # This is used in Legacy UM3 send material function and the material management page. - # GUID -> a list of material_groups - self._guid_material_groups_map = defaultdict(list) # type: Dict[str, List[MaterialGroup]] - - self._favorites = set(cura.CuraApplication.CuraApplication.getInstance().getPreferences().getValue("cura/favorite_materials").split(";")) - self.materialsUpdated.emit() - - self._update_timer = QTimer(self) - self._update_timer.setInterval(300) - - self._update_timer.setSingleShot(True) - self._update_timer.timeout.connect(self.materialsUpdated) - - container_registry = ContainerRegistry.getInstance() - container_registry.containerMetaDataChanged.connect(self._onContainerMetadataChanged) - container_registry.containerAdded.connect(self._onContainerMetadataChanged) - container_registry.containerRemoved.connect(self._onContainerMetadataChanged) - - def _onContainerMetadataChanged(self, container): - self._onContainerChanged(container) - - def _onContainerChanged(self, container): - container_type = container.getMetaDataEntry("type") - if container_type != "material": - return - - # update the maps - - self._update_timer.start() - - def getMaterialGroup(self, root_material_id: str) -> Optional[MaterialGroup]: - return self._material_group_map.get(root_material_id) - - def getRootMaterialIDForDiameter(self, root_material_id: str, approximate_diameter: str) -> str: - original_material = CuraContainerRegistry.getInstance().findInstanceContainersMetadata(id=root_material_id)[0] - if original_material["approximate_diameter"] == approximate_diameter: - return root_material_id - - matching_materials = CuraContainerRegistry.getInstance().findInstanceContainersMetadata(type = "material", brand = original_material["brand"], definition = original_material["definition"], material = original_material["material"], color_name = original_material["color_name"]) - for material in matching_materials: - if material["approximate_diameter"] == approximate_diameter: - return material["id"] - return root_material_id - - def getRootMaterialIDWithoutDiameter(self, root_material_id: str) -> str: - return self._diameter_material_map.get(root_material_id, "") - - def getMaterialGroupListByGUID(self, guid: str) -> Optional[List[MaterialGroup]]: - return self._guid_material_groups_map.get(guid) - - # Returns a dict of all material groups organized by root_material_id. - def getAllMaterialGroups(self) -> Dict[str, "MaterialGroup"]: - return self._material_group_map - - ## Gives a dictionary of all root material IDs and their associated - # MaterialNodes from the ContainerTree that are available for the given - # printer and variant. - def getAvailableMaterials(self, definition_id: str, nozzle_name: Optional[str]) -> Dict[str, MaterialNode]: - return ContainerTree.getInstance().machines[definition_id].variants[nozzle_name].materials - - # - # A convenience function to get available materials for the given machine with the extruder position. - # - def getAvailableMaterialsForMachineExtruder(self, machine: "GlobalStack", - extruder_stack: "ExtruderStack") -> Dict[str, MaterialNode]: - nozzle_name = None - if extruder_stack.variant.getId() != "empty_variant": - nozzle_name = extruder_stack.variant.getName() - - # Fetch the available materials (ContainerNode) for the current active machine and extruder setup. - materials = self.getAvailableMaterials(machine.definition.getId(), nozzle_name) - compatible_material_diameter = extruder_stack.getApproximateMaterialDiameter() - result = {key: material for key, material in materials.items() if material.container and float(material.container.getMetaDataEntry("approximate_diameter")) == compatible_material_diameter} - return result - - # - # Gets MaterialNode for the given extruder and machine with the given material name. - # Returns None if: - # 1. the given machine doesn't have materials; - # 2. cannot find any material InstanceContainers with the given settings. - # - def getMaterialNode(self, machine_definition_id: str, nozzle_name: Optional[str], - buildplate_name: Optional[str], diameter: float, root_material_id: str) -> Optional["MaterialNode"]: - container_tree = ContainerTree.getInstance() - machine_node = container_tree.machines.get(machine_definition_id) - if machine_node is None: - Logger.log("w", "Could not find machine with definition %s in the container tree", machine_definition_id) - return None - - variant_node = machine_node.variants.get(nozzle_name) - if variant_node is None: - Logger.log("w", "Could not find variant %s for machine with definition %s in the container tree", nozzle_name, machine_definition_id ) - return None - - material_node = variant_node.materials.get(root_material_id) - - if material_node is None: - Logger.log("w", "Could not find material %s for machine with definition %s and variant %s in the container tree", root_material_id, machine_definition_id, nozzle_name) - return None - - return material_node - - # - # Gets MaterialNode for the given extruder and machine with the given material type. - # Returns None if: - # 1. the given machine doesn't have materials; - # 2. cannot find any material InstanceContainers with the given settings. - # - def getMaterialNodeByType(self, global_stack: "GlobalStack", position: str, nozzle_name: str, - buildplate_name: Optional[str], material_guid: str) -> Optional["MaterialNode"]: - machine_definition = global_stack.definition - extruder = global_stack.extruderList[int(position)] - variant_name = extruder.variant.getName() - approximate_diameter = extruder.getApproximateMaterialDiameter() - - return self.getMaterialNode(machine_definition.getId(), variant_name, buildplate_name, approximate_diameter, material_guid) - - # There are 2 ways to get fallback materials; - # - A fallback by type (@sa getFallbackMaterialIdByMaterialType), which adds the generic version of this material - # - A fallback by GUID; If a material has been duplicated, it should also check if the original materials do have - # a GUID. This should only be done if the material itself does not have a quality just yet. - def getFallBackMaterialIdsByMaterial(self, material: "InstanceContainer") -> List[str]: - results = [] # type: List[str] - - material_groups = self.getMaterialGroupListByGUID(material.getMetaDataEntry("GUID")) - for material_group in material_groups: # type: ignore - if material_group.name != material.getId(): - # If the material in the group is read only, put it at the front of the list (since that is the most - # likely one to get a result) - if material_group.is_read_only: - results.insert(0, material_group.name) - else: - results.append(material_group.name) - - fallback = self.getFallbackMaterialIdByMaterialType(material.getMetaDataEntry("material")) - if fallback is not None: - results.append(fallback) - return results - - # - # Built-in quality profiles may be based on generic material IDs such as "generic_pla". - # For materials such as ultimaker_pla_orange, no quality profiles may be found, so we should fall back to use - # the generic material IDs to search for qualities. - # - # An example would be, suppose we have machine with preferred material set to "filo3d_pla" (1.75mm), but its - # extruders only use 2.85mm materials, then we won't be able to find the preferred material for this machine. - # A fallback would be to fetch a generic material of the same type "PLA" as "filo3d_pla", and in this case it will - # be "generic_pla". This function is intended to get a generic fallback material for the given material type. - # - # This function returns the generic root material ID for the given material type, where material types are "PLA", - # "ABS", etc. - # - def getFallbackMaterialIdByMaterialType(self, material_type: str) -> Optional[str]: - # For safety - if material_type not in self._fallback_materials_map: - Logger.log("w", "The material type [%s] does not have a fallback material" % material_type) - return None - fallback_material = self._fallback_materials_map[material_type] - if fallback_material: - return self.getRootMaterialIDWithoutDiameter(fallback_material["id"]) - else: - return None - - ## Get default material for given global stack, extruder position and extruder nozzle name - # you can provide the extruder_definition and then the position is ignored (useful when building up global stack in CuraStackBuilder) - def getDefaultMaterial(self, global_stack: "GlobalStack", position: str, nozzle_name: Optional[str], - extruder_definition: Optional["DefinitionContainer"] = None) -> "MaterialNode": - definition_id = global_stack.definition.getId() - machine_node = ContainerTree.getInstance().machines[definition_id] - if nozzle_name in machine_node.variants: - nozzle_node = machine_node.variants[nozzle_name] - else: - Logger.log("w", "Could not find variant {nozzle_name} for machine with definition {definition_id} in the container tree".format(nozzle_name = nozzle_name, definition_id = definition_id)) - nozzle_node = next(iter(machine_node.variants)) - - if not parseBool(global_stack.getMetaDataEntry("has_materials", False)): - return next(iter(nozzle_node.materials)) - - if extruder_definition is not None: - material_diameter = extruder_definition.getProperty("material_diameter", "value") - else: - material_diameter = global_stack.extruders[position].getCompatibleMaterialDiameter() - approximate_material_diameter = round(material_diameter) - - return nozzle_node.preferredMaterial(approximate_material_diameter) - - def removeMaterialByRootId(self, root_material_id: str): - container_registry = CuraContainerRegistry.getInstance() - results = container_registry.findContainers(id = root_material_id) - if not results: - container_registry.addWrongContainerId(root_material_id) - - for result in results: - container_registry.removeContainer(result.getMetaDataEntry("id", "")) - - @pyqtSlot("QVariant", result = bool) - def canMaterialBeRemoved(self, material_node: "MaterialNode"): - # Check if the material is active in any extruder train. In that case, the material shouldn't be removed! - # In the future we might enable this again, but right now, it's causing a ton of issues if we do (since it - # corrupts the configuration) - root_material_id = material_node.base_file - ids_to_remove = {metadata.get("id", "") for metadata in CuraContainerRegistry.getInstance().findInstanceContainersMetadata(base_file = root_material_id)} - - for extruder_stack in CuraContainerRegistry.getInstance().findContainerStacks(type = "extruder_train"): - if extruder_stack.material.getId() in ids_to_remove: - return False - return True - - ## Change the user-visible name of a material. - # \param material_node The ContainerTree node of the material to rename. - # \param name The new name for the material. - @pyqtSlot("QVariant", str) - def setMaterialName(self, material_node: "MaterialNode", name: str) -> None: - return cura.CuraApplication.CuraApplication.getMaterialManagementModel().setMaterialName(material_node, name) - - ## Deletes a material from Cura. - # - # This function does not do any safety checking any more. Please call this - # function only if: - # - The material is not read-only. - # - The material is not used in any stacks. - # If the material was not lazy-loaded yet, this will fully load the - # container. When removing this material node, all other materials with - # the same base fill will also be removed. - # \param material_node The material to remove. - @pyqtSlot("QVariant") - def removeMaterial(self, material_node: "MaterialNode") -> None: - return cura.CuraApplication.CuraApplication.getMaterialManagementModel().setMaterialName(material_node) - - def duplicateMaterialByRootId(self, root_material_id: str, new_base_id: Optional[str] = None, new_metadata: Optional[Dict[str, Any]] = None) -> Optional[str]: - result = cura.CuraApplication.CuraApplication.getInstance().getMaterialManagementModel().duplicateMaterialByBaseFile(root_material_id, new_base_id, new_metadata) - if result is None: - return "ERROR" - return result - - ## Creates a duplicate of a material with the same GUID and base_file - # metadata. - # \param material_node The node representing the material to duplicate. - # \param new_base_id A new material ID for the base material. The IDs of - # the submaterials will be based off this one. If not provided, a material - # ID will be generated automatically. - # \param new_metadata Metadata for the new material. If not provided, this - # will be duplicated from the original material. - # \return The root material ID of the duplicate material. - @pyqtSlot("QVariant", result = str) - def duplicateMaterial(self, material_node: MaterialNode, new_base_id: Optional[str] = None, new_metadata: Optional[Dict[str, Any]] = None) -> str: - result = cura.CuraApplication.CuraApplication.getInstance().getMaterialManagementModel().duplicateMaterial(material_node, new_base_id, new_metadata) - if result is None: - return "ERROR" - return result - - ## Create a new material by cloning the preferred material for the current - # material diameter and generate a new GUID. - # - # The material type is explicitly left to be the one from the preferred - # material, since this allows the user to still have SOME profiles to work - # with. - # \return The ID of the newly created material. - @pyqtSlot(result = str) - def createMaterial(self) -> str: - return cura.CuraApplication.CuraApplication.getMaterialManagementModel().createMaterial() - - @pyqtSlot(str) - def addFavorite(self, root_material_id: str) -> None: - self._favorites.add(root_material_id) - self.materialsUpdated.emit() - - # Ensure all settings are saved. - cura.CuraApplication.CuraApplication.getInstance().getPreferences().setValue("cura/favorite_materials", ";".join(list(self._favorites))) - cura.CuraApplication.CuraApplication.getInstance().saveSettings() - - @pyqtSlot(str) - def removeFavorite(self, root_material_id: str) -> None: - try: - self._favorites.remove(root_material_id) - except KeyError: - Logger.log("w", "Could not delete material %s from favorites as it was already deleted", root_material_id) - return - self.materialsUpdated.emit() - - # Ensure all settings are saved. - cura.CuraApplication.CuraApplication.getInstance().getPreferences().setValue("cura/favorite_materials", ";".join(list(self._favorites))) - cura.CuraApplication.CuraApplication.getInstance().saveSettings() - - @pyqtSlot() - def getFavorites(self): - return self._favorites diff --git a/cura/Machines/QualityManager.py b/cura/Machines/QualityManager.py deleted file mode 100644 index 4aa88d6775..0000000000 --- a/cura/Machines/QualityManager.py +++ /dev/null @@ -1,215 +0,0 @@ -# Copyright (c) 2019 Ultimaker B.V. -# Cura is released under the terms of the LGPLv3 or higher. - -from typing import Any, Dict, List, Optional, TYPE_CHECKING - -from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot - -from UM.Util import parseBool -from UM.Settings.InstanceContainer import InstanceContainer -from UM.Decorators import deprecated - -import cura.CuraApplication -from cura.Settings.ExtruderStack import ExtruderStack - -from cura.Machines.ContainerTree import ContainerTree # The implementation that replaces this manager, to keep the deprecated interface working. -from .QualityChangesGroup import QualityChangesGroup -from .QualityGroup import QualityGroup -from .QualityNode import QualityNode - -if TYPE_CHECKING: - from UM.Settings.Interfaces import DefinitionContainerInterface - from cura.Settings.GlobalStack import GlobalStack - from .QualityChangesGroup import QualityChangesGroup - - -# -# Similar to MaterialManager, QualityManager maintains a number of maps and trees for quality profile lookup. -# The models GUI and QML use are now only dependent on the QualityManager. That means as long as the data in -# QualityManager gets updated correctly, the GUI models should be updated correctly too, and the same goes for GUI. -# -# For now, updating the lookup maps and trees here is very simple: we discard the old data completely and recreate them -# again. This means the update is exactly the same as initialization. There are performance concerns about this approach -# but so far the creation of the tables and maps is very fast and there is no noticeable slowness, we keep it like this -# because it's simple. -# -class QualityManager(QObject): - __instance = None - - @classmethod - @deprecated("Use the ContainerTree structure instead.", since = "4.3") - def getInstance(cls) -> "QualityManager": - if cls.__instance is None: - cls.__instance = QualityManager() - return cls.__instance - - qualitiesUpdated = pyqtSignal() - - def __init__(self, parent = None) -> None: - super().__init__(parent) - application = cura.CuraApplication.CuraApplication.getInstance() - self._container_registry = application.getContainerRegistry() - - self._empty_quality_container = application.empty_quality_container - self._empty_quality_changes_container = application.empty_quality_changes_container - - # For quality lookup - self._machine_nozzle_buildplate_material_quality_type_to_quality_dict = {} # type: Dict[str, QualityNode] - - # For quality_changes lookup - self._machine_quality_type_to_quality_changes_dict = {} # type: Dict[str, QualityNode] - - self._default_machine_definition_id = "fdmprinter" - - self._container_registry.containerMetaDataChanged.connect(self._onContainerMetadataChanged) - self._container_registry.containerAdded.connect(self._onContainerMetadataChanged) - self._container_registry.containerRemoved.connect(self._onContainerMetadataChanged) - - def _onContainerMetadataChanged(self, container: InstanceContainer) -> None: - self._onContainerChanged(container) - - def _onContainerChanged(self, container: InstanceContainer) -> None: - container_type = container.getMetaDataEntry("type") - if container_type not in ("quality", "quality_changes"): - return - - # Returns a dict of "custom profile name" -> QualityChangesGroup - def getQualityChangesGroups(self, machine: "GlobalStack") -> List[QualityChangesGroup]: - variant_names = [extruder.variant.getName() for extruder in machine.extruderList] - material_bases = [extruder.material.getMetaDataEntry("base_file") for extruder in machine.extruderList] - extruder_enabled = [extruder.isEnabled for extruder in machine.extruderList] - machine_node = ContainerTree.getInstance().machines[machine.definition.getId()] - return machine_node.getQualityChangesGroups(variant_names, material_bases, extruder_enabled) - - ## Gets the quality groups for the current printer. - # - # Both available and unavailable quality groups will be included. Whether - # a quality group is available can be known via the field - # ``QualityGroup.is_available``. For more details, see QualityGroup. - # \return A dictionary with quality types as keys and the quality groups - # for those types as values. - def getQualityGroups(self, global_stack: "GlobalStack") -> Dict[str, QualityGroup]: - # Gather up the variant names and material base files for each extruder. - variant_names = [extruder.variant.getName() for extruder in global_stack.extruderList] - material_bases = [extruder.material.getMetaDataEntry("base_file") for extruder in global_stack.extruderList] - extruder_enabled = [extruder.isEnabled for extruder in global_stack.extruderList] - definition_id = global_stack.definition.getId() - return ContainerTree.getInstance().machines[definition_id].getQualityGroups(variant_names, material_bases, extruder_enabled) - - def getQualityGroupsForMachineDefinition(self, machine: "GlobalStack") -> Dict[str, QualityGroup]: - machine_definition_id = getMachineDefinitionIDForQualitySearch(machine.definition) - - # To find the quality container for the GlobalStack, check in the following fall-back manner: - # (1) the machine-specific node - # (2) the generic node - machine_node = self._machine_nozzle_buildplate_material_quality_type_to_quality_dict.get(machine_definition_id) - default_machine_node = self._machine_nozzle_buildplate_material_quality_type_to_quality_dict.get( - self._default_machine_definition_id) - nodes_to_check = [machine_node, default_machine_node] - - # Iterate over all quality_types in the machine node - quality_group_dict = dict() - for node in nodes_to_check: - if node and node.quality_type: - quality_group = QualityGroup(node.getMetaDataEntry("name", ""), node.quality_type) - quality_group.setGlobalNode(node) - quality_group_dict[node.quality_type] = quality_group - - return quality_group_dict - - ## Get the quality group for the preferred quality type for a certain - # global stack. - # - # If the preferred quality type is not available, ``None`` will be - # returned. - # \param machine The global stack of the machine to get the preferred - # quality group for. - # \return The preferred quality group, or ``None`` if that is not - # available. - def getDefaultQualityType(self, machine: "GlobalStack") -> Optional[QualityGroup]: - machine_node = ContainerTree.getInstance().machines[machine.definition.getId()] - quality_groups = self.getQualityGroups(machine) - result = quality_groups.get(machine_node.preferred_quality_type) - if result is not None and result.is_available: - return result - return None # If preferred quality type is not available, leave it up for the caller. - - - # - # Methods for GUI - # - - ## Deletes a custom profile. It will be gone forever. - # \param quality_changes_group The quality changes group representing the - # profile to delete. - @pyqtSlot(QObject) - def removeQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup") -> None: - return cura.CuraApplication.CuraApplication.getInstance().getQualityManagementModel().removeQualityChangesGroup(quality_changes_group) - - ## Rename a custom profile. - # - # Because the names must be unique, the new name may not actually become - # the name that was given. The actual name is returned by this function. - # \param quality_changes_group The custom profile that must be renamed. - # \param new_name The desired name for the profile. - # \return The actual new name of the profile, after making the name - # unique. - @pyqtSlot(QObject, str, result = str) - def renameQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup", new_name: str) -> str: - return cura.CuraApplication.CuraApplication.getInstance().getQualityManagementModel().renameQualityChangesGroup(quality_changes_group, new_name) - - ## Duplicates a given quality profile OR quality changes profile. - # \param new_name The desired name of the new profile. This will be made - # unique, so it might end up with a different name. - # \param quality_model_item The item of this model to duplicate, as - # dictionary. See the descriptions of the roles of this list model. - @pyqtSlot(str, "QVariantMap") - def duplicateQualityChanges(self, quality_changes_name: str, quality_model_item: Dict[str, Any]) -> None: - return cura.CuraApplication.CuraApplication.getInstance().getQualityManagementModel().duplicateQualityChanges(quality_changes_name, quality_model_item) - - ## Create quality changes containers from the user containers in the active - # stacks. - # - # This will go through the global and extruder stacks and create - # quality_changes containers from the user containers in each stack. These - # then replace the quality_changes containers in the stack and clear the - # user settings. - # \param base_name The new name for the quality changes profile. The final - # name of the profile might be different from this, because it needs to be - # made unique. - @pyqtSlot(str) - def createQualityChanges(self, base_name: str) -> None: - return cura.CuraApplication.CuraApplication.getInstance().getQualityManagementModel().createQualityChanges(base_name) - - ## Create a quality changes container with the given set-up. - # \param quality_type The quality type of the new container. - # \param new_name The name of the container. This name must be unique. - # \param machine The global stack to create the profile for. - # \param extruder_stack The extruder stack to create the profile for. If - # not provided, only a global container will be created. - def _createQualityChanges(self, quality_type: str, new_name: str, machine: "GlobalStack", extruder_stack: Optional["ExtruderStack"]) -> "InstanceContainer": - return cura.CuraApplication.CuraApplication.getInstance().getQualityManagementModel()._createQualityChanges(quality_type, new_name, machine, extruder_stack) - -# -# Gets the machine definition ID that can be used to search for Quality containers that are suitable for the given -# machine. The rule is as follows: -# 1. By default, the machine definition ID for quality container search will be "fdmprinter", which is the generic -# machine. -# 2. If a machine has its own machine quality (with "has_machine_quality = True"), we should use the given machine's -# own machine definition ID for quality search. -# Example: for an Ultimaker 3, the definition ID should be "ultimaker3". -# 3. When condition (2) is met, AND the machine has "quality_definition" defined in its definition file, then the -# definition ID specified in "quality_definition" should be used. -# Example: for an Ultimaker 3 Extended, it has "quality_definition = ultimaker3". This means Ultimaker 3 Extended -# shares the same set of qualities profiles as Ultimaker 3. -# -def getMachineDefinitionIDForQualitySearch(machine_definition: "DefinitionContainerInterface", - default_definition_id: str = "fdmprinter") -> str: - machine_definition_id = default_definition_id - if parseBool(machine_definition.getMetaDataEntry("has_machine_quality", False)): - # Only use the machine's own quality definition ID if this machine has machine quality. - machine_definition_id = machine_definition.getMetaDataEntry("quality_definition") - if machine_definition_id is None: - machine_definition_id = machine_definition.getId() - - return machine_definition_id diff --git a/cura/Machines/VariantManager.py b/cura/Machines/VariantManager.py deleted file mode 100644 index 617f85b8ca..0000000000 --- a/cura/Machines/VariantManager.py +++ /dev/null @@ -1,98 +0,0 @@ -# Copyright (c) 2019 Ultimaker B.V. -# Cura is released under the terms of the LGPLv3 or higher. - -from collections import OrderedDict -from typing import Optional, TYPE_CHECKING, Dict - -from UM.ConfigurationErrorMessage import ConfigurationErrorMessage -from UM.Decorators import deprecated -from UM.Logger import Logger -from UM.Util import parseBool - -from cura.Machines.ContainerNode import ContainerNode -from cura.Machines.VariantType import VariantType, ALL_VARIANT_TYPES -from cura.Settings.CuraContainerRegistry import CuraContainerRegistry -from cura.Settings.GlobalStack import GlobalStack - -if TYPE_CHECKING: - from UM.Settings.DefinitionContainer import DefinitionContainer - - -# -# VariantManager is THE place to look for a specific variant. It maintains two variant lookup tables with the following -# structure: -# -# [machine_definition_id] -> [variant_type] -> [variant_name] -> ContainerNode(metadata / container) -# Example: "ultimaker3" -> "buildplate" -> "Glass" (if present) -> ContainerNode -# -> ... -# -> "nozzle" -> "AA 0.4" -# -> "BB 0.8" -# -> ... -# -# [machine_definition_id] -> [machine_buildplate_type] -> ContainerNode(metadata / container) -# Example: "ultimaker3" -> "glass" (this is different from the variant name) -> ContainerNode -# -# Note that the "container" field is not loaded in the beginning because it would defeat the purpose of lazy-loading. -# A container is loaded when getVariant() is called to load a variant InstanceContainer. -# -class VariantManager: - __instance = None - - @classmethod - @deprecated("Use the ContainerTree structure instead.", since = "4.3") - def getInstance(cls) -> "VariantManager": - if cls.__instance is None: - cls.__instance = VariantManager() - return cls.__instance - - def __init__(self) -> None: - self._machine_to_variant_dict_map = dict() # type: Dict[str, Dict["VariantType", Dict[str, ContainerNode]]] - - self._exclude_variant_id_list = ["empty_variant"] - - # - # Gets the variant InstanceContainer with the given information. - # Almost the same as getVariantMetadata() except that this returns an InstanceContainer if present. - # - def getVariantNode(self, machine_definition_id: str, variant_name: str, - variant_type: Optional["VariantType"] = None) -> Optional["ContainerNode"]: - if variant_type is None: - variant_node = None - variant_type_dict = self._machine_to_variant_dict_map.get("machine_definition_id", {}) - for variant_dict in variant_type_dict.values(): - if variant_name in variant_dict: - variant_node = variant_dict[variant_name] - break - return variant_node - - return self._machine_to_variant_dict_map.get(machine_definition_id, {}).get(variant_type, {}).get(variant_name) - - def getVariantNodes(self, machine: "GlobalStack", variant_type: "VariantType") -> Dict[str, ContainerNode]: - machine_definition_id = machine.definition.getId() - return self._machine_to_variant_dict_map.get(machine_definition_id, {}).get(variant_type, {}) - - # - # Gets the default variant for the given machine definition. - # If the optional GlobalStack is given, the metadata information will be fetched from the GlobalStack instead of - # the DefinitionContainer. Because for machines such as UM2, you can enable Olsson Block, which will set - # "has_variants" to True in the GlobalStack. In those cases, we need to fetch metadata from the GlobalStack or - # it may not be correct. - # - def getDefaultVariantNode(self, machine_definition: "DefinitionContainer", - variant_type: "VariantType", - global_stack: Optional["GlobalStack"] = None) -> Optional["ContainerNode"]: - machine_definition_id = machine_definition.getId() - container_for_metadata_fetching = global_stack if global_stack is not None else machine_definition - - preferred_variant_name = None - if variant_type == VariantType.BUILD_PLATE: - if parseBool(container_for_metadata_fetching.getMetaDataEntry("has_variant_buildplates", False)): - preferred_variant_name = container_for_metadata_fetching.getMetaDataEntry("preferred_variant_buildplate_name") - else: - if parseBool(container_for_metadata_fetching.getMetaDataEntry("has_variants", False)): - preferred_variant_name = container_for_metadata_fetching.getMetaDataEntry("preferred_variant_name") - - node = None - if preferred_variant_name: - node = self.getVariantNode(machine_definition_id, preferred_variant_name, variant_type) - return node diff --git a/tests/TestMaterialManager.py b/tests/TestMaterialManager.py deleted file mode 100644 index d87ab3a63e..0000000000 --- a/tests/TestMaterialManager.py +++ /dev/null @@ -1,187 +0,0 @@ -from unittest.mock import MagicMock, patch -import pytest -from cura.Machines.MaterialManager import MaterialManager - - -mocked_registry = MagicMock() -material_1 = {"id": "test", "GUID":"TEST!", "base_file": "base_material", "definition": "fdmmachine", "approximate_diameter": "3", "brand": "generic", "material": "pla"} -material_2 = {"id": "base_material", "GUID": "TEST2!", "base_file": "test", "definition": "fdmmachine", "approximate_diameter": "3", "material": "pla"} -mocked_registry.findContainersMetadata = MagicMock(return_value = [material_1, material_2]) - - -mocked_definition = MagicMock() -mocked_definition.getId = MagicMock(return_value = "fdmmachine") -mocked_definition.getMetaDataEntry = MagicMock(return_value = []) - -# These tests are outdated -pytestmark = pytest.mark.skip - -def test_initialize(application): - # Just test if the simple loading works - with patch("UM.Application.Application.getInstance", MagicMock(return_value=application)): - manager = MaterialManager(mocked_registry) - manager.initialize() - # Double check that we actually got some material nodes - assert manager.getMaterialGroup("base_material").name == "base_material" - assert manager.getMaterialGroup("test").name == "test" - - -def test_getMaterialGroupListByGUID(application): - with patch("UM.Application.Application.getInstance", MagicMock(return_value=application)): - manager = MaterialManager(mocked_registry) - manager.initialize() - - assert manager.getMaterialGroupListByGUID("TEST!")[0].name == "test" - assert manager.getMaterialGroupListByGUID("TEST2!")[0].name == "base_material" - - -def test_getRootMaterialIDforDiameter(application): - with patch("UM.Application.Application.getInstance", MagicMock(return_value=application)): - manager = MaterialManager(mocked_registry) - manager.initialize() - - assert manager.getRootMaterialIDForDiameter("base_material", "3") == "base_material" - - -def test_getMaterialNodeByTypeMachineHasNoMaterials(application): - with patch("UM.Application.Application.getInstance", MagicMock(return_value=application)): - manager = MaterialManager(mocked_registry) - manager.initialize() - - mocked_stack = MagicMock() - assert manager.getMaterialNodeByType(mocked_stack, "0", "nozzle", "", "") is None - - -def test_getMaterialNodeByTypeMachineHasMaterialsButNoMaterialFound(application): - with patch("UM.Application.Application.getInstance", MagicMock(return_value=application)): - manager = MaterialManager(mocked_registry) - manager.initialize() - - mocked_stack = MagicMock() - mocked_stack.definition.getMetaDataEntry = MagicMock(return_value = True) # For the "has_materials" metadata - - assert manager.getMaterialNodeByType(mocked_stack, "0", "nozzle", "", "") is None - - -def test_getMaterialNodeByTypeMachineHasMaterialsAndMaterialExists(application): - with patch("UM.Application.Application.getInstance", MagicMock(return_value=application)): - manager = MaterialManager(mocked_registry) - manager.initialize() - mocked_result = MagicMock() - manager.getMaterialNode = MagicMock(return_value = mocked_result) - mocked_stack = MagicMock() - mocked_stack.definition.getMetaDataEntry = MagicMock(return_value = True) # For the "has_materials" metadata - - assert manager.getMaterialNodeByType(mocked_stack, "0", "nozzle", "", "TEST!") is mocked_result - - -def test_getAllMaterialGroups(application): - with patch("UM.Application.Application.getInstance", MagicMock(return_value=application)): - manager = MaterialManager(mocked_registry) - manager.initialize() - - material_groups = manager.getAllMaterialGroups() - - assert "base_material" in material_groups - assert "test" in material_groups - assert material_groups["base_material"].name == "base_material" - assert material_groups["test"].name == "test" - - -class TestAvailableMaterials: - def test_happy(self, application): - with patch("UM.Application.Application.getInstance", MagicMock(return_value=application)): - manager = MaterialManager(mocked_registry) - manager.initialize() - - available_materials = manager.getAvailableMaterials(mocked_definition, None, None, 3) - - assert "base_material" in available_materials - assert "test" in available_materials - - def test_wrongDiameter(self, application): - with patch("UM.Application.Application.getInstance", MagicMock(return_value=application)): - manager = MaterialManager(mocked_registry) - manager.initialize() - - available_materials = manager.getAvailableMaterials(mocked_definition, None, None, 200) - assert available_materials == {} # Nothing found. - - def test_excludedMaterials(self, application): - with patch("UM.Application.Application.getInstance", MagicMock(return_value=application)): - manager = MaterialManager(mocked_registry) - manager.initialize() - with patch.object(mocked_definition, "getMetaDataEntry", MagicMock(return_value = ["test"])): - available_materials = manager.getAvailableMaterials(mocked_definition, None, None, 3) - assert "base_material" in available_materials - assert "test" not in available_materials - - -class Test_getFallbackMaterialIdByMaterialType: - def test_happyFlow(self, application): - with patch("UM.Application.Application.getInstance", MagicMock(return_value=application)): - manager = MaterialManager(mocked_registry) - manager.initialize() - - assert manager.getFallbackMaterialIdByMaterialType("pla") == "test" - - def test_unknownMaterial(self, application): - with patch("UM.Application.Application.getInstance", MagicMock(return_value=application)): - manager = MaterialManager(mocked_registry) - manager.initialize() - assert manager.getFallbackMaterialIdByMaterialType("OMGZOMG") is None - - -def test_getMaterialNode(application): - with patch("UM.Application.Application.getInstance", MagicMock(return_value=application)): - manager = MaterialManager(mocked_registry) - manager._updateMaps() - - assert manager.getMaterialNode("fdmmachine", None, None, 3, "base_material").container_id == "test" - - -def test_getAvailableMaterialsForMachineExtruder(application): - with patch("UM.Application.Application.getInstance", MagicMock(return_value=application)): - manager = MaterialManager(mocked_registry) - manager.initialize() - - mocked_machine = MagicMock() - mocked_machine.getBuildplateName = MagicMock(return_value = "build_plate") - mocked_machine.definition = mocked_definition - mocked_extruder_stack = MagicMock() - mocked_extruder_stack.variant.getId = MagicMock(return_value = "test") - mocked_extruder_stack.getApproximateMaterialDiameter = MagicMock(return_value = 2.85) - - available_materials = manager.getAvailableMaterialsForMachineExtruder(mocked_machine, mocked_extruder_stack) - assert "base_material" in available_materials - assert "test" in available_materials - - -class TestFavorites: - def test_addFavorite(self, application): - with patch("UM.Application.Application.getInstance", MagicMock(return_value=application)): - manager = MaterialManager(mocked_registry) - manager.materialsUpdated = MagicMock() - manager.addFavorite("blarg") - assert manager.getFavorites() == {"blarg"} - - application.getPreferences().setValue.assert_called_once_with("cura/favorite_materials", "blarg") - manager.materialsUpdated.emit.assert_called_once_with() - - def test_removeNotExistingFavorite(self, application): - with patch("UM.Application.Application.getInstance", MagicMock(return_value=application)): - manager = MaterialManager(mocked_registry) - manager.materialsUpdated = MagicMock() - manager.removeFavorite("blarg") - manager.materialsUpdated.emit.assert_not_called() - - def test_removeExistingFavorite(self, application): - with patch("UM.Application.Application.getInstance", MagicMock(return_value=application)): - manager = MaterialManager(mocked_registry) - manager.materialsUpdated = MagicMock() - manager.addFavorite("blarg") - - manager.removeFavorite("blarg") - assert manager.materialsUpdated.emit.call_count == 2 - application.getPreferences().setValue.assert_called_with("cura/favorite_materials", "") - assert manager.getFavorites() == set() \ No newline at end of file diff --git a/tests/TestQualityManager.py b/tests/TestQualityManager.py deleted file mode 100644 index fb96f4476b..0000000000 --- a/tests/TestQualityManager.py +++ /dev/null @@ -1,129 +0,0 @@ -from unittest.mock import MagicMock, patch - -import pytest - -from cura.Machines.QualityChangesGroup import QualityChangesGroup -from cura.Machines.QualityManager import QualityManager - -mocked_stack = MagicMock() -mocked_extruder = MagicMock() - -mocked_material = MagicMock() -mocked_material.getMetaDataEntry = MagicMock(return_value = "base_material") - -mocked_extruder.material = mocked_material -mocked_stack.extruders = {"0": mocked_extruder} - -# These tests are outdated -pytestmark = pytest.mark.skip - -@pytest.fixture() -def material_manager(): - result = MagicMock() - result.getRootMaterialIDWithoutDiameter = MagicMock(return_value = "base_material") - return result - -@pytest.fixture() -def container_registry(): - result = MagicMock() - mocked_metadata = [{"id": "test", "definition": "fdmprinter", "quality_type": "normal", "name": "test_name", "global_quality": True, "type": "quality"}, - {"id": "test_material", "definition": "fdmprinter", "quality_type": "normal", "name": "test_name_material", "material": "base_material", "type": "quality"}, - {"id": "quality_changes_id", "definition": "fdmprinter", "type": "quality_changes", "quality_type": "amazing!", "name": "herp"}] - result.findContainersMetadata = MagicMock(return_value = mocked_metadata) - - result.uniqueName = MagicMock(return_value = "uniqueName") - return result - - -@pytest.fixture() -def quality_mocked_application(material_manager, container_registry): - result = MagicMock() - result.getMaterialManager = MagicMock(return_value=material_manager) - result.getContainerRegistry = MagicMock(return_value=container_registry) - return result - - -def test_getQualityGroups(quality_mocked_application): - manager = QualityManager(quality_mocked_application) - manager.initialize() - - assert "normal" in manager.getQualityGroups(mocked_stack) - - -def test_getQualityChangesGroup(quality_mocked_application): - manager = QualityManager(quality_mocked_application) - manager.initialize() - - assert "herp" in [qcg.name for qcg in manager.getQualityChangesGroups(mocked_stack)] - - -@pytest.mark.skip("Doesn't work on remote") -def test_getDefaultQualityType(quality_mocked_application): - manager = QualityManager(quality_mocked_application) - manager.initialize() - mocked_stack = MagicMock() - mocked_stack.definition.getMetaDataEntry = MagicMock(return_value = "normal") - assert manager.getDefaultQualityType(mocked_stack).quality_type == "normal" - - -def test_createQualityChanges(quality_mocked_application): - manager = QualityManager(quality_mocked_application) - mocked_quality_changes = MagicMock() - manager._createQualityChanges = MagicMock(return_value = mocked_quality_changes) - manager.initialize() - container_manager = MagicMock() - - manager._container_registry.addContainer = MagicMock() # Side effect we want to check. - with patch("cura.Settings.ContainerManager.ContainerManager.getInstance", container_manager): - manager.createQualityChanges("derp") - assert manager._container_registry.addContainer.called_once_with(mocked_quality_changes) - - -def test_renameQualityChangesGroup(quality_mocked_application): - manager = QualityManager(quality_mocked_application) - manager.initialize() - - mocked_container = MagicMock() - - quality_changes_group = QualityChangesGroup("zomg", "beep") - quality_changes_group.getAllNodes = MagicMock(return_value = [mocked_container]) - - # We need to check for "uniqueName" instead of "NEWRANDOMNAMEYAY" because the mocked registry always returns - # "uniqueName" when attempting to generate an unique name. - assert manager.renameQualityChangesGroup(quality_changes_group, "NEWRANDOMNAMEYAY") == "uniqueName" - assert mocked_container.setName.called_once_with("uniqueName") - - -def test_duplicateQualityChangesQualityOnly(quality_mocked_application): - manager = QualityManager(quality_mocked_application) - manager.initialize() - mocked_quality = MagicMock() - quality_group = MagicMock() - quality_group.getAllNodes = MagicMock(return_value = mocked_quality) - mocked_quality_changes = MagicMock() - - # Isolate what we want to test (in this case, we're not interested if createQualityChanges does it's job!) - manager._createQualityChanges = MagicMock(return_value = mocked_quality_changes) - manager._container_registry.addContainer = MagicMock() # Side effect we want to check. - - manager.duplicateQualityChanges("zomg", {"quality_group": quality_group, "quality_changes_group": None}) - assert manager._container_registry.addContainer.called_once_with(mocked_quality_changes) - - -def test_duplicateQualityChanges(quality_mocked_application): - manager = QualityManager(quality_mocked_application) - manager.initialize() - mocked_quality = MagicMock() - quality_group = MagicMock() - quality_group.getAllNodes = MagicMock(return_value = mocked_quality) - quality_changes_group = MagicMock() - mocked_quality_changes = MagicMock() - quality_changes_group.getAllNodes = MagicMock(return_value = [mocked_quality_changes]) - mocked_quality_changes.duplicate = MagicMock(return_value = mocked_quality_changes) - - manager._container_registry.addContainer = MagicMock() # Side effect we want to check. - - manager.duplicateQualityChanges("zomg", {"intent_category": "default", - "quality_group": quality_group, - "quality_changes_group": quality_changes_group}) - assert manager._container_registry.addContainer.called_once_with(mocked_quality_changes)