Added missing typing

This commit is contained in:
Jaime van Kessel 2019-08-02 15:01:15 +02:00
parent c35c8e0f50
commit 5f692f3028
2 changed files with 23 additions and 19 deletions

View File

@ -4,7 +4,7 @@
import os import os
import urllib.parse import urllib.parse
import uuid import uuid
from typing import Dict, Union, Any, TYPE_CHECKING, List from typing import Dict, Union, Any, TYPE_CHECKING, List, cast
from PyQt5.QtCore import QObject, QUrl from PyQt5.QtCore import QObject, QUrl
from PyQt5.QtWidgets import QMessageBox from PyQt5.QtWidgets import QMessageBox
@ -438,7 +438,7 @@ class ContainerManager(QObject):
if not path: if not path:
return return
container_list = [n.getContainer() for n in quality_changes_group.getAllNodes() if n.getContainer() is not None] container_list = [cast(InstanceContainer, n.getContainer()) for n in quality_changes_group.getAllNodes() if n.getContainer() is not None]
self._container_registry.exportQualityProfile(container_list, path, file_type) self._container_registry.exportQualityProfile(container_list, path, file_type)
__instance = None # type: ContainerManager __instance = None # type: ContainerManager

View File

@ -5,10 +5,11 @@ import os
import re import re
import configparser import configparser
from typing import Any, cast, Dict, Optional from typing import Any, cast, Dict, Optional, List, Union
from PyQt5.QtWidgets import QMessageBox from PyQt5.QtWidgets import QMessageBox
from UM.Decorators import override from UM.Decorators import override
from UM.PluginObject import PluginObject
from UM.Settings.ContainerFormatError import ContainerFormatError from UM.Settings.ContainerFormatError import ContainerFormatError
from UM.Settings.Interfaces import ContainerInterface from UM.Settings.Interfaces import ContainerInterface
from UM.Settings.ContainerRegistry import ContainerRegistry from UM.Settings.ContainerRegistry import ContainerRegistry
@ -22,6 +23,7 @@ from UM.Platform import Platform
from UM.PluginRegistry import PluginRegistry # For getting the possible profile writers to write with. from UM.PluginRegistry import PluginRegistry # For getting the possible profile writers to write with.
from UM.Util import parseBool from UM.Util import parseBool
from UM.Resources import Resources from UM.Resources import Resources
from cura.ReaderWriters.ProfileWriter import ProfileWriter
from . import ExtruderStack from . import ExtruderStack
from . import GlobalStack from . import GlobalStack
@ -50,10 +52,10 @@ class CuraContainerRegistry(ContainerRegistry):
# This will also try to convert a ContainerStack to either Extruder or # This will also try to convert a ContainerStack to either Extruder or
# Global stack based on metadata information. # Global stack based on metadata information.
@override(ContainerRegistry) @override(ContainerRegistry)
def addContainer(self, container): def addContainer(self, container: ContainerInterface) -> None:
# Note: Intentional check with type() because we want to ignore subclasses # Note: Intentional check with type() because we want to ignore subclasses
if type(container) == ContainerStack: if type(container) == ContainerStack:
container = self._convertContainerStack(container) container = self._convertContainerStack(cast(ContainerStack, container))
if isinstance(container, InstanceContainer) and type(container) != type(self.getEmptyInstanceContainer()): if isinstance(container, InstanceContainer) and type(container) != type(self.getEmptyInstanceContainer()):
# Check against setting version of the definition. # Check against setting version of the definition.
@ -61,7 +63,7 @@ class CuraContainerRegistry(ContainerRegistry):
actual_setting_version = int(container.getMetaDataEntry("setting_version", default = 0)) actual_setting_version = int(container.getMetaDataEntry("setting_version", default = 0))
if required_setting_version != actual_setting_version: if required_setting_version != actual_setting_version:
Logger.log("w", "Instance container {container_id} is outdated. Its setting version is {actual_setting_version} but it should be {required_setting_version}.".format(container_id = container.getId(), actual_setting_version = actual_setting_version, required_setting_version = required_setting_version)) Logger.log("w", "Instance container {container_id} is outdated. Its setting version is {actual_setting_version} but it should be {required_setting_version}.".format(container_id = container.getId(), actual_setting_version = actual_setting_version, required_setting_version = required_setting_version))
return #Don't add. return # Don't add.
super().addContainer(container) super().addContainer(container)
@ -71,7 +73,7 @@ class CuraContainerRegistry(ContainerRegistry):
# \param new_name \type{string} Base name, which may not be unique # \param new_name \type{string} Base name, which may not be unique
# \param fallback_name \type{string} Name to use when (stripped) new_name is empty # \param fallback_name \type{string} Name to use when (stripped) new_name is empty
# \return \type{string} Name that is unique for the specified type and name/id # \return \type{string} Name that is unique for the specified type and name/id
def createUniqueName(self, container_type, current_name, new_name, fallback_name): def createUniqueName(self, container_type: str, current_name: str, new_name: str, fallback_name: str) -> str:
new_name = new_name.strip() new_name = new_name.strip()
num_check = re.compile("(.*?)\s*#\d+$").match(new_name) num_check = re.compile("(.*?)\s*#\d+$").match(new_name)
if num_check: if num_check:
@ -92,7 +94,7 @@ class CuraContainerRegistry(ContainerRegistry):
# Both the id and the name are checked, because they may not be the same and it is better if they are both unique # Both the id and the name are checked, because they may not be the same and it is better if they are both unique
# \param container_type \type{string} Type of the container (machine, quality, ...) # \param container_type \type{string} Type of the container (machine, quality, ...)
# \param container_name \type{string} Name to check # \param container_name \type{string} Name to check
def _containerExists(self, container_type, container_name): def _containerExists(self, container_type: str, container_name: str):
container_class = ContainerStack if container_type == "machine" else InstanceContainer container_class = ContainerStack if container_type == "machine" else InstanceContainer
return self.findContainersMetadata(container_type = container_class, id = container_name, type = container_type, ignore_case = True) or \ return self.findContainersMetadata(container_type = container_class, id = container_name, type = container_type, ignore_case = True) or \
@ -100,11 +102,11 @@ class CuraContainerRegistry(ContainerRegistry):
## Exports an profile to a file ## Exports an profile to a file
# #
# \param instance_ids \type{list} the IDs of the profiles to export. # \param container_list \type{list} the containers to export
# \param file_name \type{str} the full path and filename to export to. # \param file_name \type{str} the full path and filename to export to.
# \param file_type \type{str} the file type with the format "<description> (*.<extension>)" # \param file_type \type{str} the file type with the format "<description> (*.<extension>)"
# \return True if the export succeeded, false otherwise. # \return True if the export succeeded, false otherwise.
def exportQualityProfile(self, container_list, file_name, file_type) -> bool: def exportQualityProfile(self, container_list: List[InstanceContainer], file_name: str, file_type: str) -> bool:
# Parse the fileType to deduce what plugin can save the file format. # Parse the fileType to deduce what plugin can save the file format.
# fileType has the format "<description> (*.<extension>)" # fileType has the format "<description> (*.<extension>)"
split = file_type.rfind(" (*.") # Find where the description ends and the extension starts. split = file_type.rfind(" (*.") # Find where the description ends and the extension starts.
@ -126,6 +128,8 @@ class CuraContainerRegistry(ContainerRegistry):
profile_writer = self._findProfileWriter(extension, description) profile_writer = self._findProfileWriter(extension, description)
try: try:
if profile_writer is None:
raise Exception("Unable to find a profile writer")
success = profile_writer.write(file_name, container_list) success = profile_writer.write(file_name, container_list)
except Exception as e: except Exception as e:
Logger.log("e", "Failed to export profile to %s: %s", file_name, str(e)) Logger.log("e", "Failed to export profile to %s: %s", file_name, str(e))
@ -150,7 +154,7 @@ class CuraContainerRegistry(ContainerRegistry):
# \param extension # \param extension
# \param description # \param description
# \return The plugin object matching the given extension and description. # \return The plugin object matching the given extension and description.
def _findProfileWriter(self, extension, description): def _findProfileWriter(self, extension: str, description: str) -> Optional[ProfileWriter]:
plugin_registry = PluginRegistry.getInstance() plugin_registry = PluginRegistry.getInstance()
for plugin_id, meta_data in self._getIOPlugins("profile_writer"): for plugin_id, meta_data in self._getIOPlugins("profile_writer"):
for supported_type in meta_data["profile_writer"]: # All file types this plugin can supposedly write. for supported_type in meta_data["profile_writer"]: # All file types this plugin can supposedly write.
@ -158,7 +162,7 @@ class CuraContainerRegistry(ContainerRegistry):
if supported_extension == extension: # This plugin supports a file type with the same extension. if supported_extension == extension: # This plugin supports a file type with the same extension.
supported_description = supported_type.get("description", None) supported_description = supported_type.get("description", None)
if supported_description == description: # The description is also identical. Assume it's the same file type. if supported_description == description: # The description is also identical. Assume it's the same file type.
return plugin_registry.getPluginObject(plugin_id) return cast(ProfileWriter, plugin_registry.getPluginObject(plugin_id))
return None return None
## Imports a profile from a file ## Imports a profile from a file
@ -324,7 +328,7 @@ class CuraContainerRegistry(ContainerRegistry):
return {"status": "error", "message": catalog.i18nc("@info:status", "Profile {0} has an unknown file type or is corrupted.", file_name)} return {"status": "error", "message": catalog.i18nc("@info:status", "Profile {0} has an unknown file type or is corrupted.", file_name)}
@override(ContainerRegistry) @override(ContainerRegistry)
def load(self): def load(self) -> None:
super().load() super().load()
self._registerSingleExtrusionMachinesExtruderStacks() self._registerSingleExtrusionMachinesExtruderStacks()
self._connectUpgradedExtruderStacksToMachines() self._connectUpgradedExtruderStacksToMachines()
@ -406,7 +410,7 @@ class CuraContainerRegistry(ContainerRegistry):
return result return result
## Convert an "old-style" pure ContainerStack to either an Extruder or Global stack. ## Convert an "old-style" pure ContainerStack to either an Extruder or Global stack.
def _convertContainerStack(self, container): def _convertContainerStack(self, container: ContainerStack) -> Union[ExtruderStack.ExtruderStack, GlobalStack.GlobalStack]:
assert type(container) == ContainerStack assert type(container) == ContainerStack
container_type = container.getMetaDataEntry("type") container_type = container.getMetaDataEntry("type")
@ -430,14 +434,14 @@ class CuraContainerRegistry(ContainerRegistry):
return new_stack return new_stack
def _registerSingleExtrusionMachinesExtruderStacks(self): def _registerSingleExtrusionMachinesExtruderStacks(self) -> None:
machines = self.findContainerStacks(type = "machine", machine_extruder_trains = {"0": "fdmextruder"}) machines = self.findContainerStacks(type = "machine", machine_extruder_trains = {"0": "fdmextruder"})
for machine in machines: for machine in machines:
extruder_stacks = self.findContainerStacks(type = "extruder_train", machine = machine.getId()) extruder_stacks = self.findContainerStacks(type = "extruder_train", machine = machine.getId())
if not extruder_stacks: if not extruder_stacks:
self.addExtruderStackForSingleExtrusionMachine(machine, "fdmextruder") self.addExtruderStackForSingleExtrusionMachine(machine, "fdmextruder")
def _onContainerAdded(self, container): def _onContainerAdded(self, container: ContainerInterface) -> None:
# We don't have all the machines loaded in the beginning, so in order to add the missing extruder stack # We don't have all the machines loaded in the beginning, so in order to add the missing extruder stack
# for single extrusion machines, we subscribe to the containerAdded signal, and whenever a global stack # for single extrusion machines, we subscribe to the containerAdded signal, and whenever a global stack
# is added, we check to see if an extruder stack needs to be added. # is added, we check to see if an extruder stack needs to be added.
@ -671,7 +675,7 @@ class CuraContainerRegistry(ContainerRegistry):
return extruder_stack return extruder_stack
def _findQualityChangesContainerInCuraFolder(self, name): def _findQualityChangesContainerInCuraFolder(self, name: str) -> Optional[InstanceContainer]:
quality_changes_dir = Resources.getPath(cura.CuraApplication.CuraApplication.ResourceTypes.QualityChangesInstanceContainer) quality_changes_dir = Resources.getPath(cura.CuraApplication.CuraApplication.ResourceTypes.QualityChangesInstanceContainer)
instance_container = None instance_container = None
@ -684,7 +688,7 @@ class CuraContainerRegistry(ContainerRegistry):
parser = configparser.ConfigParser(interpolation = None) parser = configparser.ConfigParser(interpolation = None)
try: try:
parser.read([file_path]) parser.read([file_path])
except: except Exception:
# Skip, it is not a valid stack file # Skip, it is not a valid stack file
continue continue
@ -716,7 +720,7 @@ class CuraContainerRegistry(ContainerRegistry):
# due to problems with loading order, some stacks may not have the proper next stack # due to problems with loading order, some stacks may not have the proper next stack
# set after upgrading, because the proper global stack was not yet loaded. This method # set after upgrading, because the proper global stack was not yet loaded. This method
# makes sure those extruders also get the right stack set. # makes sure those extruders also get the right stack set.
def _connectUpgradedExtruderStacksToMachines(self): def _connectUpgradedExtruderStacksToMachines(self) -> None:
extruder_stacks = self.findContainers(container_type = ExtruderStack.ExtruderStack) extruder_stacks = self.findContainers(container_type = ExtruderStack.ExtruderStack)
for extruder_stack in extruder_stacks: for extruder_stack in extruder_stacks:
if extruder_stack.getNextStack(): if extruder_stack.getNextStack():