Source code for approxeng.task.menu
import uuid
import copy
import logging
import yaml
from approxeng.task import register_task, Task, TaskStop
from enum import Enum, unique
from abc import abstractmethod
LOG = logging.getLogger('approxeng.task.menu')
[docs]class MenuTask(Task):
"""
A single menu, consisting of a title and a set of items, each of which will launch a
task when selected. Optionally menus may have a parent.
"""
[docs] def __init__(self, name, title, parent_task, resources=None):
super(MenuTask, self).__init__(name, resources)
self.name = name
self.title = title
self.parent_task = parent_task
self.item_index = 0
self.items = []
# True if the display should be updated
self.display_update = True
LOG.debug('Created menu task %s with title "%s"', self.name, self.title)
def add_item(self, title, task_name):
LOG.debug('Adding "%s"->%s to menu task %s', title, task_name, self.name)
self.items.append({'title': title, 'task': task_name})
[docs] def tick(self, world):
action = self.get_menu_action(world)
if action is not None:
if action is MenuAction.next:
LOG.debug('Menu action = next')
self.item_index = (self.item_index + 1) % len(self.items)
self.display_update = True
elif action is MenuAction.previous:
LOG.debug('Menu action = previous')
self.item_index = (self.item_index - 1) % len(self.items)
self.display_update = True
elif action is MenuAction.select:
LOG.debug('Menu action = select')
return self.items[self.item_index]['task']
elif action is MenuAction.up and self.parent_task is not None:
LOG.debug('Menu action = up')
return self.parent_task
elif isinstance(action, int):
LOG.debug('Menu action = select index %i', action)
if 0 <= action < len(self.items):
return self.items[action]['task']
if self.display_update:
LOG.debug('Menu, updating display')
self.display_menu(world=world, title=self.title, item_title=self.items[self.item_index]['title'],
item_index=self.item_index, item_count=len(self.items))
self.display_update = False
[docs]class KeyboardMenuTask(MenuTask):
"""
Not particularly clever implementation of :class:`~approxeng.task.menu.MenuTask` that uses print statements and
``input()`` to get menu choices. Has the advantage of working with no additional resources, so handy for testing.
"""
def unique_id(prefix):
return prefix + '_' + str(uuid.uuid4())