Skip to content

Commit

Permalink
Controversial pyright fixes (#1788)
Browse files Browse the repository at this point in the history
* Controversial type fixes

* Fix

* Fixes

* More fixes

* Fixes

* Fix

* fix circular import

* Fix

* fix doc build

* Fix doc build

* More fixes

* Fix

* fix

* fix

* addressing review feedback
  • Loading branch information
cspotcode committed May 26, 2023
1 parent 1c2975f commit 2381082
Show file tree
Hide file tree
Showing 21 changed files with 120 additions and 95 deletions.
10 changes: 7 additions & 3 deletions arcade/gl/framebuffer.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
from ctypes import c_int, string_at
from contextlib import contextmanager
from typing import Optional, Tuple, List, TYPE_CHECKING
from typing import Optional, Tuple, List, TYPE_CHECKING, Union
import weakref


from pyglet import gl

from arcade.types import RGBOrA255, RGBOrANormalized

from .texture import Texture2D
from .types import pixel_formats

Expand Down Expand Up @@ -344,7 +346,7 @@ def _use(self, *, force: bool = False):

def clear(
self,
color=(0.0, 0.0, 0.0, 0.0),
color: Union[RGBOrA255, RGBOrANormalized] =(0.0, 0.0, 0.0, 0.0),
*,
depth: float = 1.0,
normalized: bool = False,
Expand Down Expand Up @@ -386,8 +388,10 @@ def clear(
if len(color) == 3:
gl.glClearColor(color[0] / 255, color[1] / 255, color[2] / 255, 1.0)
else:
# mypy does not understand that color[3] is guaranteed to work in this codepath, pyright does.
# We can remove this type: ignore if we switch to pyright.
gl.glClearColor(
color[0] / 255, color[1] / 255, color[2] / 255, color[3] / 255
color[0] / 255, color[1] / 255, color[2] / 255, color[3] / 255 # type: ignore
)

if self.depth_attachment:
Expand Down
6 changes: 4 additions & 2 deletions arcade/gl/glsl.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from typing import Dict, Iterable, List, Optional
from typing import TYPE_CHECKING, Dict, Iterable, List, Optional
import re

from pyglet import gl
if TYPE_CHECKING:
from .context import Context as ArcadeGlContext

from .exceptions import ShaderException
from .types import SHADER_TYPE_NAMES, PyGLenum
Expand All @@ -28,7 +30,7 @@ class ShaderSource:
"""
def __init__(
self,
ctx: gl.Context,
ctx: 'ArcadeGlContext',
source: str,
common: Optional[Iterable[str]],
source_type: PyGLenum,
Expand Down
5 changes: 3 additions & 2 deletions arcade/gl/program.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
create_string_buffer,
)
from typing import Any, Dict, Iterable, Tuple, List, TYPE_CHECKING, Union, Optional
import typing
import weakref

from pyglet import gl
Expand Down Expand Up @@ -85,7 +86,7 @@ def __init__(
self._attributes = [] # type: List[AttribFormat]
#: Internal cache key used with vertex arrays
self.attribute_key = "INVALID" # type: str
self._uniforms: Dict[str, Uniform] = {}
self._uniforms: Dict[str, Union[Uniform, UniformBlock]] = {}

if self._varyings_capture_mode not in self._valid_capture_modes:
raise ValueError(
Expand Down Expand Up @@ -318,7 +319,7 @@ def set_uniform_array_safe(self, name: str, value: List[Any]):
if name not in self._uniforms:
return

uniform = self._uniforms[name]
uniform = typing.cast(Uniform, self._uniforms[name])
_len = uniform._array_length * uniform._components
if _len == 1:
self.set_uniform_safe(name, value[0])
Expand Down
6 changes: 4 additions & 2 deletions arcade/gui/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@
from arcade.gui.widgets import UISpace
from arcade.gui.widgets.dropdown import UIDropdown
from arcade.gui.widgets import UISpriteWidget
from arcade.gui.widgets.buttons import UITextureButton, UIFlatButton
from arcade.gui.widgets.slider import UISlider
from arcade.gui.widgets.buttons import UITextureButton, UITextureButtonStyle, UIFlatButton
from arcade.gui.widgets.slider import UISlider, UISliderStyle
from arcade.gui.widgets import UIWidget
from arcade.gui.property import ListProperty, DictProperty, Property, bind
from arcade.gui.mixins import UIDraggableMixin
Expand Down Expand Up @@ -75,6 +75,7 @@
"UIOnChangeEvent",
"UIOnClickEvent",
"UISlider",
"UISliderStyle",
"UIStyleBase",
"UIStyledWidget",
"UISpace",
Expand All @@ -84,6 +85,7 @@
"UITextMotionEvent",
"UITextMotionSelectEvent",
"UITextureButton",
"UITextureButtonStyle",
"UITextureToggle",
"UITextWidget",
"UIWidget",
Expand Down
4 changes: 2 additions & 2 deletions arcade/gui/examples/textured_slider.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import arcade
from arcade import Texture
from arcade.gui import UIManager, Surface, UIAnchorLayout, NinePatchTexture
from arcade.gui.widgets.slider import UISlider
from arcade.gui.widgets.slider import UISlider, UISliderStyle


class UITextureSlider(UISlider):
Expand All @@ -37,7 +37,7 @@ def __init__(
super().__init__(style=style, **kwargs)

def do_render(self, surface: Surface):
style: UISlider.UIStyle = self.get_current_style() # type: ignore
style: UISliderStyle = self.get_current_style() # type: ignore

self.prepare_render(surface)

Expand Down
5 changes: 2 additions & 3 deletions arcade/gui/surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from arcade.color import TRANSPARENT_BLACK
from arcade.gl import Framebuffer
from arcade.gui.nine_patch import NinePatchTexture
from arcade.types import Point, Rect, RGBA255
from arcade.types import RGBA255, FloatRect, Point


class Surface:
Expand Down Expand Up @@ -158,15 +158,14 @@ def limit(self, x, y, width, height):

def draw(
self,
area: Optional[Rect] = None,
area: Optional[FloatRect] = None,
) -> None:
"""
Draws the contents of the surface.
The surface will be rendered at the configured ``position``
and limited by the given ``area``. The area can be out of bounds.
:param Optional[Point] position: The position to draw the surface at.
:param Optional[Rect] area: Limit the area in the surface we're drawing (x, y, w, h)
"""
# Set blend function
Expand Down
9 changes: 5 additions & 4 deletions arcade/gui/ui_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
- TextArea with scroll support
"""
from collections import defaultdict
from typing import List, Dict, TypeVar, Iterable, Optional, Type
from typing import List, Dict, TypeVar, Iterable, Optional, Type, Union
from typing_extensions import TypeGuard

from pyglet.event import EventDispatcher, EVENT_HANDLED, EVENT_UNHANDLED

Expand Down Expand Up @@ -164,8 +165,8 @@ def get_widgets_at(self, pos, cls: Type[W] = UIWidget, layer=0) -> Iterable[W]:
:param layer: layer to search, None will search through all layers
:return: iterator of widgets of given type at position
"""
def check_type(widget) -> W: # should be TypeGuard[W]
return isinstance(widget, cls) # type: ignore
def check_type(widget) -> TypeGuard[W]:
return isinstance(widget, cls)

for widget in self.walk_widgets(layer=layer):
if check_type(widget) and widget.rect.collide_with_point(*pos):
Expand Down Expand Up @@ -319,7 +320,7 @@ def adjust_mouse_coordinates(self, x, y):
px, py = self.camera.position
return x + px, y + py

def on_event(self, event) -> bool:
def on_event(self, event) -> Union[bool, None]:
layers = sorted(self.children.keys(), reverse=True)
for layer in layers:
for child in reversed(self.children[layer]):
Expand Down
5 changes: 3 additions & 2 deletions arcade/gui/widgets/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
List,
Dict,
)
from typing_extensions import Self

from pyglet.event import EventDispatcher, EVENT_HANDLED, EVENT_UNHANDLED

Expand Down Expand Up @@ -531,7 +532,7 @@ def __iter__(self):
def resize(self, *, width=None, height=None):
self.rect = self.rect.resize(width=width, height=height)

def with_border(self, width=2, color=(0, 0, 0)) -> "UIWidget":
def with_border(self, width=2, color=(0, 0, 0)) -> Self:
"""
Sets border properties
:param width: border width
Expand Down Expand Up @@ -759,7 +760,7 @@ def __init__(
size_hint_min=size_hint_min,
size_hint_max=size_hint_max,
)
self.color = (randint(0, 255), randint(0, 255), randint(0, 255))
self.color: RGBA255 = (randint(0, 255), randint(0, 255), randint(0, 255), 255)
self.border_color = arcade.color.BATTLESHIP_GREY

self.bg_color = (
Expand Down
31 changes: 16 additions & 15 deletions arcade/gui/widgets/buttons.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,21 @@
from arcade.gui.widgets.text import UITextWidget
from arcade.text import FontNameOrNames

@dataclass
class UITextureButtonStyle(UIStyleBase):
"""
Used to style the texture button. Below is its use case.
.. code:: py
button = UITextureButton(style={"normal": UITextureButton.UIStyle(...),})
"""
font_size: int = 12
font_name: FontNameOrNames = ("calibri", "arial")
font_color: RGBA255 = arcade.color.WHITE
border_width: int = 2

class UITextureButton(UIInteractiveWidget, UIStyledWidget["UITextureButton.UIStyle"], UITextWidget):
class UITextureButton(UIInteractiveWidget, UIStyledWidget[UITextureButtonStyle], UITextWidget):
"""
A button with an image for the face of the button.
Expand All @@ -37,19 +50,7 @@ class UITextureButton(UIInteractiveWidget, UIStyledWidget["UITextureButton.UISty

_textures: Dict[str, Union[Texture, NinePatchTexture]] = DictProperty() # type: ignore

@dataclass
class UIStyle(UIStyleBase):
"""
Used to style the texture button. Below is its use case.
.. code:: py
button = UITextureButton(style={"normal": UITextureButton.UIStyle(...),})
"""
font_size: int = 12
font_name: FontNameOrNames = ("calibri", "arial")
font_color: RGBA255 = arcade.color.WHITE
border_width: int = 2
UIStyle = UITextureButtonStyle

DEFAULT_STYLE = {
"normal": UIStyle(),
Expand Down Expand Up @@ -192,7 +193,7 @@ def do_render(self, surface: Surface):
if current_texture:
surface.draw_texture(0, 0, self.content_width, self.content_height, current_texture)

def apply_style(self, style: UIStyle):
def apply_style(self, style: UITextureButtonStyle):
"""
Callback which is called right before rendering to apply changes for rendering.
"""
Expand Down
2 changes: 1 addition & 1 deletion arcade/gui/widgets/dropdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ def _update_options(self):

button = self._layout.add(
UIFlatButton(
text=option,
text=option, # type: ignore # is definitely a string
width=self.width,
height=self.height,
style=active_style
Expand Down
15 changes: 3 additions & 12 deletions arcade/gui/widgets/layout.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Iterable, List, TypeVar, Tuple, Optional
from typing import Iterable, List, TypeVar, Tuple, Optional, cast

from arcade.gui.property import bind
from arcade.gui.widgets import UIWidget, UILayout
Expand Down Expand Up @@ -549,10 +549,6 @@ def _layouting_allowed(child: UIWidget) -> Tuple[bool, bool]:

def _update_size_hints(self):

child_sorted_row_wise = [
[None for _ in range(self.column_count)] for _ in range(self.row_count)
]

max_width_per_column: list[list[tuple[int, int]]] = [
[(0, 1) for _ in range(self.row_count)] for _ in range(self.column_count)
]
Expand Down Expand Up @@ -590,11 +586,6 @@ def min_size(child: UIWidget) -> Tuple[float, float]:

max_height_per_row[row_num][col_num] = (shmn_h, row_span)

for row in child_sorted_row_wise[
row_num : row_num + row_span # noqa: E203
]:
row[col_num : col_num + col_span] = [child] * col_span # noqa: E203

principal_width_ratio_list = []
principal_height_ratio_list = []

Expand Down Expand Up @@ -658,9 +649,9 @@ def do_layout(self):
if not self.children:
return

child_sorted_row_wise = [
child_sorted_row_wise = cast(List[List[UIWidget]], [
[None for _ in range(self.column_count)] for _ in range(self.row_count)
]
])

max_width_per_column: list[list[tuple[float, int]]] = [
[(0, 1) for _ in range(self.row_count)] for _ in range(self.column_count)
Expand Down
38 changes: 20 additions & 18 deletions arcade/gui/widgets/slider.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,23 @@
from arcade.gui.property import Property, bind
from arcade.gui.style import UIStyleBase, UIStyledWidget

@dataclass
class UISliderStyle(UIStyleBase):
"""
Used to style the slider for different states. Below is its use case.
.. code:: py
class UISlider(UIStyledWidget["UISlider.UIStyle"]):
button = UITextureButton(style={"normal": UITextureButton.UIStyle(...),})
"""
bg: RGBA255 = Color(94, 104, 117)
border: RGBA255 = Color(77, 81, 87)
border_width: int = 1
filled_bar: RGBA255 = Color(50, 50, 50)
unfilled_bar: RGBA255 = Color(116, 125, 123)


class UISlider(UIStyledWidget[UISliderStyle]):
"""
A simple horizontal slider. The value of the slider can be set by moving the cursor(indicator).
Expand All @@ -41,20 +56,7 @@ class UISlider(UIStyledWidget["UISlider.UIStyle"]):
pressed = Property(False)
disabled = Property(False)

@dataclass
class UIStyle(UIStyleBase):
"""
Used to style the slider for different states. Below is its use case.
.. code:: py
button = UITextureButton(style={"normal": UITextureButton.UIStyle(...),})
"""
bg: RGBA255 = Color(94, 104, 117)
border: RGBA255 = Color(77, 81, 87)
border_width: int = 1
filled_bar: RGBA255 = Color(50, 50, 50)
unfilled_bar: RGBA255 = Color(116, 125, 123)
UIStyle = UISliderStyle

DEFAULT_STYLE = {
"normal": UIStyle(),
Expand Down Expand Up @@ -94,7 +96,7 @@ def __init__(
size_hint=None,
size_hint_min=None,
size_hint_max=None,
style: Union[Mapping[str, "UISlider.UIStyle"], None] = None, # typing: ignore
style: Union[Mapping[str, UISliderStyle], None] = None,
**kwargs,
):
super().__init__(
Expand Down Expand Up @@ -134,7 +136,7 @@ def get_current_state(self) -> str:
else:
return "normal"

def _x_for_value(self, value):
def _x_for_value(self, value: float):
x = self.content_rect.x
nval = (value - self.vmin) / self.vmax
return (
Expand Down Expand Up @@ -225,7 +227,7 @@ def do_render(self, surface: Surface):
border_width,
)

def _cursor_pos(self) -> Tuple[int, int]:
def _cursor_pos(self) -> Tuple[float, float]:
return self.value_x, int(self.y + self.height // 2)

def _is_on_cursor(self, x: float, y: float) -> bool:
Expand Down

0 comments on commit 2381082

Please sign in to comment.