This repository has been archived on 2022-12-29. You can view files and clone it, but cannot push or open issues or pull requests.
zeropod/menu.py

51 lines
1.6 KiB
Python

from board import SCL, SDA
from busio import I2C
from adafruit_ssd1306 import SSD1306_I2C
from enum import Enum, auto
from dataclasses import dataclass
from cinput import ControlInput, Button
from graphics import Graphics
class MenuType(Enum):
SUB_MENU = auto()
EXEC_CMD = auto()
EXEC_PLUGIN = auto()
@dataclass
class MenuItem:
display: str
menu_type: MenuType
class Menu:
def __init__(
self, config: list[MenuItem], cinput: ControlInput, graphics: Graphics):
self._selected_index = 0
self._menu = config
self._input = cinput
self._graphics = graphics
def _print(self, items: list[MenuItem]):
self._graphics.clear()
top_index = 0 if self._selected_index < Graphics.MAX_LINES else Graphics.MAX_LINES - self._selected_index + 1
for idx in range(top_index, top_index + Graphics.MAX_LINES):
if idx >= len(items):
break
marker = "> " if idx == self._selected_index else " "
self._graphics.text(marker + items[idx].display, 0, (idx - top_index) * Graphics.LINE_HEIGHT, 1)
self._graphics.show()
def get_selection(self):
while True:
self._print(self._menu)
pressed = self._input.get_one_shot()
if pressed == Button.DIR_U:
self._selected_index -= 1
if self._selected_index < 0:
self._selected_index = len(self._menu) - 1
elif pressed == Button.DIR_D:
self._selected_index += 1
if self._selected_index >= len(self._menu):
self._selected_index = 0