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

72 lines
2.5 KiB
Python
Raw Normal View History

from enum import Enum, auto
from dataclasses import dataclass
2022-04-23 13:37:54 -05:00
from cinput import ControlInput, Button
from graphics import Graphics
class MenuType(Enum):
SUB_MENU = auto()
2022-12-28 08:35:28 -06:00
CMD = auto()
2022-04-23 15:44:15 -05:00
EXIT_CMD = auto()
PLUGIN = auto()
@dataclass
class MenuItem:
display: str
menu_type: MenuType
2022-04-23 15:33:19 -05:00
data: dict
2022-04-23 13:37:54 -05:00
class Menu:
def __init__(
self, config: list[MenuItem], cinput: ControlInput, graphics: Graphics):
2022-04-23 15:33:19 -05:00
self._top_index = 0
2022-04-23 13:37:54 -05:00
self._selected_index = 0
2022-04-23 15:33:19 -05:00
self._menu_path = list()
2022-04-23 13:37:54 -05:00
self._menu = config
2022-04-23 15:33:19 -05:00
self._cur_menu = self._menu
2022-04-23 13:37:54 -05:00
self._input = cinput
self._graphics = graphics
def _print(self, items: list[MenuItem]):
self._graphics.clear()
2022-04-23 15:33:19 -05:00
selected_diff = self._selected_index - self._top_index
if selected_diff < 0:
self._top_index = self._selected_index
if selected_diff >= Graphics.MAX_LINES:
self._top_index = self._selected_index - Graphics.MAX_LINES + 1
2022-04-23 13:37:54 -05:00
2022-04-23 15:33:19 -05:00
for idx in range(self._top_index, self._top_index + Graphics.MAX_LINES):
2022-04-23 13:37:54 -05:00
if idx >= len(items):
break
marker = "> " if idx == self._selected_index else " "
2022-04-23 18:25:09 -05:00
self._graphics.text(marker + items[idx].display, 0, (idx - self._top_index), 1)
2022-04-23 13:37:54 -05:00
self._graphics.show()
def get_selection(self):
while True:
2022-04-23 15:33:19 -05:00
self._print(self._cur_menu)
2022-04-23 13:37:54 -05:00
pressed = self._input.get_one_shot()
2022-04-23 15:33:19 -05:00
2022-04-23 13:37:54 -05:00
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
2022-04-23 15:33:19 -05:00
elif pressed == Button.BTN_B or pressed == Button.DIR_R:
item = self._cur_menu[self._selected_index]
if item.menu_type == MenuType.SUB_MENU:
self._menu_path.append(self._selected_index)
self._selected_index = 0
else:
return item
elif pressed == Button.BTN_A or pressed == Button.DIR_L:
if len(self._menu_path) > 0:
self._selected_index = self._menu_path.pop()
self._cur_menu = self._menu
for i in range(0, len(self._menu_path)):
self._cur_menu = self._cur_menu[self._menu_path[i]].data["sub_menu"]