Browse Source

Add some missing typing

Jaime van Kessel 5 years ago
parent
commit
81b33b8649

+ 3 - 2
cura/Arranging/Arrange.py

@@ -1,6 +1,6 @@
 # Copyright (c) 2018 Ultimaker B.V.
 # Copyright (c) 2018 Ultimaker B.V.
 # Cura is released under the terms of the LGPLv3 or higher.
 # Cura is released under the terms of the LGPLv3 or higher.
-from typing import List
+from typing import List, Optional
 
 
 from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
 from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
 from UM.Logger import Logger
 from UM.Logger import Logger
@@ -8,6 +8,7 @@ from UM.Math.Polygon import Polygon
 from UM.Math.Vector import Vector
 from UM.Math.Vector import Vector
 from UM.Scene.SceneNode import SceneNode
 from UM.Scene.SceneNode import SceneNode
 from cura.Arranging.ShapeArray import ShapeArray
 from cura.Arranging.ShapeArray import ShapeArray
+from cura.BuildVolume import BuildVolume
 from cura.Scene import ZOffsetDecorator
 from cura.Scene import ZOffsetDecorator
 
 
 from collections import namedtuple
 from collections import namedtuple
@@ -27,7 +28,7 @@ LocationSuggestion = namedtuple("LocationSuggestion", ["x", "y", "penalty_points
 #
 #
 #   Note: Make sure the scale is the same between ShapeArray objects and the Arrange instance.
 #   Note: Make sure the scale is the same between ShapeArray objects and the Arrange instance.
 class Arrange:
 class Arrange:
-    build_volume = None
+    build_volume = None  # type: Optional[BuildVolume]
 
 
     def __init__(self, x, y, offset_x, offset_y, scale= 0.5):
     def __init__(self, x, y, offset_x, offset_y, scale= 0.5):
         self._scale = scale  # convert input coordinates to arrange coordinates
         self._scale = scale  # convert input coordinates to arrange coordinates

+ 9 - 5
cura/AutoSave.py

@@ -2,12 +2,16 @@
 # Cura is released under the terms of the LGPLv3 or higher.
 # Cura is released under the terms of the LGPLv3 or higher.
 
 
 from PyQt5.QtCore import QTimer
 from PyQt5.QtCore import QTimer
+from typing import Any, TYPE_CHECKING
 
 
 from UM.Logger import Logger
 from UM.Logger import Logger
 
 
+if TYPE_CHECKING:
+    from cura.CuraApplication import CuraApplication
+
 
 
 class AutoSave:
 class AutoSave:
-    def __init__(self, application):
+    def __init__(self, application: "CuraApplication") -> None:
         self._application = application
         self._application = application
         self._application.getPreferences().preferenceChanged.connect(self._triggerTimer)
         self._application.getPreferences().preferenceChanged.connect(self._triggerTimer)
 
 
@@ -22,14 +26,14 @@ class AutoSave:
         self._enabled = True
         self._enabled = True
         self._saving = False
         self._saving = False
 
 
-    def initialize(self):
+    def initialize(self) -> None:
         # only initialise if the application is created and has started
         # only initialise if the application is created and has started
         self._change_timer.timeout.connect(self._onTimeout)
         self._change_timer.timeout.connect(self._onTimeout)
         self._application.globalContainerStackChanged.connect(self._onGlobalStackChanged)
         self._application.globalContainerStackChanged.connect(self._onGlobalStackChanged)
         self._onGlobalStackChanged()
         self._onGlobalStackChanged()
         self._triggerTimer()
         self._triggerTimer()
 
 
-    def _triggerTimer(self, *args):
+    def _triggerTimer(self, *args: Any) -> None:
         if not self._saving:
         if not self._saving:
             self._change_timer.start()
             self._change_timer.start()
 
 
@@ -40,7 +44,7 @@ class AutoSave:
         else:
         else:
             self._change_timer.stop()
             self._change_timer.stop()
 
 
-    def _onGlobalStackChanged(self):
+    def _onGlobalStackChanged(self) -> None:
         if self._global_stack:
         if self._global_stack:
             self._global_stack.propertyChanged.disconnect(self._triggerTimer)
             self._global_stack.propertyChanged.disconnect(self._triggerTimer)
             self._global_stack.containersChanged.disconnect(self._triggerTimer)
             self._global_stack.containersChanged.disconnect(self._triggerTimer)
@@ -51,7 +55,7 @@ class AutoSave:
             self._global_stack.propertyChanged.connect(self._triggerTimer)
             self._global_stack.propertyChanged.connect(self._triggerTimer)
             self._global_stack.containersChanged.connect(self._triggerTimer)
             self._global_stack.containersChanged.connect(self._triggerTimer)
 
 
-    def _onTimeout(self):
+    def _onTimeout(self) -> None:
         self._saving = True # To prevent the save process from triggering another autosave.
         self._saving = True # To prevent the save process from triggering another autosave.
         Logger.log("d", "Autosaving preferences, instances and profiles")
         Logger.log("d", "Autosaving preferences, instances and profiles")
 
 

+ 5 - 5
cura/CuraApplication.py

@@ -4,7 +4,7 @@
 import os
 import os
 import sys
 import sys
 import time
 import time
-from typing import cast, TYPE_CHECKING, Optional, Callable, List
+from typing import cast, TYPE_CHECKING, Optional, Callable, List, Any
 
 
 import numpy
 import numpy
 
 
@@ -193,7 +193,7 @@ class CuraApplication(QtApplication):
 
 
         self._cura_package_manager = None
         self._cura_package_manager = None
 
 
-        self._machine_action_manager = None
+        self._machine_action_manager = None  # type: Optional[MachineActionManager.MachineActionManager]
 
 
         self.empty_container = None  # type: EmptyInstanceContainer
         self.empty_container = None  # type: EmptyInstanceContainer
         self.empty_definition_changes_container = None  # type: EmptyInstanceContainer
         self.empty_definition_changes_container = None  # type: EmptyInstanceContainer
@@ -699,7 +699,7 @@ class CuraApplication(QtApplication):
             self._message_box_callback_arguments = []
             self._message_box_callback_arguments = []
 
 
     # Cura has multiple locations where instance containers need to be saved, so we need to handle this differently.
     # Cura has multiple locations where instance containers need to be saved, so we need to handle this differently.
-    def saveSettings(self):
+    def saveSettings(self) -> None:
         if not self.started:
         if not self.started:
             # Do not do saving during application start or when data should not be saved on quit.
             # Do not do saving during application start or when data should not be saved on quit.
             return
             return
@@ -989,8 +989,8 @@ class CuraApplication(QtApplication):
     ##  Get the machine action manager
     ##  Get the machine action manager
     #   We ignore any *args given to this, as we also register the machine manager as qml singleton.
     #   We ignore any *args given to this, as we also register the machine manager as qml singleton.
     #   It wants to give this function an engine and script engine, but we don't care about that.
     #   It wants to give this function an engine and script engine, but we don't care about that.
-    def getMachineActionManager(self, *args):
-        return self._machine_action_manager
+    def getMachineActionManager(self, *args: Any) -> MachineActionManager.MachineActionManager:
+        return cast(MachineActionManager.MachineActionManager, self._machine_action_manager)
 
 
     @pyqtSlot(result = QObject)
     @pyqtSlot(result = QObject)
     def getMaterialManagementModel(self) -> MaterialManagementModel:
     def getMaterialManagementModel(self) -> MaterialManagementModel:

+ 7 - 3
cura/CuraPackageManager.py

@@ -1,7 +1,7 @@
 # Copyright (c) 2018 Ultimaker B.V.
 # Copyright (c) 2018 Ultimaker B.V.
 # Cura is released under the terms of the LGPLv3 or higher.
 # Cura is released under the terms of the LGPLv3 or higher.
 
 
-from typing import List, Tuple
+from typing import List, Tuple, TYPE_CHECKING, Optional
 
 
 from cura.CuraApplication import CuraApplication #To find some resource types.
 from cura.CuraApplication import CuraApplication #To find some resource types.
 from cura.Settings.GlobalStack import GlobalStack
 from cura.Settings.GlobalStack import GlobalStack
@@ -9,12 +9,16 @@ from cura.Settings.GlobalStack import GlobalStack
 from UM.PackageManager import PackageManager #The class we're extending.
 from UM.PackageManager import PackageManager #The class we're extending.
 from UM.Resources import Resources #To find storage paths for some resource types.
 from UM.Resources import Resources #To find storage paths for some resource types.
 
 
+if TYPE_CHECKING:
+    from UM.Qt.QtApplication import QtApplication
+    from PyQt5.QtCore import QObject
+
 
 
 class CuraPackageManager(PackageManager):
 class CuraPackageManager(PackageManager):
-    def __init__(self, application, parent = None):
+    def __init__(self, application: "QtApplication", parent: Optional["QObject"] = None):
         super().__init__(application, parent)
         super().__init__(application, parent)
 
 
-    def initialize(self):
+    def initialize(self) -> None:
         self._installation_dirs_dict["materials"] = Resources.getStoragePath(CuraApplication.ResourceTypes.MaterialInstanceContainer)
         self._installation_dirs_dict["materials"] = Resources.getStoragePath(CuraApplication.ResourceTypes.MaterialInstanceContainer)
         self._installation_dirs_dict["qualities"] = Resources.getStoragePath(CuraApplication.ResourceTypes.QualityInstanceContainer)
         self._installation_dirs_dict["qualities"] = Resources.getStoragePath(CuraApplication.ResourceTypes.QualityInstanceContainer)
 
 

+ 2 - 2
cura/Layer.py

@@ -33,10 +33,10 @@ class Layer:
     def elementCount(self):
     def elementCount(self):
         return self._element_count
         return self._element_count
 
 
-    def setHeight(self, height):
+    def setHeight(self, height: float) -> None:
         self._height = height
         self._height = height
 
 
-    def setThickness(self, thickness):
+    def setThickness(self, thickness: float) -> None:
         self._thickness = thickness
         self._thickness = thickness
 
 
     def lineMeshVertexCount(self) -> int:
     def lineMeshVertexCount(self) -> int:

+ 1 - 1
cura/LayerDataDecorator.py

@@ -9,7 +9,7 @@ from cura.LayerData import LayerData
 
 
 ## Simple decorator to indicate a scene node holds layer data.
 ## Simple decorator to indicate a scene node holds layer data.
 class LayerDataDecorator(SceneNodeDecorator):
 class LayerDataDecorator(SceneNodeDecorator):
-    def __init__(self):
+    def __init__(self) -> None:
         super().__init__()
         super().__init__()
         self._layer_data = None  # type: Optional[LayerData]
         self._layer_data = None  # type: Optional[LayerData]
 
 

+ 9 - 9
cura/LayerPolygon.py

@@ -149,17 +149,17 @@ class LayerPolygon:
     def getColors(self):
     def getColors(self):
         return self._colors
         return self._colors
 
 
-    def mapLineTypeToColor(self, line_types):
+    def mapLineTypeToColor(self, line_types: numpy.ndarray) -> numpy.ndarray:
         return self._color_map[line_types]
         return self._color_map[line_types]
 
 
-    def isInfillOrSkinType(self, line_types):
+    def isInfillOrSkinType(self, line_types: numpy.ndarray) -> numpy.ndarray:
         return self._isInfillOrSkinTypeMap[line_types]
         return self._isInfillOrSkinTypeMap[line_types]
 
 
-    def lineMeshVertexCount(self):
-        return (self._vertex_end - self._vertex_begin)
+    def lineMeshVertexCount(self) -> int:
+        return self._vertex_end - self._vertex_begin
 
 
-    def lineMeshElementCount(self):
-        return (self._index_end - self._index_begin)
+    def lineMeshElementCount(self) -> int:
+        return self._index_end - self._index_begin
 
 
     @property
     @property
     def extruder(self):
     def extruder(self):
@@ -202,7 +202,7 @@ class LayerPolygon:
         return self._jump_count
         return self._jump_count
 
 
     # Calculate normals for the entire polygon using numpy.
     # Calculate normals for the entire polygon using numpy.
-    def getNormals(self):
+    def getNormals(self) -> numpy.ndarray:
         normals = numpy.copy(self._data)
         normals = numpy.copy(self._data)
         normals[:, 1] = 0.0 # We are only interested in 2D normals
         normals[:, 1] = 0.0 # We are only interested in 2D normals
 
 
@@ -226,11 +226,11 @@ class LayerPolygon:
 
 
         return normals
         return normals
 
 
-    __color_map = None # type: numpy.ndarray[Any]
+    __color_map = None  # type: numpy.ndarray
 
 
     ##  Gets the instance of the VersionUpgradeManager, or creates one.
     ##  Gets the instance of the VersionUpgradeManager, or creates one.
     @classmethod
     @classmethod
-    def getColorMap(cls):
+    def getColorMap(cls) -> numpy.ndarray:
         if cls.__color_map is None:
         if cls.__color_map is None:
             theme = QtApplication.getInstance().getTheme()
             theme = QtApplication.getInstance().getTheme()
             cls.__color_map = numpy.array([
             cls.__color_map = numpy.array([

+ 1 - 1
cura/Machines/ContainerNode.py

@@ -26,7 +26,7 @@ class ContainerNode:
     ##  Gets the metadata of the container that this node represents.
     ##  Gets the metadata of the container that this node represents.
     #   Getting the metadata from the container directly is about 10x as fast.
     #   Getting the metadata from the container directly is about 10x as fast.
     #   \return The metadata of the container in this node.
     #   \return The metadata of the container in this node.
-    def getMetadata(self):
+    def getMetadata(self) -> Dict[str, Any]:
         return ContainerRegistry.getInstance().findContainersMetadata(id = self.container_id)[0]
         return ContainerRegistry.getInstance().findContainersMetadata(id = self.container_id)[0]
 
 
     ##  Get an entry from the metadata of the container that this node contains.
     ##  Get an entry from the metadata of the container that this node contains.

+ 3 - 3
cura/Machines/ContainerTree.py

@@ -30,7 +30,7 @@ if TYPE_CHECKING:
 #   nodes that have children) but that child node may be a node representing the
 #   nodes that have children) but that child node may be a node representing the
 #   empty instance container.
 #   empty instance container.
 class ContainerTree:
 class ContainerTree:
-    __instance = None
+    __instance = None  # type: Optional["ContainerTree"]
 
 
     @classmethod
     @classmethod
     def getInstance(cls):
     def getInstance(cls):
@@ -75,7 +75,7 @@ class ContainerTree:
         return self.machines[global_stack.definition.getId()].getQualityChangesGroups(variant_names, material_bases, extruder_enabled)
         return self.machines[global_stack.definition.getId()].getQualityChangesGroups(variant_names, material_bases, extruder_enabled)
 
 
     ##  Ran after completely starting up the application.
     ##  Ran after completely starting up the application.
-    def _onStartupFinished(self):
+    def _onStartupFinished(self) -> None:
         currently_added = ContainerRegistry.getInstance().findContainerStacks()  # Find all currently added global stacks.
         currently_added = ContainerRegistry.getInstance().findContainerStacks()  # Find all currently added global stacks.
         JobQueue.getInstance().add(self._MachineNodeLoadJob(self, currently_added))
         JobQueue.getInstance().add(self._MachineNodeLoadJob(self, currently_added))
 
 
@@ -137,7 +137,7 @@ class ContainerTree:
         #   \param container_stacks All of the stacks to pre-load the container
         #   \param container_stacks All of the stacks to pre-load the container
         #   trees for. This needs to be provided from here because the stacks
         #   trees for. This needs to be provided from here because the stacks
         #   need to be constructed on the main thread because they are QObject.
         #   need to be constructed on the main thread because they are QObject.
-        def __init__(self, tree_root: "ContainerTree", container_stacks: List["ContainerStack"]):
+        def __init__(self, tree_root: "ContainerTree", container_stacks: List["ContainerStack"]) -> None:
             self.tree_root = tree_root
             self.tree_root = tree_root
             self.container_stacks = container_stacks
             self.container_stacks = container_stacks
             super().__init__()
             super().__init__()

+ 8 - 7
cura/Machines/MachineErrorChecker.py

@@ -6,6 +6,7 @@ import time
 from collections import deque
 from collections import deque
 
 
 from PyQt5.QtCore import QObject, QTimer, pyqtSignal, pyqtProperty
 from PyQt5.QtCore import QObject, QTimer, pyqtSignal, pyqtProperty
+from typing import Optional, Any, Set
 
 
 from UM.Application import Application
 from UM.Application import Application
 from UM.Logger import Logger
 from UM.Logger import Logger
@@ -24,16 +25,16 @@ from UM.Settings.Validator import ValidatorState
 #
 #
 class MachineErrorChecker(QObject):
 class MachineErrorChecker(QObject):
 
 
-    def __init__(self, parent = None):
+    def __init__(self, parent: Optional[QObject] = None) -> None:
         super().__init__(parent)
         super().__init__(parent)
 
 
         self._global_stack = None
         self._global_stack = None
 
 
         self._has_errors = True  # Result of the error check, indicating whether there are errors in the stack
         self._has_errors = True  # Result of the error check, indicating whether there are errors in the stack
-        self._error_keys = set()  # A set of settings keys that have errors
-        self._error_keys_in_progress = set()  # The variable that stores the results of the currently in progress check
+        self._error_keys = set()  # type: Set[str] # A set of settings keys that have errors
+        self._error_keys_in_progress = set()  # type: Set[str]  # The variable that stores the results of the currently in progress check
 
 
-        self._stacks_and_keys_to_check = None  # a FIFO queue of tuples (stack, key) to check for errors
+        self._stacks_and_keys_to_check = None  # type: Optional[deque]  # a FIFO queue of tuples (stack, key) to check for errors
 
 
         self._need_to_check = False  # Whether we need to schedule a new check or not. This flag is set when a new
         self._need_to_check = False  # Whether we need to schedule a new check or not. This flag is set when a new
                                      # error check needs to take place while there is already one running at the moment.
                                      # error check needs to take place while there is already one running at the moment.
@@ -42,7 +43,7 @@ class MachineErrorChecker(QObject):
         self._application = Application.getInstance()
         self._application = Application.getInstance()
         self._machine_manager = self._application.getMachineManager()
         self._machine_manager = self._application.getMachineManager()
 
 
-        self._start_time = 0  # measure checking time
+        self._start_time = 0.  # measure checking time
 
 
         # This timer delays the starting of error check so we can react less frequently if the user is frequently
         # This timer delays the starting of error check so we can react less frequently if the user is frequently
         # changing settings.
         # changing settings.
@@ -94,13 +95,13 @@ class MachineErrorChecker(QObject):
 
 
     #   Start the error check for property changed
     #   Start the error check for property changed
     #   this is seperate from the startErrorCheck because it ignores a number property types
     #   this is seperate from the startErrorCheck because it ignores a number property types
-    def startErrorCheckPropertyChanged(self, key, property_name):
+    def startErrorCheckPropertyChanged(self, key: str, property_name: str) -> None:
         if property_name != "value":
         if property_name != "value":
             return
             return
         self.startErrorCheck()
         self.startErrorCheck()
 
 
     # Starts the error check timer to schedule a new error check.
     # Starts the error check timer to schedule a new error check.
-    def startErrorCheck(self, *args) -> None:
+    def startErrorCheck(self, *args: Any) -> None:
         if not self._check_in_progress:
         if not self._check_in_progress:
             self._need_to_check = True
             self._need_to_check = True
             self.needToWaitForResultChanged.emit()
             self.needToWaitForResultChanged.emit()

Some files were not shown because too many files changed in this diff