mirror of
https://github.com/trezor/trezor-firmware.git
synced 2024-11-18 05:28:40 +00:00
1a0b590914
WIP - typing the trezorctl apps typing functions trezorlib/cli addressing most of mypy issue for trezorlib apps and _internal folder fixing broken device tests by changing asserts in debuglink.py addressing most of mypy issues in trezorlib/cli folder adding types to some untyped functions, mypy section in setup.cfg typing what can be typed, some mypy fixes, resolving circular import issues importing type objects in "if TYPE_CHECKING:" branch fixing CI by removing assert in emulator, better ignore comments CI assert fix, style fixes, new config options fixup! CI assert fix, style fixes, new config options type fixes after rebasing on master fixing python3.6 and 3.7 unittests by importing Literal from typing_extensions couple mypy and style fixes fixes and improvements from code review silencing all but one mypy issues trial of typing the tools.expect function fixup! trial of typing the tools.expect function @expect and @session decorators correctly type-checked Optional args in CLI where relevant, not using general list/tuple/dict where possible python/Makefile commands, adding them into CI, ignoring last mypy issue documenting overload for expect decorator, two mypy fixes coming from that black style fix improved typing of decorators, pyright config file addressing or ignoring pyright errors, replacing mypy in CI by pyright fixing incomplete assert causing device tests to fail pyright issue that showed in CI but not locally, printing pyright version in CI fixup! pyright issue that showed in CI but not locally, printing pyright version in CI unifying type:ignore statements for pyright usage resolving PIL.Image issues, pyrightconfig not excluding anything replacing couple asserts with TypeGuard on safe_issubclass better error handling of usb1 import for webusb better error handling of hid import small typing details found out by strict pyright mode improvements from code review chore(python): changing List to Sequence for protobuf messages small code changes to reflect the protobuf change to Sequence importing TypedDict from typing_extensions to support 3.6 and 3.7 simplify _format_access_list function fixup! simplify _format_access_list function typing tools folder typing helper-scripts folder some click typing enforcing all functions to have typed arguments reverting the changed argument name in tools replacing TransportType with Transport making PinMatrixRequest.type protobuf attribute required reverting the protobuf change, making argument into get_pin Optional small fixes in asserts solving the session decorator type issues fixup! solving the session decorator type issues improvements from code review fixing new pyright errors introduced after version increase changing -> Iterable to -> Sequence in enumerate_devices, change in wait_for_devices style change in debuglink.py chore(python): adding type annotation to Sequences in messages.py better "self and cls" types on Transport fixup! better "self and cls" types on Transport fixing some easy things from strict pyright run
151 lines
4.2 KiB
Python
151 lines
4.2 KiB
Python
import struct
|
|
import zlib
|
|
from dataclasses import dataclass
|
|
from typing import Sequence, Tuple
|
|
|
|
from typing_extensions import Literal
|
|
|
|
from . import firmware
|
|
|
|
try:
|
|
# Explanation of having to use "Image.Image" in typing:
|
|
# https://stackoverflow.com/questions/58236138/pil-and-python-static-typing/58236618#58236618
|
|
from PIL import Image
|
|
|
|
PIL_AVAILABLE = True
|
|
except ImportError:
|
|
PIL_AVAILABLE = False
|
|
|
|
|
|
RGBPixel = Tuple[int, int, int]
|
|
|
|
|
|
def _compress(data: bytes) -> bytes:
|
|
z = zlib.compressobj(level=9, wbits=-10)
|
|
return z.compress(data) + z.flush()
|
|
|
|
|
|
def _decompress(data: bytes) -> bytes:
|
|
return zlib.decompress(data, wbits=-10)
|
|
|
|
|
|
def _from_pil_rgb(pixels: Sequence[RGBPixel]) -> bytes:
|
|
data = bytearray()
|
|
for r, g, b in pixels:
|
|
c = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | ((b & 0xF8) >> 3)
|
|
data += struct.pack(">H", c)
|
|
return bytes(data)
|
|
|
|
|
|
def _to_rgb(data: bytes) -> bytes:
|
|
res = bytearray()
|
|
for i in range(0, len(data), 2):
|
|
(c,) = struct.unpack(">H", data[i : i + 2])
|
|
r = (c & 0xF800) >> 8
|
|
g = (c & 0x07C0) >> 3
|
|
b = (c & 0x001F) << 3
|
|
res += bytes((r, g, b))
|
|
return bytes(res)
|
|
|
|
|
|
def _from_pil_grayscale(pixels: Sequence[int]) -> bytes:
|
|
data = bytearray()
|
|
for i in range(0, len(pixels), 2):
|
|
left, right = pixels[i], pixels[i + 1]
|
|
c = (left & 0xF0) | ((right & 0xF0) >> 4)
|
|
data += struct.pack(">B", c)
|
|
return bytes(data)
|
|
|
|
|
|
def _to_grayscale(data: bytes) -> bytes:
|
|
res = bytearray()
|
|
for pixel in data:
|
|
left = pixel & 0xF0
|
|
right = (pixel & 0x0F) << 4
|
|
res += bytes((left, right))
|
|
return bytes(res)
|
|
|
|
|
|
@dataclass
|
|
class Toif:
|
|
mode: firmware.ToifMode
|
|
size: Tuple[int, int]
|
|
data: bytes
|
|
|
|
def __post_init__(self) -> None:
|
|
# checking the data size
|
|
width, height = self.size
|
|
if self.mode is firmware.ToifMode.grayscale:
|
|
expected_size = width * height // 2
|
|
else:
|
|
expected_size = width * height * 2
|
|
uncompressed = _decompress(self.data)
|
|
if len(uncompressed) != expected_size:
|
|
raise ValueError(
|
|
f"Uncompressed data is {len(uncompressed)} bytes, expected {expected_size}"
|
|
)
|
|
|
|
def to_image(self) -> "Image.Image":
|
|
if not PIL_AVAILABLE:
|
|
raise RuntimeError(
|
|
"PIL is not available. Please install via 'pip install Pillow'"
|
|
)
|
|
|
|
uncompressed = _decompress(self.data)
|
|
|
|
pil_mode: Literal["L", "RGB"]
|
|
if self.mode is firmware.ToifMode.grayscale:
|
|
pil_mode = "L"
|
|
raw_data = _to_grayscale(uncompressed)
|
|
else:
|
|
pil_mode = "RGB"
|
|
raw_data = _to_rgb(uncompressed)
|
|
|
|
return Image.frombuffer(pil_mode, self.size, raw_data, "raw", pil_mode, 0, 1)
|
|
|
|
def to_bytes(self) -> bytes:
|
|
width, height = self.size
|
|
return firmware.Toif.build(
|
|
dict(format=self.mode, width=width, height=height, data=self.data)
|
|
)
|
|
|
|
def save(self, filename: str) -> None:
|
|
with open(filename, "wb") as out:
|
|
out.write(self.to_bytes())
|
|
|
|
|
|
def from_bytes(data: bytes) -> Toif:
|
|
parsed = firmware.Toif.parse(data)
|
|
return Toif(parsed.format, (parsed.width, parsed.height), parsed.data)
|
|
|
|
|
|
def load(filename: str) -> Toif:
|
|
with open(filename, "rb") as f:
|
|
return from_bytes(f.read())
|
|
|
|
|
|
def from_image(
|
|
image: "Image.Image", background: Tuple[int, int, int, int] = (0, 0, 0, 255)
|
|
) -> Toif:
|
|
if not PIL_AVAILABLE:
|
|
raise RuntimeError(
|
|
"PIL is not available. Please install via 'pip install Pillow'"
|
|
)
|
|
|
|
if image.mode == "RGBA":
|
|
img_background = Image.new("RGBA", image.size, background)
|
|
blend = Image.alpha_composite(img_background, image)
|
|
image = blend.convert("RGB")
|
|
|
|
if image.mode == "L":
|
|
toif_mode = firmware.ToifMode.grayscale
|
|
toif_data = _from_pil_grayscale(image.getdata())
|
|
elif image.mode == "RGB":
|
|
toif_mode = firmware.ToifMode.full_color
|
|
toif_data = _from_pil_rgb(image.getdata())
|
|
else:
|
|
raise ValueError(f"Unsupported image mode: {image.mode}")
|
|
|
|
data = _compress(toif_data)
|
|
return Toif(toif_mode, image.size, data)
|