"""KEYINPUT and KEYCNT (GBATEK "GBA Keypad Input"). Ten buttons, 0 = pressed. KEYCNT selects buttons and raises the keypad IRQ when any (OR) or all (AND) of them are down; the condition is checked when a key changes and when KEYCNT is written (NanoBoyAdvance ``hw/keypad/keypad.cpp``). AND asks that every selected button be down, whatever else is: "an interrupt is requested when ALL of the selected buttons are pressed" (GBATEK "Keypad Input"), as mGBA tests it and mGBA's ``keyirq`` expects (steps 2 and 12). NanoBoyAdvance asks for exactly the selected buttons. Whether a KEYCNT write re-raises a condition that already held is open (C23). """ from __future__ import annotations from gba_python.irq import IRQ, KEYPAD A, B, SELECT, START, RIGHT, LEFT, UP, DOWN, R, L = (1 << bit for bit in range(10)) ALL = 0x3FF class Keypad: def __init__(self, irq: IRQ) -> None: self.irq = irq self.input = ALL # KEYINPUT: every key released self.control = 0 def set_pressed(self, keys: int) -> None: """Set the held keys (a bit set of the constants above).""" self.input = ALL & ~keys self._check() def write_control(self, value: int, mask: int) -> None: self.control = (self.control & ~mask | value & mask) & 0xC3FF self._check() def _check(self) -> None: if not self.control & 0x4000: return selected = self.control & ALL down = ~self.input & ALL if self.control & 0x8000: if selected & down == selected: self.irq.raise_(KEYPAD) elif selected & down: self.irq.raise_(KEYPAD)